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