generated from soypat/go-module-template
-
Notifications
You must be signed in to change notification settings - Fork 0
/
glbuild.go
1208 lines (1088 loc) · 36 KB
/
glbuild.go
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
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package glbuild
import (
"bytes"
_ "embed"
"encoding/binary"
"errors"
"fmt"
"io"
"reflect"
"strconv"
"unsafe"
"github.com/soypat/glgl/math/md2"
"github.com/soypat/glgl/math/md3"
"github.com/soypat/glgl/math/ms2"
"github.com/soypat/glgl/math/ms3"
)
// Shader stores information for automatically generating SDF Shader pipelines
// and evaluating them correctly on a GPU.
type Shader interface {
// AppendShaderName appends the name of the GL shader function
// to the buffer and returns the result. It should be unique to that shader.
AppendShaderName(b []byte) []byte
// AppendShaderBody appends the body of the shader function to the
// buffer and returns the result.
AppendShaderBody(b []byte) []byte
// AppendShaderObject appends "objects" (read as data) needed to
// evaluate the shader correctly. See [ShaderObject] for more information
// on what an object can represent.
AppendShaderObjects(objs []ShaderObject) []ShaderObject
}
// ShaderObject is a handle to data needed to evaluate a [Shader] correctly.
// A ShaderObject could represent any of the following:
// - Shader Storage Buffer Object (SSBO). Is a 1D array of structured data.
// - Texture. Represents 2D data, usually images.
// - Shader uniform. Is a single structured value.
type ShaderObject struct {
// NamePtr is a pointer to the name of the buffer inside of the [Shader].
// This lets the programmer edit the name if a naming conflict is found before generating the shader bodies.
NamePtr []byte
// Element is the element of the buffer.
Element reflect.Type
// Data points to the start of buffer data.
Data unsafe.Pointer
// Size of buffer in bytes.
Size int
// Binding specifies the resource's binding point during shader execution.
// Binding should be equal to -1 until the final binding point is allocated in shader generation.
Binding int
read bool
// Write bool
}
// Shader3D can create SDF shader source code for an arbitrary 3D shape.
type Shader3D interface {
Shader
// ForEachChild iterats over the Shader3D's direct Shader3D children.
// Unary operations have one child i.e: Translate, Transform, Scale.
// Binary operations have two children i.e: Union, Intersection, Difference.
ForEachChild(userData any, fn func(userData any, s *Shader3D) error) error
// Bounds returns the Shader3D's bounding box where the SDF is negative.
Bounds() ms3.Box
}
// Shader2D can create SDF shader source code for an arbitrary 2D shape.
type Shader2D interface {
Shader
// ForEachChild iterats over the Shader2D's direct Shader2D children.
// Unary operations have one child i.e: Translate, Scale.
// Binary operations have two children i.e: Union, Intersection, Difference.
ForEach2DChild(userData any, fn func(userData any, s *Shader2D) error) error
// Bounds returns the Shader2D's bounding box where the SDF is negative.
Bounds() ms2.Box
}
// shader3D2D can create SDF shader source code for a operation that receives 2D
// shaders to generate a 3D shape.
type shader3D2D interface {
Shader3D
ForEach2DChild(userData any, fn func(userData any, s *Shader2D) error) error
}
// Programmer implements shader generation logic for Shader type.
type Programmer struct {
scratchNodes []Shader
scratch []byte
computeHeader []byte
objsScratch []ShaderObject
// names maps shader names to body hashes for checking duplicates.
names map[uint64]uint64
// Invocations size in X (local group size) to give each compute work group.
invocX int
}
func MakeShaderBufferReadOnly[T any](namePtr []byte, data []T) (ssbo ShaderObject, err error) {
var z T
ssbo = ShaderObject{
NamePtr: namePtr,
Element: reflect.TypeOf(z),
Data: unsafe.Pointer(&data[0]),
Size: int(unsafe.Sizeof(z)) * len(data),
read: true,
}
err = ssbo.Validate()
if err != nil {
return ShaderObject{}, err
}
// Until shader pipeline we do not know where our buffer will be binded.
// Programmer expects -1 binding until then.
ssbo.Binding = -1
return ssbo, nil
}
var defaultComputeHeader = []byte("#shader compute\n#version 430\n")
// NewDefaultProgrammer returns a Programmer with reasonable default parameters for use with glgl package on the local machine.
func NewDefaultProgrammer() *Programmer {
return &Programmer{
scratchNodes: make([]Shader, 64),
scratch: make([]byte, 1024), // Max length of shader token is around 1024..1060 characters.
computeHeader: defaultComputeHeader,
names: make(map[uint64]uint64),
invocX: 32,
}
}
// SetComputeInvocations sets the work group local-sizes. x*y*z must be less than maximum number of invocations.
func (p *Programmer) SetComputeInvocations(x, y, z int) {
if y != 1 || z != 1 {
panic("unsupported")
} else if x < 1 {
panic("zero or negative X invocation size")
}
p.invocX = x
}
// ComputeInvocations returns the worker group invocation size in x y and z.
func (p *Programmer) ComputeInvocations() (int, int, int) {
return p.invocX, 1, 1
}
// WriteDistanceIO creates the bare bones I/O compute program for calculating SDF
// and writes it to the writer.
func (p *Programmer) WriteComputeSDF3(w io.Writer, obj Shader3D) (int, []ShaderObject, error) {
baseName, nodes, err := ParseAppendNodes(p.scratchNodes[:0], obj)
if err != nil {
return 0, nil, err
}
// Begin writing shader source code.
n, err := w.Write(p.computeHeader)
if err != nil {
return n, nil, err
}
ngot, objs, err := p.writeShaders(w, nodes)
n += ngot
if err != nil {
return n, nil, err
}
ngot, err = fmt.Fprintf(w, `
layout(local_size_x = %d, local_size_y = 1, local_size_z = 1) in;
// Input: 3D positions at which to evaluate SDF.
layout(std140, binding = 0) buffer PositionsBuffer {
vec3 vbo_positions[];
};
// Output: Result of SDF evaluation are the distances. Maps to position buffer.
layout(std430, binding = 1) buffer DistancesBuffer {
float vbo_distances[];
};
void main() {
int idx = int( gl_GlobalInvocationID.x );
vec3 p = vbo_positions[idx]; // Get position to evaluate SDF at.
vbo_distances[idx] = %s(p); // Evaluate SDF and store to distance buffer.
}
`, p.invocX, baseName)
n += ngot
return n, objs, err
}
// WriteDistanceIO creates the bare bones I/O compute program for calculating SDF
// and writes it to the writer.
func (p *Programmer) WriteComputeSDF2(w io.Writer, obj Shader2D) (int, []ShaderObject, error) {
baseName, nodes, err := ParseAppendNodes(p.scratchNodes[:0], obj)
if err != nil {
return 0, nil, err
}
// Begin writing shader source code.
n, err := w.Write(p.computeHeader)
if err != nil {
return n, nil, err
}
ngot, objs, err := p.writeShaders(w, nodes)
n += ngot
if err != nil {
return n, objs, err
}
ngot, err = fmt.Fprintf(w, `
layout(local_size_x = %d, local_size_y = 1, local_size_z = 1) in;
// Input: 2D positions at which to evaluate SDF.
layout(std430, binding = 0) buffer PositionsBuffer {
vec2 vbo_positions[];
};
// Output: Result of SDF evaluation are the distances. Maps to position buffer.
layout(std430, binding = 1) buffer DistancesBuffer {
float vbo_distances[];
};
void main() {
int idx = int( gl_GlobalInvocationID.x );
vec2 p = vbo_positions[idx]; // Get position to evaluate SDF at.
vbo_distances[idx] = %s(p); // Evaluate SDF and store to distance buffer.
}
`, p.invocX, baseName)
n += ngot
return n, objs, err
}
//go:embed visualizer_footer.tmpl
var shaderToyVisualFooter []byte
// WriteShaderToyVisualizerSDF3 generates a OpenGL program that can be visualized in most shader visualizers such as ShaderToy.
func (p *Programmer) WriteShaderToyVisualizerSDF3(w io.Writer, obj Shader3D) (n int, objs []ShaderObject, err error) {
baseName, n, objs, err := p.WriteSDFDecl(w, obj)
if err != nil {
return 0, objs, err
}
ngot, err := w.Write([]byte("\nfloat sdf(vec3 p) { return " + baseName + "(p); }\n\n"))
n += ngot
if err != nil {
return n, objs, err
}
ngot, err = w.Write(shaderToyVisualFooter)
n += ngot
if err != nil {
return n, objs, err
}
return n, objs, nil
}
// WriteShaderDecl writes the SDF shader function declarations and returns the top-level SDF function name.
func (p *Programmer) WriteSDFDecl(w io.Writer, s Shader) (baseName string, n int, objs []ShaderObject, err error) {
baseName, nodes, err := ParseAppendNodes(p.scratchNodes[:0], s)
if err != nil {
return "", 0, nil, err
}
n, objs, err = p.writeShaders(w, nodes)
if err != nil {
return "", n, objs, err
}
return baseName, n, objs, nil
}
func (p *Programmer) writeShaders(w io.Writer, nodes []Shader) (n int, objs []ShaderObject, err error) {
clear(p.names)
p.scratch = p.scratch[:0]
p.objsScratch = p.objsScratch[:0]
currentBase := 2
for i := len(nodes) - 1; i >= 0; i-- {
// Start by generating Shader Objects.
node := nodes[i]
prevIdx := len(p.objsScratch)
p.objsScratch = node.AppendShaderObjects(p.objsScratch)
newObjects := p.objsScratch[prevIdx:]
for i := range newObjects {
if newObjects[i].Binding != -1 {
return n, nil, fmt.Errorf("shader buffer object binding should be set to -1 until shader generated for %T, %q", node, newObjects[i].NamePtr)
}
newObjects[i].Binding = currentBase
currentBase++
obj := newObjects[i]
nameHash := hash(obj.NamePtr, 0)
_, nameConflict := p.names[nameHash]
if nameConflict {
return n, nil, fmt.Errorf("shader buffer object name conflict resolution not implemented: %T has buffer conflicting name %q of type %s", node, obj.NamePtr, obj.Element.String())
}
p.names[nameHash] = nameHash
blockName := unsafe.String(&obj.NamePtr[0], len(obj.NamePtr)) + "Buffer"
p.scratch, err = AppendShaderBufferDecl(p.scratch, blockName, "", obj)
if err != nil {
return n, nil, err
}
}
}
if len(p.scratch) > 0 {
// Write shader buffer declarations if any.
ngot, err := w.Write(p.scratch)
n += ngot
if err != nil {
return n, nil, err
}
}
for i := len(nodes) - 1; i >= 0; i-- {
node := nodes[i]
var name, body []byte
p.scratch, name, body = AppendShaderSource(p.scratch[:0], node)
nameHash := hash(name, 0)
bodyHash := hash(body, nameHash) // Body hash mixes name as well.
gotBodyHash, nameConflict := p.names[nameHash]
if nameConflict {
// Name already exists in tree, check if bodies are identical.
if bodyHash == gotBodyHash {
continue // Shader already written and is identical, skip.
}
return n, nil, fmt.Errorf("duplicate %T shader name %q w/ body:\n%s", node, name, body)
} else {
p.names[nameHash] = bodyHash // Not found, add it.
}
ngot, err := w.Write(p.scratch)
n += ngot
if err != nil {
return n, nil, err
}
}
objs = append(objs[:0], p.objsScratch...) // Clone slice and return it.
return n, objs, err
}
const shorteningBufsize = 1024
func ShortenNames3D(root *Shader3D, maxRewriteLen int) error {
scratch := make([]byte, shorteningBufsize)
rewrite3 := func(a any, s3 *Shader3D) error {
scratch = rewriteName3(s3, scratch, maxRewriteLen)
return nil
}
rewrite2 := func(a any, s2 *Shader2D) error {
scratch = rewriteName2(s2, scratch, maxRewriteLen)
return nil
}
err := forEachNode(*root, rewrite3, rewrite2)
if err != nil {
return err
}
return rewrite3(nil, root)
}
func ShortenNames2D(root *Shader2D, maxRewriteLen int) error {
scratch := make([]byte, shorteningBufsize)
rewrite3 := func(a any, s3 *Shader3D) error {
scratch = rewriteName3(s3, scratch, maxRewriteLen)
return nil
}
rewrite2 := func(a any, s2 *Shader2D) error {
scratch = rewriteName2(s2, scratch, maxRewriteLen)
return nil
}
err := forEachNode(*root, rewrite3, rewrite2)
if err != nil {
return err
}
return rewrite2(nil, root)
}
func rewriteName3(s3 *Shader3D, scratch []byte, rewritelen int) []byte {
sd3 := *s3
name, scratch := makeShortname(sd3, scratch, rewritelen)
if name == nil {
return scratch
}
*s3 = &nameOverloadShader3D{Shader: sd3, name: name}
return scratch
}
func rewriteName2(s2 *Shader2D, scratch []byte, rewritelen int) []byte {
sd2 := *s2
name, scratch := makeShortname(sd2, scratch, rewritelen)
if name == nil {
return scratch
}
*s2 = &nameOverloadShader2D{Shader: sd2, name: name}
return scratch
}
// makeNewName creates.
func makeShortname(s Shader, scratch []byte, rewritelen int) (newNameOrNil []byte, newScratch []byte) {
var h uint64 = 0xff51afd7ed558ccd
scratch = s.AppendShaderName(scratch[:0])
if len(scratch) < rewritelen {
return nil, scratch // Already short name, no need to rewrite.
}
newName := append([]byte{}, scratch[:rewritelen]...)
h = hash(scratch, h)
scratch = s.AppendShaderBody(scratch[:0])
h = hash(scratch, h)
newName = strconv.AppendUint(newName, h, 32)
return newName, scratch
}
// ParseAppendNodes parses the shader object tree and appends all nodes in Depth First order
// to the dst Shader argument buffer and returns the result.
func ParseAppendNodes(dst []Shader, root Shader) (baseName string, nodes []Shader, err error) {
if root == nil {
return "", nil, errors.New("nil shader object")
}
baseName = string(root.AppendShaderName([]byte{}))
if baseName == "" {
return "", nil, errors.New("empty shader name")
}
dst, err = AppendAllNodes(dst, root)
if err != nil {
return "", nil, err
}
return baseName, dst, nil
}
// WriteShaders iterates over the argument nodes in reverse order and
// writes their GL code to the writer. scratch is an auxiliary buffer to avoid heap allocations.
//
// WriteShaders does not check for repeated shader names nor long tokens which may yield errors in the GL.
func WriteShaders(w io.Writer, nodes []Shader, scratch []byte) (n int, newscratch []byte, err error) {
if scratch == nil {
scratch = make([]byte, 1024)
}
var ngot int
for i := len(nodes) - 1; i >= 0; i-- {
ngot, scratch, err = WriteShader(w, nodes[i], scratch[:0])
n += ngot
if err != nil {
return n, scratch, err
}
}
return n, scratch, nil
}
func WriteShader(w io.Writer, s Shader, scratch []byte) (int, []byte, error) {
scratch = scratch[:0]
scratch = append(scratch, "float "...)
scratch = s.AppendShaderName(scratch)
if _, ok := s.(Shader3D); ok {
scratch = append(scratch, "(vec3 p) {\n"...)
} else {
scratch = append(scratch, "(vec2 p) {\n"...)
}
scratch = s.AppendShaderBody(scratch)
scratch = append(scratch, "\n}\n\n"...)
n, err := w.Write(scratch)
return n, scratch, err
}
// AppendShaderBufferDecl appends the [ShaderObject] as a Shader Storage Buffer Object (SSBO). Returns an error if not a buffer.
//
// layout(<ssbo.std>, binding = <base>) buffer <BlockName> {
// <ssbo.Element> <ssbo.NamePtr>[];
// } <instanceName>;
func AppendShaderBufferDecl(dst []byte, BlockName, instanceName string, ssbo ShaderObject) ([]byte, error) {
err := ssbo.Validate()
if err != nil {
return dst, err
} else if BlockName == "" && instanceName == "" {
return nil, errors.New("AppendShaderBufferDecl requires BlockName for a valid SSBO declaration")
}
const std = "std140" // Subject to change, would be provided by ShaderBuffer.
typename, err := glTypename(ssbo.Element)
if err != nil {
return dst, fmt.Errorf("typename failed for %q: %w", ssbo.NamePtr, err)
}
dst = append(dst, "layout("...)
dst = append(dst, std...)
dst = append(dst, ",binding="...)
dst = strconv.AppendInt(dst, int64(ssbo.Binding), 10)
dst = append(dst, ") buffer"...)
if len(BlockName) > 0 {
dst = append(dst, ' ')
dst = append(dst, BlockName...)
}
dst = append(dst, " {\n\t"...)
dst = append(dst, typename...)
dst = append(dst, ' ')
dst = append(dst, ssbo.NamePtr...)
dst = append(dst, "[];\n}"...)
if len(instanceName) > 0 {
dst = append(dst, ' ')
dst = append(dst, instanceName...)
}
dst = append(dst, ";\n"...)
return dst, nil
}
func (obj ShaderObject) Validate() error {
if obj.Data == nil {
return errors.New("shader object nil data pointer")
} else if obj.Size == 0 {
return errors.New("shader object zero/negative length data")
} else if obj.Size < 0 {
return errors.New("shader object negative length of data")
} else if !obj.read {
return errors.New("shader object no usage defined")
} else if len(obj.NamePtr) == 0 {
return errors.New("shader object zero-length name")
} else if obj.Binding < 0 {
return errors.New("shader object negative binding point")
}
_, err := glTypename(obj.Element)
if err != nil {
return err
}
return nil
}
func glTypename(tp reflect.Type) (typename string, err error) {
switch tp {
case reflect.TypeOf(md2.Vec{}):
typename = "dvec2"
case reflect.TypeOf(md3.Vec{}):
typename = "dvec3"
case reflect.TypeOf(float64(0)):
typename = "double"
case reflect.TypeOf(float32(0)):
typename = "float"
case reflect.TypeOf(ms2.Vec{}):
typename = "vec2"
case reflect.TypeOf(ms3.Vec{}):
typename = "vec3"
case reflect.TypeOf([2]ms2.Vec{}), reflect.TypeOf(ms3.Quat{}):
typename = "vec4"
case reflect.TypeOf(ms2.Mat2{}):
typename = "mat2"
case reflect.TypeOf(ms3.Mat3{}):
typename = "mat3"
case reflect.TypeOf(ms3.Mat4{}):
typename = "mat4"
case reflect.TypeOf(uint32(0)):
typename = "uint"
case reflect.TypeOf(int32(0)):
typename = "int"
case reflect.TypeOf([2]uint32{}):
typename = "uvec2"
case reflect.TypeOf([2]int32{}):
typename = "ivec2"
case reflect.TypeOf([3]uint32{}):
typename = "uvec3"
case reflect.TypeOf([3]int32{}):
typename = "ivec3"
case nil:
err = errors.New("nil element type")
default:
err = fmt.Errorf("equivalent type not implemented for %s", tp.String())
}
return typename, err
}
// AppendShaderSource appends the GL code of a single shader to the dst byte buffer. If dst's
// capacity is grown during the writing the buffer with augmented capacity is returned. If not the same input dst is returned.
// name and body byte slices pointing to the result buffer are also returned for convenience.
func AppendShaderSource(dst []byte, s Shader) (result, name, body []byte) {
dst = append(dst, "float "...)
nameStart := len(dst)
dst = s.AppendShaderName(dst)
nameEnd := len(dst)
_, is3D := s.(Shader3D)
if is3D {
dst = append(dst, "(vec3 p){\n"...)
} else {
dst = append(dst, "(vec2 p){\n"...)
}
bodyStart := len(dst)
dst = s.AppendShaderBody(dst)
bodyEnd := len(dst)
dst = append(dst, "\n}\n"...)
return dst, dst[nameStart:nameEnd], dst[bodyStart:bodyEnd]
}
// AppendAllNodes BFS iterates over all of root's descendants and appends all nodes
// found to dst.
//
// To generate shaders one must iterate over nodes in reverse order to ensure
// the first iterated nodes are the nodes with no dependencies on other nodes.
func AppendAllNodes(dst []Shader, root Shader) ([]Shader, error) {
var userData any
children := []Shader{root}
nextChild := 0
nilChild := errors.New("got nil child in AppendAllNodes")
for len(children[nextChild:]) > 0 {
newChildren := children[nextChild:]
for _, obj := range newChildren {
nextChild++
obj3, ok3 := obj.(Shader3D)
obj2, ok2 := obj.(Shader2D)
if !ok2 && !ok3 {
return nil, fmt.Errorf("found shader %T that does not implement Shader3D nor Shader2D", obj)
}
var err error
if ok3 {
// Got Shader3D in obj.
err = obj3.ForEachChild(userData, func(userData any, s *Shader3D) error {
if s == nil || *s == nil {
return nilChild
}
children = append(children, *s)
return nil
})
if obj32, ok32 := obj.(shader3D2D); ok32 {
// The Shader3D obj contains Shader2D children, such is case for 2D->3D operations i.e: revolution and extrusion operations.
err = obj32.ForEach2DChild(userData, func(userData any, s *Shader2D) error {
if s == nil || *s == nil {
return nilChild
}
children = append(children, *s)
return nil
})
}
}
if err == nil && !ok3 && ok2 {
// Got Shader2D in obj.
err = obj2.ForEach2DChild(userData, func(userData any, s *Shader2D) error {
if s == nil || *s == nil {
return nilChild
}
children = append(children, *s)
return nil
})
}
if err != nil {
return nil, err
}
}
}
dst = append(dst, children...)
return dst, nil
}
func forEachNode(root Shader, fn3 func(any, *Shader3D) error, fn2 func(any, *Shader2D) error) error {
var userData any
children := []Shader{root}
nextChild := 0
nilChild := errors.New("got nil child in AppendAllNodes")
for len(children[nextChild:]) > 0 {
newChildren := children[nextChild:]
for _, obj := range newChildren {
nextChild++
obj3, ok3 := obj.(Shader3D)
obj2, ok2 := obj.(Shader2D)
if !ok2 && !ok3 {
return fmt.Errorf("found shader %T that does not implement Shader3D nor Shader2D", obj)
}
var err error
if ok3 {
// Got Shader3D in obj.
err = obj3.ForEachChild(userData, func(userData any, s *Shader3D) error {
if s == nil || *s == nil {
return nilChild
}
children = append(children, *s)
return fn3(userData, s)
})
if obj32, ok32 := obj.(shader3D2D); ok32 {
// The Shader3D obj contains Shader2D children, such is case for 2D->3D operations i.e: revolution and extrusion operations.
err = obj32.ForEach2DChild(userData, func(userData any, s *Shader2D) error {
if s == nil || *s == nil {
return nilChild
}
children = append(children, *s)
return fn2(userData, s)
})
}
}
if err == nil && !ok3 && ok2 {
// Got Shader2D in obj.
err = obj2.ForEach2DChild(userData, func(userData any, s *Shader2D) error {
if s == nil || *s == nil {
return nilChild
}
children = append(children, *s)
return fn2(userData, s)
})
}
if err != nil {
return err
}
}
}
return nil
}
func AppendDefineDecl(b []byte, aliasToDefine, aliasReplace string) []byte {
b = append(b, "#define "...)
b = append(b, aliasToDefine...)
b = append(b, ' ')
b = append(b, aliasReplace...)
b = append(b, '\n')
return b
}
func AppendUndefineDecl(b []byte, aliasToUndefine string) []byte {
b = append(b, "#undef "...)
b = append(b, aliasToUndefine...)
b = append(b, '\n')
return b
}
func AppendDistanceDecl(b []byte, floatVarname, sdfPositionArgInput string, s Shader) []byte {
b = append(b, "float "...)
b = append(b, floatVarname...)
b = append(b, '=')
b = s.AppendShaderName(b)
b = append(b, '(')
b = append(b, sdfPositionArgInput...)
b = append(b, ");\n"...)
return b
}
func AppendVec3Decl(b []byte, vec3Varname string, v ms3.Vec) []byte {
b = append(b, "vec3 "...)
b = append(b, vec3Varname...)
b = append(b, "=vec3("...)
arr := v.Array()
b = AppendFloats(b, ',', '-', '.', arr[:]...)
b = append(b, ')', ';', '\n')
return b
}
func AppendVec2Decl(b []byte, vec2Varname string, v ms2.Vec) []byte {
b = append(b, "vec2 "...)
b = append(b, vec2Varname...)
b = append(b, "=vec2("...)
arr := v.Array()
b = AppendFloats(b, ',', '-', '.', arr[:]...)
b = append(b, ')', ';', '\n')
return b
}
func AppendFloatDecl(b []byte, floatVarname string, v float32) []byte {
b = append(b, "float "...)
b = append(b, floatVarname...)
b = append(b, '=')
b = AppendFloat(b, '-', '.', v)
b = append(b, ';', '\n')
return b
}
func AppendMat2Decl(b []byte, mat2Varname string, m22 ms2.Mat2) []byte {
arr := m22.Array()
return appendMatDecl(b, "mat2", mat2Varname, 2, 2, arr[:])
}
func AppendMat3Decl(b []byte, mat3Varname string, m33 ms3.Mat3) []byte {
arr := m33.Array()
return appendMatDecl(b, "mat3", mat3Varname, 3, 3, arr[:])
}
func AppendMat4Decl(b []byte, mat4Varname string, m44 ms3.Mat4) []byte {
arr := m44.Array()
return appendMatDecl(b, "mat4", mat4Varname, 4, 4, arr[:])
}
func appendMatDecl(b []byte, typename, name string, row, col int, arr []float32) []byte {
b = append(b, typename...)
b = append(b, ' ')
b = append(b, name...)
b = append(b, '=')
b = append(b, typename...)
b = append(b, '(')
for i := 0; i < row; i++ {
for j := 0; j < col; j++ {
v := arr[j*row+i] // Column major access, as per OpenGL standard.
b = AppendFloat(b, '-', '.', v)
last := i == row-1 && j == col-1
if !last {
b = append(b, ',')
}
}
}
b = append(b, ");\n"...)
return b
}
const decimalDigits = 9
func AppendFloat(b []byte, neg, decimal byte, v float32) []byte {
start := len(b)
b = strconv.AppendFloat(b, float64(v), 'f', decimalDigits, 32)
idx := bytes.IndexByte(b[start:], '.')
if decimal != '.' && idx >= 0 {
b[start+idx] = decimal
}
if b[start] == '-' {
b[start] = neg
}
// Finally trim zeroes.
end := len(b)
for i := len(b) - 1; idx >= 0 && i > idx+start && b[i] == '0'; i-- {
end--
}
// TODO(soypat): Round off when find N consecutive 9's?
return b[:end]
}
func AppendFloats(b []byte, sep, neg, decimal byte, s ...float32) []byte {
for i, v := range s {
b = AppendFloat(b, neg, decimal, v)
if sep != 0 && i != len(s)-1 {
b = append(b, sep)
}
}
return b
}
const maxLineLim = 500
func AppendFloatSliceDecl(b []byte, floatSliceVarname string, vecs []float32) []byte {
lineStart := len(b)
b = appendStartSliceDecl(b, "float", floatSliceVarname, len(vecs))
for i, v := range vecs {
last := i == len(vecs)-1
b = AppendFloat(b, '-', '.', v)
if !last {
b = append(b, ',')
lineLen := len(b) - lineStart
if lineLen > maxLineLim {
b = append(b, '\n') // Break up line for VERY long polygon vertex lists.
lineStart = len(b)
}
}
}
b = append(b, ");\n"...)
return b
}
func AppendVec2SliceDecl(b []byte, vec2Varname string, vecs []ms2.Vec) []byte {
lineStart := len(b)
b = appendStartSliceDecl(b, "vec2", vec2Varname, len(vecs))
for i, v := range vecs {
last := i == len(vecs)-1
b = append(b, "vec2("...)
b = AppendFloats(b, ',', '-', '.', v.X, v.Y)
b = append(b, ')')
if !last {
b = append(b, ',')
lineLen := len(b) - lineStart
if lineLen > maxLineLim {
b = append(b, '\n') // Break up line for VERY long polygon vertex lists.
lineStart = len(b)
}
}
}
b = append(b, ");\n"...)
return b
}
func AppendVec3SliceDecl(b []byte, vec3Varname string, vecs []ms3.Vec) []byte {
lineStart := len(b)
b = appendStartSliceDecl(b, "vec3", vec3Varname, len(vecs))
for i, v := range vecs {
last := i == len(vecs)-1
b = append(b, "vec3("...)
b = AppendFloats(b, ',', '-', '.', v.X, v.Y, v.Z)
b = append(b, ')')
if !last {
b = append(b, ',')
lineLen := len(b) - lineStart
if lineLen > maxLineLim {
b = append(b, '\n') // Break up line for VERY long polygon vertex lists.
lineStart = len(b)
}
}
}
b = append(b, ");\n"...)
return b
}
func appendStartSliceDecl(b []byte, typeName, varName string, length int) []byte {
l := int64(length)
typeStart := len(b)
b = append(b, typeName...)
b = append(b, "["...)
b = strconv.AppendInt(b, l, 10)
b = append(b, ']')
typeEnd := len(b)
b = append(b, varName...)
b = append(b, '=')
b = append(b, b[typeStart:typeEnd]...) // Reuse typename appended earlier.
b = append(b, '(')
return b
}
type XYZBits uint8
const (
xBit XYZBits = 1 << iota
yBit
zBit
)
func (xyz XYZBits) X() bool { return xyz&xBit != 0 }
func (xyz XYZBits) Y() bool { return xyz&yBit != 0 }
func (xyz XYZBits) Z() bool { return xyz&zBit != 0 }
func NewXYZBits(x, y, z bool) XYZBits {
return XYZBits(b2i(x) | b2i(y)<<1 | b2i(z)<<2)
}
func (xyz XYZBits) AppendMapped(b []byte, Map [3]byte) []byte {
if xyz.X() {
b = append(b, Map[0])
}
if xyz.Y() {
b = append(b, Map[1])
}
if xyz.Z() {
b = append(b, Map[2])
}
return b
}
func (xyz XYZBits) AppendMapped_XYZ(b []byte) []byte {
return xyz.AppendMapped(b, [3]byte{'X', 'Y', 'Z'})
}
func (xyz XYZBits) AppendMapped_xyz(b []byte) []byte {
return xyz.AppendMapped(b, [3]byte{'x', 'y', 'z'})
}
func (xyz XYZBits) AppendMapped_rgb(b []byte) []byte {
return xyz.AppendMapped(b, [3]byte{'r', 'g', 'b'})
}
func b2i(b bool) int {
if b {
return 1
}
return 0
}
// OverloadShader3DBounds overloads a [Shader3D] Bounds method with the argument bounding box.
func OverloadShader3DBounds(s Shader3D, bb ms3.Box) Shader3D {
return &overloadBounds3{
Shader3D: s,
bb: bb,
}
}
type overloadBounds3 struct {
Shader3D
bb ms3.Box
}
func (ob3 *overloadBounds3) Bounds() ms3.Box { return ob3.bb }
// Evaluate implements the gleval.SDF3 interface.
func (ob3 *overloadBounds3) Evaluate(pos []ms3.Vec, dist []float32, userData any) error {
sdf, ok := ob3.Shader3D.(sdf3)
if !ok {
return fmt.Errorf("%T does not implement gleval.SDF3", ob3.Shader3D)
}
return sdf.Evaluate(pos, dist, userData)
}
// OverloadShader2DBounds overloads a [Shader2D] Bounds method with the argument bounding box.
func OverloadShader2DBounds(s Shader2D, bb ms2.Box) Shader2D {
return &overloadBounds2{
Shader2D: s,
bb: bb,
}
}
type overloadBounds2 struct {
Shader2D
bb ms2.Box
}
func (ob2 *overloadBounds2) Bounds() ms2.Box { return ob2.bb }
// Evaluate implements the gleval.SDF2 interface.
func (ob3 *overloadBounds2) Evaluate(pos []ms2.Vec, dist []float32, userData any) error {
sdf, ok := ob3.Shader2D.(sdf2)
if !ok {
return fmt.Errorf("%T does not implement gleval.SDF3", ob3.Shader2D)
}
return sdf.Evaluate(pos, dist, userData)
}
var _ Shader3D = (*CachedShader3D)(nil) // Interface implementation compile-time check.
// CachedShader3D implements the Shader3D interface with results it caches for another Shader3D on a call to RefreshCache.
type CachedShader3D struct {
Shader Shader3D
bb ms3.Box
data []byte
bodyOffset int
}
// RefreshCache updates the cache with current values of the underlying shader.
func (c3 *CachedShader3D) RefreshCache() {
c3.bb = c3.Shader.Bounds()