AtlatestRepositorysigil-geometry

sigil-geometry / tree / testtest-layout.sgl

1;;; The byte layout contract with GPU consumers (sigil-graphics).
2;;;
3;;; These tests pin the representation, not the maths: sizes, float32
4;;; storage, column-major order, and native byte order. A change that
5;;; breaks one of them breaks every shader fed by this package.
6
7(import (sigil test)
8 (sigil geometry))
9
10(define (floats bv)
11 (let loop ((i (- (quotient-4 (bytevector-length bv)) 1)) (acc '()))
12 (if (< i 0) acc (loop (- i 1) (cons (bytevector-ieee-single-ref bv (* 4 i)) acc)))))
14;; `quotient` is not bound on this Sigil's toplevel; sizes here are
15;; multiples of 4.
16(define (quotient-4 n) (let loop ((k 0) (r n)) (if (< r 4) k (loop (+ k 1) (- r 4)))))
18(test-group "sizes"
19 (test "every value is a bytevector of 4-byte floats"
20 (assert-equal 8 (bytevector-length (make-vec2)))
21 (assert-equal 12 (bytevector-length (make-vec3)))
22 (assert-equal 16 (bytevector-length (make-vec4)))
23 (assert-equal 16 (bytevector-length (make-quat)))
24 (assert-equal 36 (bytevector-length (make-mat3)))
25 (assert-equal 64 (bytevector-length (make-mat4)))
26 (assert-equal 48 (bytevector-length (mat3->std140 (make-mat3))))))
28(test-group "column-major"
29 (test "mat4 translation is floats 12 13 14"
30 (assert-equal '(1.0 0.0 0.0 0.0 0.0 1.0 0.0 0.0 0.0 0.0 1.0 0.0 7.0 8.0 9.0 1.0)
31 (floats (mat4-translation (vec3 7 8 9)))))
33 (test "the perspective -1 is float 11 (column 2, row 3)"
34 (let ((p (floats (mat4-perspective 1.0 1.0 1.0 10.0))))
35 (assert-equal -1.0 (list-ref p 11))
36 ;; row-major storage would put the -1 here instead
37 (assert-true (float-approx=? (/ 20.0 -9.0) (list-ref p 14)))
38 (assert-equal 0.0 (list-ref p 15))))
40 (test "mat3 column c row r is float 3c + r"
41 (let ((m (make-mat3)))
42 (mat3-set! m 2 0 5.0)
43 (assert-equal 5.0 (list-ref (floats m) 6)))))
45(test-group "float32 storage"
46 (test "writes round to float32"
47 (assert-equal 0.10000000149011612 (vec3-x (vec3 0.1 0 0))))
49 (test "the bytes are IEEE-754 single precision"
50 ;; 1.0f is 0x3F800000
51 (let ((v (vec3 1 0 0)))
52 (assert-equal #x3F800000
53 (+ (* 16777216 (bytevector-u8-ref v (if (little-host?) 3 0)))
54 (* 65536 (bytevector-u8-ref v (if (little-host?) 2 1)))
55 (* 256 (bytevector-u8-ref v (if (little-host?) 1 2)))
56 (bytevector-u8-ref v (if (little-host?) 0 3)))))))
58(define (little-host?)
59 (let ((b (make-bytevector 4 0)))
60 (bytevector-ieee-single-set! b 0 1.0)
61 (= (bytevector-u8-ref b 3) #x3F)))
63(test-group "byte order"
64 (test "values are stored in native byte order"
65 (let ((v (vec4 1.5 -2 3 4))
66 (native (make-bytevector 16 0)))
67 (for-each (lambda (i x) (bytevector-ieee-single-set! native (* 4 i) x))
68 '(0 1 2 3) '(1.5 -2 3 4))
69 (assert-equal native v))))