1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
|
;;; Chickadee Game Toolkit
;;; Copyright © 2016, 2019 David Thompson <davet@gnu.org>
;;;
;;; Chickadee is free software: you can redistribute it and/or modify
;;; it under the terms of the GNU General Public License as published
;;; by the Free Software Foundation, either version 3 of the License,
;;; or (at your option) any later version.
;;;
;;; Chickadee is distributed in the hope that it will be useful, but
;;; WITHOUT ANY WARRANTY; without even the implied warranty of
;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
;;; General Public License for more details.
;;;
;;; You should have received a copy of the GNU General Public License
;;; along with this program. If not, see
;;; <http://www.gnu.org/licenses/>.
(define-module (chickadee render shader)
#:use-module (ice-9 format)
#:use-module (ice-9 rdelim)
#:use-module (ice-9 match)
#:use-module (ice-9 pretty-print)
#:use-module (ice-9 regex)
#:use-module (oop goops)
#:use-module (system foreign)
#:use-module (rnrs bytevectors)
#:use-module (rnrs io ports)
#:use-module (srfi srfi-1)
#:use-module (srfi srfi-4)
#:use-module (srfi srfi-9)
#:use-module (srfi srfi-9 gnu)
#:use-module (gl)
#:use-module (chickadee math matrix)
#:use-module (chickadee math vector)
#:use-module (chickadee render color)
#:use-module (chickadee render gl)
#:use-module (chickadee render gpu)
#:use-module (chickadee render texture)
#:export (shader-data-type?
bool
int
unsigned-int
float
float-vec2
float-vec3
float-vec4
mat4
sampler-2d
uniform-namespace?
uniform-namespace-ref
uniform-namespace-for-each
define-shader-type
make-shader
shader?
null-shader
load-shader
strings->shader
shader-uniform
shader-uniforms
shader-attributes
shader-uniform-set!
uniform?
uniform-name
uniform-type
uniform-value
attribute?
attribute-name
attribute-location
attribute-type
*shader-state*))
;;;
;;; Data Types
;;;
(define-record-type <shader-data-type>
(%make-shader-data-type name size validator serializer setter null)
shader-data-type?
(name shader-data-type-name)
(size shader-data-type-size)
(validator shader-data-type-validator)
(serializer shader-data-type-serializer)
(setter shader-data-type-setter)
(null shader-data-type-null))
(define (display-shader-data-type type port)
(format port "#<shader-data-type name: ~a size: ~d null: ~a>"
(shader-data-type-name type)
(shader-data-type-size type)
(shader-data-type-null type)))
(set-record-type-printer! <shader-data-type> display-shader-data-type)
(define* (make-shader-data-type #:key name size validator serializer setter null)
(%make-shader-data-type name size validator serializer setter null))
(define (shader-data-type-serialize type bv data)
(let ((serialize (shader-data-type-serializer type)))
(if (vector? data)
(let ((size (shader-data-type-size type)))
(let loop ((i 0))
(when (< i (vector-length data))
(serialize bv (* i size) (vector-ref data i))
(loop (+ i 1)))))
(serialize bv 0 data))))
(define (shader-data-type-apply-uniform type location count pointer)
((shader-data-type-setter type) location count pointer))
(define (shader-data-type-validate type data)
(let ((valid? (shader-data-type-validator type)))
(if (vector? data)
(let loop ((i 0))
(if (and (< i (vector-length data))
(valid? (vector-ref data i)))
(loop (+ i 1))
#t))
(valid? data))))
(define-syntax-rule (define-shader-data-type var . args)
(define var (make-shader-data-type . args)))
;; Primitive types:
(define-shader-data-type bool
#:name 'bool
#:size 4
#:validator boolean?
#:serializer
(lambda (bv i bool)
(bytevector-s32-native-set! bv i (if bool 1 0)))
#:setter gl-uniform1iv
#:null #false)
(define-shader-data-type int
#:name 'int
#:size 4
#:validator integer?
#:serializer
(lambda (bv i n)
(bytevector-s32-native-set! bv i n))
#:setter gl-uniform1iv
#:null 0)
(define-shader-data-type unsigned-int
#:name 'unsigned-int
#:size 4
#:validator
(lambda (i)
(and (integer? i) (>= i 0)))
#:serializer
(lambda (bv i u)
(bytevector-u32-native-set! bv i u))
#:setter gl-uniform1uiv
#:null 0)
(define-shader-data-type float
#:name 'float
#:size 4
#:validator number?
#:serializer
(lambda (bv i f)
(bytevector-ieee-single-native-set! bv i f))
#:setter gl-uniform1fv
#:null 0.0)
(define-shader-data-type float-vec2
#:name 'float-vec2
#:size 8 ; 8 bytes = 2 floats = 1 vec2
#:validator vec2?
#:serializer
(let ((unwrap-vec2 (@@ (chickadee math vector) unwrap-vec2)))
(lambda (bv i v)
(bytevector-copy! (unwrap-vec2 v) 0 bv i 8)))
#:setter gl-uniform2fv
#:null (vec2 0.0 0.0))
(define-shader-data-type float-vec3
#:name 'float-vec3
#:size 12 ; 12 bytes = 3 floats = 1 vec3
#:validator vec3?
#:serializer
(let ((unwrap-vec3 (@@ (chickadee math vector) unwrap-vec3)))
(lambda (bv i v)
(bytevector-copy! (unwrap-vec3 v) 0 bv i 12)))
#:setter gl-uniform3fv
#:null (vec3 0.0 0.0 0.0))
(define-shader-data-type float-vec4
#:name 'float-vec4
#:size 16 ; 16 bytes = 4 floats = 1 vec4
#:validator color?
#:serializer
(lambda (bv i v)
;; As of now, there is no vec4 Scheme type, but we do want to
;; accept colors as vec4s since there is no special color type in
;; GLSL.
(bytevector-ieee-single-native-set! bv i (color-r v))
(bytevector-ieee-single-native-set! bv (+ i 4) (color-g v))
(bytevector-ieee-single-native-set! bv (+ i 8) (color-b v))
(bytevector-ieee-single-native-set! bv (+ i 12) (color-a v)))
#:setter gl-uniform4fv
#:null (color 0.0 0.0 0.0 0.0))
(define-shader-data-type mat4
#:name 'mat4
#:size 64 ; 4 rows x 4 columns = 16 floats x 4 bytes each = 64 bytes
#:validator matrix4?
#:serializer
(let ((matrix4-bv (@@ (chickadee math matrix) matrix4-bv)))
(lambda (bv i m)
;; 4 rows x 4 columns x 4 bytes per float = 4^3
(bytevector-copy! (matrix4-bv m) 0 bv i (* 4 4 4))))
#:setter (lambda (location count ptr)
(gl-uniform-matrix4fv location count #f ptr))
#:null (make-identity-matrix4))
(define-shader-data-type sampler-2d
#:name 'sampler-2d
#:size 4
#:validator integer?
#:serializer
(lambda (bv i texture-unit)
(bytevector-s32-native-set! bv i texture-unit))
#:setter gl-uniform1iv
#:null 0)
;;;
;;; Shader Structs
;;;
;; A meta-vtable that has two additional slots: one for the struct
;; name, and another for the lookup table that maps struct field names
;; to their respective struct index and shader data type.
(define <shader-struct>
(make-vtable (string-append standard-vtable-fields "pwpw")
(lambda (vt port)
(format port "#<shader-struct ~a>"
(shader-struct-fields vt)))))
(define (shader-struct? struct)
(eq? (struct-vtable (struct-vtable struct)) <shader-struct>))
(define shader-struct-name-index vtable-offset-user)
(define shader-struct-fields-index (+ vtable-offset-user 1))
(define (shader-struct-name vtable)
(struct-ref vtable shader-struct-name-index))
(define (shader-struct-fields vtable)
(struct-ref vtable shader-struct-fields-index))
(define (shader-struct-type-check vtable field value)
(match (assq-ref (shader-struct-fields vtable) field)
((_ type size)
(define (validate value)
(unless (or (and (struct? value) (eq? (struct-vtable value) type))
(shader-data-type-validate type value))
(error "invalid type for shader struct field" field value)))
(cond
((= size 1)
(validate value))
((and (vector? value)
(= (vector-length value) size))
(let loop ((i 0))
(when (< i (vector-length value))
(validate (vector-ref value i))
(loop (+ i 1)))))
((vector? value)
(error "incorrect vector size" value))
(else
(error "expected vector, got" value))))))
(define (shader-struct-default vtable field)
(match (assq-ref (shader-struct-fields vtable) field)
((_ type size)
(let ((default (if (eq? (struct-vtable type) <shader-struct>)
(apply make-struct/no-tail type
(map (match-lambda
((sub-field _ _ _)
(shader-struct-default type sub-field)))
(shader-struct-fields type)))
(shader-data-type-null type))))
(if (= size 1)
default
(make-vector size default))))))
(define (make-shader-struct-field-table fields+types)
;; Map field names to their struct indices and shader types.
(let loop ((i 0)
(fields+types fields+types))
(match fields+types
(() '())
(((name #(type size)) . rest)
(cons (list name i type size)
(loop (+ i 1) rest)))
(((name type) . rest)
(cons (list name i type 1)
(loop (+ i 1) rest))))))
(define (display-shader-struct-instance obj port)
(let ((vtable (struct-vtable obj)))
(format port "#<~a" (shader-struct-name vtable))
(let loop ((fields (shader-struct-fields vtable)))
(match fields
(() #f)
(((name index type size) . rest)
(format port " ~a[~d ~a]: ~a"
name size (shader-data-type-name type) (struct-ref obj index))
(loop rest))))
(display ">" port)))
(define (make-display-name sym)
(let ((str (symbol->string sym)))
(if (and (string-prefix? "<" str)
(string-suffix? ">" str))
(substring str 1 (- (string-length str) 1))
str)))
(define (make-shader-struct name fields+types)
(make-struct/no-tail <shader-struct>
(make-struct-layout
(string-concatenate
(map (const "pw") fields+types)))
display-shader-struct-instance
(make-display-name name)
(make-shader-struct-field-table fields+types)))
(define (shader-struct-ref struct field)
(match (assq-ref (shader-struct-fields (struct-vtable struct)) field)
(#f
(error "unknown struct field" field))
((index _ _)
(struct-ref struct index))))
(define-syntax define-accessors
(syntax-rules ()
((_ <struct> field getter)
(define getter
(let ((index (match (assq-ref (shader-struct-fields <struct>) 'field)
((i _ _) i))))
(lambda (obj)
(struct-ref obj index)))))
((_ <struct> field getter setter)
(begin
(define-accessors <struct> field getter)
(define setter
(let ((index (match (assq-ref (shader-struct-fields <struct>) 'field)
((i _ _) i))))
(lambda (obj value)
(shader-struct-type-check <struct> 'field value)
(struct-set! obj index value))))))))
(define-syntax define-shader-type
(syntax-rules ()
((_ <name> constructor predicate (field-type field-name . field-rest) ...)
(begin
(define <name>
(make-shader-struct '<name> (list (list 'field-name field-type) ...)))
(define* (constructor #:key (field-name (shader-struct-default <name> 'field-name)) ...)
(shader-struct-type-check <name> 'field-name field-name) ...
(make-struct/no-tail <name> field-name ...))
(define (predicate obj)
(and (struct? obj) (eq? (struct-vtable obj) <name>)))
(define-accessors <name> field-name . field-rest) ...))))
;;;
;;; Shaders
;;;
(define-record-type <shader>
(%make-shader id attributes uniforms scratch scratch-pointer)
shader?
(id shader-id)
(attributes shader-attributes)
(uniforms shader-uniforms)
;; Scratch space for serializing uniform values.
(scratch shader-scratch)
;; Create the pointer once and hold onto it to reduce needless
;; garbage creation.
(scratch-pointer shader-scratch-pointer))
;; Represents a single active uniform location in a shader program.
(define-record-type <uniform>
(make-uniform name location type size value)
uniform?
(name uniform-name)
(location uniform-location)
(type uniform-type)
(size uniform-size)
(value uniform-value %set-uniform-value!))
;; variable name -> {uniform, namespace, uniform array} map
(define-record-type <uniform-namespace>
(make-uniform-namespace name members)
uniform-namespace?
(name uniform-namespace-name)
(members uniform-namespace-members))
(define (fresh-uniform-namespace name)
(make-uniform-namespace name (make-hash-table)))
(define (uniform-namespace-set! namespace name value)
(hashq-set! (uniform-namespace-members namespace) name value))
(define (uniform-namespace-ref namespace name)
(hashq-ref (uniform-namespace-members namespace) name))
(define (uniform-namespace-ref-or-create-namespace namespace name)
(or (uniform-namespace-ref namespace name)
(let ((new-ns (fresh-uniform-namespace name)))
(uniform-namespace-set! namespace name new-ns)
new-ns)))
(define (uniform-namespace-ref-or-create-array namespace name)
(or (uniform-namespace-ref namespace name)
(let ((new-arr (fresh-uniform-array name)))
(uniform-namespace-set! namespace name new-arr)
new-arr)))
(define (uniform-namespace-for-each proc namespace)
(hash-for-each proc (uniform-namespace-members namespace)))
;; variable name -> {uniform, namespace} map
(define-record-type <uniform-array>
(make-uniform-array name namespaces size)
uniform-array?
(name uniform-array-name)
(namespaces uniform-array-namespaces)
(size uniform-array-size set-uniform-array-size!))
(define (fresh-uniform-array name)
(make-uniform-array name (make-hash-table) 0))
(define (uniform-array-namespace-ref array i)
(hashv-ref (uniform-array-namespaces array) i))
(define (uniform-array-namespace-add! array i)
(let ((ns (fresh-uniform-namespace (uniform-array-name array))))
(hashv-set! (uniform-array-namespaces array) i ns)
(set-uniform-array-size! array (max (uniform-array-size array) (+ i 1)))
ns))
(define (uniform-array-ref-or-create array i)
(or (uniform-array-namespace-ref array i)
(uniform-array-namespace-add! array i)))
(define-record-type <attribute>
(make-attribute name location type)
attribute?
(name attribute-name)
(location attribute-location)
(type attribute-type))
(define null-shader (%make-shader 0 (make-hash-table) (make-hash-table) #f #f))
(define <<shader>> (class-of null-shader))
(define-method (gpu-finalize (shader <<shader>>))
(gl-delete-program (shader-id shader)))
(define (apply-shader shader)
(gl-use-program (shader-id shader)))
(define *shader-state* (make-gpu-state apply-shader null-shader))
(define (make-shader vertex-port fragment-port)
"Read GLSL source from VERTEX-PORT and FRAGMENT-PORT and compile
them into a GPU shader program."
(define (shader-compiled? id)
(let ((status (make-u32vector 1)))
(gl-get-shaderiv id (version-2-0 compile-status)
(bytevector->pointer status))
(= (u32vector-ref status 0) 1)))
(define (shader-linked? id)
(let ((status (make-u32vector 1)))
(gl-get-programiv id (version-2-0 link-status)
(bytevector->pointer status))
(= (u32vector-ref status 0) 1)))
(define (info-log length-proc log-proc id)
(let ((log-length-bv (make-u32vector 1)))
(length-proc id (version-2-0 info-log-length)
(bytevector->pointer log-length-bv))
(u32vector-ref log-length-bv 0)
;; Add one byte to account for the null string terminator.
(let* ((log-length (u32vector-ref log-length-bv 0))
(log (make-u8vector (1+ log-length))))
(log-proc id log-length %null-pointer (bytevector->pointer log))
(utf8->string log))))
(define (compilation-error id)
(info-log gl-get-shaderiv gl-get-shader-info-log id))
(define (linking-error id)
(info-log gl-get-programiv gl-get-program-info-log id))
(define (make-shader-stage type port)
(let ((id (gl-create-shader type))
(source (get-bytevector-all port)))
(gl-shader-source id 1
(bytevector->pointer
(u64vector
(pointer-address (bytevector->pointer source))))
(bytevector->pointer
(u32vector (bytevector-length source))))
(gl-compile-shader id)
(unless (shader-compiled? id)
(let ((error-log (compilation-error id)))
(gl-delete-shader id) ; clean up GPU resource.
(display "shader compilation failed:\n")
(display error-log (current-error-port))
(error "failed to compile shader")))
id))
(define (uniform-count id)
(let ((bv (make-u32vector 1)))
(gl-get-programiv id
(arb-shader-objects active-uniforms)
(bytevector->pointer bv))
(u32vector-ref bv 0)))
(define (utf8->string* bv length)
(let ((bv* (make-bytevector length)))
(bytevector-copy! bv 0 bv* 0 length)
(utf8->string bv*)))
(define (parse-data-type type)
(cond
((= type (version-2-0 bool)) bool)
((= type (data-type int)) int)
((= type (data-type unsigned-int)) unsigned-int)
((= type (data-type float)) float)
((= type (version-2-0 float-vec2)) float-vec2)
((= type (version-2-0 float-vec3)) float-vec3)
((= type (version-2-0 float-vec4)) float-vec4)
((= type (version-2-0 float-mat4)) mat4)
((= type (version-2-0 sampler-2d)) sampler-2d)
(else
(error "unsupported OpenGL type" type))))
(define (uniform-name->symbol name)
;; array uniform names have a suffix like "[0]" that needs to be
;; removed to produce the actual uniform variable name that our
;; shader interface will recognize.
(string->symbol
(let ((i (string-contains name "[")))
(if i (substring name 0 i) name))))
(define (parse-array-index name)
(let* ((start (string-contains name "["))
(end (- (string-length name) 1)))
(and start (string->number (substring name (+ start 1) end)))))
(define (struct? name)
(string-contains name "."))
(define (namespace->alist table)
(hash-map->list
(lambda (key value)
(cons key
(cond
((uniform-namespace? value)
(namespace->alist value))
((uniform-array? value)
(hash-map->list (lambda (key value)
(cons key (namespace->alist value)))
(uniform-array-namespaces value)))
(else
(list (uniform-location value)
(shader-data-type-name (uniform-type value))
(uniform-size value))))))
(uniform-namespace-members table)))
(define (parse-struct name uniform namespace)
;; Deconstruct the uniform name to produce a path through the
;; namespace tree, follow it to the end and add the uniform as a
;; leaf node in the tree.
(let inner ((path (string-split name #\.))
(namespace namespace))
(match path
;; Yay, we're done!
((leaf)
(uniform-namespace-set! namespace (uniform-name->symbol leaf) uniform))
((branch . rest)
(let ((new-name (uniform-name->symbol branch))
(index (parse-array-index branch)))
;; If there is an index included in the branch name like
;; "[1]" then that means we have a nested array of structs
;; within the struct. Otherwise, it's just a single nested
;; struct.
(if index
(let ((new-namespace
(uniform-array-ref-or-create
(uniform-namespace-ref-or-create-array namespace
new-name)
index)))
(inner rest new-namespace))
(let ((new-namespace
(uniform-namespace-ref-or-create-namespace namespace
new-name)))
(inner rest new-namespace))))))))
(define (extract-uniforms id)
(let ((total (uniform-count id))
(namespace (fresh-uniform-namespace "root")))
;; OpenGL has an API for shader program introspection that we
;; use to extract all active uniforms. This uniform data must
;; then be parsed and turned into a data structure that can be
;; used to translate Scheme data (either primitives or compound
;; structures) to the GPU when it comes time to actually render
;; something with the shader.
(let loop ((i 0)
(texture-unit 0)
(scratch-size 0))
(if (< i total)
(let ((length-bv (make-u32vector 1))
(size-bv (make-u32vector 1))
(type-bv (make-u32vector 1))
(name-bv (make-bytevector 255)))
(gl-get-active-uniform id i
(bytevector-length name-bv)
(bytevector->pointer length-bv)
(bytevector->pointer size-bv)
(bytevector->pointer type-bv)
(bytevector->pointer name-bv))
(let* ((name-length (u32vector-ref length-bv 0))
(name (utf8->string* name-bv name-length))
(location (gl-get-uniform-location id name))
(size (u32vector-ref size-bv 0))
(type (parse-data-type (u32vector-ref type-bv 0)))
(sampler? (eq? type sampler-2d))
(default (cond
(sampler?
texture-unit)
((= size 1)
(shader-data-type-null type))
(else
(make-vector size (shader-data-type-null type)))))
(uniform (make-uniform name location type size default)))
(if (struct? name)
;; The complicated path: Parse struct name and
;; build a branch of a tree structure.
(parse-struct name uniform namespace)
;; The easy path: A top-level primitive.
(uniform-namespace-set! namespace
(uniform-name->symbol name)
uniform))
(loop (1+ i)
;; A sampler uniform uses up one texture unit,
;; so move on to the next one in that case.
(if sampler?
(1+ texture-unit)
texture-unit)
;; Ensure we have enough space to serialize the
;; largest bit of data we send to the shader.
(max scratch-size
(* size
(shader-data-type-size type))))))
(begin
(pretty-print (namespace->alist namespace))
(values namespace scratch-size))))))
(define (attribute-count id)
(let ((bv (make-u32vector 1)))
(gl-get-programiv id
(arb-shader-objects active-attributes)
(bytevector->pointer bv))
(u32vector-ref bv 0)))
(define (extract-attributes id)
(let ((total (attribute-count id))
(table (make-hash-table)))
(let loop ((i 0))
(unless (= i total)
(let ((length-bv (make-u32vector 1))
(size-bv (make-u32vector 1))
(type-bv (make-u32vector 1))
(name-bv (make-bytevector 255)))
(gl-get-active-attrib id i
(bytevector-length name-bv)
(bytevector->pointer length-bv)
(bytevector->pointer size-bv)
(bytevector->pointer type-bv)
(bytevector->pointer name-bv))
(let* ((length (u32vector-ref length-bv 0))
(name (utf8->string* name-bv length))
(size (u32vector-ref size-bv 0))
(type (parse-data-type (u32vector-ref type-bv 0)))
(location (gl-get-attrib-location id name)))
(unless (= size 1)
(error "unsupported attribute size" name size))
(hash-set! table name (make-attribute name location type))))
(loop (1+ i))))
table))
(let ((vertex-id (make-shader-stage (version-2-0 vertex-shader)
vertex-port))
(fragment-id (make-shader-stage (version-2-0 fragment-shader)
fragment-port))
(id (gl-create-program)))
(gl-attach-shader id vertex-id)
(gl-attach-shader id fragment-id)
(gl-link-program id)
(unless (shader-linked? id)
(let ((error-log (linking-error id)))
(gl-delete-program id)
(error "failed to link shader" error-log)))
(gl-delete-shader vertex-id)
(gl-delete-shader fragment-id)
(call-with-values
(lambda () (extract-uniforms id))
(lambda (namespace scratch-size)
(let ((scratch (make-bytevector scratch-size)))
(gpu-guard
(%make-shader id (extract-attributes id) namespace
scratch (bytevector->pointer scratch))))))))
(define (load-shader vertex-source-file fragment-source-file)
"Compile the GLSL source code within VERTEX-SOURCE-FILE and
FRAGMENT-SOURCE-FILE into a GPU shader program."
(call-with-input-file vertex-source-file
(lambda (vertex-port)
(call-with-input-file fragment-source-file
(lambda (fragment-port)
(make-shader vertex-port fragment-port))))))
(define (strings->shader vertex-source fragment-source)
"Compile VERTEX-SOURCE, the GLSL code for the vertex shader,
and FRAGMENT-SOURCE, the GLSL code for the fragment shader, into a GPU
shader program."
(call-with-input-string vertex-source
(lambda (vertex-port)
(call-with-input-string fragment-source
(lambda (fragment-port)
(make-shader vertex-port fragment-port))))))
(define (shader-uniform shader name)
"Return the metadata for the uniform NAME in SHADER."
(let ((uniform (uniform-namespace-ref (shader-uniforms shader) name)))
(or uniform (error "no such uniform" name))))
(define (shader-uniform-set! shader uniform-name x)
(define (traverse uniform value)
(cond
;; A leaf node of the uniform tree representing a single uniform
;; location as determined by OpenGL.
((uniform? uniform)
(let ((type (uniform-type uniform)))
;; A vector of a primitive type must be the exact size that
;; the shader expects.
(when (and (> (uniform-size uniform) 1)
(not (= (uniform-size uniform) (vector-length x))))
(error "vector size mismatch for uniform" uniform-name))
;; TODO: Figure out a way to avoid unnecessary uniform
;; updates. Maybe UBOs would help address this?
(shader-data-type-serialize type (shader-scratch shader) value)
(shader-data-type-apply-uniform type (uniform-location uniform) 1
(shader-scratch-pointer shader))
(%set-uniform-value! uniform value)))
;; A nested namespace indicates that this must be a struct.
((uniform-namespace? uniform)
(if (shader-struct? value)
(uniform-namespace-for-each
(lambda (key uniform)
(traverse uniform (shader-struct-ref value key)))
uniform)
(error "expected shader struct" x)))
;; A nested array namespace indicates that this must be an array
;; of structs.
((uniform-array? uniform)
(let ((size (uniform-array-size uniform)))
;; Vector size must match what the shader expects.
(if (and (vector? value)
(= size (vector-length value)))
(let loop ((i 0))
(when (< i size)
(traverse (uniform-array-namespace-ref uniform i)
(vector-ref value i))))
(error "vector size mismatch for uniform"
(uniform-array-name uniform)))))))
;; Walk the uniform namespace tree until we get to a leaf node or
;; nodes.
(traverse (shader-uniform shader uniform-name) x))
|