Commitd62da89bRecorded25 Sep 2026Repositorysigil-geometry

Add sigil-geometry: 3D maths for games and graphics

Message

Vectors (vec2, vec3, vec4), 3x3 and 4x4 matrices, quaternions, camera matrices (perspective, orthographic, look-at) and ray casts against planes, boxes and triangles.

Values are float32 bytevectors in native byte order; matrices are column-major (the OpenGL convention), so a mat4 goes to a shader uniform as it is. Every operation that produces a value has an allocation-free ! form that writes into a destination, which may alias any input. The hot paths use helper procedures rather than syntax-rules macros: under native codegen a macro-introduced global is looked up through %hygiene-ref at run time and allocates on every call.

Tests cover known values (camera matrices against numpy references), inverse * m = identity, quaternion/matrix round trips, the byte layout contract, the facade's exports, and property tests over a fixed-seed generator. scripts/check-targets runs the suite and an allocation check of the ! forms as bytecode, native ELF and wasm through the app in harness/.

Changed
 .gitignore                             |   2 +
 harness/.gitignore                     |   4 ++
 harness/package.sgl                    |  42 +++++++++++++++++++
 harness/run-wasm.mjs                   |  55 ++++++++++++++++++++++++
 harness/sigil.lock                     |  42 +++++++++++++++++++
 harness/src/geometry-harness/alloc.sgl | 147 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
 harness/src/geometry-harness/main.sgl  |  52 +++++++++++++++++++++++
 manifest.scm                           |  12 ++++++
 package.sgl                            |  16 +++++++
 scripts/check-targets                  | 185 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
 sigil.lock                             |  30 +++++++++++++
 src/sigil/geometry.sgl                 |  82 ++++++++++++++++++++++++++++++++++++
 src/sigil/geometry/camera.sgl          | 142 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
 src/sigil/geometry/mat3.sgl            | 205 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
 src/sigil/geometry/mat4.sgl            | 329 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
 src/sigil/geometry/quat.sgl            | 236 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
 src/sigil/geometry/ray.sgl             | 198 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
 src/sigil/geometry/vec.sgl             | 354 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
 test/test-camera.sgl                   | 109 +++++++++++++++++++++++++++++++++++++++++++++++
 test/test-facade.sgl                   |  48 +++++++++++++++++++++
 test/test-layout.sgl                   |  69 ++++++++++++++++++++++++++++++
 test/test-mat3.sgl                     |  85 +++++++++++++++++++++++++++++++++++++
 test/test-mat4.sgl                     | 185 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
 test/test-properties.sgl               | 166 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
 test/test-quat.sgl                     | 141 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
 test/test-ray.sgl                      | 142 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
 test/test-vec.sgl                      | 136 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
 27 files changed, 3214 insertions(+)
Diff
.gitignoreadded
@@ -0,0 +1,2 @@
+1
build/
+2
.sigil/
harness/.gitignoreadded
@@ -0,0 +1,4 @@
+1
build/
+2
.sigil/
+3
src/geometry-harness/suite/
+4
src/geometry-harness/suite.sgl
harness/package.sgladded
@@ -0,0 +1,42 @@
+1
;;; sigil-geometry-harness - run sigil-geometry's tests on every target
+2
;;;
+3
;;; Not part of the library. A small app that compiles the package's
+4
;;; test files (turned into libraries by scripts/check-targets) together
+5
;;; with an allocation check of every `!` form, so the same code runs as
+6
;;; bytecode (dev), a native ELF (release) and native wasm (web).
+7
;;;
+8
;;; Use scripts/check-targets from the package root rather than building
+9
;;; this directly: it generates src/geometry-harness/suite/ first.
+10
+11
(package
+12
name: "sigil-geometry-harness"
+13
version: "0.0.0"
+14
sigil: "0.22"
+15
description: "Target harness for sigil-geometry (tests and allocation check)"
+16
license: "BSD-3-Clause"
+17
entry: '(geometry-harness main)
+18
bundle-name: "geometry-harness"
+19
+20
configs: (list
+21
(config name: 'dev output-dir: "build/dev" debug?: #t optimize: 0 bundle?: #t)
+22
(config name: 'release output-dir: "build/release" debug?: #f optimize: 2
+23
backend: 'native bundle?: #t)
+24
(config name: 'web output-dir: "build/web" toolchain: 'zig target: "wasm32-wasi"
+25
backend: 'native debug?: #f optimize: 2 bundle?: #t features: '(web wasm)))
+26
+27
dependencies: (list
+28
(from-path dir: ".." package: "sigil-geometry")
+29
(from-git url: "codeberg:sigil/sigil" package: "sigil-test" version: ">=0.22.5")
+30
(from-git url: "codeberg:sigil/sigil" package: "sigil-wasm-runtime" version: ">=0.22.5"
+31
configs: '(web)))
+32
+33
tasks: (list
+34
(task
+35
name: 'build
+36
description: "Compile the harness (and link the wasm on the web config)"
+37
steps: (list
+38
(compile-sigil-modules sources: "src/**/*.sgl")
+39
(lambda (ctx)
+40
(if (memq (target-os ctx) '(wasm wasi))
+41
((link-web-application name: "geometry-harness") ctx)
+42
ctx))))))
harness/run-wasm.mjsadded
@@ -0,0 +1,55 @@
+1
// Boot a Sigil wasm32-wasi web build under Node the way sigil-web-app.js does
+2
// (sigil_wasm_init, then sigil_wasm_start) and print what the program writes.
+3
// A minimal hand-rolled WASI: stdout/stderr, clocks, random; no filesystem.
+4
import fs from "node:fs";
+5
+6
const wasmPath = process.argv[2];
+7
if (!wasmPath || !fs.existsSync(wasmPath)) {
+8
console.error(`SETUP-FAILED: no wasm at ${wasmPath}`);
+9
process.exit(2);
+10
}
+11
const module = await WebAssembly.compile(fs.readFileSync(wasmPath));
+12
let instance = null;
+13
const decoder = new TextDecoder();
+14
const view = () => new DataView(instance.exports.memory.buffer);
+15
const u8 = () => new Uint8Array(instance.exports.memory.buffer);
+16
const known = {
+17
fd_write(fd, iovs, n, nwritten) {
+18
let written = 0;
+19
for (let i = 0; i < n; i++) {
+20
const ptr = view().getUint32(iovs + i * 8, true);
+21
const len = view().getUint32(iovs + i * 8 + 4, true);
+22
const text = decoder.decode(u8().subarray(ptr, ptr + len));
+23
(fd === 2 ? process.stderr : process.stdout).write(text);
+24
written += len;
+25
}
+26
if (nwritten) view().setUint32(nwritten, written, true);
+27
return 0;
+28
},
+29
proc_exit(code) { throw new Error(`WASI proc_exit(${code})`); },
+30
args_sizes_get(a, b) { view().setUint32(a, 0, true); view().setUint32(b, 0, true); return 0; },
+31
environ_sizes_get(a, b) { view().setUint32(a, 0, true); view().setUint32(b, 0, true); return 0; },
+32
clock_time_get(_id, _p, t) { view().setBigUint64(t, process.hrtime.bigint(), true); return 0; },
+33
random_get(ptr, len) { const b = u8(); for (let i = 0; i < len; i++) b[ptr + i] = (Math.random() * 256) | 0; return 0; },
+34
fd_fdstat_get(fd, s) { u8().fill(0, s, s + 24); view().setUint8(s, 2); return 0; },
+35
fd_filestat_get(fd, s) { u8().fill(0, s, s + 64); view().setUint8(s + 16, 2); return 0; },
+36
fd_prestat_get() { return 8; },
+37
fd_prestat_dir_name() { return 8; },
+38
path_open() { return 44; },
+39
};
+40
const imports = { wasi_snapshot_preview1: {} };
+41
for (const e of WebAssembly.Module.imports(module)) {
+42
if (e.kind !== "function") continue;
+43
imports[e.module] ??= {};
+44
imports[e.module][e.name] = (e.module === "wasi_snapshot_preview1" && known[e.name]) || (() => 0);
+45
}
+46
instance = await WebAssembly.instantiate(module, imports);
+47
const ex = instance.exports;
+48
if (typeof ex.sigil_wasm_native_start !== "function") {
+49
console.error("SETUP-FAILED: not a native-codegen wasm build (no sigil_wasm_native_start)");
+50
process.exit(2);
+51
}
+52
if (ex.sigil_wasm_init() !== 0) { console.error("SETUP-FAILED: sigil_wasm_init"); process.exit(2); }
+53
const rc = ex.sigil_wasm_start();
+54
process.stderr.write(`sigil_wasm_start -> ${rc}\n`);
+55
process.exit(rc === 0 ? 0 : 1);
harness/sigil.lockadded
@@ -0,0 +1,42 @@
+1
;; Auto-generated by sigil deps install. Do not edit.
+2
(lock
+3
(package name: "sigil-stdlib"
+4
url: "codeberg:sigil/sigil"
+5
ref: ">=0.22, <1.0"
+6
sha: "2a9065f277a6210627ca64a9abbcfa5dc8f58c7b"
+7
package-selector: "sigil-stdlib"
+8
version: "0.22.7")
+9
(package name: "sigil-test"
+10
url: "codeberg:sigil/sigil"
+11
ref: ">=0.22.5"
+12
sha: "2a9065f277a6210627ca64a9abbcfa5dc8f58c7b"
+13
package-selector: "sigil-test"
+14
version: "0.22.7")
+15
(package name: "sigil-wasm-runtime"
+16
url: "codeberg:sigil/sigil"
+17
ref: ">=0.22.5"
+18
sha: "2a9065f277a6210627ca64a9abbcfa5dc8f58c7b"
+19
package-selector: "sigil-wasm-runtime"
+20
version: "0.22.7")
+21
(package name: "sigil-lib"
+22
url: "codeberg:sigil/sigil"
+23
ref: ">=0.21"
+24
sha: "2a9065f277a6210627ca64a9abbcfa5dc8f58c7b"
+25
package-selector: "sigil-lib"
+26
version: "0.22.7")
+27
(package name: "sigil-json"
+28
url: "codeberg:sigil/sigil-json"
+29
ref: "^0.16.0"
+30
sha: "55c9e74712b5f79b45d41c65cfe0aef2c8f7e155"
+31
version: "0.16.0")
+32
(package name: "sigil-crypto"
+33
url: "codeberg:sigil/sigil-crypto"
+34
ref: "^0.16.0"
+35
sha: "e0a4e8891214b012cdfb1794456eb84d8b9633ad"
+36
version: "0.16.7")
+37
(package name: "sigil-sqlite"
+38
url: "codeberg:sigil/sigil-sqlite"
+39
ref: "^0.16.0"
+40
sha: "569ef1063dda8f5989968644af31fc09c64b4bfe"
+41
version: "0.16.3")
+42
)
harness/src/geometry-harness/alloc.sgladded
@@ -0,0 +1,147 @@
+1
;;; (geometry-harness alloc) - allocation check for the ! forms
+2
;;;
+3
;;; Each check calls one operation CALLS times on preallocated values
+4
;;; and reads the GC's allocation counter before and after. The same
+5
;;; loop around an empty thunk is the baseline, subtracted from every
+6
;;; row, so the loop, the closure call and `gc-stats` itself cancel out.
+7
;;;
+8
;;; A positive control (the allocating `vec3-add`) must show at least
+9
;;; one allocation per call; if it does not, the counter is not
+10
;;; measuring anything and the check reports SETUP-FAILED rather than
+11
;;; a pass.
+12
+13
(define-library (geometry-harness alloc)
+14
(import (sigil core) (sigil io) (sigil gc) (sigil geometry))
+15
(export run-alloc-check)
+16
(begin
+17
(define calls 1000)
+18
+19
;; An op "allocates" if it shows more than this many allocations over
+20
;; CALLS calls (1%): room for a stray GC bookkeeping object, far
+21
;; below one per call.
+22
(define tolerance 10)
+23
+24
(define (allocations) (cdr (assq 'allocations (gc-stats))))
+25
+26
(define (repeat thunk)
+27
(let loop ((i 0))
+28
(when (< i calls)
+29
(thunk)
+30
(loop (+ i 1)))))
+31
+32
(define (measure thunk)
+33
(thunk)
+34
(let* ((before (allocations))
+35
(_ (repeat thunk))
+36
(after (allocations)))
+37
(- after before)))
+38
+39
;; Inputs and destinations, made once.
+40
(define a3 (vec3 1 2 3))
+41
(define b3 (vec3 -4 5 0.5))
+42
(define d3 (make-vec3))
+43
(define a2 (vec2 1 2))
+44
(define b2 (vec2 3 -1))
+45
(define d2 (make-vec2))
+46
(define a4 (vec4 1 2 3 4))
+47
(define b4 (vec4 4 3 2 1))
+48
(define d4 (make-vec4))
+49
(define qa (quat-from-axis-angle (vec3 1 2 3) 0.7))
+50
(define qb (quat-from-axis-angle (vec3 0 1 0) -1.2))
+51
(define qd (make-quat))
+52
(define ma (mat4-from-trs (vec3 1 2 3) qa (vec3 1 2 0.5)))
+53
(define mb (mat4-look-at (vec3 3 4 5) (vec3 0 0 0) (vec3 0 1 0)))
+54
(define md (make-mat4))
+55
(define na (mat3-from-mat4 ma))
+56
(define nd (make-mat3))
+57
(define std (make-bytevector 48 0))
+58
(define plane (vec4 0 1 0 0))
+59
(define origin (vec3 0.2 5 0.3))
+60
(define down (vec3 0 -1 0))
+61
(define lo (vec3 -1 -1 -1))
+62
(define hi (vec3 1 1 1))
+63
(define t0 (vec3 0 0 0))
+64
(define t1 (vec3 1 0 0))
+65
(define t2 (vec3 0 0 1))
+66
(define eye (vec3 2 1.7 6))
+67
(define target (vec3 0 1 0))
+68
(define up (vec3 0 1 0))
+69
(define axis (vec3 1 1 0))
+70
(define scale (vec3 2 2 2))
+71
+72
(define checks
+73
(list
+74
(cons "vec2-add!" (lambda () (vec2-add! d2 a2 b2)))
+75
(cons "vec2-normalize!" (lambda () (vec2-normalize! d2 a2)))
+76
(cons "vec3-add!" (lambda () (vec3-add! d3 a3 b3)))
+77
(cons "vec3-sub!" (lambda () (vec3-sub! d3 a3 b3)))
+78
(cons "vec3-scale!" (lambda () (vec3-scale! d3 a3 2.5)))
+79
(cons "vec3-add-scaled!" (lambda () (vec3-add-scaled! d3 a3 b3 0.5)))
+80
(cons "vec3-cross!" (lambda () (vec3-cross! d3 a3 b3)))
+81
(cons "vec3-normalize!" (lambda () (vec3-normalize! d3 b3)))
+82
(cons "vec3-lerp!" (lambda () (vec3-lerp! d3 a3 b3 0.3)))
+83
(cons "vec3-dot" (lambda () (vec3-dot a3 b3)))
+84
(cons "vec3-length" (lambda () (vec3-length b3)))
+85
(cons "vec3-distance" (lambda () (vec3-distance a3 b3)))
+86
(cons "vec3-min!" (lambda () (vec3-min! d3 a3 b3)))
+87
(cons "vec4-lerp!" (lambda () (vec4-lerp! d4 a4 b4 0.5)))
+88
(cons "vec4-normalize!" (lambda () (vec4-normalize! d4 a4)))
+89
(cons "mat4-mul!" (lambda () (mat4-mul! md ma mb)))
+90
(cons "mat4-mul! (aliased)" (lambda () (mat4-mul! md md mb)))
+91
(cons "mat4-transpose!" (lambda () (mat4-transpose! md ma)))
+92
(cons "mat4-inverse!" (lambda () (mat4-inverse! md ma)))
+93
(cons "mat4-determinant" (lambda () (mat4-determinant ma)))
+94
(cons "mat4-identity!" (lambda () (mat4-identity! md)))
+95
(cons "mat4-copy!" (lambda () (mat4-copy! md ma)))
+96
(cons "mat4-translation!" (lambda () (mat4-translation! md a3)))
+97
(cons "mat4-scaling!" (lambda () (mat4-scaling! md scale)))
+98
(cons "mat4-rotation-y!" (lambda () (mat4-rotation-y! md 0.4)))
+99
(cons "mat4-rotation!" (lambda () (mat4-rotation! md axis 0.4)))
+100
(cons "mat4-from-quat!" (lambda () (mat4-from-quat! md qa)))
+101
(cons "mat4-from-trs!" (lambda () (mat4-from-trs! md a3 qa scale)))
+102
(cons "mat4-transform-point!" (lambda () (mat4-transform-point! d3 ma a3)))
+103
(cons "mat4-transform-direction!" (lambda () (mat4-transform-direction! d3 ma a3)))
+104
(cons "mat4-transform-vec4!" (lambda () (mat4-transform-vec4! d4 ma a4)))
+105
(cons "mat4-perspective!" (lambda () (mat4-perspective! md 1.2 1.777 0.1 100.0)))
+106
(cons "mat4-orthographic!" (lambda () (mat4-orthographic! md 0.0 480.0 0.0 270.0 -1.0 1.0)))
+107
(cons "mat4-look-at!" (lambda () (mat4-look-at! md eye target up)))
+108
(cons "mat3-mul!" (lambda () (mat3-mul! nd na na)))
+109
(cons "mat3-inverse!" (lambda () (mat3-inverse! nd na)))
+110
(cons "mat3-normal-matrix!" (lambda () (mat3-normal-matrix! nd ma)))
+111
(cons "mat3-from-mat4!" (lambda () (mat3-from-mat4! nd ma)))
+112
(cons "mat3-from-quat!" (lambda () (mat3-from-quat! nd qa)))
+113
(cons "mat3-transform-vec3!" (lambda () (mat3-transform-vec3! d3 na a3)))
+114
(cons "mat3->std140!" (lambda () (mat3->std140! std na)))
+115
(cons "quat-mul!" (lambda () (quat-mul! qd qa qb)))
+116
(cons "quat-slerp!" (lambda () (quat-slerp! qd qa qb 0.3)))
+117
(cons "quat-nlerp!" (lambda () (quat-nlerp! qd qa qb 0.3)))
+118
(cons "quat-normalize!" (lambda () (quat-normalize! qd qa)))
+119
(cons "quat-conjugate!" (lambda () (quat-conjugate! qd qa)))
+120
(cons "quat-from-axis-angle!" (lambda () (quat-from-axis-angle! qd axis 0.9)))
+121
(cons "quat-from-mat4!" (lambda () (quat-from-mat4! qd mb)))
+122
(cons "quat-rotate-vec3!" (lambda () (quat-rotate-vec3! d3 qa a3)))
+123
(cons "ray-point!" (lambda () (ray-point! d3 origin down 2.0)))
+124
(cons "ray-plane" (lambda () (ray-plane origin down plane)))
+125
(cons "ray-aabb" (lambda () (ray-aabb origin down lo hi)))
+126
(cons "ray-triangle" (lambda () (ray-triangle origin down t0 t1 t2)))
+127
(cons "ray-triangle-hit!" (lambda () (ray-triangle-hit! d3 origin down t0 t1 t2)))
+128
(cons "plane-signed-distance" (lambda () (plane-signed-distance plane a3)))))
+129
+130
;;; Run every check. Prints one line per op and returns a list:
+131
;;; (checked allocating-count control-ok?).
+132
(define (run-alloc-check)
+133
(let* ((baseline (measure (lambda () #f)))
+134
(control (- (measure (lambda () (vec3-add a3 b3))) baseline))
+135
;; one bytevector per call, less the same noise allowance
+136
(control-ok? (>= control (- calls tolerance))))
+137
(println "alloc: baseline ~a allocations per ~a empty calls" baseline calls)
+138
(println "alloc: control vec3-add (allocating form) ~a over ~a calls ~a"
+139
control calls (if control-ok? "(counter works)" "(COUNTER NOT MEASURING)"))
+140
(let loop ((cs checks) (checked 0) (bad 0))
+141
(if (null? cs)
+142
(list checked bad control-ok?)
+143
(let* ((name (car (car cs)))
+144
(delta (- (measure (cdr (car cs))) baseline))
+145
(allocates? (> delta tolerance)))
+146
(println "alloc: ~a ~a ~a" (if allocates? "ALLOCATES" "zero") name delta)
+147
(loop (cdr cs) (+ checked 1) (if allocates? (+ bad 1) bad)))))))))
harness/src/geometry-harness/main.sgladded
@@ -0,0 +1,52 @@
+1
;;; (geometry-harness main) - run the suite and the allocation check
+2
;;;
+3
;;; Prints one verdict line last:
+4
;;; HARNESS-VERDICT: PASS tests=N failed=0 alloc-checked=M alloc-bad=K
+5
;;; alloc-control=ok geometry-code=native
+6
;;; PASS means every test passed and the allocation counter's positive
+7
;;; control fired. The allocation result (alloc-bad) and the kind of
+8
;;; code the geometry procedures ran as (native or bytecode) are
+9
;;; reported for scripts/check-targets to gate per target.
+10
+11
(define-library (geometry-harness main)
+12
;; (sigil core) is imported explicitly: on sigil 0.22.7 a native wasm
+13
;; app whose modules never import it dies at boot with
+14
;; "unbound variable '%set-spec!'" (core's init is only ordered first
+15
;; when core is in the reachable import set).
+16
(import (sigil core)
+17
(sigil io)
+18
(sigil test)
+19
(sigil geometry)
+20
(geometry-harness alloc)
+21
(geometry-harness suite))
+22
(export main)
+23
(begin
+24
;; A bytecode closure prints as #<procedure>; natively compiled code
+25
;; does not. This says which code the tests and the allocation check
+26
;; actually exercised.
+27
(define (code-kind proc)
+28
(if (string=? (format "~s" proc) "#<procedure>") "bytecode" "native"))
+29
+30
(define (main . args)
+31
(println "harness: ~a suite modules" (length suite-modules))
+32
(println "harness: vec3-lerp! prints as ~a, so geometry code is ~a"
+33
(format "~s" vec3-lerp!) (code-kind vec3-lerp!))
+34
(let* ((alloc (run-alloc-check))
+35
(alloc-checked (car alloc))
+36
(alloc-bad (cadr alloc))
+37
(control-ok? (caddr alloc))
+38
(summary (run-tests-filtered (lambda (td) #t)))
+39
(total (test-summary-total summary))
+40
(failed (test-summary-failed summary)))
+41
(for-each (lambda (r)
+42
(unless (test-result-passed? r)
+43
(println "FAILED: ~a > ~a: ~a"
+44
(test-result-group r) (test-result-name r)
+45
(test-result-message r))))
+46
(test-summary-results summary))
+47
(let ((pass? (and control-ok? (= failed 0) (> total 0))))
+48
(println "HARNESS-VERDICT: ~a tests=~a failed=~a alloc-checked=~a alloc-bad=~a alloc-control=~a geometry-code=~a"
+49
(if pass? "PASS" "FAIL") total failed alloc-checked alloc-bad
+50
(if control-ok? "ok" "SETUP-FAILED")
+51
(code-kind vec3-lerp!))
+52
(if pass? 0 1))))))
manifest.scmadded
@@ -0,0 +1,12 @@
+1
;; sigil-geometry Development Environment
+2
;; Use with: guix shell -m manifest.scm
+3
;;
+4
;; sigil-geometry is pure Sigil with no C. binaryen (wasm-opt) and node
+5
;; are only needed for the wasm allocation check in bench/wasm-alloc.
+6
+7
(specifications->manifest
+8
'("gcc-toolchain"
+9
"make"
+10
"pkg-config"
+11
"binaryen"
+12
"node"))
package.sgladded
@@ -0,0 +1,16 @@
+1
;;; sigil-geometry - 3D maths for games and graphics
+2
;;;
+3
;;; Vectors, matrices, quaternions, camera matrices and ray casts, as
+4
;;; float32 bytevectors a GPU uniform can take directly. Pure Sigil: the
+5
;;; same code runs on bytecode, native and wasm.
+6
+7
(package
+8
name: "sigil-geometry"
+9
version: "0.1.0"
+10
sigil: "0.22"
+11
description: "3D maths for games and graphics: vectors, matrices, quaternions, cameras, rays"
+12
url: "https://codeberg.org/sigil/sigil-geometry"
+13
license: "BSD-3-Clause"
+14
authors: (list "David Wilson <david@daviwil.com>")
+15
+16
dependencies: (list))
scripts/check-targetsadded
@@ -0,0 +1,185 @@
+1
#!/usr/bin/env bash
+2
# Run sigil-geometry's test suite and the allocation check of every !
+3
# form on each target: bytecode (dev), native ELF (release) and native
+4
# wasm (web, run under Node).
+5
#
+6
# scripts/check-targets all three targets
+7
# TARGETS="release web" scripts/check-targets
+8
# SIGIL=/path/to/sigil scripts/check-targets
+9
#
+10
# How: every test/test-*.sgl except test-facade.sgl (which reads source
+11
# files, so it only means something on the host) is wrapped as a library
+12
# under harness/src/geometry-harness/suite/, and the harness app in
+13
# harness/ compiles them with the allocation check. Each target prints a
+14
# HARNESS-VERDICT line, which this script parses.
+15
#
+16
# A target passes only when its verdict is PASS, the test count equals
+17
# the number of (test ...) forms in the generated suite (every test ran),
+18
# and at least MIN_ALLOC_CHECKS ! forms were measured. A target with no
+19
# verdict line is SETUP-FAILED, which is not a pass and not a test
+20
# failure: nothing was measured.
+21
#
+22
# The web target needs wasm-opt (binaryen) and node on PATH:
+23
# guix shell -m manifest.scm -- scripts/check-targets
+24
#
+25
# Exit status: 0 every target passed, 1 a target failed, 2 setup failed.
+26
+27
set -euo pipefail
+28
+29
ROOT=$(cd "$(dirname "$0")/.." && pwd)
+30
HARNESS="$ROOT/harness"
+31
SUITE="$HARNESS/src/geometry-harness/suite"
+32
SIGIL=${SIGIL:-sigil}
+33
TARGETS=${TARGETS:-"dev release web"}
+34
MIN_ALLOC_CHECKS=50
+35
LOGS=$(mktemp -d "${TMPDIR:-/tmp}/geometry-check-targets.XXXXXX")
+36
+37
echo "check-targets: sigil $("$SIGIL" --version 2>&1 | head -1)"
+38
echo "check-targets: logs in $LOGS"
+39
+40
# --- generate the suite ------------------------------------------------
+41
+42
rm -rf "$SUITE" "$SUITE.sgl"
+43
mkdir -p "$SUITE"
+44
+45
names=()
+46
for test_file in "$ROOT"/test/test-*.sgl; do
+47
base=$(basename "$test_file" .sgl)
+48
[ "$base" = "test-facade" ] && continue
+49
names+=("$base")
+50
out="$SUITE/$base.sgl"
+51
# Split the file into its leading (import ...) form and everything
+52
# else; the import specs go into the library's import clause.
+53
awk -v name="$base" '
+54
BEGIN { depth = 0; in_import = 0; done_import = 0 }
+55
!done_import && !in_import && /^\(import/ { in_import = 1 }
+56
in_import {
+57
line = $0
+58
opens = gsub(/\(/, "(", line); closes = gsub(/\)/, ")", line)
+59
depth += opens - closes
+60
imports = imports $0 "\n"
+61
if (depth == 0) { in_import = 0; done_import = 1 }
+62
next
+63
}
+64
{ body = body " " $0 "\n" }
+65
END {
+66
if (!done_import) { print "no (import ...) form found" > "/dev/stderr"; exit 1 }
+67
sub(/^\(import[ \t\n]*/, "", imports)
+68
sub(/\)[ \t\n]*$/, "", imports)
+69
printf ";; GENERATED from test/%s.sgl by scripts/check-targets. Do not edit.\n", name
+70
printf "(define-library (geometry-harness suite %s)\n", name
+71
printf " (import (sigil core)\n %s)\n", imports
+72
printf " (export %s-loaded)\n", name
+73
printf " (begin\n (define %s-loaded (quote %s))\n", name, name
+74
printf "%s))\n", body
+75
}' "$test_file" > "$out"
+76
# Guard the generated artifact: non-empty, the right library, and the
+77
# same number of (test ...) forms as its source.
+78
src_tests=$(grep -c '(test "' "$test_file" || true)
+79
gen_tests=$(grep -c '(test "' "$out" || true)
+80
if ! grep -q "^(define-library (geometry-harness suite $base)" "$out" \
+81
|| [ "$src_tests" -ne "$gen_tests" ] || [ "$src_tests" -eq 0 ]; then
+82
echo "SETUP-FAILED: generating $out (tests: source $src_tests, generated $gen_tests)"
+83
exit 2
+84
fi
+85
done
+86
+87
expected_tests=$(cat "$SUITE"/*.sgl | grep -c '(test "' || true)
+88
+89
{
+90
echo ";; GENERATED by scripts/check-targets. Do not edit."
+91
echo "(define-library (geometry-harness suite)"
+92
echo " (import (sigil core)"
+93
for n in "${names[@]}"; do echo " (geometry-harness suite $n)"; done
+94
echo " )"
+95
echo " (export suite-modules)"
+96
echo " (begin"
+97
echo " (define suite-modules"
+98
echo " (list $(for n in "${names[@]}"; do printf '%s-loaded ' "$n"; done)))))"
+99
} > "$SUITE.sgl"
+100
+101
echo "check-targets: generated ${#names[@]} suite modules, $expected_tests tests"
+102
+103
# --- build and run each target -----------------------------------------
+104
+105
cd "$HARNESS"
+106
"$SIGIL" deps install > "$LOGS/deps.log" 2>&1 || { echo "SETUP-FAILED: deps install (see $LOGS/deps.log)"; exit 2; }
+107
+108
status=0
+109
summary=()
+110
+111
for target in $TARGETS; do
+112
log="$LOGS/$target.log"
+113
case "$target" in
+114
dev) config=dev; run=(./build/dev/bin/geometry-harness) ;;
+115
release) config=release; run=(./build/release/bin/geometry-harness) ;;
+116
web) config=web; run=(node "$HARNESS/run-wasm.mjs" ./build/web/geometry-harness.wasm)
+117
for tool in wasm-opt node; do
+118
if ! command -v "$tool" > /dev/null; then
+119
echo "SETUP-FAILED: web needs $tool on PATH (guix shell -m manifest.scm)"
+120
exit 2
+121
fi
+122
done ;;
+123
*) echo "SETUP-FAILED: unknown target $target"; exit 2 ;;
+124
esac
+125
+126
if ! "$SIGIL" build --config "$config" > "$LOGS/$target.build.log" 2>&1; then
+127
echo "SETUP-FAILED: $target build (see $LOGS/$target.build.log)"
+128
status=2; summary+=("$target SETUP-FAILED build"); continue
+129
fi
+130
+131
set +e
+132
"${run[@]}" > "$log" 2>&1
+133
run_rc=$?
+134
set -e
+135
+136
verdict=$(grep '^HARNESS-VERDICT: ' "$log" | tail -1 || true)
+137
if [ -z "$verdict" ]; then
+138
echo "SETUP-FAILED: $target printed no verdict (exit $run_rc); last lines:"
+139
tail -5 "$log" | sed 's/^/ /'
+140
status=2; summary+=("$target SETUP-FAILED no-verdict"); continue
+141
fi
+142
+143
field() { echo "$verdict" | sed -n "s/.* $1=\([0-9]*\).*/\1/p"; }
+144
tests=$(field tests); failed=$(field failed); tests=${tests:--1}; failed=${failed:--1}
+145
checked=$(field alloc-checked); bad=$(field alloc-bad); checked=${checked:--1}; bad=${bad:--1}
+146
code=$(echo "$verdict" | sed -n 's/.* geometry-code=\([a-z]*\).*/\1/p')
+147
+148
grep -E '^(FAILED:|alloc: ALLOCATES)' "$log" | sed "s/^/ $target: /" || true
+149
+150
# Presence: each target must have run the kind of code it claims to
+151
# measure. dev is all bytecode; web must run sigil-geometry natively.
+152
# release reports what it got: on sigil 0.22.7 an ELF bundle loads
+153
# dependency packages from their .sgb, so the geometry code there is
+154
# bytecode called from native code, and the allocation rows measure
+155
# that call bridge rather than the library. Allocation is gated only
+156
# where the geometry code is uniformly bytecode (dev) or native.
+157
case "$target" in
+158
dev) want=bytecode; gate_alloc=yes ;;
+159
web) want=native; gate_alloc=yes ;;
+160
release) want="$code"
+161
if [ "$code" = native ]; then gate_alloc=yes; else gate_alloc=no; fi ;;
+162
esac
+163
if [ -z "$code" ] || [ "$code" != "$want" ]; then
+164
echo "SETUP-FAILED: $target ran geometry code as '$code', expected $want"
+165
status=2; summary+=("$target SETUP-FAILED geometry-code=$code"); continue
+166
fi
+167
+168
alloc_ok=yes
+169
if [ "$gate_alloc" = yes ] && [ "$bad" -ne 0 ]; then alloc_ok=no; fi
+170
note=""
+171
[ "$gate_alloc" = no ] && note=" (alloc not gated: geometry-code=$code, alloc-bad=$bad)"
+172
+173
if [[ "$verdict" == "HARNESS-VERDICT: PASS "* ]] && [ "$run_rc" -eq 0 ] \
+174
&& [ "$tests" -eq "$expected_tests" ] && [ "$failed" -eq 0 ] \
+175
&& [ "$checked" -ge "$MIN_ALLOC_CHECKS" ] && [ "$alloc_ok" = yes ]; then
+176
summary+=("$target PASS tests=$tests/$expected_tests geometry-code=$code alloc-checked=$checked alloc-bad=$bad$note")
+177
else
+178
[ "$status" -eq 0 ] && status=1
+179
summary+=("$target FAIL tests=$tests/$expected_tests failed=$failed geometry-code=$code alloc-checked=$checked alloc-bad=$bad exit=$run_rc$note")
+180
fi
+181
done
+182
+183
echo
+184
for line in "${summary[@]}"; do echo "check-targets: $line"; done
+185
exit "$status"
sigil.lockadded
@@ -0,0 +1,30 @@
+1
;; Auto-generated by sigil deps install. Do not edit.
+2
(lock
+3
(package name: "sigil-stdlib"
+4
url: "codeberg:sigil/sigil"
+5
ref: ">=0.22, <1.0"
+6
sha: "2a9065f277a6210627ca64a9abbcfa5dc8f58c7b"
+7
package-selector: "sigil-stdlib"
+8
version: "0.22.7")
+9
(package name: "sigil-json"
+10
url: "codeberg:sigil/sigil-json"
+11
ref: "^0.16.0"
+12
sha: "55c9e74712b5f79b45d41c65cfe0aef2c8f7e155"
+13
version: "0.16.0")
+14
(package name: "sigil-crypto"
+15
url: "codeberg:sigil/sigil-crypto"
+16
ref: "^0.16.0"
+17
sha: "e0a4e8891214b012cdfb1794456eb84d8b9633ad"
+18
version: "0.16.7")
+19
(package name: "sigil-sqlite"
+20
url: "codeberg:sigil/sigil-sqlite"
+21
ref: "^0.16.0"
+22
sha: "569ef1063dda8f5989968644af31fc09c64b4bfe"
+23
version: "0.16.3")
+24
(package name: "sigil-lib"
+25
url: "codeberg:sigil/sigil"
+26
ref: ">=0.21"
+27
sha: "2a9065f277a6210627ca64a9abbcfa5dc8f58c7b"
+28
package-selector: "sigil-lib"
+29
version: "0.22.7")
+30
)
src/sigil/geometry.sgladded
@@ -0,0 +1,82 @@
+1
;;; (sigil geometry) - 3D maths for games and graphics
+2
;;;
+3
;;; Imports every module of the package in one line:
+4
;;;
+5
;;; ```scheme
+6
;;; (import (sigil geometry))
+7
;;; ```
+8
;;;
+9
;;; - `(sigil geometry vec)`: vec2, vec3, vec4
+10
;;; - `(sigil geometry mat3)`, `(sigil geometry mat4)`: matrices
+11
;;; - `(sigil geometry quat)`: rotation quaternions
+12
;;; - `(sigil geometry camera)`: perspective, orthographic, look-at
+13
;;; - `(sigil geometry ray)`: ray casts against planes, boxes, triangles
+14
;;;
+15
;;; Every value is a float32 bytevector in native byte order; matrices
+16
;;; are column-major. See the README for the layout contract.
+17
;;;
+18
;;; The export list below must name every export of the six modules;
+19
;;; test/test-facade.sgl checks it.
+20
+21
(define-library (sigil geometry)
+22
(import (sigil geometry vec)
+23
(sigil geometry mat3)
+24
(sigil geometry mat4)
+25
(sigil geometry quat)
+26
(sigil geometry camera)
+27
(sigil geometry ray))
+28
(export
+29
;; (sigil geometry vec)
+30
vec2 make-vec2 vec2? vec2-x vec2-y vec2-set! vec2-copy vec2-copy!
+31
vec2-add vec2-add! vec2-sub vec2-sub! vec2-mul vec2-mul! vec2-scale
+32
vec2-scale! vec2-negate vec2-negate! vec2-dot vec2-length
+33
vec2-length-squared vec2-distance vec2-normalize vec2-normalize!
+34
vec2-lerp vec2-lerp! vec2-approx=? vec2->list vec3 make-vec3 vec3?
+35
vec3-x vec3-y vec3-z vec3-set! vec3-copy vec3-copy! vec3-add vec3-add!
+36
vec3-sub vec3-sub! vec3-mul vec3-mul! vec3-scale vec3-scale!
+37
vec3-negate vec3-negate! vec3-add-scaled vec3-add-scaled! vec3-dot
+38
vec3-cross vec3-cross! vec3-length vec3-length-squared vec3-distance
+39
vec3-distance-squared vec3-normalize vec3-normalize! vec3-lerp
+40
vec3-lerp! vec3-min vec3-min! vec3-max vec3-max! vec3-approx=?
+41
vec3->list vec4 make-vec4 vec4? vec4-x vec4-y vec4-z vec4-w vec4-set!
+42
vec4-copy vec4-copy! vec4-add vec4-add! vec4-sub vec4-sub! vec4-mul
+43
vec4-mul! vec4-scale vec4-scale! vec4-negate vec4-negate! vec4-dot
+44
vec4-length vec4-length-squared vec4-normalize vec4-normalize!
+45
vec4-lerp vec4-lerp! vec4-approx=? vec4->list float-approx=?
+46
degrees->radians radians->degrees
+47
;; (sigil geometry mat3)
+48
mat3 make-mat3 mat3? mat3-ref mat3-set! list->mat3 mat3->list
+49
mat3-identity mat3-identity! mat3-copy mat3-copy! mat3-mul mat3-mul!
+50
mat3-transpose mat3-transpose! mat3-determinant mat3-inverse
+51
mat3-inverse! mat3-from-mat4 mat3-from-mat4! mat3-normal-matrix
+52
mat3-normal-matrix! mat3-from-quat mat3-from-quat! mat3-transform-vec3
+53
mat3-transform-vec3! mat3->std140 mat3->std140! mat3-approx=?
+54
;; (sigil geometry mat4)
+55
mat4 make-mat4 mat4? mat4-ref mat4-set! list->mat4 mat4->list
+56
mat4-identity mat4-identity! mat4-copy mat4-copy! mat4-mul mat4-mul!
+57
mat4-transpose mat4-transpose! mat4-determinant mat4-inverse
+58
mat4-inverse! mat4-translation mat4-translation! mat4-scaling
+59
mat4-scaling! mat4-rotation-x mat4-rotation-x! mat4-rotation-y
+60
mat4-rotation-y! mat4-rotation-z mat4-rotation-z! mat4-rotation
+61
mat4-rotation! mat4-from-quat mat4-from-quat! mat4-from-trs
+62
mat4-from-trs! mat4-get-translation mat4-get-translation!
+63
mat4-transform-point mat4-transform-point! mat4-transform-direction
+64
mat4-transform-direction! mat4-transform-vec4 mat4-transform-vec4!
+65
mat4-approx=?
+66
;; (sigil geometry quat)
+67
quat make-quat quat? quat-x quat-y quat-z quat-w quat-set! quat-copy
+68
quat-copy! quat->list quat-identity quat-identity! quat-from-axis-angle
+69
quat-from-axis-angle! quat-from-mat3 quat-from-mat3! quat-from-mat4
+70
quat-from-mat4! quat-mul quat-mul! quat-conjugate quat-conjugate!
+71
quat-inverse quat-inverse! quat-dot quat-length quat-normalize
+72
quat-normalize! quat-slerp quat-slerp! quat-nlerp quat-nlerp!
+73
quat-rotate-vec3 quat-rotate-vec3! quat-angle quat-approx=?
+74
quat-same-rotation?
+75
;; (sigil geometry camera)
+76
mat4-perspective mat4-perspective! mat4-orthographic mat4-orthographic!
+77
mat4-look-at mat4-look-at!
+78
;; (sigil geometry ray)
+79
ray-point ray-point! plane-from-point-normal plane-from-point-normal!
+80
plane-from-points plane-from-points! plane-signed-distance ray-plane
+81
ray-aabb ray-triangle ray-triangle-hit! aabb-contains-point?
+82
aabb-overlap?))
src/sigil/geometry/camera.sgladded
@@ -0,0 +1,142 @@
+1
;;; (sigil geometry camera) - projection and view matrices
+2
;;;
+3
;;; The matrices follow OpenGL's conventions, which is what WebGL2 and
+4
;;; sigil-graphics' GL backends use:
+5
;;;
+6
;;; - right-handed view space, the camera looking down -Z with +Y up;
+7
;;; - clip space z from -1 (near) to +1 (far) after the divide by w.
+8
;;;
+9
;;; They match `gluPerspective`, `glOrtho` and `gluLookAt`, so a
+10
;;; reference from any GL tutorial applies. All results are mat4s in the
+11
;;; package's layout (64 bytes, column-major, float32).
+12
;;;
+13
;;; ```scheme
+14
;;; (define proj (mat4-perspective (degrees->radians 70.0) (/ 480.0 270.0) 0.1 100.0))
+15
;;; (define view (mat4-look-at (vec3 0 1.7 5) (vec3 0 1.7 0) (vec3 0 1 0)))
+16
;;; (define view-proj (mat4-mul proj view))
+17
;;; ```
+18
+19
(define-library (sigil geometry camera)
+20
(import (sigil core) (sigil math))
+21
(export
+22
mat4-perspective mat4-perspective!
+23
mat4-orthographic mat4-orthographic!
+24
mat4-look-at mat4-look-at!)
+25
+26
(begin
+27
;; Float index -> float32 at byte offset 4*i, native byte order.
+28
;; Procedures, not syntax-rules macros: native codegen looks up a
+29
;; macro-introduced global through %hygiene-ref at run time, which
+30
;; allocates on every call.
+31
(define (f@ v i) (bytevector-ieee-single-ref v (* 4 i)))
+32
(define (f! v i x) (bytevector-ieee-single-set! v (* 4 i) x))
+33
;; Write all 16 floats in column-major order; returns `d`.
+34
(define (set16! d a0 a1 a2 a3 a4 a5 a6 a7 a8 a9 a10 a11 a12 a13 a14 a15)
+35
(f! d 0 a0) (f! d 1 a1) (f! d 2 a2) (f! d 3 a3)
+36
(f! d 4 a4) (f! d 5 a5) (f! d 6 a6) (f! d 7 a7)
+37
(f! d 8 a8) (f! d 9 a9) (f! d 10 a10) (f! d 11 a11)
+38
(f! d 12 a12) (f! d 13 a13) (f! d 14 a14) (f! d 15 a15)
+39
d)
+40
+41
(define pi 3.141592653589793)
+42
+43
(define (new) (make-bytevector 64 0))
+44
+45
;;; A perspective projection (`gluPerspective`): `fovy` is the full
+46
;;; vertical field of view in radians, `aspect` is width / height,
+47
;;; and `near` and `far` are positive distances in front of the
+48
;;; camera. Raises an error for arguments that give no projection
+49
;;; (fovy outside (0, pi), aspect <= 0, near <= 0, far <= near).
+50
(define (mat4-perspective! dst fovy aspect near far)
+51
(unless (and (> fovy 0.0) (< fovy pi))
+52
(error "mat4-perspective: fovy must be between 0 and pi radians" fovy))
+53
(unless (> aspect 0.0)
+54
(error "mat4-perspective: aspect must be positive" aspect))
+55
(unless (and (> near 0.0) (> far near))
+56
(error "mat4-perspective: need 0 < near < far" near far))
+57
(let* ((f (/ 1.0 (tan (* 0.5 fovy))))
+58
(nf (/ 1.0 (- near far))))
+59
(set16! dst
+60
(/ f aspect) 0.0 0.0 0.0
+61
0.0 f 0.0 0.0
+62
0.0 0.0 (* (+ far near) nf) -1.0
+63
0.0 0.0 (* 2.0 far near nf) 0.0)))
+64
(define (mat4-perspective fovy aspect near far)
+65
(mat4-perspective! (new) fovy aspect near far))
+66
+67
;;; An orthographic projection (`glOrtho`) of the box from
+68
;;; (left, bottom, -near) to (right, top, -far) in view space.
+69
;;; Raises an error when any pair of opposite planes coincide.
+70
(define (mat4-orthographic! dst left right bottom top near far)
+71
(when (or (= left right) (= bottom top) (= near far))
+72
(error "mat4-orthographic: opposite planes must differ"
+73
(list left right bottom top near far)))
+74
(let ((lr (/ 1.0 (- left right)))
+75
(bt (/ 1.0 (- bottom top)))
+76
(nf (/ 1.0 (- near far))))
+77
(set16! dst
+78
(* -2.0 lr) 0.0 0.0 0.0
+79
0.0 (* -2.0 bt) 0.0 0.0
+80
0.0 0.0 (* 2.0 nf) 0.0
+81
(* (+ left right) lr) (* (+ top bottom) bt) (* (+ far near) nf) 1.0)))
+82
(define (mat4-orthographic left right bottom top near far)
+83
(mat4-orthographic! (new) left right bottom top near far))
+84
+85
;;; A view matrix (`gluLookAt`) for a camera at the vec3 `eye` looking
+86
;;; toward the vec3 `target`, with the vec3 `up` giving the rough
+87
;;; up direction. `target` lands on the view-space -Z axis.
+88
;;;
+89
;;; When `eye` equals `target` the result is the identity. When `up`
+90
;;; is parallel to the view direction (looking straight up or down),
+91
;;; the world axis least aligned with the view direction stands in
+92
;;; for `up`, so the result is always a valid rotation.
+93
(define (mat4-look-at! dst eye target up)
+94
(let* ((ex (f@ eye 0)) (ey (f@ eye 1)) (ez (f@ eye 2))
+95
(fx (- (f@ target 0) ex))
+96
(fy (- (f@ target 1) ey))
+97
(fz (- (f@ target 2) ez))
+98
(flen (sqrt (+ (* fx fx) (* fy fy) (* fz fz)))))
+99
(if (= flen 0.0)
+100
(set16! dst 1.0 0.0 0.0 0.0 0.0 1.0 0.0 0.0 0.0 0.0 1.0 0.0 0.0 0.0 0.0 1.0)
+101
(let* ((fx (/ fx flen)) (fy (/ fy flen)) (fz (/ fz flen))
+102
(ux (f@ up 0)) (uy (f@ up 1)) (uz (f@ up 2))
+103
;; s = f x up
+104
(sx (- (* fy uz) (* fz uy)))
+105
(sy (- (* fz ux) (* fx uz)))
+106
(sz (- (* fx uy) (* fy ux)))
+107
(slen (sqrt (+ (* sx sx) (* sy sy) (* sz sz)))))
+108
(if (< slen 1e-6)
+109
;; up is parallel to f: use the world axis least
+110
;; aligned with f instead.
+111
(let* ((ax (abs fx)) (ay (abs fy)) (az (abs fz))
+112
(alt (cond ((and (<= ax ay) (<= ax az)) 0)
+113
((<= ay az) 1)
+114
(else 2)))
+115
(ux (if (= alt 0) 1.0 0.0))
+116
(uy (if (= alt 1) 1.0 0.0))
+117
(uz (if (= alt 2) 1.0 0.0))
+118
(sx (- (* fy uz) (* fz uy)))
+119
(sy (- (* fz ux) (* fx uz)))
+120
(sz (- (* fx uy) (* fy ux)))
+121
(slen (sqrt (+ (* sx sx) (* sy sy) (* sz sz)))))
+122
(finish-look-at! dst ex ey ez fx fy fz
+123
(/ sx slen) (/ sy slen) (/ sz slen)))
+124
(finish-look-at! dst ex ey ez fx fy fz
+125
(/ sx slen) (/ sy slen) (/ sz slen)))))))
+126
+127
;; Given unit forward f and unit side s, u = s x f, and the matrix
+128
;; rows are s, u, -f, with the eye moved to the origin.
+129
(define (finish-look-at! dst ex ey ez fx fy fz sx sy sz)
+130
(let ((ux (- (* sy fz) (* sz fy)))
+131
(uy (- (* sz fx) (* sx fz)))
+132
(uz (- (* sx fy) (* sy fx))))
+133
(set16! dst
+134
sx ux (- fx) 0.0
+135
sy uy (- fy) 0.0
+136
sz uz (- fz) 0.0
+137
(- (+ (* sx ex) (* sy ey) (* sz ez)))
+138
(- (+ (* ux ex) (* uy ey) (* uz ez)))
+139
(+ (* fx ex) (* fy ey) (* fz ez))
+140
1.0)))
+141
+142
(define (mat4-look-at eye target up) (mat4-look-at! (new) eye target up))))
src/sigil/geometry/mat3.sgladded
@@ -0,0 +1,205 @@
+1
;;; (sigil geometry mat3) - 3x3 float32 matrices, column-major
+2
;;;
+3
;;; A mat3 is a 36-byte bytevector of 9 float32 values in native byte
+4
;;; order, column by column: the element at column `c`, row `r` is
+5
;;; float `c*3 + r`.
+6
;;;
+7
;;; The tight 36-byte layout is NOT what a std140 uniform block expects
+8
;;; for a `mat3`: there each column is padded to 4 floats. Use
+9
;;; `mat3->std140!` to write the padded 48-byte form.
+10
;;;
+11
;;; Like mat4, every matrix-producing operation has an allocating form
+12
;;; and a `!` form whose destination may alias any input.
+13
+14
(define-library (sigil geometry mat3)
+15
(import (sigil core) (sigil math))
+16
(export
+17
mat3 make-mat3 mat3? mat3-ref mat3-set! list->mat3 mat3->list
+18
mat3-identity mat3-identity! mat3-copy mat3-copy!
+19
mat3-mul mat3-mul! mat3-transpose mat3-transpose!
+20
mat3-determinant mat3-inverse mat3-inverse!
+21
mat3-from-mat4 mat3-from-mat4! mat3-normal-matrix mat3-normal-matrix!
+22
mat3-from-quat mat3-from-quat!
+23
mat3-transform-vec3 mat3-transform-vec3!
+24
mat3->std140 mat3->std140!
+25
mat3-approx=?)
+26
+27
(begin
+28
;; Float index -> float32 at byte offset 4*i, native byte order.
+29
;; Procedures, not syntax-rules macros: native codegen looks up a
+30
;; macro-introduced global through %hygiene-ref at run time, which
+31
;; allocates on every call.
+32
(define (f@ v i) (bytevector-ieee-single-ref v (* 4 i)))
+33
(define (f! v i x) (bytevector-ieee-single-set! v (* 4 i) x))
+34
;; Write all 9 floats in column-major order; returns `d`. Every
+35
;; argument is evaluated before the first write, which is what lets a
+36
;; `!` form's destination alias its inputs.
+37
(define (set9! d a0 a1 a2 a3 a4 a5 a6 a7 a8)
+38
(f! d 0 a0) (f! d 1 a1) (f! d 2 a2)
+39
(f! d 3 a3) (f! d 4 a4) (f! d 5 a5)
+40
(f! d 6 a6) (f! d 7 a7) (f! d 8 a8)
+41
d)
+42
+43
(define (new) (make-bytevector 36 0))
+44
+45
;;; A new mat3 from 9 values in column-major order.
+46
(define (mat3 a0 a1 a2 a3 a4 a5 a6 a7 a8)
+47
(set9! (new) a0 a1 a2 a3 a4 a5 a6 a7 a8))
+48
+49
;;; A new identity mat3.
+50
(define (make-mat3) (mat3-identity! (new)))
+51
+52
;;; True for a bytevector of mat3 size (36 bytes).
+53
(define (mat3? m) (and (bytevector? m) (= (bytevector-length m) 36)))
+54
+55
;;; The element at column `col`, row `row`.
+56
(define (mat3-ref m col row) (f@ m (+ (* col 3) row)))
+57
+58
;;; Set the element at column `col`, row `row`; returns `m`.
+59
(define (mat3-set! m col row x) (f! m (+ (* col 3) row) x) m)
+60
+61
;;; A new mat3 from a list of 9 numbers in column-major order.
+62
(define (list->mat3 lst)
+63
(unless (= (length lst) 9)
+64
(error "list->mat3: expected 9 numbers" (length lst)))
+65
(let ((m (new)))
+66
(let loop ((i 0) (xs lst))
+67
(if (null? xs)
+68
m
+69
(begin (f! m i (car xs)) (loop (+ i 1) (cdr xs)))))))
+70
+71
;;; The 9 floats in column-major order.
+72
(define (mat3->list m)
+73
(let loop ((i 8) (acc '()))
+74
(if (< i 0) acc (loop (- i 1) (cons (f@ m i) acc)))))
+75
+76
(define (mat3-identity! dst) (set9! dst 1.0 0.0 0.0 0.0 1.0 0.0 0.0 0.0 1.0))
+77
(define (mat3-identity) (mat3-identity! (new)))
+78
+79
(define (mat3-copy! dst m)
+80
(unless (eq? dst m) (bytevector-copy! dst 0 m 0 36))
+81
dst)
+82
(define (mat3-copy m) (mat3-copy! (new) m))
+83
+84
;;; `a * b`: the transform that applies `b`, then `a`.
+85
(define (mat3-mul! dst a b)
+86
(let ((a00 (f@ a 0)) (a01 (f@ a 1)) (a02 (f@ a 2))
+87
(a10 (f@ a 3)) (a11 (f@ a 4)) (a12 (f@ a 5))
+88
(a20 (f@ a 6)) (a21 (f@ a 7)) (a22 (f@ a 8))
+89
(b00 (f@ b 0)) (b01 (f@ b 1)) (b02 (f@ b 2))
+90
(b10 (f@ b 3)) (b11 (f@ b 4)) (b12 (f@ b 5))
+91
(b20 (f@ b 6)) (b21 (f@ b 7)) (b22 (f@ b 8)))
+92
(set9! dst
+93
(+ (* a00 b00) (* a10 b01) (* a20 b02))
+94
(+ (* a01 b00) (* a11 b01) (* a21 b02))
+95
(+ (* a02 b00) (* a12 b01) (* a22 b02))
+96
(+ (* a00 b10) (* a10 b11) (* a20 b12))
+97
(+ (* a01 b10) (* a11 b11) (* a21 b12))
+98
(+ (* a02 b10) (* a12 b11) (* a22 b12))
+99
(+ (* a00 b20) (* a10 b21) (* a20 b22))
+100
(+ (* a01 b20) (* a11 b21) (* a21 b22))
+101
(+ (* a02 b20) (* a12 b21) (* a22 b22)))))
+102
(define (mat3-mul a b) (mat3-mul! (new) a b))
+103
+104
(define (mat3-transpose! dst m)
+105
(let ((m0 (f@ m 0)) (m1 (f@ m 1)) (m2 (f@ m 2))
+106
(m3 (f@ m 3)) (m4 (f@ m 4)) (m5 (f@ m 5))
+107
(m6 (f@ m 6)) (m7 (f@ m 7)) (m8 (f@ m 8)))
+108
(set9! dst m0 m3 m6 m1 m4 m7 m2 m5 m8)))
+109
(define (mat3-transpose m) (mat3-transpose! (new) m))
+110
+111
(define (mat3-determinant m)
+112
(let ((a00 (f@ m 0)) (a01 (f@ m 1)) (a02 (f@ m 2))
+113
(a10 (f@ m 3)) (a11 (f@ m 4)) (a12 (f@ m 5))
+114
(a20 (f@ m 6)) (a21 (f@ m 7)) (a22 (f@ m 8)))
+115
(+ (* a00 (- (* a22 a11) (* a12 a21)))
+116
(* a01 (- (* a12 a20) (* a22 a10)))
+117
(* a02 (- (* a21 a10) (* a11 a20))))))
+118
+119
;; Inverse of the 3x3 given column-major elements; #f when singular.
+120
;; With `transpose?` it writes the inverse-transpose instead.
+121
(define (invert3! dst a00 a01 a02 a10 a11 a12 a20 a21 a22 transpose?)
+122
(let* ((b01 (- (* a22 a11) (* a12 a21)))
+123
(b11 (+ (- (* a22 a10)) (* a12 a20)))
+124
(b21 (- (* a21 a10) (* a11 a20)))
+125
(det (+ (* a00 b01) (* a01 b11) (* a02 b21))))
+126
(if (= det 0.0)
+127
#f
+128
(let* ((d (/ 1.0 det))
+129
(r0 (* b01 d))
+130
(r1 (* d (+ (- (* a22 a01)) (* a02 a21))))
+131
(r2 (* d (- (* a12 a01) (* a02 a11))))
+132
(r3 (* b11 d))
+133
(r4 (* d (- (* a22 a00) (* a02 a20))))
+134
(r5 (* d (+ (- (* a12 a00)) (* a02 a10))))
+135
(r6 (* b21 d))
+136
(r7 (* d (+ (- (* a21 a00)) (* a01 a20))))
+137
(r8 (* d (- (* a11 a00) (* a01 a10)))))
+138
(if transpose?
+139
(set9! dst r0 r3 r6 r1 r4 r7 r2 r5 r8)
+140
(set9! dst r0 r1 r2 r3 r4 r5 r6 r7 r8))))))
+141
+142
;;; Write the inverse of `m` into `dst` and return `dst`, or return #f
+143
;;; and leave `dst` untouched when `m` is singular.
+144
(define (mat3-inverse! dst m)
+145
(invert3! dst (f@ m 0) (f@ m 1) (f@ m 2) (f@ m 3) (f@ m 4) (f@ m 5)
+146
(f@ m 6) (f@ m 7) (f@ m 8) #f))
+147
(define (mat3-inverse m) (mat3-inverse! (new) m))
+148
+149
;;; The upper-left 3x3 of the mat4 `m` (its rotation and scale).
+150
(define (mat3-from-mat4! dst m)
+151
(set9! dst (f@ m 0) (f@ m 1) (f@ m 2) (f@ m 4) (f@ m 5) (f@ m 6)
+152
(f@ m 8) (f@ m 9) (f@ m 10)))
+153
(define (mat3-from-mat4 m) (mat3-from-mat4! (new) m))
+154
+155
;;; The normal matrix of the mat4 model(-view) matrix `m`: the
+156
;;; inverse-transpose of its upper-left 3x3, which keeps normals
+157
;;; perpendicular to surfaces under non-uniform scale. Returns #f and
+158
;;; leaves `dst` untouched when that 3x3 is singular.
+159
(define (mat3-normal-matrix! dst m)
+160
(invert3! dst (f@ m 0) (f@ m 1) (f@ m 2) (f@ m 4) (f@ m 5) (f@ m 6)
+161
(f@ m 8) (f@ m 9) (f@ m 10) #t))
+162
(define (mat3-normal-matrix m) (mat3-normal-matrix! (new) m))
+163
+164
;;; The rotation matrix of the unit quaternion `q` (x y z w).
+165
(define (mat3-from-quat! dst q)
+166
(let* ((x (f@ q 0)) (y (f@ q 1)) (z (f@ q 2)) (w (f@ q 3))
+167
(x2 (+ x x)) (y2 (+ y y)) (z2 (+ z z))
+168
(xx (* x x2)) (yx (* y x2)) (yy (* y y2))
+169
(zx (* z x2)) (zy (* z y2)) (zz (* z z2))
+170
(wx (* w x2)) (wy (* w y2)) (wz (* w z2)))
+171
(set9! dst
+172
(- 1.0 yy zz) (+ yx wz) (- zx wy)
+173
(- yx wz) (- 1.0 xx zz) (+ zy wx)
+174
(+ zx wy) (- zy wx) (- 1.0 xx yy))))
+175
(define (mat3-from-quat q) (mat3-from-quat! (new) q))
+176
+177
;;; `m * v` for the vec3 `v`.
+178
(define (mat3-transform-vec3! dst m v)
+179
(let ((x (f@ v 0)) (y (f@ v 1)) (z (f@ v 2)))
+180
(let ((rx (+ (* (f@ m 0) x) (* (f@ m 3) y) (* (f@ m 6) z)))
+181
(ry (+ (* (f@ m 1) x) (* (f@ m 4) y) (* (f@ m 7) z)))
+182
(rz (+ (* (f@ m 2) x) (* (f@ m 5) y) (* (f@ m 8) z))))
+183
(f! dst 0 rx) (f! dst 1 ry) (f! dst 2 rz)
+184
dst)))
+185
(define (mat3-transform-vec3 m v) (mat3-transform-vec3! (make-bytevector 12 0) m v))
+186
+187
;;; Write `m` in std140 uniform-block layout into the 48-byte `dst`:
+188
;;; three columns, each 3 floats followed by one float of padding
+189
;;; (written as 0). `dst` must not alias `m`.
+190
(define (mat3->std140! dst m)
+191
(f! dst 0 (f@ m 0)) (f! dst 1 (f@ m 1)) (f! dst 2 (f@ m 2)) (f! dst 3 0.0)
+192
(f! dst 4 (f@ m 3)) (f! dst 5 (f@ m 4)) (f! dst 6 (f@ m 5)) (f! dst 7 0.0)
+193
(f! dst 8 (f@ m 6)) (f! dst 9 (f@ m 7)) (f! dst 10 (f@ m 8)) (f! dst 11 0.0)
+194
dst)
+195
(define (mat3->std140 m) (mat3->std140! (make-bytevector 48 0) m))
+196
+197
;;; True when every element differs by at most `eps` (default 1e-5).
+198
(define (mat3-approx=? a b . eps)
+199
(let ((e (if (null? eps) 1e-5 (car eps))))
+200
(let loop ((i 0))
+201
(cond ((= i 9) #t)
+202
((let ((x (f@ a i)) (y (f@ b i)))
+203
(<= (abs (- x y)) (* e (max 1.0 (abs x) (abs y)))))
+204
(loop (+ i 1)))
+205
(else #f)))))))
src/sigil/geometry/mat4.sgladded
@@ -0,0 +1,329 @@
+1
;;; (sigil geometry mat4) - 4x4 float32 matrices, column-major
+2
;;;
+3
;;; A mat4 is a 64-byte bytevector of 16 float32 values in native byte
+4
;;; order, stored column by column (the OpenGL convention): the element
+5
;;; at column `c`, row `r` is float `c*4 + r`. A translation therefore
+6
;;; sits in floats 12, 13 and 14. These bytes are what a GL uniform
+7
;;; `mat4` expects with no transpose.
+8
;;;
+9
;;; Points are column vectors and matrices multiply on the left:
+10
;;; `(mat4-mul a b)` is the transform that applies `b` first, then `a`.
+11
;;;
+12
;;; Every operation that produces a matrix has an allocating form and
+13
;;; a `!` form that writes into a destination and returns it. The
+14
;;; destination may be the same bytevector as any input.
+15
+16
(define-library (sigil geometry mat4)
+17
(import (sigil core) (sigil math))
+18
(export
+19
mat4 make-mat4 mat4? mat4-ref mat4-set! list->mat4 mat4->list
+20
mat4-identity mat4-identity! mat4-copy mat4-copy!
+21
mat4-mul mat4-mul! mat4-transpose mat4-transpose!
+22
mat4-determinant mat4-inverse mat4-inverse!
+23
mat4-translation mat4-translation! mat4-scaling mat4-scaling!
+24
mat4-rotation-x mat4-rotation-x! mat4-rotation-y mat4-rotation-y!
+25
mat4-rotation-z mat4-rotation-z! mat4-rotation mat4-rotation!
+26
mat4-from-quat mat4-from-quat! mat4-from-trs mat4-from-trs!
+27
mat4-get-translation mat4-get-translation!
+28
mat4-transform-point mat4-transform-point!
+29
mat4-transform-direction mat4-transform-direction!
+30
mat4-transform-vec4 mat4-transform-vec4!
+31
mat4-approx=?)
+32
+33
(begin
+34
;; Float index -> float32 at byte offset 4*i, native byte order.
+35
;; Procedures, not syntax-rules macros: native codegen looks up a
+36
;; macro-introduced global through %hygiene-ref at run time, which
+37
;; allocates on every call.
+38
(define (f@ v i) (bytevector-ieee-single-ref v (* 4 i)))
+39
(define (f! v i x) (bytevector-ieee-single-set! v (* 4 i) x))
+40
+41
;; Write all 16 floats, in storage (column-major) order; returns `d`.
+42
;; Every argument is evaluated before the first write, which is what
+43
;; lets a `!` form's destination alias its inputs.
+44
(define (set16! d a0 a1 a2 a3 a4 a5 a6 a7 a8 a9 a10 a11 a12 a13 a14 a15)
+45
(f! d 0 a0) (f! d 1 a1) (f! d 2 a2) (f! d 3 a3)
+46
(f! d 4 a4) (f! d 5 a5) (f! d 6 a6) (f! d 7 a7)
+47
(f! d 8 a8) (f! d 9 a9) (f! d 10 a10) (f! d 11 a11)
+48
(f! d 12 a12) (f! d 13 a13) (f! d 14 a14) (f! d 15 a15)
+49
d)
+50
+51
(define (new) (make-bytevector 64 0))
+52
+53
;;; A new mat4 from 16 values in column-major order: the first four
+54
;;; are column 0 (rows 0 to 3), and so on.
+55
(define (mat4 a0 a1 a2 a3 a4 a5 a6 a7 a8 a9 a10 a11 a12 a13 a14 a15)
+56
(set16! (new) a0 a1 a2 a3 a4 a5 a6 a7 a8 a9 a10 a11 a12 a13 a14 a15))
+57
+58
;;; A new identity mat4.
+59
(define (make-mat4) (mat4-identity! (new)))
+60
+61
;;; True for a bytevector of mat4 size (64 bytes).
+62
(define (mat4? m) (and (bytevector? m) (= (bytevector-length m) 64)))
+63
+64
;;; The element at column `col`, row `row`.
+65
(define (mat4-ref m col row) (f@ m (+ (* col 4) row)))
+66
+67
;;; Set the element at column `col`, row `row`; returns `m`.
+68
(define (mat4-set! m col row x) (f! m (+ (* col 4) row) x) m)
+69
+70
;;; A new mat4 from a list of 16 numbers in column-major order.
+71
(define (list->mat4 lst)
+72
(unless (= (length lst) 16)
+73
(error "list->mat4: expected 16 numbers" (length lst)))
+74
(let ((m (new)))
+75
(let loop ((i 0) (xs lst))
+76
(if (null? xs)
+77
m
+78
(begin (f! m i (car xs)) (loop (+ i 1) (cdr xs)))))))
+79
+80
;;; The 16 floats in column-major order.
+81
(define (mat4->list m)
+82
(let loop ((i 15) (acc '()))
+83
(if (< i 0) acc (loop (- i 1) (cons (f@ m i) acc)))))
+84
+85
(define (mat4-identity! dst)
+86
(set16! dst 1.0 0.0 0.0 0.0 0.0 1.0 0.0 0.0 0.0 0.0 1.0 0.0 0.0 0.0 0.0 1.0))
+87
(define (mat4-identity) (mat4-identity! (new)))
+88
+89
(define (mat4-copy! dst m)
+90
(unless (eq? dst m) (bytevector-copy! dst 0 m 0 64))
+91
dst)
+92
(define (mat4-copy m) (mat4-copy! (new) m))
+93
+94
;;; `a * b`: the transform that applies `b`, then `a`.
+95
;;;
+96
;;; ```scheme
+97
;;; ;; model-view-projection, written into one reused matrix
+98
;;; (mat4-mul! mvp view model)
+99
;;; (mat4-mul! mvp proj mvp)
+100
;;; ```
+101
(define (mat4-mul! dst a b)
+102
(let ((a00 (f@ a 0)) (a01 (f@ a 1)) (a02 (f@ a 2)) (a03 (f@ a 3))
+103
(a10 (f@ a 4)) (a11 (f@ a 5)) (a12 (f@ a 6)) (a13 (f@ a 7))
+104
(a20 (f@ a 8)) (a21 (f@ a 9)) (a22 (f@ a 10)) (a23 (f@ a 11))
+105
(a30 (f@ a 12)) (a31 (f@ a 13)) (a32 (f@ a 14)) (a33 (f@ a 15))
+106
(b00 (f@ b 0)) (b01 (f@ b 1)) (b02 (f@ b 2)) (b03 (f@ b 3))
+107
(b10 (f@ b 4)) (b11 (f@ b 5)) (b12 (f@ b 6)) (b13 (f@ b 7))
+108
(b20 (f@ b 8)) (b21 (f@ b 9)) (b22 (f@ b 10)) (b23 (f@ b 11))
+109
(b30 (f@ b 12)) (b31 (f@ b 13)) (b32 (f@ b 14)) (b33 (f@ b 15)))
+110
;; aCR is column C, row R. Result column j = a * (column j of b).
+111
(set16! dst
+112
(+ (* a00 b00) (* a10 b01) (* a20 b02) (* a30 b03))
+113
(+ (* a01 b00) (* a11 b01) (* a21 b02) (* a31 b03))
+114
(+ (* a02 b00) (* a12 b01) (* a22 b02) (* a32 b03))
+115
(+ (* a03 b00) (* a13 b01) (* a23 b02) (* a33 b03))
+116
(+ (* a00 b10) (* a10 b11) (* a20 b12) (* a30 b13))
+117
(+ (* a01 b10) (* a11 b11) (* a21 b12) (* a31 b13))
+118
(+ (* a02 b10) (* a12 b11) (* a22 b12) (* a32 b13))
+119
(+ (* a03 b10) (* a13 b11) (* a23 b12) (* a33 b13))
+120
(+ (* a00 b20) (* a10 b21) (* a20 b22) (* a30 b23))
+121
(+ (* a01 b20) (* a11 b21) (* a21 b22) (* a31 b23))
+122
(+ (* a02 b20) (* a12 b21) (* a22 b22) (* a32 b23))
+123
(+ (* a03 b20) (* a13 b21) (* a23 b22) (* a33 b23))
+124
(+ (* a00 b30) (* a10 b31) (* a20 b32) (* a30 b33))
+125
(+ (* a01 b30) (* a11 b31) (* a21 b32) (* a31 b33))
+126
(+ (* a02 b30) (* a12 b31) (* a22 b32) (* a32 b33))
+127
(+ (* a03 b30) (* a13 b31) (* a23 b32) (* a33 b33)))))
+128
(define (mat4-mul a b) (mat4-mul! (new) a b))
+129
+130
(define (mat4-transpose! dst m)
+131
(let ((m0 (f@ m 0)) (m1 (f@ m 1)) (m2 (f@ m 2)) (m3 (f@ m 3))
+132
(m4 (f@ m 4)) (m5 (f@ m 5)) (m6 (f@ m 6)) (m7 (f@ m 7))
+133
(m8 (f@ m 8)) (m9 (f@ m 9)) (m10 (f@ m 10)) (m11 (f@ m 11))
+134
(m12 (f@ m 12)) (m13 (f@ m 13)) (m14 (f@ m 14)) (m15 (f@ m 15)))
+135
(set16! dst m0 m4 m8 m12 m1 m5 m9 m13 m2 m6 m10 m14 m3 m7 m11 m15)))
+136
(define (mat4-transpose m) (mat4-transpose! (new) m))
+137
+138
;;; The determinant.
+139
(define (mat4-determinant m)
+140
(let ((a00 (f@ m 0)) (a01 (f@ m 1)) (a02 (f@ m 2)) (a03 (f@ m 3))
+141
(a10 (f@ m 4)) (a11 (f@ m 5)) (a12 (f@ m 6)) (a13 (f@ m 7))
+142
(a20 (f@ m 8)) (a21 (f@ m 9)) (a22 (f@ m 10)) (a23 (f@ m 11))
+143
(a30 (f@ m 12)) (a31 (f@ m 13)) (a32 (f@ m 14)) (a33 (f@ m 15)))
+144
(let ((b00 (- (* a00 a11) (* a01 a10)))
+145
(b01 (- (* a00 a12) (* a02 a10)))
+146
(b02 (- (* a00 a13) (* a03 a10)))
+147
(b03 (- (* a01 a12) (* a02 a11)))
+148
(b04 (- (* a01 a13) (* a03 a11)))
+149
(b05 (- (* a02 a13) (* a03 a12)))
+150
(b06 (- (* a20 a31) (* a21 a30)))
+151
(b07 (- (* a20 a32) (* a22 a30)))
+152
(b08 (- (* a20 a33) (* a23 a30)))
+153
(b09 (- (* a21 a32) (* a22 a31)))
+154
(b10 (- (* a21 a33) (* a23 a31)))
+155
(b11 (- (* a22 a33) (* a23 a32))))
+156
(+ (- (* b00 b11) (* b01 b10)) (* b02 b09) (* b03 b08)
+157
(- (* b04 b07)) (* b05 b06)))))
+158
+159
;;; Write the inverse of `m` into `dst` and return `dst`, or return #f
+160
;;; and leave `dst` untouched when `m` is singular (determinant 0).
+161
(define (mat4-inverse! dst m)
+162
(let ((a00 (f@ m 0)) (a01 (f@ m 1)) (a02 (f@ m 2)) (a03 (f@ m 3))
+163
(a10 (f@ m 4)) (a11 (f@ m 5)) (a12 (f@ m 6)) (a13 (f@ m 7))
+164
(a20 (f@ m 8)) (a21 (f@ m 9)) (a22 (f@ m 10)) (a23 (f@ m 11))
+165
(a30 (f@ m 12)) (a31 (f@ m 13)) (a32 (f@ m 14)) (a33 (f@ m 15)))
+166
(let* ((b00 (- (* a00 a11) (* a01 a10)))
+167
(b01 (- (* a00 a12) (* a02 a10)))
+168
(b02 (- (* a00 a13) (* a03 a10)))
+169
(b03 (- (* a01 a12) (* a02 a11)))
+170
(b04 (- (* a01 a13) (* a03 a11)))
+171
(b05 (- (* a02 a13) (* a03 a12)))
+172
(b06 (- (* a20 a31) (* a21 a30)))
+173
(b07 (- (* a20 a32) (* a22 a30)))
+174
(b08 (- (* a20 a33) (* a23 a30)))
+175
(b09 (- (* a21 a32) (* a22 a31)))
+176
(b10 (- (* a21 a33) (* a23 a31)))
+177
(b11 (- (* a22 a33) (* a23 a32)))
+178
(det (+ (- (* b00 b11) (* b01 b10)) (* b02 b09) (* b03 b08)
+179
(- (* b04 b07)) (* b05 b06))))
+180
(if (= det 0.0)
+181
#f
+182
(let ((d (/ 1.0 det)))
+183
(set16! dst
+184
(* d (+ (- (* a11 b11) (* a12 b10)) (* a13 b09)))
+185
(* d (- (- (* a02 b10) (* a01 b11)) (* a03 b09)))
+186
(* d (+ (- (* a31 b05) (* a32 b04)) (* a33 b03)))
+187
(* d (- (- (* a22 b04) (* a21 b05)) (* a23 b03)))
+188
(* d (- (- (* a12 b08) (* a10 b11)) (* a13 b07)))
+189
(* d (+ (- (* a00 b11) (* a02 b08)) (* a03 b07)))
+190
(* d (- (- (* a32 b02) (* a30 b05)) (* a33 b01)))
+191
(* d (+ (- (* a20 b05) (* a22 b02)) (* a23 b01)))
+192
(* d (+ (- (* a10 b10) (* a11 b08)) (* a13 b06)))
+193
(* d (- (- (* a01 b08) (* a00 b10)) (* a03 b06)))
+194
(* d (+ (- (* a30 b04) (* a31 b02)) (* a33 b00)))
+195
(* d (- (- (* a21 b02) (* a20 b04)) (* a23 b00)))
+196
(* d (- (- (* a11 b07) (* a10 b09)) (* a12 b06)))
+197
(* d (+ (- (* a00 b09) (* a01 b07)) (* a02 b06)))
+198
(* d (- (- (* a31 b01) (* a30 b03)) (* a32 b00)))
+199
(* d (+ (- (* a20 b03) (* a21 b01)) (* a22 b00)))))))))
+200
+201
;;; The inverse of `m` as a new matrix, or #f when `m` is singular.
+202
(define (mat4-inverse m) (mat4-inverse! (new) m))
+203
+204
;;; A translation by the vec3 `v`.
+205
(define (mat4-translation! dst v)
+206
(set16! dst 1.0 0.0 0.0 0.0 0.0 1.0 0.0 0.0 0.0 0.0 1.0 0.0
+207
(f@ v 0) (f@ v 1) (f@ v 2) 1.0))
+208
(define (mat4-translation v) (mat4-translation! (new) v))
+209
+210
;;; A scale by the vec3 `v` along x, y and z.
+211
(define (mat4-scaling! dst v)
+212
(set16! dst (f@ v 0) 0.0 0.0 0.0 0.0 (f@ v 1) 0.0 0.0 0.0 0.0 (f@ v 2) 0.0
+213
0.0 0.0 0.0 1.0))
+214
(define (mat4-scaling v) (mat4-scaling! (new) v))
+215
+216
;;; A rotation of `angle` radians about the x axis, counterclockwise
+217
;;; when looking from +x toward the origin (y turns toward z).
+218
(define (mat4-rotation-x! dst angle)
+219
(let ((c (cos angle)) (s (sin angle)))
+220
(set16! dst 1.0 0.0 0.0 0.0 0.0 c s 0.0 0.0 (- s) c 0.0 0.0 0.0 0.0 1.0)))
+221
(define (mat4-rotation-x angle) (mat4-rotation-x! (new) angle))
+222
+223
;;; A rotation of `angle` radians about the y axis (z turns toward x).
+224
(define (mat4-rotation-y! dst angle)
+225
(let ((c (cos angle)) (s (sin angle)))
+226
(set16! dst c 0.0 (- s) 0.0 0.0 1.0 0.0 0.0 s 0.0 c 0.0 0.0 0.0 0.0 1.0)))
+227
(define (mat4-rotation-y angle) (mat4-rotation-y! (new) angle))
+228
+229
;;; A rotation of `angle` radians about the z axis (x turns toward y).
+230
(define (mat4-rotation-z! dst angle)
+231
(let ((c (cos angle)) (s (sin angle)))
+232
(set16! dst c s 0.0 0.0 (- s) c 0.0 0.0 0.0 0.0 1.0 0.0 0.0 0.0 0.0 1.0)))
+233
(define (mat4-rotation-z angle) (mat4-rotation-z! (new) angle))
+234
+235
;;; A rotation of `angle` radians about the vec3 `axis`, which need
+236
;;; not be unit length. A zero axis gives the identity.
+237
(define (mat4-rotation! dst axis angle)
+238
(let* ((x (f@ axis 0)) (y (f@ axis 1)) (z (f@ axis 2))
+239
(len (sqrt (+ (* x x) (* y y) (* z z)))))
+240
(if (= len 0.0)
+241
(mat4-identity! dst)
+242
(let* ((x (/ x len)) (y (/ y len)) (z (/ z len))
+243
(c (cos angle)) (s (sin angle)) (t (- 1.0 c)))
+244
(set16! dst
+245
(+ (* x x t) c) (+ (* y x t) (* z s)) (- (* z x t) (* y s)) 0.0
+246
(- (* x y t) (* z s)) (+ (* y y t) c) (+ (* z y t) (* x s)) 0.0
+247
(+ (* x z t) (* y s)) (- (* y z t) (* x s)) (+ (* z z t) c) 0.0
+248
0.0 0.0 0.0 1.0)))))
+249
(define (mat4-rotation axis angle) (mat4-rotation! (new) axis angle))
+250
+251
;;; The rotation matrix of the unit quaternion `q` (x y z w).
+252
(define (mat4-from-quat! dst q)
+253
(mat4-from-trs-values! dst 0.0 0.0 0.0 q 1.0 1.0 1.0))
+254
(define (mat4-from-quat q) (mat4-from-quat! (new) q))
+255
+256
;;; Translation * rotation * scale: scale by the vec3 `s`, rotate by
+257
;;; the quaternion `q`, then move by the vec3 `t`. The usual model
+258
;;; matrix for an object with a position, orientation and size.
+259
(define (mat4-from-trs! dst t q s)
+260
(mat4-from-trs-values! dst (f@ t 0) (f@ t 1) (f@ t 2) q (f@ s 0) (f@ s 1) (f@ s 2)))
+261
(define (mat4-from-trs t q s) (mat4-from-trs! (new) t q s))
+262
+263
(define (mat4-from-trs-values! dst tx ty tz q sx sy sz)
+264
(let* ((x (f@ q 0)) (y (f@ q 1)) (z (f@ q 2)) (w (f@ q 3))
+265
(x2 (+ x x)) (y2 (+ y y)) (z2 (+ z z))
+266
(xx (* x x2)) (yx (* y x2)) (yy (* y y2))
+267
(zx (* z x2)) (zy (* z y2)) (zz (* z z2))
+268
(wx (* w x2)) (wy (* w y2)) (wz (* w z2)))
+269
(set16! dst
+270
(* sx (- 1.0 yy zz)) (* sx (+ yx wz)) (* sx (- zx wy)) 0.0
+271
(* sy (- yx wz)) (* sy (- 1.0 xx zz)) (* sy (+ zy wx)) 0.0
+272
(* sz (+ zx wy)) (* sz (- zy wx)) (* sz (- 1.0 xx yy)) 0.0
+273
tx ty tz 1.0)))
+274
+275
;;; The translation part of `m` (floats 12, 13, 14) as a vec3.
+276
(define (mat4-get-translation! dst m)
+277
(f! dst 0 (f@ m 12)) (f! dst 1 (f@ m 13)) (f! dst 2 (f@ m 14))
+278
dst)
+279
(define (mat4-get-translation m) (mat4-get-translation! (make-bytevector 12 0) m))
+280
+281
;;; Transform the vec3 point `p` (w = 1) and divide by the resulting
+282
;;; w, so a projection matrix yields normalized device coordinates.
+283
;;; When the resulting w is 0 the undivided x, y, z are written.
+284
(define (mat4-transform-point! dst m p)
+285
(let* ((x (f@ p 0)) (y (f@ p 1)) (z (f@ p 2))
+286
(rx (+ (* (f@ m 0) x) (* (f@ m 4) y) (* (f@ m 8) z) (f@ m 12)))
+287
(ry (+ (* (f@ m 1) x) (* (f@ m 5) y) (* (f@ m 9) z) (f@ m 13)))
+288
(rz (+ (* (f@ m 2) x) (* (f@ m 6) y) (* (f@ m 10) z) (f@ m 14)))
+289
(rw (+ (* (f@ m 3) x) (* (f@ m 7) y) (* (f@ m 11) z) (f@ m 15))))
+290
(if (or (= rw 1.0) (= rw 0.0))
+291
(begin (f! dst 0 rx) (f! dst 1 ry) (f! dst 2 rz))
+292
(let ((inv (/ 1.0 rw)))
+293
(f! dst 0 (* rx inv)) (f! dst 1 (* ry inv)) (f! dst 2 (* rz inv))))
+294
dst))
+295
(define (mat4-transform-point m p) (mat4-transform-point! (make-bytevector 12 0) m p))
+296
+297
;;; Transform the vec3 direction `d` (w = 0): rotation and scale
+298
;;; apply, translation does not.
+299
(define (mat4-transform-direction! dst m d)
+300
(let ((x (f@ d 0)) (y (f@ d 1)) (z (f@ d 2)))
+301
(let ((rx (+ (* (f@ m 0) x) (* (f@ m 4) y) (* (f@ m 8) z)))
+302
(ry (+ (* (f@ m 1) x) (* (f@ m 5) y) (* (f@ m 9) z)))
+303
(rz (+ (* (f@ m 2) x) (* (f@ m 6) y) (* (f@ m 10) z))))
+304
(f! dst 0 rx) (f! dst 1 ry) (f! dst 2 rz)
+305
dst)))
+306
(define (mat4-transform-direction m d)
+307
(mat4-transform-direction! (make-bytevector 12 0) m d))
+308
+309
;;; `m * v` for the vec4 `v`, with no divide.
+310
(define (mat4-transform-vec4! dst m v)
+311
(let ((x (f@ v 0)) (y (f@ v 1)) (z (f@ v 2)) (w (f@ v 3)))
+312
(let ((rx (+ (* (f@ m 0) x) (* (f@ m 4) y) (* (f@ m 8) z) (* (f@ m 12) w)))
+313
(ry (+ (* (f@ m 1) x) (* (f@ m 5) y) (* (f@ m 9) z) (* (f@ m 13) w)))
+314
(rz (+ (* (f@ m 2) x) (* (f@ m 6) y) (* (f@ m 10) z) (* (f@ m 14) w)))
+315
(rw (+ (* (f@ m 3) x) (* (f@ m 7) y) (* (f@ m 11) z) (* (f@ m 15) w))))
+316
(f! dst 0 rx) (f! dst 1 ry) (f! dst 2 rz) (f! dst 3 rw)
+317
dst)))
+318
(define (mat4-transform-vec4 m v) (mat4-transform-vec4! (make-bytevector 16 0) m v))
+319
+320
;;; True when every element differs by at most `eps` (default 1e-5,
+321
;;; relative above magnitude 1).
+322
(define (mat4-approx=? a b . eps)
+323
(let ((e (if (null? eps) 1e-5 (car eps))))
+324
(let loop ((i 0))
+325
(cond ((= i 16) #t)
+326
((let ((x (f@ a i)) (y (f@ b i)))
+327
(<= (abs (- x y)) (* e (max 1.0 (abs x) (abs y)))))
+328
(loop (+ i 1)))
+329
(else #f)))))))
src/sigil/geometry/quat.sgladded
@@ -0,0 +1,236 @@
+1
;;; (sigil geometry quat) - rotation quaternions
+2
;;;
+3
;;; A quaternion is a 16-byte bytevector of 4 float32 values in native
+4
;;; byte order: x y z w, with w the scalar part. The identity is
+5
;;; (0 0 0 1). It has the same layout as a vec4, so a shader can take it
+6
;;; as a `vec4` uniform.
+7
;;;
+8
;;; `(quat-mul a b)` is the rotation that applies `b`, then `a`, the
+9
;;; same order as `mat4-mul`. Rotations expect unit quaternions;
+10
;;; `quat-normalize!` restores unit length after many multiplications.
+11
+12
(define-library (sigil geometry quat)
+13
(import (sigil core) (sigil math))
+14
(export
+15
quat make-quat quat? quat-x quat-y quat-z quat-w quat-set!
+16
quat-copy quat-copy! quat->list
+17
quat-identity quat-identity!
+18
quat-from-axis-angle quat-from-axis-angle!
+19
quat-from-mat3 quat-from-mat3! quat-from-mat4 quat-from-mat4!
+20
quat-mul quat-mul! quat-conjugate quat-conjugate! quat-inverse quat-inverse!
+21
quat-dot quat-length quat-normalize quat-normalize!
+22
quat-slerp quat-slerp! quat-nlerp quat-nlerp!
+23
quat-rotate-vec3 quat-rotate-vec3!
+24
quat-angle quat-approx=? quat-same-rotation?)
+25
+26
(begin
+27
;; Float index -> float32 at byte offset 4*i, native byte order.
+28
;; Procedures, not syntax-rules macros: native codegen looks up a
+29
;; macro-introduced global through %hygiene-ref at run time, which
+30
;; allocates on every call.
+31
(define (f@ v i) (bytevector-ieee-single-ref v (* 4 i)))
+32
(define (f! v i x) (bytevector-ieee-single-set! v (* 4 i) x))
+33
+34
(define (new) (make-bytevector 16 0))
+35
+36
;;; A new quaternion from its four components (x y z w). This does
+37
;;; not normalize.
+38
(define (quat x y z w) (quat-set! (new) x y z w))
+39
+40
;;; A new identity quaternion (0 0 0 1).
+41
(define (make-quat) (quat-identity! (new)))
+42
+43
;;; True for a bytevector of quaternion size (16 bytes).
+44
(define (quat? q) (and (bytevector? q) (= (bytevector-length q) 16)))
+45
+46
(define (quat-x q) (f@ q 0))
+47
(define (quat-y q) (f@ q 1))
+48
(define (quat-z q) (f@ q 2))
+49
(define (quat-w q) (f@ q 3))
+50
+51
;;; Set all four components; returns `q`.
+52
(define (quat-set! q x y z w) (f! q 0 x) (f! q 1 y) (f! q 2 z) (f! q 3 w) q)
+53
+54
(define (quat-copy! dst q) (quat-set! dst (f@ q 0) (f@ q 1) (f@ q 2) (f@ q 3)))
+55
(define (quat-copy q) (quat-copy! (new) q))
+56
+57
(define (quat->list q) (list (f@ q 0) (f@ q 1) (f@ q 2) (f@ q 3)))
+58
+59
(define (quat-identity! dst) (quat-set! dst 0.0 0.0 0.0 1.0))
+60
(define (quat-identity) (quat-identity! (new)))
+61
+62
;;; The rotation of `angle` radians about the vec3 `axis` (need not be
+63
;;; unit length; a zero axis gives the identity). Positive angles turn
+64
;;; counterclockwise looking from the tip of the axis, as in
+65
;;; `mat4-rotation`.
+66
(define (quat-from-axis-angle! dst axis angle)
+67
(let* ((x (f@ axis 0)) (y (f@ axis 1)) (z (f@ axis 2))
+68
(len (sqrt (+ (* x x) (* y y) (* z z)))))
+69
(if (= len 0.0)
+70
(quat-identity! dst)
+71
(let* ((half (* 0.5 angle))
+72
(s (/ (sin half) len)))
+73
(quat-set! dst (* x s) (* y s) (* z s) (cos half))))))
+74
(define (quat-from-axis-angle axis angle) (quat-from-axis-angle! (new) axis angle))
+75
+76
;; Shoemake's method. mRC is row R, column C of a pure rotation.
+77
(define (from-rotation! dst m00 m01 m02 m10 m11 m12 m20 m21 m22)
+78
(let ((trace (+ m00 m11 m22)))
+79
(cond
+80
((> trace 0.0)
+81
(let ((s (* 2.0 (sqrt (+ trace 1.0)))))
+82
(quat-set! dst (/ (- m21 m12) s) (/ (- m02 m20) s) (/ (- m10 m01) s)
+83
(* 0.25 s))))
+84
((and (> m00 m11) (> m00 m22))
+85
(let ((s (* 2.0 (sqrt (max 1e-12 (- (+ 1.0 m00) m11 m22))))))
+86
(quat-set! dst (* 0.25 s) (/ (+ m01 m10) s) (/ (+ m02 m20) s)
+87
(/ (- m21 m12) s))))
+88
((> m11 m22)
+89
(let ((s (* 2.0 (sqrt (max 1e-12 (- (+ 1.0 m11) m00 m22))))))
+90
(quat-set! dst (/ (+ m01 m10) s) (* 0.25 s) (/ (+ m12 m21) s)
+91
(/ (- m02 m20) s))))
+92
(else
+93
(let ((s (* 2.0 (sqrt (max 1e-12 (- (+ 1.0 m22) m00 m11))))))
+94
(quat-set! dst (/ (+ m02 m20) s) (/ (+ m12 m21) s) (* 0.25 s)
+95
(/ (- m10 m01) s)))))))
+96
+97
;;; The quaternion of the rotation in the mat3 `m`, which must be a
+98
;;; pure rotation (orthonormal, determinant 1).
+99
(define (quat-from-mat3! dst m)
+100
;; column-major: row R, column C is float C*3 + R
+101
(from-rotation! dst
+102
(f@ m 0) (f@ m 3) (f@ m 6)
+103
(f@ m 1) (f@ m 4) (f@ m 7)
+104
(f@ m 2) (f@ m 5) (f@ m 8)))
+105
(define (quat-from-mat3 m) (quat-from-mat3! (new) m))
+106
+107
;;; The quaternion of the rotation in the upper-left 3x3 of the mat4
+108
;;; `m`, which must be a pure rotation (no scale).
+109
(define (quat-from-mat4! dst m)
+110
;; column-major: row R, column C is float C*4 + R
+111
(from-rotation! dst
+112
(f@ m 0) (f@ m 4) (f@ m 8)
+113
(f@ m 1) (f@ m 5) (f@ m 9)
+114
(f@ m 2) (f@ m 6) (f@ m 10)))
+115
(define (quat-from-mat4 m) (quat-from-mat4! (new) m))
+116
+117
;;; `a * b`: the rotation that applies `b`, then `a`.
+118
(define (quat-mul! dst a b)
+119
(let ((ax (f@ a 0)) (ay (f@ a 1)) (az (f@ a 2)) (aw (f@ a 3))
+120
(bx (f@ b 0)) (by (f@ b 1)) (bz (f@ b 2)) (bw (f@ b 3)))
+121
(quat-set! dst
+122
(- (+ (* aw bx) (* ax bw) (* ay bz)) (* az by))
+123
(+ (- (* aw by) (* ax bz)) (* ay bw) (* az bx))
+124
(+ (- (+ (* aw bz) (* ax by)) (* ay bx)) (* az bw))
+125
(- (* aw bw) (* ax bx) (* ay by) (* az bz)))))
+126
(define (quat-mul a b) (quat-mul! (new) a b))
+127
+128
;;; (-x -y -z w): the inverse rotation of a unit quaternion.
+129
(define (quat-conjugate! dst q)
+130
(quat-set! dst (- (f@ q 0)) (- (f@ q 1)) (- (f@ q 2)) (f@ q 3)))
+131
(define (quat-conjugate q) (quat-conjugate! (new) q))
+132
+133
;;; The multiplicative inverse, for quaternions of any length. A zero
+134
;;; quaternion gives zero.
+135
(define (quat-inverse! dst q)
+136
(let* ((x (f@ q 0)) (y (f@ q 1)) (z (f@ q 2)) (w (f@ q 3))
+137
(n (+ (* x x) (* y y) (* z z) (* w w))))
+138
(if (= n 0.0)
+139
(quat-set! dst 0.0 0.0 0.0 0.0)
+140
(let ((inv (/ 1.0 n)))
+141
(quat-set! dst (* (- x) inv) (* (- y) inv) (* (- z) inv) (* w inv))))))
+142
(define (quat-inverse q) (quat-inverse! (new) q))
+143
+144
(define (quat-dot a b)
+145
(+ (* (f@ a 0) (f@ b 0)) (* (f@ a 1) (f@ b 1))
+146
(* (f@ a 2) (f@ b 2)) (* (f@ a 3) (f@ b 3))))
+147
+148
(define (quat-length q) (sqrt (quat-dot q q)))
+149
+150
;;; Unit-length copy of `q`. A zero quaternion becomes the identity.
+151
(define (quat-normalize! dst q)
+152
(let ((len (quat-length q)))
+153
(if (> len 0.0)
+154
(let ((inv (/ 1.0 len)))
+155
(quat-set! dst (* (f@ q 0) inv) (* (f@ q 1) inv) (* (f@ q 2) inv)
+156
(* (f@ q 3) inv)))
+157
(quat-identity! dst))))
+158
(define (quat-normalize q) (quat-normalize! (new) q))
+159
+160
;;; Normalized linear interpolation from `a` to `b` by `t`, along the
+161
;;; shorter arc. Cheaper than slerp and close to it for small angles;
+162
;;; the speed is not constant over large ones.
+163
(define (quat-nlerp! dst a b t)
+164
(let* ((sign (if (< (quat-dot a b) 0.0) -1.0 1.0))
+165
(u (- 1.0 t))
+166
(bt (* sign t)))
+167
(quat-set! dst
+168
(+ (* u (f@ a 0)) (* bt (f@ b 0)))
+169
(+ (* u (f@ a 1)) (* bt (f@ b 1)))
+170
(+ (* u (f@ a 2)) (* bt (f@ b 2)))
+171
(+ (* u (f@ a 3)) (* bt (f@ b 3))))
+172
(quat-normalize! dst dst)))
+173
(define (quat-nlerp a b t) (quat-nlerp! (new) a b t))
+174
+175
;;; Spherical linear interpolation from unit `a` (t = 0) to unit `b`
+176
;;; (t = 1) along the shorter arc, at constant angular speed. For
+177
;;; nearly equal rotations it falls back to nlerp.
+178
;;;
+179
;;; ```scheme
+180
;;; ;; blend two poses' orientations, into a reused quaternion
+181
;;; (quat-slerp! pose-rot rot-a rot-b 0.25)
+182
;;; ```
+183
(define (quat-slerp! dst a b t)
+184
(let* ((ax (f@ a 0)) (ay (f@ a 1)) (az (f@ a 2)) (aw (f@ a 3))
+185
(d (quat-dot a b))
+186
(sign (if (< d 0.0) -1.0 1.0))
+187
(cosine (* sign d)))
+188
(if (> cosine 0.9995)
+189
(quat-nlerp! dst a b t)
+190
(let* ((theta (acos (min 1.0 cosine)))
+191
(inv-sin (/ 1.0 (sin theta)))
+192
(wa (* (sin (* (- 1.0 t) theta)) inv-sin))
+193
(wb (* sign (sin (* t theta)) inv-sin)))
+194
(quat-set! dst
+195
(+ (* wa ax) (* wb (f@ b 0)))
+196
(+ (* wa ay) (* wb (f@ b 1)))
+197
(+ (* wa az) (* wb (f@ b 2)))
+198
(+ (* wa aw) (* wb (f@ b 3))))))))
+199
(define (quat-slerp a b t) (quat-slerp! (new) a b t))
+200
+201
;;; Rotate the vec3 `v` by the unit quaternion `q`.
+202
(define (quat-rotate-vec3! dst q v)
+203
;; t = 2 (q.xyz x v); v' = v + w t + q.xyz x t
+204
(let* ((qx (f@ q 0)) (qy (f@ q 1)) (qz (f@ q 2)) (qw (f@ q 3))
+205
(vx (f@ v 0)) (vy (f@ v 1)) (vz (f@ v 2))
+206
(tx (* 2.0 (- (* qy vz) (* qz vy))))
+207
(ty (* 2.0 (- (* qz vx) (* qx vz))))
+208
(tz (* 2.0 (- (* qx vy) (* qy vx)))))
+209
(f! dst 0 (+ vx (* qw tx) (- (* qy tz) (* qz ty))))
+210
(f! dst 1 (+ vy (* qw ty) (- (* qz tx) (* qx tz))))
+211
(f! dst 2 (+ vz (* qw tz) (- (* qx ty) (* qy tx))))
+212
dst))
+213
(define (quat-rotate-vec3 q v) (quat-rotate-vec3! (make-bytevector 12 0) q v))
+214
+215
;;; The rotation angle of the unit quaternion `q`, in radians, 0 to pi
+216
;;; (the shorter way round).
+217
(define (quat-angle q)
+218
(* 2.0 (acos (min 1.0 (abs (f@ q 3))))))
+219
+220
;;; Component-wise comparison within `eps` (default 1e-5). Note that
+221
;;; `q` and `-q` are the same rotation but not approx=?; use
+222
;;; `quat-same-rotation?` for that.
+223
(define (quat-approx=? a b . eps)
+224
(let ((e (if (null? eps) 1e-5 (car eps))))
+225
(let loop ((i 0))
+226
(cond ((= i 4) #t)
+227
((let ((x (f@ a i)) (y (f@ b i)))
+228
(<= (abs (- x y)) (* e (max 1.0 (abs x) (abs y)))))
+229
(loop (+ i 1)))
+230
(else #f)))))
+231
+232
;;; True when unit quaternions `a` and `b` describe the same rotation
+233
;;; within `eps` (default 1e-5), treating `q` and `-q` as equal.
+234
(define (quat-same-rotation? a b . eps)
+235
(let ((e (if (null? eps) 1e-5 (car eps))))
+236
(>= (abs (quat-dot a b)) (- 1.0 e))))))
src/sigil/geometry/ray.sgladded
@@ -0,0 +1,198 @@
+1
;;; (sigil geometry ray) - ray casts against planes, boxes and triangles
+2
;;;
+3
;;; A ray is an `origin` vec3 and a `dir` vec3, passed as two arguments.
+4
;;; `dir` need not be unit length: every hit is reported as the
+5
;;; parameter `t` with the hit point at `origin + dir * t`, so distances
+6
;;; come out in units of `dir`'s length.
+7
;;;
+8
;;; That makes a sight line a ray whose `dir` is `target - eye`: a hit
+9
;;; with `t` below 1 is something between the two.
+10
;;;
+11
;;; ```scheme
+12
;;; (vec3-sub! dir target eye)
+13
;;; (let ((t (ray-aabb eye dir crate-min crate-max)))
+14
;;; (and t (< t 1.0))) ; => #t when the crate blocks the view
+15
;;; ```
+16
;;;
+17
;;; The cast functions return a flonum `t >= 0` or #f and allocate
+18
;;; nothing. A plane is a vec4 (a b c d) holding the points p where
+19
;;; a*px + b*py + c*pz + d = 0, with (a b c) its normal. A box (AABB) is
+20
;;; its minimum and maximum corners as two vec3s.
+21
+22
(define-library (sigil geometry ray)
+23
(import (sigil core) (sigil math))
+24
(export
+25
ray-point ray-point!
+26
plane-from-point-normal plane-from-point-normal!
+27
plane-from-points plane-from-points!
+28
plane-signed-distance
+29
ray-plane ray-aabb ray-triangle ray-triangle-hit!
+30
aabb-contains-point? aabb-overlap?)
+31
+32
(begin
+33
;; Float index -> float32 at byte offset 4*i, native byte order.
+34
;; Procedures, not syntax-rules macros: native codegen looks up a
+35
;; macro-introduced global through %hygiene-ref at run time, which
+36
;; allocates on every call.
+37
(define (f@ v i) (bytevector-ieee-single-ref v (* 4 i)))
+38
(define (f! v i x) (bytevector-ieee-single-set! v (* 4 i) x))
+39
+40
;;; `origin + dir * t` into the vec3 `dst`.
+41
(define (ray-point! dst origin dir t)
+42
(let ((x (+ (f@ origin 0) (* (f@ dir 0) t)))
+43
(y (+ (f@ origin 1) (* (f@ dir 1) t)))
+44
(z (+ (f@ origin 2) (* (f@ dir 2) t))))
+45
(f! dst 0 x) (f! dst 1 y) (f! dst 2 z)
+46
dst))
+47
(define (ray-point origin dir t) (ray-point! (make-bytevector 12 0) origin dir t))
+48
+49
;;; The plane through the vec3 `point` with the vec3 `normal`, as a
+50
;;; vec4 with a unit normal. A zero normal raises an error.
+51
(define (plane-from-point-normal! dst point normal)
+52
(let* ((nx (f@ normal 0)) (ny (f@ normal 1)) (nz (f@ normal 2))
+53
(len (sqrt (+ (* nx nx) (* ny ny) (* nz nz)))))
+54
(when (= len 0.0)
+55
(error "plane-from-point-normal: zero normal"))
+56
(let ((nx (/ nx len)) (ny (/ ny len)) (nz (/ nz len)))
+57
(f! dst 0 nx) (f! dst 1 ny) (f! dst 2 nz)
+58
(f! dst 3 (- (+ (* nx (f@ point 0)) (* ny (f@ point 1)) (* nz (f@ point 2)))))
+59
dst)))
+60
(define (plane-from-point-normal point normal)
+61
(plane-from-point-normal! (make-bytevector 16 0) point normal))
+62
+63
;;; The plane through three vec3 points. Its normal faces the side
+64
;;; from which `a`, `b`, `c` run counterclockwise (the right-hand
+65
;;; rule, the same winding as a front face in GL). Collinear points
+66
;;; raise an error.
+67
(define (plane-from-points! dst a b c)
+68
(let* ((ax (f@ a 0)) (ay (f@ a 1)) (az (f@ a 2))
+69
(e1x (- (f@ b 0) ax)) (e1y (- (f@ b 1) ay)) (e1z (- (f@ b 2) az))
+70
(e2x (- (f@ c 0) ax)) (e2y (- (f@ c 1) ay)) (e2z (- (f@ c 2) az))
+71
(nx (- (* e1y e2z) (* e1z e2y)))
+72
(ny (- (* e1z e2x) (* e1x e2z)))
+73
(nz (- (* e1x e2y) (* e1y e2x)))
+74
(len (sqrt (+ (* nx nx) (* ny ny) (* nz nz)))))
+75
(when (= len 0.0)
+76
(error "plane-from-points: the points are collinear"))
+77
(let ((nx (/ nx len)) (ny (/ ny len)) (nz (/ nz len)))
+78
(f! dst 0 nx) (f! dst 1 ny) (f! dst 2 nz)
+79
(f! dst 3 (- (+ (* nx ax) (* ny ay) (* nz az))))
+80
dst)))
+81
(define (plane-from-points a b c) (plane-from-points! (make-bytevector 16 0) a b c))
+82
+83
;;; The signed distance from the vec3 `p` to `plane`: positive on the
+84
;;; side the normal faces. In world units when the normal is unit
+85
;;; length, as the plane constructors make it.
+86
(define (plane-signed-distance plane p)
+87
(+ (* (f@ plane 0) (f@ p 0)) (* (f@ plane 1) (f@ p 1)) (* (f@ plane 2) (f@ p 2))
+88
(f@ plane 3)))
+89
+90
;;; Where the ray meets `plane`: `t >= 0`, or #f when the ray is
+91
;;; parallel to the plane or points away from it. Both sides of the
+92
;;; plane count.
+93
(define (ray-plane origin dir plane)
+94
(let ((denom (+ (* (f@ plane 0) (f@ dir 0))
+95
(* (f@ plane 1) (f@ dir 1))
+96
(* (f@ plane 2) (f@ dir 2)))))
+97
(if (= denom 0.0)
+98
#f
+99
(let ((t (/ (- (plane-signed-distance plane origin)) denom)))
+100
(if (>= t 0.0) t #f)))))
+101
+102
;; Larger than any t a float32 ray can produce.
+103
(define huge 1e300)
+104
+105
;; The t at which a ray with origin coordinate `o` and direction
+106
;; coordinate `d` enters the slab lo..hi on one axis, and the t at
+107
;; which it leaves. A ray parallel to the slab (d = 0) is inside it
+108
;; for all t (enter -huge, exit huge) or for none (enter huge, exit
+109
;; -huge, an empty interval).
+110
(define (slab-enter o d lo hi)
+111
(if (= d 0.0)
+112
(if (or (< o lo) (> o hi)) huge (- huge))
+113
(min (/ (- lo o) d) (/ (- hi o) d))))
+114
(define (slab-exit o d lo hi)
+115
(if (= d 0.0)
+116
(if (or (< o lo) (> o hi)) (- huge) huge)
+117
(max (/ (- lo o) d) (/ (- hi o) d))))
+118
+119
;;; Where the ray enters the box from `box-min` to `box-max`: the
+120
;;; smallest `t >= 0` inside the box, which is 0.0 when `origin` is
+121
;;; already inside, or #f when the ray misses. A ray skimming a face
+122
;;; counts as a hit.
+123
;;;
+124
;;; The slab test: each axis narrows the interval of `t` inside the
+125
;;; box. `dir` components are read from float32, so a nonzero one is
+126
;;; at least about 1.4e-45 and its reciprocal stays finite.
+127
(define (ray-aabb origin dir box-min box-max)
+128
;; Written out per axis, with no loop and no macro, so a call
+129
;; allocates nothing on any target.
+130
(let* ((ox (f@ origin 0)) (oy (f@ origin 1)) (oz (f@ origin 2))
+131
(dx (f@ dir 0)) (dy (f@ dir 1)) (dz (f@ dir 2))
+132
(lx (f@ box-min 0)) (ly (f@ box-min 1)) (lz (f@ box-min 2))
+133
(hx (f@ box-max 0)) (hy (f@ box-max 1)) (hz (f@ box-max 2))
+134
(near (max 0.0
+135
(slab-enter ox dx lx hx)
+136
(slab-enter oy dy ly hy)
+137
(slab-enter oz dz lz hz)))
+138
(far (min (slab-exit ox dx lx hx)
+139
(slab-exit oy dy ly hy)
+140
(slab-exit oz dz lz hz))))
+141
(if (> near far) #f near)))
+142
+143
;; Moller-Trumbore. Writes (t u v) into dst when dst is a vec3, and
+144
;; returns t, or #f on a miss. Both faces count.
+145
(define (triangle-cast origin dir a b c dst)
+146
(let* ((ax (f@ a 0)) (ay (f@ a 1)) (az (f@ a 2))
+147
(e1x (- (f@ b 0) ax)) (e1y (- (f@ b 1) ay)) (e1z (- (f@ b 2) az))
+148
(e2x (- (f@ c 0) ax)) (e2y (- (f@ c 1) ay)) (e2z (- (f@ c 2) az))
+149
(dx (f@ dir 0)) (dy (f@ dir 1)) (dz (f@ dir 2))
+150
;; p = dir x e2
+151
(px (- (* dy e2z) (* dz e2y)))
+152
(py (- (* dz e2x) (* dx e2z)))
+153
(pz (- (* dx e2y) (* dy e2x)))
+154
(det (+ (* e1x px) (* e1y py) (* e1z pz))))
+155
(if (< (abs det) 1e-12)
+156
#f
+157
(let* ((inv (/ 1.0 det))
+158
(sx (- (f@ origin 0) ax))
+159
(sy (- (f@ origin 1) ay))
+160
(sz (- (f@ origin 2) az))
+161
(u (* inv (+ (* sx px) (* sy py) (* sz pz)))))
+162
(if (or (< u 0.0) (> u 1.0))
+163
#f
+164
(let* ((qx (- (* sy e1z) (* sz e1y)))
+165
(qy (- (* sz e1x) (* sx e1z)))
+166
(qz (- (* sx e1y) (* sy e1x)))
+167
(v (* inv (+ (* dx qx) (* dy qy) (* dz qz)))))
+168
(if (or (< v 0.0) (> (+ u v) 1.0))
+169
#f
+170
(let ((t (* inv (+ (* e2x qx) (* e2y qy) (* e2z qz)))))
+171
(cond ((< t 0.0) #f)
+172
(dst (f! dst 0 t) (f! dst 1 u) (f! dst 2 v) t)
+173
(else t))))))))))
+174
+175
;;; Where the ray meets the triangle with vec3 corners `a`, `b`, `c`:
+176
;;; `t >= 0`, or #f on a miss. Both faces count.
+177
(define (ray-triangle origin dir a b c)
+178
(triangle-cast origin dir a b c #f))
+179
+180
;;; Like `ray-triangle`, and on a hit also writes (t u v) into the
+181
;;; vec3 `dst`, where u and v are the barycentric weights of `b` and
+182
;;; `c` (the hit point is a*(1-u-v) + b*u + c*v), for interpolating
+183
;;; texture coordinates at a picked point. Returns `t` or #f; `dst` is
+184
;;; untouched on a miss.
+185
(define (ray-triangle-hit! dst origin dir a b c)
+186
(triangle-cast origin dir a b c dst))
+187
+188
;;; True when the vec3 `p` lies inside or on the box.
+189
(define (aabb-contains-point? box-min box-max p)
+190
(and (<= (f@ box-min 0) (f@ p 0) (f@ box-max 0))
+191
(<= (f@ box-min 1) (f@ p 1) (f@ box-max 1))
+192
(<= (f@ box-min 2) (f@ p 2) (f@ box-max 2))))
+193
+194
;;; True when two boxes overlap or touch.
+195
(define (aabb-overlap? a-min a-max b-min b-max)
+196
(and (<= (f@ a-min 0) (f@ b-max 0)) (<= (f@ b-min 0) (f@ a-max 0))
+197
(<= (f@ a-min 1) (f@ b-max 1)) (<= (f@ b-min 1) (f@ a-max 1))
+198
(<= (f@ a-min 2) (f@ b-max 2)) (<= (f@ b-min 2) (f@ a-max 2))))))
src/sigil/geometry/vec.sgladded
@@ -0,0 +1,354 @@
+1
;;; (sigil geometry vec) - 2, 3 and 4 component float32 vectors
+2
;;;
+3
;;; A vector is a bytevector of float32 values in native byte order:
+4
;;; vec2 is 8 bytes (x y), vec3 is 12 (x y z), vec4 is 16 (x y z w).
+5
;;; Reads return flonums (double precision); writes round to float32.
+6
;;;
+7
;;; Every operation that produces a vector comes in two forms:
+8
;;;
+9
;;; ```scheme
+10
;;; (vec3-add a b) ; a new vec3
+11
;;; (vec3-add! dst a b) ; writes into dst, returns dst, allocates nothing
+12
;;; ```
+13
;;;
+14
;;; `dst` may be the same bytevector as any input. Operations that return
+15
;;; a number (`vec3-dot`, `vec3-length`) never allocate.
+16
+17
(define-library (sigil geometry vec)
+18
(import (sigil core) (sigil math))
+19
(export
+20
;; vec2
+21
vec2 make-vec2 vec2? vec2-x vec2-y vec2-set! vec2-copy vec2-copy!
+22
vec2-add vec2-add! vec2-sub vec2-sub! vec2-mul vec2-mul!
+23
vec2-scale vec2-scale! vec2-negate vec2-negate!
+24
vec2-dot vec2-length vec2-length-squared vec2-distance
+25
vec2-normalize vec2-normalize! vec2-lerp vec2-lerp!
+26
vec2-approx=? vec2->list
+27
+28
;; vec3
+29
vec3 make-vec3 vec3? vec3-x vec3-y vec3-z vec3-set! vec3-copy vec3-copy!
+30
vec3-add vec3-add! vec3-sub vec3-sub! vec3-mul vec3-mul!
+31
vec3-scale vec3-scale! vec3-negate vec3-negate!
+32
vec3-add-scaled vec3-add-scaled!
+33
vec3-dot vec3-cross vec3-cross!
+34
vec3-length vec3-length-squared vec3-distance vec3-distance-squared
+35
vec3-normalize vec3-normalize! vec3-lerp vec3-lerp!
+36
vec3-min vec3-min! vec3-max vec3-max!
+37
vec3-approx=? vec3->list
+38
+39
;; vec4
+40
vec4 make-vec4 vec4? vec4-x vec4-y vec4-z vec4-w vec4-set! vec4-copy vec4-copy!
+41
vec4-add vec4-add! vec4-sub vec4-sub! vec4-mul vec4-mul!
+42
vec4-scale vec4-scale! vec4-negate vec4-negate!
+43
vec4-dot vec4-length vec4-length-squared
+44
vec4-normalize vec4-normalize! vec4-lerp vec4-lerp!
+45
vec4-approx=? vec4->list
+46
+47
;; shared
+48
float-approx=? degrees->radians radians->degrees)
+49
+50
(begin
+51
;; Float index -> float32 at byte offset 4*i, native byte order.
+52
;; Procedures, not syntax-rules macros: native codegen looks up a
+53
;; macro-introduced global through %hygiene-ref at run time, which
+54
;; allocates on every call.
+55
(define (f@ v i) (bytevector-ieee-single-ref v (* 4 i)))
+56
(define (f! v i x) (bytevector-ieee-single-set! v (* 4 i) x))
+57
+58
;;; The default tolerance for the `approx=?` comparisons: 1e-5,
+59
;;; relative to the larger magnitude once that exceeds 1.
+60
(define default-epsilon 1e-5)
+61
+62
;;; True when `a` and `b` differ by at most `eps` (default 1e-5),
+63
;;; scaled by the larger magnitude when that is above 1.
+64
;;;
+65
;;; ```scheme
+66
;;; (float-approx=? 1.0 1.000001) ; => #t
+67
;;; ```
+68
(define (float-approx=? a b . eps)
+69
(let ((e (if (null? eps) default-epsilon (car eps))))
+70
(<= (abs (- a b)) (* e (max 1.0 (abs a) (abs b))))))
+71
+72
(define (eps-of rest) (if (null? rest) default-epsilon (car rest)))
+73
+74
(define pi 3.141592653589793)
+75
+76
;;; Degrees to radians.
+77
(define (degrees->radians d) (* d (/ pi 180.0)))
+78
+79
;;; Radians to degrees.
+80
(define (radians->degrees r) (* r (/ 180.0 pi)))
+81
+82
;; ------------------------------------------------------------
+83
;; vec2
+84
;; ------------------------------------------------------------
+85
+86
;;; A new vec2 holding `x` and `y`.
+87
(define (vec2 x y)
+88
(let ((v (make-bytevector 8 0)))
+89
(f! v 0 x) (f! v 1 y)
+90
v))
+91
+92
;;; A new vec2 of zeros.
+93
(define (make-vec2) (make-bytevector 8 0))
+94
+95
;;; True for a bytevector of vec2 size (8 bytes).
+96
(define (vec2? v) (and (bytevector? v) (= (bytevector-length v) 8)))
+97
+98
(define (vec2-x v) (f@ v 0))
+99
(define (vec2-y v) (f@ v 1))
+100
+101
;;; Set both components of `v`; returns `v`.
+102
(define (vec2-set! v x y) (f! v 0 x) (f! v 1 y) v)
+103
+104
(define (vec2-copy v) (vec2-copy! (make-vec2) v))
+105
(define (vec2-copy! dst v) (f! dst 0 (f@ v 0)) (f! dst 1 (f@ v 1)) dst)
+106
+107
(define (vec2-add! dst a b)
+108
(vec2-set! dst (+ (f@ a 0) (f@ b 0)) (+ (f@ a 1) (f@ b 1))))
+109
(define (vec2-add a b) (vec2-add! (make-vec2) a b))
+110
+111
(define (vec2-sub! dst a b)
+112
(vec2-set! dst (- (f@ a 0) (f@ b 0)) (- (f@ a 1) (f@ b 1))))
+113
(define (vec2-sub a b) (vec2-sub! (make-vec2) a b))
+114
+115
;;; Component-wise product.
+116
(define (vec2-mul! dst a b)
+117
(vec2-set! dst (* (f@ a 0) (f@ b 0)) (* (f@ a 1) (f@ b 1))))
+118
(define (vec2-mul a b) (vec2-mul! (make-vec2) a b))
+119
+120
(define (vec2-scale! dst v s)
+121
(vec2-set! dst (* (f@ v 0) s) (* (f@ v 1) s)))
+122
(define (vec2-scale v s) (vec2-scale! (make-vec2) v s))
+123
+124
(define (vec2-negate! dst v) (vec2-set! dst (- (f@ v 0)) (- (f@ v 1))))
+125
(define (vec2-negate v) (vec2-negate! (make-vec2) v))
+126
+127
(define (vec2-dot a b) (+ (* (f@ a 0) (f@ b 0)) (* (f@ a 1) (f@ b 1))))
+128
(define (vec2-length-squared v) (vec2-dot v v))
+129
(define (vec2-length v) (sqrt (vec2-dot v v)))
+130
(define (vec2-distance a b)
+131
(let ((dx (- (f@ a 0) (f@ b 0))) (dy (- (f@ a 1) (f@ b 1))))
+132
(sqrt (+ (* dx dx) (* dy dy)))))
+133
+134
;;; Unit-length copy of `v`. A zero vector stays zero.
+135
(define (vec2-normalize! dst v)
+136
(let ((len (vec2-length v)))
+137
(if (> len 0.0)
+138
(vec2-scale! dst v (/ 1.0 len))
+139
(vec2-set! dst 0.0 0.0))))
+140
(define (vec2-normalize v) (vec2-normalize! (make-vec2) v))
+141
+142
;;; `a + (b - a) * t`.
+143
(define (vec2-lerp! dst a b t)
+144
(let ((ax (f@ a 0)) (ay (f@ a 1)))
+145
(vec2-set! dst (+ ax (* (- (f@ b 0) ax) t)) (+ ay (* (- (f@ b 1) ay) t)))))
+146
(define (vec2-lerp a b t) (vec2-lerp! (make-vec2) a b t))
+147
+148
(define (vec2-approx=? a b . eps)
+149
(let ((e (eps-of eps)))
+150
(and (float-approx=? (f@ a 0) (f@ b 0) e)
+151
(float-approx=? (f@ a 1) (f@ b 1) e))))
+152
+153
(define (vec2->list v) (list (f@ v 0) (f@ v 1)))
+154
+155
;; ------------------------------------------------------------
+156
;; vec3
+157
;; ------------------------------------------------------------
+158
+159
;;; A new vec3 holding `x`, `y` and `z`.
+160
;;;
+161
;;; ```scheme
+162
;;; (vec3->list (vec3-cross (vec3 1 0 0) (vec3 0 1 0))) ; => (0 0 1)
+163
;;; ```
+164
(define (vec3 x y z)
+165
(let ((v (make-bytevector 12 0)))
+166
(f! v 0 x) (f! v 1 y) (f! v 2 z)
+167
v))
+168
+169
;;; A new vec3 of zeros.
+170
(define (make-vec3) (make-bytevector 12 0))
+171
+172
;;; True for a bytevector of vec3 size (12 bytes).
+173
(define (vec3? v) (and (bytevector? v) (= (bytevector-length v) 12)))
+174
+175
(define (vec3-x v) (f@ v 0))
+176
(define (vec3-y v) (f@ v 1))
+177
(define (vec3-z v) (f@ v 2))
+178
+179
;;; Set all three components of `v`; returns `v`.
+180
(define (vec3-set! v x y z) (f! v 0 x) (f! v 1 y) (f! v 2 z) v)
+181
+182
(define (vec3-copy v) (vec3-copy! (make-vec3) v))
+183
(define (vec3-copy! dst v) (vec3-set! dst (f@ v 0) (f@ v 1) (f@ v 2)))
+184
+185
(define (vec3-add! dst a b)
+186
(vec3-set! dst (+ (f@ a 0) (f@ b 0)) (+ (f@ a 1) (f@ b 1)) (+ (f@ a 2) (f@ b 2))))
+187
(define (vec3-add a b) (vec3-add! (make-vec3) a b))
+188
+189
(define (vec3-sub! dst a b)
+190
(vec3-set! dst (- (f@ a 0) (f@ b 0)) (- (f@ a 1) (f@ b 1)) (- (f@ a 2) (f@ b 2))))
+191
(define (vec3-sub a b) (vec3-sub! (make-vec3) a b))
+192
+193
;;; Component-wise product.
+194
(define (vec3-mul! dst a b)
+195
(vec3-set! dst (* (f@ a 0) (f@ b 0)) (* (f@ a 1) (f@ b 1)) (* (f@ a 2) (f@ b 2))))
+196
(define (vec3-mul a b) (vec3-mul! (make-vec3) a b))
+197
+198
(define (vec3-scale! dst v s)
+199
(vec3-set! dst (* (f@ v 0) s) (* (f@ v 1) s) (* (f@ v 2) s)))
+200
(define (vec3-scale v s) (vec3-scale! (make-vec3) v s))
+201
+202
;;; `a + b * s`: a step of `s` along `b` from `a`.
+203
(define (vec3-add-scaled! dst a b s)
+204
(vec3-set! dst
+205
(+ (f@ a 0) (* (f@ b 0) s))
+206
(+ (f@ a 1) (* (f@ b 1) s))
+207
(+ (f@ a 2) (* (f@ b 2) s))))
+208
(define (vec3-add-scaled a b s) (vec3-add-scaled! (make-vec3) a b s))
+209
+210
(define (vec3-negate! dst v) (vec3-set! dst (- (f@ v 0)) (- (f@ v 1)) (- (f@ v 2))))
+211
(define (vec3-negate v) (vec3-negate! (make-vec3) v))
+212
+213
(define (vec3-dot a b)
+214
(+ (* (f@ a 0) (f@ b 0)) (* (f@ a 1) (f@ b 1)) (* (f@ a 2) (f@ b 2))))
+215
+216
;;; Right-handed cross product: x cross y is z.
+217
(define (vec3-cross! dst a b)
+218
(let ((ax (f@ a 0)) (ay (f@ a 1)) (az (f@ a 2))
+219
(bx (f@ b 0)) (by (f@ b 1)) (bz (f@ b 2)))
+220
(vec3-set! dst
+221
(- (* ay bz) (* az by))
+222
(- (* az bx) (* ax bz))
+223
(- (* ax by) (* ay bx)))))
+224
(define (vec3-cross a b) (vec3-cross! (make-vec3) a b))
+225
+226
(define (vec3-length-squared v) (vec3-dot v v))
+227
(define (vec3-length v) (sqrt (vec3-dot v v)))
+228
(define (vec3-distance-squared a b)
+229
(let ((dx (- (f@ a 0) (f@ b 0))) (dy (- (f@ a 1) (f@ b 1))) (dz (- (f@ a 2) (f@ b 2))))
+230
(+ (* dx dx) (* dy dy) (* dz dz))))
+231
(define (vec3-distance a b) (sqrt (vec3-distance-squared a b)))
+232
+233
;;; Unit-length copy of `v`. A zero vector stays zero.
+234
(define (vec3-normalize! dst v)
+235
(let ((len (vec3-length v)))
+236
(if (> len 0.0)
+237
(vec3-scale! dst v (/ 1.0 len))
+238
(vec3-set! dst 0.0 0.0 0.0))))
+239
(define (vec3-normalize v) (vec3-normalize! (make-vec3) v))
+240
+241
;;; `a + (b - a) * t`.
+242
(define (vec3-lerp! dst a b t)
+243
(let ((ax (f@ a 0)) (ay (f@ a 1)) (az (f@ a 2)))
+244
(vec3-set! dst
+245
(+ ax (* (- (f@ b 0) ax) t))
+246
(+ ay (* (- (f@ b 1) ay) t))
+247
(+ az (* (- (f@ b 2) az) t)))))
+248
(define (vec3-lerp a b t) (vec3-lerp! (make-vec3) a b t))
+249
+250
;;; Component-wise minimum (for growing a bounding box).
+251
(define (vec3-min! dst a b)
+252
(vec3-set! dst (min (f@ a 0) (f@ b 0)) (min (f@ a 1) (f@ b 1)) (min (f@ a 2) (f@ b 2))))
+253
(define (vec3-min a b) (vec3-min! (make-vec3) a b))
+254
+255
;;; Component-wise maximum.
+256
(define (vec3-max! dst a b)
+257
(vec3-set! dst (max (f@ a 0) (f@ b 0)) (max (f@ a 1) (f@ b 1)) (max (f@ a 2) (f@ b 2))))
+258
(define (vec3-max a b) (vec3-max! (make-vec3) a b))
+259
+260
(define (vec3-approx=? a b . eps)
+261
(let ((e (eps-of eps)))
+262
(and (float-approx=? (f@ a 0) (f@ b 0) e)
+263
(float-approx=? (f@ a 1) (f@ b 1) e)
+264
(float-approx=? (f@ a 2) (f@ b 2) e))))
+265
+266
(define (vec3->list v) (list (f@ v 0) (f@ v 1) (f@ v 2)))
+267
+268
;; ------------------------------------------------------------
+269
;; vec4
+270
;; ------------------------------------------------------------
+271
+272
;;; A new vec4 holding `x`, `y`, `z` and `w`.
+273
(define (vec4 x y z w)
+274
(let ((v (make-bytevector 16 0)))
+275
(f! v 0 x) (f! v 1 y) (f! v 2 z) (f! v 3 w)
+276
v))
+277
+278
;;; A new vec4 of zeros.
+279
(define (make-vec4) (make-bytevector 16 0))
+280
+281
;;; True for a bytevector of vec4 size (16 bytes). A quaternion has
+282
;;; the same size and also passes.
+283
(define (vec4? v) (and (bytevector? v) (= (bytevector-length v) 16)))
+284
+285
(define (vec4-x v) (f@ v 0))
+286
(define (vec4-y v) (f@ v 1))
+287
(define (vec4-z v) (f@ v 2))
+288
(define (vec4-w v) (f@ v 3))
+289
+290
;;; Set all four components of `v`; returns `v`.
+291
(define (vec4-set! v x y z w) (f! v 0 x) (f! v 1 y) (f! v 2 z) (f! v 3 w) v)
+292
+293
(define (vec4-copy v) (vec4-copy! (make-vec4) v))
+294
(define (vec4-copy! dst v) (vec4-set! dst (f@ v 0) (f@ v 1) (f@ v 2) (f@ v 3)))
+295
+296
(define (vec4-add! dst a b)
+297
(vec4-set! dst
+298
(+ (f@ a 0) (f@ b 0)) (+ (f@ a 1) (f@ b 1))
+299
(+ (f@ a 2) (f@ b 2)) (+ (f@ a 3) (f@ b 3))))
+300
(define (vec4-add a b) (vec4-add! (make-vec4) a b))
+301
+302
(define (vec4-sub! dst a b)
+303
(vec4-set! dst
+304
(- (f@ a 0) (f@ b 0)) (- (f@ a 1) (f@ b 1))
+305
(- (f@ a 2) (f@ b 2)) (- (f@ a 3) (f@ b 3))))
+306
(define (vec4-sub a b) (vec4-sub! (make-vec4) a b))
+307
+308
;;; Component-wise product.
+309
(define (vec4-mul! dst a b)
+310
(vec4-set! dst
+311
(* (f@ a 0) (f@ b 0)) (* (f@ a 1) (f@ b 1))
+312
(* (f@ a 2) (f@ b 2)) (* (f@ a 3) (f@ b 3))))
+313
(define (vec4-mul a b) (vec4-mul! (make-vec4) a b))
+314
+315
(define (vec4-scale! dst v s)
+316
(vec4-set! dst (* (f@ v 0) s) (* (f@ v 1) s) (* (f@ v 2) s) (* (f@ v 3) s)))
+317
(define (vec4-scale v s) (vec4-scale! (make-vec4) v s))
+318
+319
(define (vec4-negate! dst v)
+320
(vec4-set! dst (- (f@ v 0)) (- (f@ v 1)) (- (f@ v 2)) (- (f@ v 3))))
+321
(define (vec4-negate v) (vec4-negate! (make-vec4) v))
+322
+323
(define (vec4-dot a b)
+324
(+ (* (f@ a 0) (f@ b 0)) (* (f@ a 1) (f@ b 1))
+325
(* (f@ a 2) (f@ b 2)) (* (f@ a 3) (f@ b 3))))
+326
(define (vec4-length-squared v) (vec4-dot v v))
+327
(define (vec4-length v) (sqrt (vec4-dot v v)))
+328
+329
;;; Unit-length copy of `v`. A zero vector stays zero.
+330
(define (vec4-normalize! dst v)
+331
(let ((len (vec4-length v)))
+332
(if (> len 0.0)
+333
(vec4-scale! dst v (/ 1.0 len))
+334
(vec4-set! dst 0.0 0.0 0.0 0.0))))
+335
(define (vec4-normalize v) (vec4-normalize! (make-vec4) v))
+336
+337
;;; `a + (b - a) * t`.
+338
(define (vec4-lerp! dst a b t)
+339
(let ((ax (f@ a 0)) (ay (f@ a 1)) (az (f@ a 2)) (aw (f@ a 3)))
+340
(vec4-set! dst
+341
(+ ax (* (- (f@ b 0) ax) t))
+342
(+ ay (* (- (f@ b 1) ay) t))
+343
(+ az (* (- (f@ b 2) az) t))
+344
(+ aw (* (- (f@ b 3) aw) t)))))
+345
(define (vec4-lerp a b t) (vec4-lerp! (make-vec4) a b t))
+346
+347
(define (vec4-approx=? a b . eps)
+348
(let ((e (eps-of eps)))
+349
(and (float-approx=? (f@ a 0) (f@ b 0) e)
+350
(float-approx=? (f@ a 1) (f@ b 1) e)
+351
(float-approx=? (f@ a 2) (f@ b 2) e)
+352
(float-approx=? (f@ a 3) (f@ b 3) e))))
+353
+354
(define (vec4->list v) (list (f@ v 0) (f@ v 1) (f@ v 2) (f@ v 3)))))
test/test-camera.sgladded
@@ -0,0 +1,109 @@
+1
;;; Tests for (sigil geometry camera)
+2
;;;
+3
;;; Reference matrices were computed in numpy (float64) straight from the
+4
;;; gluPerspective, glOrtho and gluLookAt definitions, then rounded to 9
+5
;;; places. They are written here column by column.
+6
+7
(import (sigil test)
+8
(sigil geometry))
+9
+10
(define (assert-mat4 expected actual)
+11
(unless (mat4-approx=? expected actual)
+12
(assert-equal (mat4->list expected) (mat4->list actual))))
+13
+14
(define (assert-vec3 expected actual)
+15
(unless (vec3-approx=? expected actual)
+16
(assert-equal (vec3->list expected) (vec3->list actual))))
+17
+18
(test-group "perspective"
+19
(test "60 degrees, 16:9, near 0.1, far 100"
+20
(assert-mat4 (mat4 0.974278579 0 0 0
+21
0 1.732050808 0 0
+22
0 0 -1.002002002 -1
+23
0 0 -0.2002002 0)
+24
(mat4-perspective (degrees->radians 60) (/ 16.0 9.0) 0.1 100)))
+25
+26
(test "90 degrees, square, near 1, far 3"
+27
(assert-mat4 (mat4 1 0 0 0 0 1 0 0 0 0 -2 -1 0 0 -3 0)
+28
(mat4-perspective (degrees->radians 90) 1 1 3)))
+29
+30
(test "near and far planes map to NDC z -1 and +1"
+31
(let ((p (mat4-perspective (degrees->radians 70) 1.5 0.5 40)))
+32
(assert-true (float-approx=? -1.0 (vec3-z (mat4-transform-point p (vec3 0 0 -0.5)))))
+33
(assert-true (float-approx=? 1.0 (vec3-z (mat4-transform-point p (vec3 0 0 -40)))))))
+34
+35
(test "the top edge of the view maps to NDC y = 1"
+36
;; at distance 1 with fovy 90 degrees the top edge is y = 1
+37
(let ((p (mat4-perspective (degrees->radians 90) 1 0.1 10)))
+38
(assert-vec3 (vec3 0 1 (vec3-z (mat4-transform-point p (vec3 0 1 -1))))
+39
(mat4-transform-point p (vec3 0 1 -1)))))
+40
+41
(test "bad arguments raise"
+42
(assert-error (mat4-perspective 0 1 0.1 10))
+43
(assert-error (mat4-perspective 1 0 0.1 10))
+44
(assert-error (mat4-perspective 1 1 0 10))
+45
(assert-error (mat4-perspective 1 1 5 5))
+46
(assert-error (mat4-perspective 4 1 0.1 10)))
+47
+48
(test "! form writes into dst"
+49
(let ((dst (make-mat4)))
+50
(assert-true (eq? dst (mat4-perspective! dst 1.0 1.0 1.0 2.0)))
+51
(assert-mat4 (mat4-perspective 1.0 1.0 1.0 2.0) dst))))
+52
+53
(test-group "orthographic"
+54
(test "a 480x270 screen box"
+55
(assert-mat4 (mat4 0.004166667 0 0 0
+56
0 0.007407407 0 0
+57
0 0 -1 0
+58
-1 -1 0 1)
+59
(mat4-orthographic 0 480 0 270 -1 1)))
+60
+61
(test "the unit box only flips z"
+62
(assert-mat4 (mat4 1 0 0 0 0 1 0 0 0 0 -1 0 0 0 0 1)
+63
(mat4-orthographic -1 1 -1 1 -1 1)))
+64
+65
(test "coincident planes raise"
+66
(assert-error (mat4-orthographic 1 1 0 1 0 1))))
+67
+68
(test-group "look-at"
+69
(test "gl-matrix's reference case"
+70
(assert-mat4 (mat4 1 0 0 0 0 0 1 0 0 -1 0 0 0 0 -2 1)
+71
(mat4-look-at (vec3 0 2 0) (vec3 0 0.6 0) (vec3 0 0 -1))))
+72
+73
(test "a camera on +Z looking at the origin is a pure translation"
+74
(assert-mat4 (mat4-translation (vec3 0 0 -5))
+75
(mat4-look-at (vec3 0 0 5) (vec3 0 0 0) (vec3 0 1 0))))
+76
+77
(test "z-up camera"
+78
(assert-mat4 (mat4 0.8 0 -0.6 0 -0.6 0 -0.8 0 0 1 0 0 0.4 -3 2.2 1)
+79
(mat4-look-at (vec3 1 2 3) (vec3 4 6 3) (vec3 0 0 1))))
+80
+81
(test "an oblique camera"
+82
(assert-mat4 (mat4 0.6 -0.458769875 0.655385536 0
+83
0 0.819231921 0.573462344 0
+84
-0.8 -0.344077407 0.491539152 0
+85
2.2 -0.180231023 -6.717701748 1)
+86
(mat4-look-at (vec3 3 4 5) (vec3 -1 0.5 2) (vec3 0 1 0))))
+87
+88
(test "the target lands on -Z at its distance"
+89
(let* ((eye (vec3 3 4 5)) (target (vec3 -1 0.5 2))
+90
(v (mat4-look-at eye target (vec3 0 1 0))))
+91
(assert-vec3 (vec3 0 0 (- (vec3-distance eye target)))
+92
(mat4-transform-point v target))))
+93
+94
(test "eye equal to target gives the identity"
+95
(assert-mat4 (make-mat4) (mat4-look-at (vec3 1 1 1) (vec3 1 1 1) (vec3 0 1 0))))
+96
+97
(test "looking straight down still gives a rotation"
+98
(let ((v (mat4-look-at (vec3 0 10 0) (vec3 0 0 0) (vec3 0 1 0))))
+99
(assert-true (float-approx=? 1.0 (mat4-determinant v)))
+100
(assert-vec3 (vec3 0 0 -10) (mat4-transform-point v (vec3 0 0 0))))))
+101
+102
(test-group "a whole camera"
+103
(test "view-projection puts the target at the centre of the screen"
+104
(let* ((proj (mat4-perspective (degrees->radians 70) (/ 480.0 270.0) 0.1 100))
+105
(view (mat4-look-at (vec3 2 1.7 6) (vec3 0 1 0) (vec3 0 1 0)))
+106
(ndc (mat4-transform-point (mat4-mul proj view) (vec3 0 1 0))))
+107
(assert-true (float-approx=? 0.0 (vec3-x ndc)))
+108
(assert-true (float-approx=? 0.0 (vec3-y ndc)))
+109
(assert-true (< -1.0 (vec3-z ndc) 1.0)))))
test/test-facade.sgladded
@@ -0,0 +1,48 @@
+1
;;; (sigil geometry) must re-export every export of the six modules.
+2
;;;
+3
;;; Reads the export lists from source (run from the package root, as
+4
;;; `sigil test` does) and compares them as sets.
+5
+6
(import (sigil test)
+7
(sigil io)
+8
(sigil fs)
+9
(sigil geometry))
+10
+11
(define module-files
+12
'("src/sigil/geometry/vec.sgl"
+13
"src/sigil/geometry/mat3.sgl"
+14
"src/sigil/geometry/mat4.sgl"
+15
"src/sigil/geometry/quat.sgl"
+16
"src/sigil/geometry/camera.sgl"
+17
"src/sigil/geometry/ray.sgl"))
+18
+19
(define (exports-of path)
+20
(let* ((lib (read (open-input-string (read-file-string path))))
+21
(clause (assq 'export (cddr lib))))
+22
(if clause (cdr clause) '())))
+23
+24
(define (missing from in)
+25
(filter (lambda (name) (not (memq name in))) from))
+26
+27
(test-group "facade"
+28
(test "the module files are where the test expects"
+29
(for-each (lambda (f) (assert-true (file-exists? f))) module-files)
+30
(assert-true (> (length (exports-of "src/sigil/geometry/mat4.sgl")) 10)))
+31
+32
(test "every module export is re-exported"
+33
(let ((facade (exports-of "src/sigil/geometry.sgl"))
+34
(all (apply append (map exports-of module-files))))
+35
(assert-equal '() (missing all facade))))
+36
+37
(test "the facade exports nothing the modules lack"
+38
(let ((facade (exports-of "src/sigil/geometry.sgl"))
+39
(all (apply append (map exports-of module-files))))
+40
(assert-equal '() (missing facade all))))
+41
+42
(test "names from each module resolve through the facade"
+43
(assert-true (procedure? vec3-cross!))
+44
(assert-true (procedure? mat3->std140!))
+45
(assert-true (procedure? mat4-inverse!))
+46
(assert-true (procedure? quat-slerp!))
+47
(assert-true (procedure? mat4-look-at!))
+48
(assert-true (procedure? ray-triangle-hit!))))
test/test-layout.sgladded
@@ -0,0 +1,69 @@
+1
;;; The byte layout contract with GPU consumers (sigil-graphics).
+2
;;;
+3
;;; These tests pin the representation, not the maths: sizes, float32
+4
;;; storage, column-major order, and native byte order. A change that
+5
;;; breaks one of them breaks every shader fed by this package.
+6
+7
(import (sigil test)
+8
(sigil geometry))
+9
+10
(define (floats bv)
+11
(let loop ((i (- (quotient-4 (bytevector-length bv)) 1)) (acc '()))
+12
(if (< i 0) acc (loop (- i 1) (cons (bytevector-ieee-single-ref bv (* 4 i)) acc)))))
+13
+14
;; `quotient` is not bound on this Sigil's toplevel; sizes here are
+15
;; multiples of 4.
+16
(define (quotient-4 n) (let loop ((k 0) (r n)) (if (< r 4) k (loop (+ k 1) (- r 4)))))
+17
+18
(test-group "sizes"
+19
(test "every value is a bytevector of 4-byte floats"
+20
(assert-equal 8 (bytevector-length (make-vec2)))
+21
(assert-equal 12 (bytevector-length (make-vec3)))
+22
(assert-equal 16 (bytevector-length (make-vec4)))
+23
(assert-equal 16 (bytevector-length (make-quat)))
+24
(assert-equal 36 (bytevector-length (make-mat3)))
+25
(assert-equal 64 (bytevector-length (make-mat4)))
+26
(assert-equal 48 (bytevector-length (mat3->std140 (make-mat3))))))
+27
+28
(test-group "column-major"
+29
(test "mat4 translation is floats 12 13 14"
+30
(assert-equal '(1.0 0.0 0.0 0.0 0.0 1.0 0.0 0.0 0.0 0.0 1.0 0.0 7.0 8.0 9.0 1.0)
+31
(floats (mat4-translation (vec3 7 8 9)))))
+32
+33
(test "the perspective -1 is float 11 (column 2, row 3)"
+34
(let ((p (floats (mat4-perspective 1.0 1.0 1.0 10.0))))
+35
(assert-equal -1.0 (list-ref p 11))
+36
;; row-major storage would put the -1 here instead
+37
(assert-true (float-approx=? (/ 20.0 -9.0) (list-ref p 14)))
+38
(assert-equal 0.0 (list-ref p 15))))
+39
+40
(test "mat3 column c row r is float 3c + r"
+41
(let ((m (make-mat3)))
+42
(mat3-set! m 2 0 5.0)
+43
(assert-equal 5.0 (list-ref (floats m) 6)))))
+44
+45
(test-group "float32 storage"
+46
(test "writes round to float32"
+47
(assert-equal 0.10000000149011612 (vec3-x (vec3 0.1 0 0))))
+48
+49
(test "the bytes are IEEE-754 single precision"
+50
;; 1.0f is 0x3F800000
+51
(let ((v (vec3 1 0 0)))
+52
(assert-equal #x3F800000
+53
(+ (* 16777216 (bytevector-u8-ref v (if (little-host?) 3 0)))
+54
(* 65536 (bytevector-u8-ref v (if (little-host?) 2 1)))
+55
(* 256 (bytevector-u8-ref v (if (little-host?) 1 2)))
+56
(bytevector-u8-ref v (if (little-host?) 0 3)))))))
+57
+58
(define (little-host?)
+59
(let ((b (make-bytevector 4 0)))
+60
(bytevector-ieee-single-set! b 0 1.0)
+61
(= (bytevector-u8-ref b 3) #x3F)))
+62
+63
(test-group "byte order"
+64
(test "values are stored in native byte order"
+65
(let ((v (vec4 1.5 -2 3 4))
+66
(native (make-bytevector 16 0)))
+67
(for-each (lambda (i x) (bytevector-ieee-single-set! native (* 4 i) x))
+68
'(0 1 2 3) '(1.5 -2 3 4))
+69
(assert-equal native v))))
test/test-mat3.sgladded
@@ -0,0 +1,85 @@
+1
;;; Tests for (sigil geometry mat3)
+2
+3
(import (sigil test)
+4
(sigil geometry))
+5
+6
(define (assert-mat3 expected actual)
+7
(unless (mat3-approx=? expected actual)
+8
(assert-equal (mat3->list expected) (mat3->list actual))))
+9
+10
(define (assert-vec3 expected actual)
+11
(unless (vec3-approx=? expected actual)
+12
(assert-equal (vec3->list expected) (vec3->list actual))))
+13
+14
;; Rows (2 0 1) (1 3 2) (1 1 2). numpy (float64): det = 6, and the
+15
;; inverse is 1/6 times rows (4 1 -3) (0 3 -3) (-2 -2 6).
+16
(define fixture3 (list->mat3 '(2 1 1 0 3 1 1 2 2)))
+17
+18
(test-group "mat3"
+19
(test "identity and layout"
+20
(assert-equal '(1.0 0.0 0.0 0.0 1.0 0.0 0.0 0.0 1.0) (mat3->list (make-mat3)))
+21
(assert-equal 36 (bytevector-length (make-mat3)))
+22
(assert-true (= 5.0 (mat3-ref (mat3 1 2 3 4 5 6 7 8 9) 1 1)))
+23
(assert-true (= 7.0 (mat3-ref (mat3 1 2 3 4 5 6 7 8 9) 2 0))))
+24
+25
(test "multiply"
+26
;; rows of a: (1 2 3) (4 5 6) (7 8 9); a*a rows: (30 36 42) (66 81 96)
+27
;; (102 126 150)
+28
(let ((a (mat3 1 4 7 2 5 8 3 6 9)))
+29
(assert-mat3 (mat3 30 66 102 36 81 126 42 96 150) (mat3-mul a a))
+30
(mat3-mul! a a a)
+31
(assert-mat3 (mat3 30 66 102 36 81 126 42 96 150) a)))
+32
+33
(test "transpose"
+34
(assert-mat3 (mat3 1 4 7 2 5 8 3 6 9) (mat3-transpose (mat3 1 2 3 4 5 6 7 8 9))))
+35
+36
(test "determinant and inverse"
+37
(assert-true (float-approx=? 6.0 (mat3-determinant fixture3)))
+38
(assert-mat3 (mat3 0.666666667 0 -0.333333333
+39
0.166666667 0.5 -0.333333333
+40
-0.5 -0.5 1)
+41
(mat3-inverse fixture3))
+42
(assert-mat3 (make-mat3) (mat3-mul (mat3-inverse fixture3) fixture3))
+43
(assert-mat3 (make-mat3) (mat3-mul fixture3 (mat3-inverse fixture3))))
+44
+45
(test "singular gives #f and leaves dst alone"
+46
(let ((dst (mat3 9 9 9 9 9 9 9 9 9)))
+47
(assert-false (mat3-inverse! dst (mat3 1 2 3 2 4 6 0 0 1)))
+48
(assert-mat3 (mat3 9 9 9 9 9 9 9 9 9) dst)))
+49
+50
(test "from-mat4 takes the upper-left 3x3"
+51
(let ((r (mat4-rotation (vec3 1 1 0) 0.5)))
+52
(assert-mat3 (mat3 (mat4-ref r 0 0) (mat4-ref r 0 1) (mat4-ref r 0 2)
+53
(mat4-ref r 1 0) (mat4-ref r 1 1) (mat4-ref r 1 2)
+54
(mat4-ref r 2 0) (mat4-ref r 2 1) (mat4-ref r 2 2))
+55
(mat3-from-mat4 (mat4-mul (mat4-translation (vec3 4 5 6)) r)))))
+56
+57
(test "normal matrix of a rotation is the rotation"
+58
(let ((r (mat4-rotation (vec3 0 1 1) 1.2)))
+59
(assert-mat3 (mat3-from-mat4 r) (mat3-normal-matrix r))))
+60
+61
(test "normal matrix keeps normals perpendicular under non-uniform scale"
+62
;; A surface along the line x = y in the xy plane has normal (1 -1 0)/..
+63
;; After scaling x by 4 its tangent (1 1 0) becomes (4 1 0); the
+64
;; transformed normal must stay perpendicular to it.
+65
(let* ((model (mat4-scaling (vec3 4 1 1)))
+66
(n (mat3-transform-vec3 (mat3-normal-matrix model) (vec3 1 -1 0)))
+67
(tangent (mat4-transform-direction model (vec3 1 1 0))))
+68
(assert-true (float-approx=? 0.0 (vec3-dot n tangent)))))
+69
+70
(test "from-quat matches mat4-from-quat"
+71
(let ((q (quat-from-axis-angle (vec3 1 2 3) 0.8)))
+72
(assert-mat3 (mat3-from-mat4 (mat4-from-quat q)) (mat3-from-quat q))))
+73
+74
(test "transform-vec3"
+75
(assert-vec3 (vec3 14 32 50)
+76
(mat3-transform-vec3 (mat3 1 4 7 2 5 8 3 6 9) (vec3 1 2 3))))
+77
+78
(test "std140 pads each column to four floats"
+79
(let ((p (mat3->std140 (mat3 1 2 3 4 5 6 7 8 9))))
+80
(assert-equal 48 (bytevector-length p))
+81
(assert-equal '(1.0 2.0 3.0 0.0 4.0 5.0 6.0 0.0 7.0 8.0 9.0 0.0)
+82
(let loop ((i 11) (acc '()))
+83
(if (< i 0)
+84
acc
+85
(loop (- i 1) (cons (bytevector-ieee-single-ref p (* 4 i)) acc))))))))
test/test-mat4.sgladded
@@ -0,0 +1,185 @@
+1
;;; Tests for (sigil geometry mat4)
+2
+3
(import (sigil test)
+4
(sigil geometry))
+5
+6
(define pi 3.141592653589793)
+7
+8
(define (assert-mat4 expected actual)
+9
(unless (mat4-approx=? expected actual)
+10
(assert-equal (mat4->list expected) (mat4->list actual))))
+11
+12
(define (assert-vec3 expected actual)
+13
(unless (vec3-approx=? expected actual)
+14
(assert-equal (vec3->list expected) (vec3->list actual))))
+15
+16
(define (assert-float expected actual)
+17
(unless (float-approx=? expected actual)
+18
(assert-equal expected actual)))
+19
+20
;; A matrix with no special structure, used by several tests. Its rows are
+21
;; (2 0 1 3) (1 1 0 2) (0 3 1 1) (1 0 2 1). Reference values from numpy
+22
;; (float64): det = -1, and the inverse has integer rows
+23
;; (-11 15 -5 8) (-3 4 -1 2) (2 -3 1 -1) (7 -9 3 -5).
+24
(define general
+25
(list->mat4 '(2 1 0 1 0 1 3 0 1 0 1 2 3 2 1 1)))
+26
+27
(test-group "mat4 - construction"
+28
(test "make-mat4 and mat4-identity are the identity"
+29
(assert-equal '(1.0 0.0 0.0 0.0 0.0 1.0 0.0 0.0 0.0 0.0 1.0 0.0 0.0 0.0 0.0 1.0)
+30
(mat4->list (make-mat4)))
+31
(assert-mat4 (make-mat4) (mat4-identity)))
+32
+33
(test "mat4 takes values in column-major order"
+34
(let ((m (mat4 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16)))
+35
;; column 1, row 0 is the fifth value
+36
(assert-float 5.0 (mat4-ref m 1 0))
+37
(assert-float 4.0 (mat4-ref m 0 3))
+38
(assert-float 15.0 (mat4-ref m 3 2))))
+39
+40
(test "mat4-set! addresses (column, row)"
+41
(let ((m (make-mat4)))
+42
(mat4-set! m 3 0 7.5)
+43
(assert-float 7.5 (list-ref (mat4->list m) 12))))
+44
+45
(test "list->mat4 rejects the wrong length"
+46
(assert-error (list->mat4 '(1 2 3))))
+47
+48
(test "copy is independent"
+49
(let* ((a (mat4-translation (vec3 1 2 3))) (b (mat4-copy a)))
+50
(mat4-identity! a)
+51
(assert-float 1.0 (mat4-ref b 3 0))
+52
(assert-true (eq? a (mat4-copy! a a))))))
+53
+54
(test-group "mat4 - multiply and transpose"
+55
(test "identity is neutral"
+56
(assert-mat4 general (mat4-mul (make-mat4) general))
+57
(assert-mat4 general (mat4-mul general (make-mat4))))
+58
+59
(test "known product"
+60
;; Rows of a: (1 2 3 4) (5 6 7 8) (9 10 11 12) (13 14 15 16); b = a.
+61
;; a*a rows: (90 100 110 120) (202 228 254 280) (314 356 398 440)
+62
;; (426 484 542 600).
+63
(let ((a (mat4 1 5 9 13 2 6 10 14 3 7 11 15 4 8 12 16)))
+64
(assert-mat4 (mat4 90 202 314 426 100 228 356 484 110 254 398 542 120 280 440 600)
+65
(mat4-mul a a))))
+66
+67
(test "mul applies the right-hand matrix first"
+68
(let ((tr (mat4-translation (vec3 10 0 0)))
+69
(sc (mat4-scaling (vec3 2 2 2)))
+70
(p (vec3 1 1 1)))
+71
;; scale, then translate
+72
(assert-vec3 (vec3 12 2 2) (mat4-transform-point (mat4-mul tr sc) p))
+73
;; translate, then scale
+74
(assert-vec3 (vec3 22 2 2) (mat4-transform-point (mat4-mul sc tr) p))))
+75
+76
(test "mul! with dst aliasing either input"
+77
(let ((expected (mat4-mul general (mat4-rotation-x 0.3))))
+78
(let ((a (mat4-copy general)))
+79
(mat4-mul! a a (mat4-rotation-x 0.3))
+80
(assert-mat4 expected a))
+81
(let ((b (mat4-rotation-x 0.3)))
+82
(mat4-mul! b general b)
+83
(assert-mat4 expected b)))
+84
(let ((sq (mat4-mul general general)) (a (mat4-copy general)))
+85
(mat4-mul! a a a)
+86
(assert-mat4 sq a)))
+87
+88
(test "transpose"
+89
(assert-mat4 (mat4 1 5 9 13 2 6 10 14 3 7 11 15 4 8 12 16)
+90
(mat4-transpose (mat4 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16)))
+91
(let ((a (mat4-copy general)))
+92
(mat4-transpose! a a)
+93
(assert-mat4 (mat4-transpose general) a))))
+94
+95
(test-group "mat4 - determinant and inverse"
+96
(test "determinant"
+97
(assert-float 1.0 (mat4-determinant (make-mat4)))
+98
(assert-float 24.0 (mat4-determinant (mat4-scaling (vec3 2 3 4))))
+99
(assert-float -1.0 (mat4-determinant general)))
+100
+101
(test "inverse of a known matrix"
+102
;; numpy.linalg.inv(general), written column by column
+103
(let ((inv (mat4-inverse general)))
+104
(assert-mat4 (mat4 -11 -3 2 7 15 4 -3 -9 -5 -1 1 3 8 2 -1 -5) inv)
+105
(assert-mat4 (make-mat4) (mat4-mul inv general))
+106
(assert-mat4 (make-mat4) (mat4-mul general inv))))
+107
+108
(test "inverse of a translation is the opposite translation"
+109
(assert-mat4 (mat4-translation (vec3 -1 -2 -3))
+110
(mat4-inverse (mat4-translation (vec3 1 2 3)))))
+111
+112
(test "inverse of a scale"
+113
(assert-mat4 (mat4-scaling (vec3 0.5 0.25 0.125))
+114
(mat4-inverse (mat4-scaling (vec3 2 4 8)))))
+115
+116
(test "inverse of a rotation is its transpose"
+117
(let ((r (mat4-rotation (vec3 1 2 3) 0.7)))
+118
(assert-mat4 (mat4-transpose r) (mat4-inverse r))))
+119
+120
(test "singular matrix gives #f and leaves dst alone"
+121
(let ((dst (mat4-translation (vec3 5 6 7)))
+122
(singular (mat4-scaling (vec3 1 0 1))))
+123
(assert-false (mat4-inverse! dst singular))
+124
(assert-mat4 (mat4-translation (vec3 5 6 7)) dst)
+125
(assert-false (mat4-inverse (make-bytevector 64 0)))))
+126
+127
(test "inverse! in place"
+128
(let ((a (mat4-copy general)))
+129
(assert-true (eq? a (mat4-inverse! a a)))
+130
(assert-mat4 (make-mat4) (mat4-mul a general)))))
+131
+132
(test-group "mat4 - builders"
+133
(test "translation sits in floats 12, 13, 14"
+134
(let ((m (mat4-translation (vec3 1 2 3))))
+135
(assert-equal '(1.0 2.0 3.0 1.0)
+136
(map (lambda (i) (bytevector-ieee-single-ref m (* 4 i))) '(12 13 14 15)))
+137
(assert-vec3 (vec3 1 2 3) (mat4-get-translation m))))
+138
+139
(test "rotation-x turns y toward z"
+140
(assert-vec3 (vec3 0 0 1) (mat4-transform-direction (mat4-rotation-x (/ pi 2)) (vec3 0 1 0))))
+141
+142
(test "rotation-y turns z toward x"
+143
(assert-vec3 (vec3 1 0 0) (mat4-transform-direction (mat4-rotation-y (/ pi 2)) (vec3 0 0 1))))
+144
+145
(test "rotation-z turns x toward y"
+146
(assert-vec3 (vec3 0 1 0) (mat4-transform-direction (mat4-rotation-z (/ pi 2)) (vec3 1 0 0))))
+147
+148
(test "axis rotation matches the single-axis builders"
+149
(assert-mat4 (mat4-rotation-x 0.4) (mat4-rotation (vec3 1 0 0) 0.4))
+150
(assert-mat4 (mat4-rotation-y 0.4) (mat4-rotation (vec3 0 2 0) 0.4))
+151
(assert-mat4 (mat4-rotation-z -1.1) (mat4-rotation (vec3 0 0 5) -1.1)))
+152
+153
(test "a zero axis gives the identity"
+154
(assert-mat4 (make-mat4) (mat4-rotation (make-vec3) 1.0)))
+155
+156
(test "from-trs is translation * rotation * scale"
+157
(let ((t (vec3 1 2 3))
+158
(q (quat-from-axis-angle (vec3 0 1 0) 0.9))
+159
(s (vec3 2 3 4)))
+160
(assert-mat4 (mat4-mul (mat4-translation t)
+161
(mat4-mul (mat4-from-quat q) (mat4-scaling s)))
+162
(mat4-from-trs t q s)))))
+163
+164
(test-group "mat4 - transforms"
+165
(test "transform-point applies translation"
+166
(assert-vec3 (vec3 11 2 3)
+167
(mat4-transform-point (mat4-translation (vec3 10 0 0)) (vec3 1 2 3))))
+168
+169
(test "transform-direction ignores translation"
+170
(assert-vec3 (vec3 1 2 3)
+171
(mat4-transform-direction (mat4-translation (vec3 10 0 0)) (vec3 1 2 3))))
+172
+173
(test "transform-point divides by w"
+174
;; w' = 2 for every point: the result is halved
+175
(let ((m (mat4 1 0 0 0 0 1 0 0 0 0 1 0 0 0 0 2)))
+176
(assert-vec3 (vec3 2 3 4) (mat4-transform-point m (vec3 4 6 8)))))
+177
+178
(test "transform-vec4 keeps w"
+179
(let ((r (mat4-transform-vec4 (mat4-translation (vec3 1 2 3)) (vec4 1 1 1 1))))
+180
(assert-equal '(2.0 3.0 4.0 1.0) (vec4->list r))))
+181
+182
(test "transform! forms may alias the input vector"
+183
(let ((p (vec3 1 2 3)))
+184
(mat4-transform-point! p (mat4-rotation-z (/ pi 2)) p)
+185
(assert-vec3 (vec3 -2 1 3) p))))
test/test-properties.sgladded
@@ -0,0 +1,166 @@
+1
;;; Property tests over deterministic pseudo-random inputs.
+2
;;;
+3
;;; A MINSTD generator with a fixed seed, so a failure reproduces
+4
;;; exactly. Each property runs over 200 cases and reports the first
+5
;;; failing case's inputs.
+6
+7
(import (sigil test)
+8
(sigil geometry))
+9
+10
(define cases 200)
+11
+12
;; MINSTD: s' = s * 48271 mod (2^31 - 1)
+13
(define seed 20260925)
+14
(define (next-unit!)
+15
(set! seed (modulo (* seed 48271) 2147483647))
+16
(/ seed 2147483647.0))
+17
+18
;; uniform in [lo, hi)
+19
(define (uniform lo hi) (+ lo (* (- hi lo) (next-unit!))))
+20
+21
(define (random-vec3 r) (vec3 (uniform (- r) r) (uniform (- r) r) (uniform (- r) r)))
+22
+23
;; A unit quaternion from a random vec4, skipping near-zero draws.
+24
(define (random-quat)
+25
(let ((q (quat (uniform -1 1) (uniform -1 1) (uniform -1 1) (uniform -1 1))))
+26
(if (< (quat-length q) 0.1)
+27
(random-quat)
+28
(quat-normalize q))))
+29
+30
;; A well-conditioned model matrix: translation within 10, any rotation,
+31
;; scale between 0.5 and 2 on each axis.
+32
(define (random-trs)
+33
(mat4-from-trs (random-vec3 10)
+34
(random-quat)
+35
(vec3 (uniform 0.5 2) (uniform 0.5 2) (uniform 0.5 2))))
+36
+37
(define (random-mat4)
+38
(let ((m (make-mat4)))
+39
(let loop ((i 0))
+40
(when (< i 16)
+41
(bytevector-ieee-single-set! m (* 4 i) (uniform -3 3))
+42
(loop (+ i 1))))
+43
m))
+44
+45
;; Run `check` on `cases` generated inputs; fail with the first bad input.
+46
(define (for-all generate check)
+47
(let loop ((i 0))
+48
(when (< i cases)
+49
(let ((input (generate)))
+50
(if (check input)
+51
(loop (+ i 1))
+52
(assert-equal (list 'case i 'holds) (list 'case i 'fails-for input)))))))
+53
+54
(define eps 1e-4)
+55
+56
(test-group "matrix properties"
+57
(test "inverse * m = identity and m * inverse = identity"
+58
(for-all random-trs
+59
(lambda (m)
+60
(let ((inv (mat4-inverse m)))
+61
(and inv
+62
(mat4-approx=? (make-mat4) (mat4-mul inv m) eps)
+63
(mat4-approx=? (make-mat4) (mat4-mul m inv) eps))))))
+64
+65
(test "inverse of a general matrix, when it has one"
+66
;; Near-singular draws amplify float32 error, so only draws with
+67
;; |det| >= 0.5 are held to the bound. `checked` counts them, and a
+68
;; floor makes sure the property did not pass by skipping everything.
+69
(let ((checked 0))
+70
(for-all random-mat4
+71
(lambda (m)
+72
(let ((inv (mat4-inverse m)))
+73
(or (not inv)
+74
(< (abs (mat4-determinant m)) 0.5)
+75
(begin
+76
(set! checked (+ checked 1))
+77
(mat4-approx=? (make-mat4) (mat4-mul inv m) 1e-3))))))
+78
(assert-true (>= checked 100))))
+79
+80
(test "mat3 inverse * m = identity"
+81
(for-all (lambda () (mat3-from-mat4 (random-trs)))
+82
(lambda (m)
+83
(mat3-approx=? (make-mat3) (mat3-mul (mat3-inverse m) m) eps))))
+84
+85
(test "transforming by a product equals transforming twice"
+86
(for-all (lambda () (list (random-trs) (random-trs) (random-vec3 5)))
+87
(lambda (in)
+88
(let ((a (car in)) (b (cadr in)) (p (caddr in)))
+89
(vec3-approx=? (mat4-transform-point (mat4-mul a b) p)
+90
(mat4-transform-point a (mat4-transform-point b p))
+91
eps)))))
+92
+93
(test "the transpose of a product is the product of transposes, reversed"
+94
(for-all (lambda () (list (random-mat4) (random-mat4)))
+95
(lambda (in)
+96
(let ((a (car in)) (b (cadr in)))
+97
(mat4-approx=? (mat4-transpose (mat4-mul a b))
+98
(mat4-mul (mat4-transpose b) (mat4-transpose a))
+99
eps))))))
+100
+101
(test-group "quaternion properties"
+102
(test "quat -> mat4 -> quat is the same rotation"
+103
(for-all random-quat
+104
(lambda (q) (quat-same-rotation? q (quat-from-mat4 (mat4-from-quat q)) eps))))
+105
+106
(test "quat -> mat3 -> quat is the same rotation"
+107
(for-all random-quat
+108
(lambda (q) (quat-same-rotation? q (quat-from-mat3 (mat3-from-quat q)) eps))))
+109
+110
(test "rotating by q equals transforming by its matrix"
+111
(for-all (lambda () (cons (random-quat) (random-vec3 5)))
+112
(lambda (in)
+113
(vec3-approx=? (quat-rotate-vec3 (car in) (cdr in))
+114
(mat4-transform-direction (mat4-from-quat (car in)) (cdr in))
+115
eps))))
+116
+117
(test "rotation keeps length"
+118
(for-all (lambda () (cons (random-quat) (random-vec3 5)))
+119
(lambda (in)
+120
(float-approx=? (vec3-length (cdr in))
+121
(vec3-length (quat-rotate-vec3 (car in) (cdr in)))
+122
eps))))
+123
+124
(test "slerp stays unit length and moves at constant angle"
+125
(for-all (lambda () (list (random-quat) (random-quat) (uniform 0 1)))
+126
(lambda (in)
+127
(let* ((a (car in)) (b (cadr in)) (t (caddr in))
+128
(s (quat-slerp a b t))
+129
(total (quat-angle (quat-mul (quat-conjugate a) b)))
+130
(part (quat-angle (quat-mul (quat-conjugate a) s))))
+131
(and (float-approx=? 1.0 (quat-length s) eps)
+132
(< (abs (- part (* t total))) 1e-3)))))))
+133
+134
(test-group "! forms agree with allocating forms, with dst aliased"
+135
(test "mat4-mul! into either input"
+136
(for-all (lambda () (list (random-mat4) (random-mat4)))
+137
(lambda (in)
+138
(let* ((a (car in)) (b (cadr in)) (expected (mat4-mul a b))
+139
(a2 (mat4-copy a)) (b2 (mat4-copy b)))
+140
(mat4-mul! a2 a2 b)
+141
(mat4-mul! b2 a b2)
+142
(and (mat4-approx=? expected a2 eps) (mat4-approx=? expected b2 eps))))))
+143
+144
(test "mat4-inverse! and mat3-inverse! in place"
+145
(for-all random-trs
+146
(lambda (m)
+147
(let ((expected (mat4-inverse m)) (m2 (mat4-copy m))
+148
(n (mat3-from-mat4 m)))
+149
(mat4-inverse! m2 m2)
+150
(let ((n-expected (mat3-inverse n)))
+151
(mat3-inverse! n n)
+152
(and (mat4-approx=? expected m2 eps)
+153
(mat3-approx=? n-expected n eps)))))))
+154
+155
(test "quat-mul!, quat-slerp! and vec3-cross! in place"
+156
(for-all (lambda () (list (random-quat) (random-quat) (random-vec3 3) (random-vec3 3)))
+157
(lambda (in)
+158
(let* ((qa (car in)) (qb (cadr in)) (u (caddr in)) (v (cadddr in))
+159
(mul (quat-mul qa qb)) (sl (quat-slerp qa qb 0.3)) (cr (vec3-cross u v))
+160
(qa2 (quat-copy qa)) (qb2 (quat-copy qb)) (u2 (vec3-copy u)))
+161
(quat-mul! qa2 qa2 qb)
+162
(quat-slerp! qb2 qa qb2 0.3)
+163
(vec3-cross! u2 u2 v)
+164
(and (quat-approx=? mul qa2 eps)
+165
(quat-approx=? sl qb2 eps)
+166
(vec3-approx=? cr u2 eps)))))))
test/test-quat.sgladded
@@ -0,0 +1,141 @@
+1
;;; Tests for (sigil geometry quat)
+2
+3
(import (sigil test)
+4
(sigil geometry))
+5
+6
(define pi 3.141592653589793)
+7
+8
(define (assert-vec3 expected actual)
+9
(unless (vec3-approx=? expected actual)
+10
(assert-equal (vec3->list expected) (vec3->list actual))))
+11
+12
(define (assert-quat expected actual)
+13
(unless (quat-approx=? expected actual)
+14
(assert-equal (quat->list expected) (quat->list actual))))
+15
+16
(define (assert-same-rotation expected actual)
+17
(unless (quat-same-rotation? expected actual)
+18
(assert-equal (quat->list expected) (quat->list actual))))
+19
+20
(define (assert-mat4 expected actual)
+21
(unless (mat4-approx=? expected actual)
+22
(assert-equal (mat4->list expected) (mat4->list actual))))
+23
+24
(define z-axis (vec3 0 0 1))
+25
+26
(define (quat-scale-neg q) (quat (- (quat-x q)) (- (quat-y q)) (- (quat-z q)) (- (quat-w q))))
+27
+28
;; Each case lands in a different branch of the matrix -> quaternion
+29
;; conversion: positive trace, then the largest diagonal element on x,
+30
;; y and z (rotations near pi have negative trace).
+31
(define rotation-cases
+32
(list (cons "positive trace" (quat-from-axis-angle (vec3 1 2 3) 0.5))
+33
(cons "x dominant" (quat-from-axis-angle (vec3 1 0 0) pi))
+34
(cons "y dominant" (quat-from-axis-angle (vec3 0.1 1 0.2) 3.0))
+35
(cons "z dominant" (quat-from-axis-angle (vec3 0 0.1 1) 3.1))
+36
(cons "identity" (make-quat))))
+37
+38
(define rot-0 (quat-from-axis-angle z-axis 0.0))
+39
(define rot-90 (quat-from-axis-angle z-axis (/ pi 2)))
+40
+41
(test-group "quat - construction"
+42
(test "identity"
+43
(assert-equal '(0.0 0.0 0.0 1.0) (quat->list (make-quat)))
+44
(assert-equal '(0.0 0.0 0.0 1.0) (quat->list (quat-identity))))
+45
+46
(test "axis-angle"
+47
;; 90 degrees about z: (0 0 sin 45 cos 45)
+48
(assert-quat (quat 0 0 0.70710678 0.70710678) (quat-from-axis-angle z-axis (/ pi 2)))
+49
;; the axis is normalized
+50
(assert-quat (quat-from-axis-angle z-axis 1.0) (quat-from-axis-angle (vec3 0 0 9) 1.0)))
+51
+52
(test "zero axis gives the identity"
+53
(assert-quat (make-quat) (quat-from-axis-angle (make-vec3) 2.0)))
+54
+55
(test "angle"
+56
(assert-true (float-approx=? 1.2 (quat-angle (quat-from-axis-angle (vec3 1 1 1) 1.2))))))
+57
+58
(test-group "quat - rotation"
+59
(test "rotate x by 90 degrees about z gives y"
+60
(assert-vec3 (vec3 0 1 0) (quat-rotate-vec3 (quat-from-axis-angle z-axis (/ pi 2)) (vec3 1 0 0))))
+61
+62
(test "same direction as mat4-rotation"
+63
(let ((axis (vec3 1 -2 0.5)) (v (vec3 0.3 4 -2)))
+64
(assert-vec3 (mat4-transform-direction (mat4-rotation axis 2.1) v)
+65
(quat-rotate-vec3 (quat-from-axis-angle axis 2.1) v))))
+66
+67
(test "mul applies the right-hand rotation first"
+68
(let ((qa (quat-from-axis-angle (vec3 1 0 0) 0.7))
+69
(qb (quat-from-axis-angle (vec3 0 1 0) -1.3))
+70
(v (vec3 1 2 3)))
+71
(assert-vec3 (quat-rotate-vec3 qa (quat-rotate-vec3 qb v))
+72
(quat-rotate-vec3 (quat-mul qa qb) v))
+73
(assert-mat4 (mat4-mul (mat4-from-quat qa) (mat4-from-quat qb))
+74
(mat4-from-quat (quat-mul qa qb)))))
+75
+76
(test "conjugate undoes a unit rotation"
+77
(let ((q (quat-from-axis-angle (vec3 2 1 -1) 0.9)))
+78
(assert-quat (make-quat) (quat-mul q (quat-conjugate q)))))
+79
+80
(test "inverse works for non-unit quaternions"
+81
(let ((q (quat 1 2 3 4)))
+82
(assert-quat (make-quat) (quat-mul q (quat-inverse q)))
+83
(assert-quat (make-quat) (quat-mul (quat-inverse q) q))))
+84
+85
(test "normalize"
+86
(assert-true (float-approx=? 1.0 (quat-length (quat-normalize (quat 1 2 3 4)))))
+87
(assert-quat (make-quat) (quat-normalize (quat 0 0 0 0))))
+88
+89
(test "mul! and rotate! may alias"
+90
(let* ((qa (quat-from-axis-angle (vec3 1 0 0) 0.7))
+91
(qb (quat-from-axis-angle (vec3 0 1 0) -1.3))
+92
(expected (quat-mul qa qb))
+93
(a (quat-copy qa)))
+94
(quat-mul! a a qb)
+95
(assert-quat expected a))
+96
(let ((v (vec3 1 0 0)))
+97
(quat-rotate-vec3! v (quat-from-axis-angle z-axis (/ pi 2)) v)
+98
(assert-vec3 (vec3 0 1 0) v))))
+99
+100
(test-group "quat - matrix round trips"
+101
(test "quat -> mat4 -> quat"
+102
(for-each (lambda (c)
+103
(assert-same-rotation (cdr c) (quat-from-mat4 (mat4-from-quat (cdr c)))))
+104
rotation-cases))
+105
+106
(test "quat -> mat3 -> quat"
+107
(for-each (lambda (c)
+108
(assert-same-rotation (cdr c) (quat-from-mat3 (mat3-from-quat (cdr c)))))
+109
rotation-cases))
+110
+111
(test "mat4 -> quat -> mat4"
+112
(for-each (lambda (m)
+113
(assert-mat4 m (mat4-from-quat (quat-from-mat4 m))))
+114
(list (mat4-rotation-x 0.3) (mat4-rotation-y 3.0) (mat4-rotation-z -2.9)
+115
(mat4-rotation (vec3 1 1 1) (* 2 (/ pi 3))))))
+116
+117
(test "quat-from-mat4 ignores translation"
+118
(let ((q (quat-from-axis-angle (vec3 0 1 0) 1.1)))
+119
(assert-same-rotation q (quat-from-mat4 (mat4-from-trs (vec3 5 6 7) q (vec3 1 1 1)))))))
+120
+121
(test-group "quat - interpolation"
+122
(test "slerp endpoints"
+123
(assert-quat rot-0 (quat-slerp rot-0 rot-90 0))
+124
(assert-quat rot-90 (quat-slerp rot-0 rot-90 1)))
+125
+126
(test "slerp midpoint is half the angle"
+127
(assert-quat (quat-from-axis-angle z-axis (/ pi 4)) (quat-slerp rot-0 rot-90 0.5))
+128
(assert-quat (quat-from-axis-angle z-axis (/ pi 8)) (quat-slerp rot-0 rot-90 0.25)))
+129
+130
(test "slerp takes the shorter arc"
+131
;; -b is the same rotation as b
+132
(assert-same-rotation (quat-slerp rot-0 rot-90 0.5)
+133
(quat-slerp rot-0 (quat-scale-neg rot-90) 0.5)))
+134
+135
(test "slerp of nearly equal rotations falls back to nlerp"
+136
(let ((c (quat-from-axis-angle z-axis 0.001)))
+137
(assert-same-rotation (quat-from-axis-angle z-axis 0.0005) (quat-slerp rot-0 c 0.5))))
+138
+139
(test "nlerp stays unit length"
+140
(assert-true (float-approx=? 1.0 (quat-length (quat-nlerp rot-0 rot-90 0.3))))))
+141
test/test-ray.sgladded
@@ -0,0 +1,142 @@
+1
;;; Tests for (sigil geometry ray)
+2
+3
(import (sigil test)
+4
(sigil geometry))
+5
+6
(define (assert-float expected actual)
+7
(unless (and actual (float-approx=? expected actual))
+8
(assert-equal expected actual)))
+9
+10
(define (assert-vec4 expected actual)
+11
(unless (vec4-approx=? expected actual)
+12
(assert-equal (vec4->list expected) (vec4->list actual))))
+13
+14
(define ground (vec4 0 1 0 0))
+15
+16
(define box-lo (vec3 -1 -1 -1))
+17
(define box-hi (vec3 1 1 1))
+18
+19
(define tri-a (vec3 0 0 0))
+20
(define tri-b (vec3 1 0 0))
+21
(define tri-c (vec3 0 1 0))
+22
+23
(test-group "planes"
+24
(test "from a point and a normal"
+25
(assert-vec4 (vec4 0 1 0 -2) (plane-from-point-normal (vec3 5 2 -7) (vec3 0 3 0))))
+26
+27
(test "from three counterclockwise points faces +z"
+28
(assert-vec4 (vec4 0 0 1 0) (plane-from-points tri-a tri-b tri-c))
+29
(assert-vec4 (vec4 0 0 -1 0) (plane-from-points tri-a tri-c tri-b)))
+30
+31
(test "degenerate input raises"
+32
(assert-error (plane-from-point-normal (vec3 0 0 0) (vec3 0 0 0)))
+33
(assert-error (plane-from-points (vec3 0 0 0) (vec3 1 1 1) (vec3 2 2 2))))
+34
+35
(test "signed distance"
+36
(let ((ground (plane-from-point-normal (vec3 0 2 0) (vec3 0 1 0))))
+37
(assert-float 3.0 (plane-signed-distance ground (vec3 9 5 9)))
+38
(assert-float -2.0 (plane-signed-distance ground (vec3 0 0 0))))))
+39
+40
(test-group "ray-plane"
+41
(test "straight down onto the ground"
+42
(assert-float 5.0 (ray-plane (vec3 0 5 0) (vec3 0 -1 0) ground)))
+43
+44
(test "t is in units of dir"
+45
(assert-float 2.5 (ray-plane (vec3 0 5 0) (vec3 0 -2 0) ground)))
+46
+47
(test "an oblique ray"
+48
(let* ((o (vec3 0 4 0)) (d (vec3 3 -4 0)) (t (ray-plane o d ground)))
+49
(assert-float 1.0 t)
+50
(assert-float 3.0 (vec3-x (ray-point o d t)))))
+51
+52
(test "from below also hits"
+53
(assert-float 5.0 (ray-plane (vec3 0 -5 0) (vec3 0 1 0) ground)))
+54
+55
(test "parallel and pointing away miss"
+56
(assert-false (ray-plane (vec3 0 5 0) (vec3 1 0 0) ground))
+57
(assert-false (ray-plane (vec3 0 5 0) (vec3 0 1 0) ground))))
+58
+59
(test-group "ray-aabb"
+60
(test "head-on"
+61
(assert-float 4.0 (ray-aabb (vec3 -5 0 0) (vec3 1 0 0) box-lo box-hi)))
+62
+63
(test "diagonal"
+64
(assert-float 2.0 (ray-aabb (vec3 -3 -3 -3) (vec3 1 1 1) box-lo box-hi)))
+65
+66
(test "from inside is 0"
+67
(assert-float 0.0 (ray-aabb (vec3 0.5 0 0) (vec3 0 0 1) box-lo box-hi)))
+68
+69
(test "zero dir components inside their slab"
+70
(assert-float 4.0 (ray-aabb (vec3 -5 0.5 0.5) (vec3 1 0 0) box-lo box-hi)))
+71
+72
(test "zero dir component outside its slab misses"
+73
(assert-false (ray-aabb (vec3 -5 2 0) (vec3 1 0 0) box-lo box-hi)))
+74
+75
(test "passing beside the box misses"
+76
(assert-false (ray-aabb (vec3 -5 0 0) (vec3 1 1 0) box-lo box-hi)))
+77
+78
(test "box behind the ray misses"
+79
(assert-false (ray-aabb (vec3 5 0 0) (vec3 1 0 0) box-lo box-hi)))
+80
+81
(test "skimming a face counts"
+82
(assert-float 4.0 (ray-aabb (vec3 -5 1 0) (vec3 1 0 0) box-lo box-hi)))
+83
+84
(test "sight line: t below 1 means the box is in the way"
+85
(let* ((eye (vec3 -5 0 0))
+86
(target (vec3 5 0 0))
+87
(dir (vec3-sub target eye)))
+88
(assert-float 0.4 (ray-aabb eye dir box-lo box-hi))))
+89
+90
(test "sight line: a target in front of the box is not blocked"
+91
(let* ((eye (vec3 -5 0 0))
+92
(dir (vec3-sub (vec3 -3 0 0) eye))
+93
(t (ray-aabb eye dir box-lo box-hi)))
+94
(assert-true (> t 1.0)))))
+95
+96
(test-group "ray-triangle"
+97
(test "hit from the front"
+98
(assert-float 1.0 (ray-triangle (vec3 0.25 0.25 1) (vec3 0 0 -1) tri-a tri-b tri-c)))
+99
+100
(test "hit from the back"
+101
(assert-float 1.0 (ray-triangle (vec3 0.25 0.25 -1) (vec3 0 0 1) tri-a tri-b tri-c)))
+102
+103
(test "t is in units of dir"
+104
(assert-float 0.25 (ray-triangle (vec3 0.25 0.25 1) (vec3 0 0 -4) tri-a tri-b tri-c)))
+105
+106
(test "misses outside the triangle"
+107
(assert-false (ray-triangle (vec3 0.6 0.6 1) (vec3 0 0 -1) tri-a tri-b tri-c))
+108
(assert-false (ray-triangle (vec3 -0.1 0.5 1) (vec3 0 0 -1) tri-a tri-b tri-c)))
+109
+110
(test "parallel and behind miss"
+111
(assert-false (ray-triangle (vec3 0.25 0.25 1) (vec3 1 0 0) tri-a tri-b tri-c))
+112
(assert-false (ray-triangle (vec3 0.25 0.25 1) (vec3 0 0 1) tri-a tri-b tri-c)))
+113
+114
(test "an edge counts"
+115
(assert-float 1.0 (ray-triangle (vec3 0.5 0 1) (vec3 0 0 -1) tri-a tri-b tri-c)))
+116
+117
(test "hit! writes t and the barycentric weights"
+118
(let* ((dst (make-vec3))
+119
(t (ray-triangle-hit! dst (vec3 0.2 0.3 2) (vec3 0 0 -1) tri-a tri-b tri-c)))
+120
(assert-float 2.0 t)
+121
(assert-true (vec3-approx=? (vec3 2 0.2 0.3) dst))))
+122
+123
(test "hit! leaves dst alone on a miss"
+124
(let ((dst (vec3 7 7 7)))
+125
(assert-false (ray-triangle-hit! dst (vec3 2 2 1) (vec3 0 0 -1) tri-a tri-b tri-c))
+126
(assert-true (vec3-approx=? (vec3 7 7 7) dst)))))
+127
+128
(test-group "boxes"
+129
(test "contains-point"
+130
(assert-true (aabb-contains-point? box-lo box-hi (vec3 0 0 0)))
+131
(assert-true (aabb-contains-point? box-lo box-hi (vec3 1 1 1)))
+132
(assert-false (aabb-contains-point? box-lo box-hi (vec3 1.01 0 0))))
+133
+134
(test "overlap"
+135
(assert-true (aabb-overlap? box-lo box-hi (vec3 0.5 0.5 0.5) (vec3 3 3 3)))
+136
(assert-true (aabb-overlap? box-lo box-hi (vec3 1 -1 -1) (vec3 2 1 1)))
+137
(assert-false (aabb-overlap? box-lo box-hi (vec3 1.5 0 0) (vec3 3 1 1)))
+138
(assert-false (aabb-overlap? box-lo box-hi (vec3 0 0 2) (vec3 1 1 3)))))
+139
+140
(test-group "ray-point"
+141
(test "origin + dir * t"
+142
(assert-true (vec3-approx=? (vec3 3 5 7) (ray-point (vec3 1 1 1) (vec3 1 2 3) 2)))))
test/test-vec.sgladded
@@ -0,0 +1,136 @@
+1
;;; Tests for (sigil geometry vec)
+2
+3
(import (sigil test)
+4
(sigil geometry))
+5
+6
;; On a mismatch, fail through assert-equal on lists so the report shows
+7
;; both values.
+8
(define (assert-vec3 expected actual)
+9
(unless (vec3-approx=? expected actual)
+10
(assert-equal (vec3->list expected) (vec3->list actual))))
+11
+12
(define (assert-float expected actual)
+13
(unless (float-approx=? expected actual)
+14
(assert-equal expected actual)))
+15
+16
(test-group "vec3 - construction and access"
+17
(test "components read back"
+18
(let ((v (vec3 1 2 3)))
+19
(assert-equal '(1.0 2.0 3.0) (vec3->list v))
+20
(assert-float 2.0 (vec3-y v))))
+21
+22
(test "make-vec3 is zeros"
+23
(assert-equal '(0.0 0.0 0.0) (vec3->list (make-vec3))))
+24
+25
(test "values round to float32"
+26
;; 0.1 is not a float32; the nearest one is 0.100000001490116...
+27
(assert-false (= 0.1 (vec3-x (vec3 0.1 0 0))))
+28
(assert-float 0.1 (vec3-x (vec3 0.1 0 0))))
+29
+30
(test "vec3? checks the size"
+31
(assert-true (vec3? (vec3 1 2 3)))
+32
(assert-false (vec3? (vec4 1 2 3 4)))
+33
(assert-false (vec3? '(1 2 3))))
+34
+35
(test "set! and copy"
+36
(let* ((a (vec3 1 2 3)) (b (vec3-copy a)))
+37
(vec3-set! a 7 8 9)
+38
(assert-vec3 (vec3 1 2 3) b)
+39
(assert-vec3 (vec3 7 8 9) (vec3-copy! b a)))))
+40
+41
(test-group "vec3 - arithmetic"
+42
(test "add, sub, mul, scale, negate"
+43
(let ((a (vec3 1 2 3)) (b (vec3 4 5 6)))
+44
(assert-vec3 (vec3 5 7 9) (vec3-add a b))
+45
(assert-vec3 (vec3 -3 -3 -3) (vec3-sub a b))
+46
(assert-vec3 (vec3 4 10 18) (vec3-mul a b))
+47
(assert-vec3 (vec3 2 4 6) (vec3-scale a 2))
+48
(assert-vec3 (vec3 -1 -2 -3) (vec3-negate a))
+49
(assert-vec3 (vec3 9 12 15) (vec3-add-scaled a b 2))))
+50
+51
(test "dot and cross"
+52
(assert-float 32.0 (vec3-dot (vec3 1 2 3) (vec3 4 5 6)))
+53
(assert-vec3 (vec3 0 0 1) (vec3-cross (vec3 1 0 0) (vec3 0 1 0)))
+54
(assert-vec3 (vec3 1 0 0) (vec3-cross (vec3 0 1 0) (vec3 0 0 1)))
+55
(assert-vec3 (vec3 0 1 0) (vec3-cross (vec3 0 0 1) (vec3 1 0 0)))
+56
(assert-vec3 (vec3 -3 6 -3) (vec3-cross (vec3 1 2 3) (vec3 4 5 6))))
+57
+58
(test "length and distance"
+59
(assert-float 5.0 (vec3-length (vec3 3 4 0)))
+60
(assert-float 25.0 (vec3-length-squared (vec3 0 3 4)))
+61
(assert-float 13.0 (vec3-distance (vec3 1 1 1) (vec3 4 5 13)))
+62
(assert-float 169.0 (vec3-distance-squared (vec3 1 1 1) (vec3 4 5 13))))
+63
+64
(test "normalize"
+65
(assert-vec3 (vec3 0.6 0.8 0) (vec3-normalize (vec3 3 4 0)))
+66
(assert-float 1.0 (vec3-length (vec3-normalize (vec3 -2 7 1)))))
+67
+68
(test "normalizing a zero vector gives zero, not an error"
+69
(assert-vec3 (vec3 0 0 0) (vec3-normalize (make-vec3))))
+70
+71
(test "lerp"
+72
(let ((a (vec3 0 10 -4)) (b (vec3 10 20 4)))
+73
(assert-vec3 a (vec3-lerp a b 0))
+74
(assert-vec3 b (vec3-lerp a b 1))
+75
(assert-vec3 (vec3 2.5 12.5 -2) (vec3-lerp a b 0.25))))
+76
+77
(test "min and max"
+78
(assert-vec3 (vec3 1 -5 3) (vec3-min (vec3 1 2 3) (vec3 4 -5 6)))
+79
(assert-vec3 (vec3 4 2 6) (vec3-max (vec3 1 2 3) (vec3 4 -5 6)))))
+80
+81
(test-group "vec3 - ! forms"
+82
(test "write into dst and return it"
+83
(let* ((dst (make-vec3)) (r (vec3-add! dst (vec3 1 2 3) (vec3 1 1 1))))
+84
(assert-true (eq? dst r))
+85
(assert-vec3 (vec3 2 3 4) dst)))
+86
+87
(test "dst may alias an input"
+88
(let ((a (vec3 1 2 3)))
+89
(vec3-cross! a a (vec3 4 5 6))
+90
(assert-vec3 (vec3 -3 6 -3) a))
+91
(let ((b (vec3 4 5 6)))
+92
(vec3-cross! b (vec3 1 2 3) b)
+93
(assert-vec3 (vec3 -3 6 -3) b))
+94
(let ((a (vec3 3 4 0)))
+95
(vec3-normalize! a a)
+96
(assert-vec3 (vec3 0.6 0.8 0) a))
+97
(let ((a (vec3 0 10 -4)))
+98
(vec3-lerp! a a (vec3 10 20 4) 0.5)
+99
(assert-vec3 (vec3 5 15 0) a))))
+100
+101
(test-group "vec2"
+102
(test "basics"
+103
(let ((a (vec2 3 4)) (b (vec2 1 2)))
+104
(assert-equal '(4.0 6.0) (vec2->list (vec2-add a b)))
+105
(assert-equal '(2.0 2.0) (vec2->list (vec2-sub a b)))
+106
(assert-equal '(3.0 8.0) (vec2->list (vec2-mul a b)))
+107
(assert-equal '(-3.0 -4.0) (vec2->list (vec2-negate a)))
+108
(assert-float 11.0 (vec2-dot a b))
+109
(assert-float 5.0 (vec2-length a))
+110
(assert-float 25.0 (vec2-length-squared a))
+111
(assert-float 2.8284271 (vec2-distance a b))
+112
(assert-true (vec2-approx=? (vec2 0.6 0.8) (vec2-normalize a)))
+113
(assert-true (vec2-approx=? (vec2 2 3) (vec2-lerp b a 0.5)))
+114
(assert-true (vec2-approx=? (vec2 6 8) (vec2-scale a 2)))
+115
(assert-equal 8 (bytevector-length (make-vec2)))
+116
(assert-true (vec2? (vec2-copy a))))))
+117
+118
(test-group "vec4"
+119
(test "basics"
+120
(let ((a (vec4 1 2 3 4)) (b (vec4 4 3 2 1)))
+121
(assert-equal '(5.0 5.0 5.0 5.0) (vec4->list (vec4-add a b)))
+122
(assert-equal '(-3.0 -1.0 1.0 3.0) (vec4->list (vec4-sub a b)))
+123
(assert-equal '(4.0 6.0 6.0 4.0) (vec4->list (vec4-mul a b)))
+124
(assert-equal '(2.0 4.0 6.0 8.0) (vec4->list (vec4-scale a 2)))
+125
(assert-equal '(-1.0 -2.0 -3.0 -4.0) (vec4->list (vec4-negate a)))
+126
(assert-float 20.0 (vec4-dot a b))
+127
(assert-float 30.0 (vec4-length-squared a))
+128
(assert-float 1.0 (vec4-length (vec4-normalize a)))
+129
(assert-true (vec4-approx=? (vec4 2.5 2.5 2.5 2.5) (vec4-lerp a b 0.5)))
+130
(assert-float 4.0 (vec4-w a))
+131
(assert-equal 16 (bytevector-length (vec4-copy a))))))
+132
+133
(test-group "angles"
+134
(test "degrees and radians"
+135
(assert-float 3.141592653589793 (degrees->radians 180))
+136
(assert-float 90.0 (radians->degrees (/ 3.141592653589793 2)))))