Skip to content

Instantly share code, notes, and snippets.

@neuro-sys
Last active March 7, 2021 16:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save neuro-sys/000dfb94fcbef847e685c2e3a28c5d85 to your computer and use it in GitHub Desktop.
Save neuro-sys/000dfb94fcbef847e685c2e3a28c5d85 to your computer and use it in GitHub Desktop.
fixed point vector operations
0 warnings !
vocabulary f8
f8 definitions
\ fixed point 8.8 conversion
: d>f8 ( d -- f8 ) 256 * ;
: f8>d ( f8 -- d ) 256 / ;
: f8mul ( n0 n1 - n2 ) * 256 / ;
: f8div ( n0 n1 - n2 ) / 256 * ;
\ end f8
vocabulary vec
vec definitions
also f8
0 \ vector3
dup constant v.x 1 cells +
dup constant v.y 1 cells +
dup constant v.z 1 cells +
constant vector3
: v.x v.x + ;
: v.y v.y + ;
: v.z v.z + ;
: v.x@ v.x @ ;
: v.y@ v.y @ ;
: v.z@ v.z @ ;
create v0 vector3 allot
create v1 vector3 allot
: savev0 ( v0 -- )
v0 v.z ! v0 v.y ! v0 v.x ! ;
: savev1 ( v1 -- )
v1 v.z ! v1 v.y ! v1 v.x ! ;
: savev01 ( v0 v1 -- )
savev1 savev0 ;
: vadd ( v0 v1 -- v2 )
savev01
v0 v.x@ v1 v.x@ +
v0 v.y@ v1 v.y@ +
v0 v.z@ v1 v.z@ +
;
: vsub ( v0 v1 -- v2 )
savev01
v0 v.x@ v1 v.x@ -
v0 v.y@ v1 v.y@ -
v0 v.z@ v1 v.z@ -
;
: vmul ( v0 v1 -- v2 )
savev01
v0 v.x@ v1 v.x@ *
v0 v.y@ v1 v.y@ *
v0 v.z@ v1 v.z@ *
;
: vdiv ( v0 v1 -- v2 )
savev01
v0 v.x@ v1 v.x@ /
v0 v.y@ v1 v.y@ /
v0 v.z@ v1 v.z@ /
;
: vlen ( v0 -- n )
savev0
v0 v.x@ dup *
v0 v.y@ dup *
v0 v.z@ dup * + +
s>f fsqrt f>s
;
: vdot ( v0 v1 -- n )
savev01
v0 v.x@ v1 v.x@ f8mul
v0 v.y@ v1 v.y@ f8mul
v0 v.z@ v1 v.z@ f8mul
+ +
;
: vcross ( v0 v1 -- v2 )
savev01
v0 v.y@ v1 v.z@ f8mul
v0 v.z@ v1 v.y@ f8mul -
v0 v.z@ v1 v.x@ f8mul
v0 v.x@ v1 v.z@ f8mul -
v0 v.x@ v1 v.y@ f8mul
v0 v.y@ v1 v.x@ f8mul -
;
\ end vec
cr ." (13, 42, 85) . (3, 5, 9) = "
13 d>f8
42 d>f8
85 d>f8
3 d>f8
5 d>f8
9 d>f8
vdot f8>d .
cr ." (13, 42, 85) x (3, 5, 9) = "
13 d>f8
42 d>f8
85 d>f8
3 d>f8
5 d>f8
9 d>f8
vcross savev0
v0 v.x@ f8>d .
v0 v.y@ f8>d .
v0 v.z@ f8>d .
bye
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment