AtlatestRepositorysigil-geometry
1# sigil-geometry
2
33D maths for games and graphics in [Sigil](https://codeberg.org/sigil/sigil):
4vectors, matrices, quaternions, camera matrices and ray casts.
5
6Every value is a float32 bytevector laid out the way a GPU uniform
7expects it, so a matrix goes to a shader with no conversion. Every
8operation that produces a vector or matrix has an allocation-free `!`
9form that writes into a destination you reuse from frame to frame. The
10package is pure Sigil and runs the same on bytecode, native and wasm.
12## Install
14```scheme
15(dependencies: (list
16 (from-git url: "codeberg:sigil/sigil-geometry" version: "^0.1")))
17```
19```scheme
20(import (sigil geometry))
21```
23## Example: a camera matrix for a shader
25The vertex shader:
27```glsl
28uniform mat4 u_mvp;
29in vec3 a_position;
30void main() { gl_Position = u_mvp * vec4(a_position, 1.0); }
31```
33The Sigil side. The matrices are made once; each frame rewrites them in
34place:
36```scheme
37(import (sigil geometry))
39(define proj (mat4-perspective (degrees->radians 70.0) (/ 480.0 270.0) 0.1 100.0))
40(define view (make-mat4))
41(define model (make-mat4))
42(define mvp (make-mat4))
44(define eye (vec3 0 1.7 5))
45(define target (vec3 0 1.7 0))
46(define up (vec3 0 1 0))
47(define spin (make-quat))
49(define (update-camera! seconds)
50 (quat-from-axis-angle! spin up seconds)
51 (mat4-from-quat! model spin)
52 (mat4-look-at! view eye target up)
53 (mat4-mul! mvp view model) ; view * model
54 (mat4-mul! mvp proj mvp) ; proj * view * model
55 mvp) ; 64 bytes, column-major float32
56```
58`mvp` is the uniform's data as it stands: sigil-graphics' 3D path takes
59the bytevector directly. With sigil-graphics 0.11's `set-shader-uniform`,
60which takes a list of numbers and reaches the fragment stage only, pass
61`(mat4->list mvp)`; the list is in the column-major order GLSL expects.
63## The layout contract
65This is what GPU-facing code (sigil-graphics) relies on. It is pinned by
66`test/test-layout.sgl`.
68| value | bytes | contents |
69|---|---|---|
70| vec2 | 8 | x y |
71| vec3 | 12 | x y z |
72| vec4 | 16 | x y z w |
73| quat | 16 | x y z w (w is the scalar part; identity is 0 0 0 1) |
74| mat3 | 36 | 9 floats, column-major |
75| mat4 | 64 | 16 floats, column-major |
77- **float32**, IEEE-754 single precision, in **native byte order**
78 (little-endian on x86-64, aarch64 and wasm32). That is the order GL
79 reads client memory in.
80- **Column-major**, the OpenGL convention: element (column `c`, row `r`)
81 of a mat4 is float `c*4 + r`. A translation sits in floats 12, 13
82 and 14. Pass a mat4 to GL with no transpose.
83- **Column vectors, multiplied on the left.** `(mat4-mul a b)` applies
84 `b` first, then `a`. `(quat-mul a b)` follows the same order.
85- **OpenGL clip space.** The camera looks down -Z in a right-handed view
86 space with +Y up, and projections map depth to -1..1 after the divide
87 by w. The results match `gluPerspective`, `glOrtho` and `gluLookAt`.
88- A **std140 uniform block** pads each mat3 column to 4 floats, so it
89 does not take the tight 36-byte mat3. `mat3->std140!` writes the
90 48-byte padded form. A mat4 needs no padding.
91- Reads return flonums (double precision); writes round to float32, so
92 `(vec3-x (vec3 0.1 0 0))` is 0.10000000149011612.
94sigil-geometry and sigil-graphics do not depend on each other: the
95contract is the bytes.
97## Conventions
99- **Two forms.** `(vec3-add a b)` returns a new vec3. `(vec3-add! dst a b)`
100 writes into `dst`, returns `dst`, and allocates nothing. The destination
101 may be the same bytevector as any input: `(mat4-mul! m m other)` is fine.
102- **Scalars never allocate.** `vec3-dot`, `vec3-length`,
103 `mat4-determinant`, `quat-angle` and the ray casts return a number (or
104 #f) directly.
105- **`make-` gives a useful starting value.** `make-vec3` is zeros;
106 `make-mat3`, `make-mat4` and `make-quat` are the identity.
107- **Failure is a value where it can happen in normal use.**
108 `mat4-inverse!` returns #f for a singular matrix and leaves `dst`
109 untouched; a ray cast that misses returns #f; normalizing a zero vector
110 gives zero. Arguments that describe nothing (a perspective with
111 `near <= 0`, a plane with a zero normal) raise an error.
112- **Tolerant comparison.** `vec3-approx=?`, `mat4-approx=?` and friends
113 take an optional epsilon (default 1e-5, relative above magnitude 1,
114 must be positive). A NaN on either side is never approx=?.
115 `quat-same-rotation?` compares components up to sign, so `q` and `-q`
116 match and a non-unit quaternion does not match a unit one. Passing the
117 epsilon explicitly allocates one list cell per call (it is a rest
118 argument); the default allocates nothing.
120## API
122### Vectors: `(sigil geometry vec)`
124For each of vec2, vec3 and vec4 (a `!` marks a form that also has an
125allocating twin without the `!`):
127| | |
128|---|---|
129| make | `vec3`, `make-vec3`, `vec3-copy`, `vec3-copy!`, `vec3-set!`, `vec3?` (size check) |
130| access | `vec3-x`, `vec3-y`, `vec3-z` (`vec4-w`), `vec3->list` |
131| arithmetic | `vec3-add!`, `vec3-sub!`, `vec3-mul!` (per component), `vec3-scale!`, `vec3-negate!`, `vec3-lerp!` |
132| measure | `vec3-dot`, `vec3-length`, `vec3-length-squared`, `vec3-normalize!`, `vec2-distance`, `vec3-distance` |
133| vec3 only | `vec3-cross!`, `vec3-add-scaled!` (a + b·s), `vec3-min!`, `vec3-max!`, `vec3-distance-squared` |
134| compare | `vec3-approx=?`, `float-approx=?` |
135| angles | `degrees->radians`, `radians->degrees` |
137### Matrices: `(sigil geometry mat4)`, `(sigil geometry mat3)`
139| | mat4 | mat3 |
140|---|---|---|
141| make | `mat4` (16 values), `make-mat4`, `mat4-identity!`, `list->mat4`, `mat4-copy!`, `mat4?` | `mat3`, `make-mat3`, `mat3-identity!`, `list->mat3`, `mat3-copy!`, `mat3?` |
142| access | `mat4-ref m col row`, `mat4-set!`, `mat4->list` | `mat3-ref`, `mat3-set!`, `mat3->list` |
143| algebra | `mat4-mul!`, `mat4-transpose!`, `mat4-inverse!`, `mat4-determinant` | `mat3-mul!`, `mat3-transpose!`, `mat3-inverse!`, `mat3-determinant` |
144| build | `mat4-translation!`, `mat4-scaling!`, `mat4-rotation-x!` / `-y!` / `-z!`, `mat4-rotation! axis angle`, `mat4-from-quat!`, `mat4-from-trs! t q s` | `mat3-from-mat4!`, `mat3-normal-matrix!`, `mat3-from-quat!` |
145| apply | `mat4-transform-point!` (w = 1, divides by w), `mat4-transform-direction!` (w = 0), `mat4-transform-vec4!`, `mat4-get-translation!` | `mat3-transform-vec3!` |
146| upload | the bytevector itself | `mat3->std140!` |
147| compare | `mat4-approx=?` | `mat3-approx=?` |
149### Quaternions: `(sigil geometry quat)`
151`quat`, `make-quat`, `quat?`, `quat-identity!`, `quat-from-axis-angle!`,
152`quat-from-mat3!`, `quat-from-mat4!`, `quat-mul!`, `quat-conjugate!`,
153`quat-inverse!`, `quat-normalize!`, `quat-dot`, `quat-length`,
154`quat-slerp!`, `quat-nlerp!`, `quat-rotate-vec3!`, `quat-angle`,
155`quat-x` / `-y` / `-z` / `-w`, `quat-set!`, `quat-copy!`, `quat->list`,
156`quat-approx=?`, `quat-same-rotation?`.
158`quat-slerp!` blends two orientations at constant angular speed along
159the shorter arc, which is what pose blending needs; `quat-nlerp!` is the
160cheaper approximation.
162### Cameras: `(sigil geometry camera)`
164| | |
165|---|---|
166| `(mat4-perspective! dst fovy aspect near far)` | `fovy` is the full vertical angle in radians; `aspect` is width / height |
167| `(mat4-orthographic! dst left right bottom top near far)` | the view-space box from (left, bottom, -near) to (right, top, -far) |
168| `(mat4-look-at! dst eye target up)` | a view matrix; looking straight along `up` still gives a valid rotation |
170### Rays: `(sigil geometry ray)`
172A ray is an `origin` vec3 and a `dir` vec3. `dir` need not be unit
173length: casts return the parameter `t` of the hit point `origin + dir·t`.
174That makes a sight line a ray with `dir = target - eye`, where a hit with
175`t < 1` is something in between:
177```scheme
178(vec3-sub! dir player-eye guard-eye)
179(let ((t (ray-aabb guard-eye dir crate-min crate-max)))
180 (and t (< t 1.0))) ; #t: the crate blocks the guard's view
181```
183| | |
184|---|---|
185| `(ray-plane origin dir plane)` | `t >= 0` or #f; a plane is a vec4 (a b c d) for a·x + b·y + c·z + d = 0 |
186| `(ray-aabb origin dir box-min box-max)` | entry `t` (0.0 from inside) or #f |
187| `(ray-triangle origin dir a b c)` | `t` or #f, either face |
188| `(ray-triangle-hit! dst origin dir a b c)` | also writes (t u v) into `dst`: u and v weight `b` and `c`, for texture coordinates at a picked point |
189| `(ray-point! dst origin dir t)` | the point at `t` |
190| `plane-from-point-normal!`, `plane-from-points!`, `plane-signed-distance` | planes with unit normals; counterclockwise points face the viewer |
191| `aabb-contains-point?`, `aabb-overlap?` | box tests |
193## Allocation, measured
195`scripts/check-targets` counts GC allocations over 1000 calls of each of
196123 checks, against an empty-loop baseline and a positive control. The
197checks cover all 80 exported `!` forms, the scalar, ray and comparison
198functions, and the other branches of the ops that have them (a
199projection's divide by w, a singular inverse, a degenerate look-at, each
200branch of the matrix-to-quaternion conversion, zero-length normalize, ray
201misses). The script refuses to run if an exported `!` form has no check.
202Results with sigil 0.22.7:
204| target | allocations per call |
205|---|---|
206| native wasm (the web) | 0 for all 123 |
207| bytecode | 0 for all 123 |
208| native ELF | 0 for 87; the other 36 allocate where the call crosses from native code into bytecode (see below) |
210On a native ELF build, sigil 0.22.7 loads a dependency package's
211compiled bytecode rather than its native code, so an app's calls into
212sigil-geometry cross from native to bytecode. That crossing allocates one
213object per argument for calls with 4 or more arguments, and 2 for a call
214to a procedure with a rest argument (the `approx=?` family). It is a
215property of the toolchain's ELF bundles, not of this package, and the
216wasm build is not affected.
218What the package avoids in its hot paths, and why (each measured to
219allocate on every call under native codegen):
221- `syntax-rules` macros whose template names a global: native codegen
222 looks the global up at run time through `%hygiene-ref`, which conses.
223 Helper procedures cost nothing.
224- Named-let loops (3 to 5 objects per call) and `case-lambda` (2 to 4):
225 loops are top-level recursive procedures instead.
226- Passing a rest argument (one list cell).
228Sigil 0.22.7 also answers #t to `(<= x y)`, `(>= x y)` and `(= x y)` when
229an operand is NaN, so the comparisons here are written with `<` and `>`,
230which answer correctly.
232## Development
234```sh
235sigil deps install
236sigil test # the suite on the host (bytecode)
237guix shell -m manifest.scm -- scripts/check-targets
238 # suite + allocation check on bytecode,
239 # native ELF and wasm (needs wasm-opt, node)
240```
242`scripts/check-targets` turns each test file into a library, compiles it
243into the app in `harness/` with the allocation check, runs it on each
244target (wasm under Node), and reports per target. A target passes when
245every test ran and passed and, where the geometry code is native or all
246bytecode, none of the 123 checks allocated.
248## License
250BSD-3-Clause