-
Notifications
You must be signed in to change notification settings - Fork 0
/
compute.go
2202 lines (2053 loc) · 56.1 KB
/
compute.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
// SPDX-License-Identifier: Unlicense OR MIT
package gpu
import (
"bytes"
"encoding/binary"
"errors"
"fmt"
"hash/maphash"
"image"
"image/color"
"image/draw"
"image/png"
"math"
"math/bits"
"os"
"runtime"
"sort"
"time"
"unsafe"
"gioui.org/cpu"
"gioui.org/shader"
"gioui.org/shader/gio"
"gioui.org/shader/piet"
"github.com/Seikaijyu/gio/gpu/internal/driver"
"github.com/Seikaijyu/gio/internal/byteslice"
"github.com/Seikaijyu/gio/internal/f32"
"github.com/Seikaijyu/gio/internal/f32color"
"github.com/Seikaijyu/gio/internal/ops"
"github.com/Seikaijyu/gio/internal/scene"
"github.com/Seikaijyu/gio/layout"
"github.com/Seikaijyu/gio/op"
)
type compute struct {
ctx driver.Device
collector collector
enc encoder
texOps []textureOp
viewport image.Point
maxTextureDim int
srgb bool
atlases []*textureAtlas
frameCount uint
moves []atlasMove
programs struct {
elements computeProgram
tileAlloc computeProgram
pathCoarse computeProgram
backdrop computeProgram
binning computeProgram
coarse computeProgram
kernel4 computeProgram
}
buffers struct {
config sizedBuffer
scene sizedBuffer
state sizedBuffer
memory sizedBuffer
}
output struct {
blitPipeline driver.Pipeline
buffer sizedBuffer
uniforms *copyUniforms
uniBuf driver.Buffer
layerVertices []layerVertex
descriptors *piet.Kernel4DescriptorSetLayout
nullMaterials driver.Texture
}
// imgAllocs maps imageOpData.handles to allocs.
imgAllocs map[interface{}]*atlasAlloc
// materials contains the pre-processed materials (transformed images for
// now, gradients etc. later) packed in a texture atlas. The atlas is used
// as source in kernel4.
materials struct {
// allocs maps texture ops the their atlases and FillImage offsets.
allocs map[textureKey]materialAlloc
pipeline driver.Pipeline
buffer sizedBuffer
quads []materialVertex
uniforms struct {
u *materialUniforms
buf driver.Buffer
}
}
timers struct {
profile string
t *timers
compact *timer
render *timer
blit *timer
}
// CPU fallback fields.
useCPU bool
dispatcher *dispatcher
// The following fields hold scratch space to avoid garbage.
zeroSlice []byte
memHeader *memoryHeader
conf *config
}
type materialAlloc struct {
alloc *atlasAlloc
offset image.Point
}
type layer struct {
rect image.Rectangle
alloc *atlasAlloc
ops []paintOp
materials *textureAtlas
}
type allocQuery struct {
atlas *textureAtlas
size image.Point
empty bool
format driver.TextureFormat
bindings driver.BufferBinding
nocompact bool
}
type atlasAlloc struct {
atlas *textureAtlas
rect image.Rectangle
cpu bool
dead bool
frameCount uint
}
type atlasMove struct {
src *textureAtlas
dstPos image.Point
srcRect image.Rectangle
cpu bool
}
type textureAtlas struct {
image driver.Texture
format driver.TextureFormat
bindings driver.BufferBinding
hasCPU bool
cpuImage cpu.ImageDescriptor
size image.Point
allocs []*atlasAlloc
packer packer
realized bool
lastFrame uint
compact bool
}
type copyUniforms struct {
scale [2]float32
pos [2]float32
uvScale [2]float32
_ [8]byte // Pad to 16 bytes.
}
type materialUniforms struct {
scale [2]float32
pos [2]float32
emulatesRGB float32
_ [12]byte // Pad to 16 bytes
}
type collector struct {
hasher maphash.Hash
profile bool
reader ops.Reader
states []f32.Affine2D
clear bool
clearColor f32color.RGBA
clipStates []clipState
order []hashIndex
transStack []transEntry
prevFrame opsCollector
frame opsCollector
}
type transEntry struct {
t f32.Affine2D
relTrans f32.Affine2D
}
type hashIndex struct {
index int
hash uint64
}
type opsCollector struct {
paths []byte
clipCmds []clipCmd
ops []paintOp
layers []layer
}
type paintOp struct {
clipStack []clipCmd
offset image.Point
state paintKey
intersect f32.Rectangle
hash uint64
layer int
texOpIdx int
}
// clipCmd describes a clipping command ready to be used for the compute
// pipeline.
type clipCmd struct {
// union of the bounds of the operations that are clipped.
union f32.Rectangle
state clipKey
path []byte
pathKey ops.Key
absBounds f32.Rectangle
}
type encoderState struct {
relTrans f32.Affine2D
clip *clipState
paintKey
}
// clipKey completely describes a clip operation (along with its path) and is appropriate
// for hashing and equality checks.
type clipKey struct {
bounds f32.Rectangle
strokeWidth float32
relTrans f32.Affine2D
pathHash uint64
}
// paintKey completely defines a paint operation. It is suitable for hashing and
// equality checks.
type paintKey struct {
t f32.Affine2D
matType materialType
// Current paint.ImageOp
image imageOpData
// Current paint.ColorOp, if any.
color color.NRGBA
// Current paint.LinearGradientOp.
stop1 f32.Point
stop2 f32.Point
color1 color.NRGBA
color2 color.NRGBA
}
type clipState struct {
absBounds f32.Rectangle
parent *clipState
path []byte
pathKey ops.Key
intersect f32.Rectangle
clipKey
}
type layerVertex struct {
posX, posY float32
u, v float32
}
// materialVertex describes a vertex of a quad used to render a transformed
// material.
type materialVertex struct {
posX, posY float32
u, v float32
}
// textureKey identifies textureOp.
type textureKey struct {
handle interface{}
transform f32.Affine2D
bounds image.Rectangle
}
// textureOp represents an paintOp that requires texture space.
type textureOp struct {
img imageOpData
key textureKey
// offset is the integer offset separated from key.transform to increase cache hit rate.
off image.Point
// matAlloc is the atlas placement for material.
matAlloc materialAlloc
// imgAlloc is the atlas placement for the source image
imgAlloc *atlasAlloc
}
type encoder struct {
scene []scene.Command
npath int
npathseg int
ntrans int
}
// sizedBuffer holds a GPU buffer, or its equivalent CPU memory.
type sizedBuffer struct {
size int
buffer driver.Buffer
// cpuBuf is initialized when useCPU is true.
cpuBuf cpu.BufferDescriptor
}
// computeProgram holds a compute program, or its equivalent CPU implementation.
type computeProgram struct {
prog driver.Program
// CPU fields.
progInfo *cpu.ProgramInfo
descriptors unsafe.Pointer
buffers []*cpu.BufferDescriptor
}
// config matches Config in setup.h
type config struct {
n_elements uint32 // paths
n_pathseg uint32
width_in_tiles uint32
height_in_tiles uint32
tile_alloc memAlloc
bin_alloc memAlloc
ptcl_alloc memAlloc
pathseg_alloc memAlloc
anno_alloc memAlloc
trans_alloc memAlloc
}
// memAlloc matches Alloc in mem.h
type memAlloc struct {
offset uint32
//size uint32
}
// memoryHeader matches the header of Memory in mem.h.
type memoryHeader struct {
mem_offset uint32
mem_error uint32
}
// rect is a oriented rectangle.
type rectangle [4]f32.Point
const (
layersBindings = driver.BufferBindingShaderStorageWrite | driver.BufferBindingTexture
materialsBindings = driver.BufferBindingFramebuffer | driver.BufferBindingShaderStorageRead
// Materials and layers can share texture storage if their bindings match.
combinedBindings = layersBindings | materialsBindings
)
// GPU structure sizes and constants.
const (
tileWidthPx = 32
tileHeightPx = 32
ptclInitialAlloc = 1024
kernel4OutputUnit = 2
kernel4AtlasUnit = 3
pathSize = 12
binSize = 8
pathsegSize = 52
annoSize = 32
transSize = 24
stateSize = 60
stateStride = 4 + 2*stateSize
)
// mem.h constants.
const (
memNoError = 0 // NO_ERROR
memMallocFailed = 1 // ERR_MALLOC_FAILED
)
func newCompute(ctx driver.Device) (*compute, error) {
caps := ctx.Caps()
maxDim := caps.MaxTextureSize
// Large atlas textures cause artifacts due to precision loss in
// shaders.
if cap := 8192; maxDim > cap {
maxDim = cap
}
// The compute programs can only span 128x64 tiles. Limit to 64 for now, and leave the
// complexity of a rectangular limit for later.
if computeCap := 4096; maxDim > computeCap {
maxDim = computeCap
}
g := &compute{
ctx: ctx,
maxTextureDim: maxDim,
srgb: caps.Features.Has(driver.FeatureSRGB),
conf: new(config),
memHeader: new(memoryHeader),
}
shaders := []struct {
prog *computeProgram
src shader.Sources
info *cpu.ProgramInfo
}{
{&g.programs.elements, piet.Shader_elements_comp, piet.ElementsProgramInfo},
{&g.programs.tileAlloc, piet.Shader_tile_alloc_comp, piet.Tile_allocProgramInfo},
{&g.programs.pathCoarse, piet.Shader_path_coarse_comp, piet.Path_coarseProgramInfo},
{&g.programs.backdrop, piet.Shader_backdrop_comp, piet.BackdropProgramInfo},
{&g.programs.binning, piet.Shader_binning_comp, piet.BinningProgramInfo},
{&g.programs.coarse, piet.Shader_coarse_comp, piet.CoarseProgramInfo},
{&g.programs.kernel4, piet.Shader_kernel4_comp, piet.Kernel4ProgramInfo},
}
if !caps.Features.Has(driver.FeatureCompute) {
if !cpu.Supported {
return nil, errors.New("gpu: missing support for compute programs")
}
g.useCPU = true
}
if g.useCPU {
g.dispatcher = newDispatcher(runtime.NumCPU())
} else {
null, err := ctx.NewTexture(driver.TextureFormatRGBA8, 1, 1, driver.FilterNearest, driver.FilterNearest, driver.BufferBindingShaderStorageRead)
if err != nil {
g.Release()
return nil, err
}
g.output.nullMaterials = null
}
copyVert, copyFrag, err := newShaders(ctx, gio.Shader_copy_vert, gio.Shader_copy_frag)
if err != nil {
g.Release()
return nil, err
}
defer copyVert.Release()
defer copyFrag.Release()
pipe, err := ctx.NewPipeline(driver.PipelineDesc{
VertexShader: copyVert,
FragmentShader: copyFrag,
VertexLayout: driver.VertexLayout{
Inputs: []driver.InputDesc{
{Type: shader.DataTypeFloat, Size: 2, Offset: 0},
{Type: shader.DataTypeFloat, Size: 2, Offset: 4 * 2},
},
Stride: int(unsafe.Sizeof(g.output.layerVertices[0])),
},
PixelFormat: driver.TextureFormatOutput,
BlendDesc: driver.BlendDesc{
Enable: true,
SrcFactor: driver.BlendFactorOne,
DstFactor: driver.BlendFactorOneMinusSrcAlpha,
},
Topology: driver.TopologyTriangles,
})
if err != nil {
g.Release()
return nil, err
}
g.output.blitPipeline = pipe
g.output.uniforms = new(copyUniforms)
buf, err := ctx.NewBuffer(driver.BufferBindingUniforms, int(unsafe.Sizeof(*g.output.uniforms)))
if err != nil {
g.Release()
return nil, err
}
g.output.uniBuf = buf
materialVert, materialFrag, err := newShaders(ctx, gio.Shader_material_vert, gio.Shader_material_frag)
if err != nil {
g.Release()
return nil, err
}
defer materialVert.Release()
defer materialFrag.Release()
pipe, err = ctx.NewPipeline(driver.PipelineDesc{
VertexShader: materialVert,
FragmentShader: materialFrag,
VertexLayout: driver.VertexLayout{
Inputs: []driver.InputDesc{
{Type: shader.DataTypeFloat, Size: 2, Offset: 0},
{Type: shader.DataTypeFloat, Size: 2, Offset: 4 * 2},
},
Stride: int(unsafe.Sizeof(g.materials.quads[0])),
},
PixelFormat: driver.TextureFormatRGBA8,
Topology: driver.TopologyTriangles,
})
if err != nil {
g.Release()
return nil, err
}
g.materials.pipeline = pipe
g.materials.uniforms.u = new(materialUniforms)
buf, err = ctx.NewBuffer(driver.BufferBindingUniforms, int(unsafe.Sizeof(*g.materials.uniforms.u)))
if err != nil {
g.Release()
return nil, err
}
g.materials.uniforms.buf = buf
for _, shader := range shaders {
if !g.useCPU {
p, err := ctx.NewComputeProgram(shader.src)
if err != nil {
g.Release()
return nil, err
}
shader.prog.prog = p
} else {
shader.prog.progInfo = shader.info
}
}
if g.useCPU {
{
desc := new(piet.ElementsDescriptorSetLayout)
g.programs.elements.descriptors = unsafe.Pointer(desc)
g.programs.elements.buffers = []*cpu.BufferDescriptor{desc.Binding0(), desc.Binding1(), desc.Binding2(), desc.Binding3()}
}
{
desc := new(piet.Tile_allocDescriptorSetLayout)
g.programs.tileAlloc.descriptors = unsafe.Pointer(desc)
g.programs.tileAlloc.buffers = []*cpu.BufferDescriptor{desc.Binding0(), desc.Binding1()}
}
{
desc := new(piet.Path_coarseDescriptorSetLayout)
g.programs.pathCoarse.descriptors = unsafe.Pointer(desc)
g.programs.pathCoarse.buffers = []*cpu.BufferDescriptor{desc.Binding0(), desc.Binding1()}
}
{
desc := new(piet.BackdropDescriptorSetLayout)
g.programs.backdrop.descriptors = unsafe.Pointer(desc)
g.programs.backdrop.buffers = []*cpu.BufferDescriptor{desc.Binding0(), desc.Binding1()}
}
{
desc := new(piet.BinningDescriptorSetLayout)
g.programs.binning.descriptors = unsafe.Pointer(desc)
g.programs.binning.buffers = []*cpu.BufferDescriptor{desc.Binding0(), desc.Binding1()}
}
{
desc := new(piet.CoarseDescriptorSetLayout)
g.programs.coarse.descriptors = unsafe.Pointer(desc)
g.programs.coarse.buffers = []*cpu.BufferDescriptor{desc.Binding0(), desc.Binding1()}
}
{
desc := new(piet.Kernel4DescriptorSetLayout)
g.programs.kernel4.descriptors = unsafe.Pointer(desc)
g.programs.kernel4.buffers = []*cpu.BufferDescriptor{desc.Binding0(), desc.Binding1()}
g.output.descriptors = desc
}
}
return g, nil
}
func newShaders(ctx driver.Device, vsrc, fsrc shader.Sources) (vert driver.VertexShader, frag driver.FragmentShader, err error) {
vert, err = ctx.NewVertexShader(vsrc)
if err != nil {
return
}
frag, err = ctx.NewFragmentShader(fsrc)
if err != nil {
vert.Release()
}
return
}
func (g *compute) Frame(frameOps *op.Ops, target RenderTarget, viewport image.Point) error {
g.frameCount++
g.collect(viewport, frameOps)
return g.frame(target)
}
func (g *compute) collect(viewport image.Point, ops *op.Ops) {
g.viewport = viewport
g.collector.reset()
g.texOps = g.texOps[:0]
g.collector.collect(ops, viewport, &g.texOps)
}
func (g *compute) Clear(col color.NRGBA) {
g.collector.clear = true
g.collector.clearColor = f32color.LinearFromSRGB(col)
}
func (g *compute) frame(target RenderTarget) error {
viewport := g.viewport
defFBO := g.ctx.BeginFrame(target, g.collector.clear, viewport)
defer g.ctx.EndFrame()
t := &g.timers
if g.collector.profile && t.t == nil && g.ctx.Caps().Features.Has(driver.FeatureTimers) {
t.t = newTimers(g.ctx)
t.compact = t.t.newTimer()
t.render = t.t.newTimer()
t.blit = t.t.newTimer()
}
if err := g.uploadImages(); err != nil {
return err
}
if err := g.renderMaterials(); err != nil {
return err
}
g.layer(viewport, g.texOps)
t.render.begin()
if err := g.renderLayers(viewport); err != nil {
return err
}
t.render.end()
d := driver.LoadDesc{
ClearColor: g.collector.clearColor,
}
if g.collector.clear {
g.collector.clear = false
d.Action = driver.LoadActionClear
}
t.blit.begin()
g.blitLayers(d, defFBO, viewport)
t.blit.end()
t.compact.begin()
if err := g.compactAllocs(); err != nil {
return err
}
t.compact.end()
if g.collector.profile && t.t.ready() {
com, ren, blit := t.compact.Elapsed, t.render.Elapsed, t.blit.Elapsed
ft := com + ren + blit
q := 100 * time.Microsecond
ft = ft.Round(q)
com, ren, blit = com.Round(q), ren.Round(q), blit.Round(q)
t.profile = fmt.Sprintf("ft:%7s com: %7s ren:%7s blit:%7s", ft, com, ren, blit)
}
return nil
}
func (g *compute) dumpAtlases() {
for i, a := range g.atlases {
dump := image.NewRGBA(image.Rectangle{Max: a.size})
err := driver.DownloadImage(g.ctx, a.image, dump)
if err != nil {
panic(err)
}
nrgba := image.NewNRGBA(dump.Bounds())
draw.Draw(nrgba, image.Rectangle{}, dump, image.Point{}, draw.Src)
var buf bytes.Buffer
if err := png.Encode(&buf, nrgba); err != nil {
panic(err)
}
if err := os.WriteFile(fmt.Sprintf("dump-%d.png", i), buf.Bytes(), 0600); err != nil {
panic(err)
}
}
}
func (g *compute) Profile() string {
return g.timers.profile
}
func (g *compute) compactAllocs() error {
const (
maxAllocAge = 3
maxAtlasAge = 10
)
atlases := g.atlases
for _, a := range atlases {
if len(a.allocs) > 0 && g.frameCount-a.lastFrame > maxAtlasAge {
a.compact = true
}
}
for len(atlases) > 0 {
var (
dstAtlas *textureAtlas
format driver.TextureFormat
bindings driver.BufferBinding
)
g.moves = g.moves[:0]
addedLayers := false
useCPU := false
fill:
for len(atlases) > 0 {
srcAtlas := atlases[0]
allocs := srcAtlas.allocs
if !srcAtlas.compact {
atlases = atlases[1:]
continue
}
if addedLayers && (format != srcAtlas.format || srcAtlas.bindings&bindings != srcAtlas.bindings) {
break
}
format = srcAtlas.format
bindings = srcAtlas.bindings
for len(srcAtlas.allocs) > 0 {
a := srcAtlas.allocs[0]
n := len(srcAtlas.allocs)
if g.frameCount-a.frameCount > maxAllocAge {
a.dead = true
srcAtlas.allocs[0] = srcAtlas.allocs[n-1]
srcAtlas.allocs = srcAtlas.allocs[:n-1]
continue
}
size := a.rect.Size()
alloc, fits := g.atlasAlloc(allocQuery{
atlas: dstAtlas,
size: size,
format: format,
bindings: bindings,
nocompact: true,
})
if !fits {
break fill
}
dstAtlas = alloc.atlas
allocs = append(allocs, a)
addedLayers = true
useCPU = useCPU || a.cpu
dstAtlas.allocs = append(dstAtlas.allocs, a)
pos := alloc.rect.Min
g.moves = append(g.moves, atlasMove{
src: srcAtlas, dstPos: pos, srcRect: a.rect, cpu: a.cpu,
})
a.atlas = dstAtlas
a.rect = image.Rectangle{Min: pos, Max: pos.Add(a.rect.Size())}
srcAtlas.allocs[0] = srcAtlas.allocs[n-1]
srcAtlas.allocs = srcAtlas.allocs[:n-1]
}
srcAtlas.compact = false
srcAtlas.realized = false
srcAtlas.packer.clear()
srcAtlas.packer.newPage()
srcAtlas.packer.maxDims = image.Pt(g.maxTextureDim, g.maxTextureDim)
atlases = atlases[1:]
}
if !addedLayers {
break
}
outputSize := dstAtlas.packer.sizes[0]
if err := g.realizeAtlas(dstAtlas, useCPU, outputSize); err != nil {
return err
}
for _, move := range g.moves {
if !move.cpu {
g.ctx.CopyTexture(dstAtlas.image, move.dstPos, move.src.image, move.srcRect)
} else {
src := move.src.cpuImage.Data()
dst := dstAtlas.cpuImage.Data()
sstride := move.src.size.X * 4
dstride := dstAtlas.size.X * 4
copyImage(dst, dstride, move.dstPos, src, sstride, move.srcRect)
}
}
}
for i := len(g.atlases) - 1; i >= 0; i-- {
a := g.atlases[i]
if len(a.allocs) == 0 && g.frameCount-a.lastFrame > maxAtlasAge {
a.Release()
n := len(g.atlases)
g.atlases[i] = g.atlases[n-1]
g.atlases = g.atlases[:n-1]
}
}
return nil
}
func copyImage(dst []byte, dstStride int, dstPos image.Point, src []byte, srcStride int, srcRect image.Rectangle) {
sz := srcRect.Size()
soff := srcRect.Min.Y*srcStride + srcRect.Min.X*4
doff := dstPos.Y*dstStride + dstPos.X*4
rowLen := sz.X * 4
for y := 0; y < sz.Y; y++ {
srow := src[soff : soff+rowLen]
drow := dst[doff : doff+rowLen]
copy(drow, srow)
soff += srcStride
doff += dstStride
}
}
func (g *compute) renderLayers(viewport image.Point) error {
layers := g.collector.frame.layers
for len(layers) > 0 {
var materials, dst *textureAtlas
addedLayers := false
g.enc.reset()
for len(layers) > 0 {
l := &layers[0]
if l.alloc != nil {
layers = layers[1:]
continue
}
if materials != nil {
if l.materials != nil && materials != l.materials {
// Only one materials texture per compute pass.
break
}
} else {
materials = l.materials
}
size := l.rect.Size()
alloc, fits := g.atlasAlloc(allocQuery{
atlas: dst,
empty: true,
format: driver.TextureFormatRGBA8,
bindings: combinedBindings,
// Pad to avoid overlap.
size: size.Add(image.Pt(1, 1)),
})
if !fits {
// Only one output atlas per compute pass.
break
}
dst = alloc.atlas
dst.compact = true
addedLayers = true
l.alloc = &alloc
dst.allocs = append(dst.allocs, l.alloc)
encodeLayer(*l, alloc.rect.Min, viewport, &g.enc, g.texOps)
layers = layers[1:]
}
if !addedLayers {
break
}
outputSize := dst.packer.sizes[0]
tileDims := image.Point{
X: (outputSize.X + tileWidthPx - 1) / tileWidthPx,
Y: (outputSize.Y + tileHeightPx - 1) / tileHeightPx,
}
w, h := tileDims.X*tileWidthPx, tileDims.Y*tileHeightPx
if err := g.realizeAtlas(dst, g.useCPU, image.Pt(w, h)); err != nil {
return err
}
if err := g.render(materials, dst.image, dst.cpuImage, tileDims, dst.size.X*4); err != nil {
return err
}
}
return nil
}
func (g *compute) blitLayers(d driver.LoadDesc, fbo driver.Texture, viewport image.Point) {
layers := g.collector.frame.layers
g.output.layerVertices = g.output.layerVertices[:0]
for _, l := range layers {
placef := layout.FPt(l.alloc.rect.Min)
sizef := layout.FPt(l.rect.Size())
r := f32.FRect(l.rect)
quad := [4]layerVertex{
{posX: float32(r.Min.X), posY: float32(r.Min.Y), u: placef.X, v: placef.Y},
{posX: float32(r.Max.X), posY: float32(r.Min.Y), u: placef.X + sizef.X, v: placef.Y},
{posX: float32(r.Max.X), posY: float32(r.Max.Y), u: placef.X + sizef.X, v: placef.Y + sizef.Y},
{posX: float32(r.Min.X), posY: float32(r.Max.Y), u: placef.X, v: placef.Y + sizef.Y},
}
g.output.layerVertices = append(g.output.layerVertices, quad[0], quad[1], quad[3], quad[3], quad[2], quad[1])
g.ctx.PrepareTexture(l.alloc.atlas.image)
}
if len(g.output.layerVertices) > 0 {
vertexData := byteslice.Slice(g.output.layerVertices)
g.output.buffer.ensureCapacity(false, g.ctx, driver.BufferBindingVertices, len(vertexData))
g.output.buffer.buffer.Upload(vertexData)
}
g.ctx.BeginRenderPass(fbo, d)
defer g.ctx.EndRenderPass()
if len(layers) == 0 {
return
}
g.ctx.Viewport(0, 0, viewport.X, viewport.Y)
g.ctx.BindPipeline(g.output.blitPipeline)
g.ctx.BindVertexBuffer(g.output.buffer.buffer, 0)
start := 0
for len(layers) > 0 {
count := 0
atlas := layers[0].alloc.atlas
for len(layers) > 0 {
l := layers[0]
if l.alloc.atlas != atlas {
break
}
layers = layers[1:]
const verticesPerQuad = 6
count += verticesPerQuad
}
// Transform positions to clip space: [-1, -1] - [1, 1], and texture
// coordinates to texture space: [0, 0] - [1, 1].
clip := f32.Affine2D{}.Scale(f32.Pt(0, 0), f32.Pt(2/float32(viewport.X), 2/float32(viewport.Y))).Offset(f32.Pt(-1, -1))
sx, _, ox, _, sy, oy := clip.Elems()
g.output.uniforms.scale = [2]float32{sx, sy}
g.output.uniforms.pos = [2]float32{ox, oy}
g.output.uniforms.uvScale = [2]float32{1 / float32(atlas.size.X), 1 / float32(atlas.size.Y)}
g.output.uniBuf.Upload(byteslice.Struct(g.output.uniforms))
g.ctx.BindUniforms(g.output.uniBuf)
g.ctx.BindTexture(0, atlas.image)
g.ctx.DrawArrays(start, count)
start += count
}
}
func (g *compute) renderMaterials() error {
m := &g.materials
for k, place := range m.allocs {
if place.alloc.dead {
delete(m.allocs, k)
}
}
texOps := g.texOps
for len(texOps) > 0 {
m.quads = m.quads[:0]
var (
atlas *textureAtlas
imgAtlas *textureAtlas
)
// A material is clipped to avoid drawing outside its atlas bounds.
// However, imprecision in the clipping may cause a single pixel
// overflow.
var padding = image.Pt(1, 1)
var allocStart int
for len(texOps) > 0 {
op := &texOps[0]
if a, exists := m.allocs[op.key]; exists {
g.touchAlloc(a.alloc)
op.matAlloc = a
texOps = texOps[1:]
continue
}
if imgAtlas != nil && op.imgAlloc.atlas != imgAtlas {
// Only one image atlas per render pass.
break
}
imgAtlas = op.imgAlloc.atlas
quad := g.materialQuad(imgAtlas.size, op.key.transform, op.img, op.imgAlloc.rect.Min)
boundsf := quadBounds(quad)
bounds := boundsf.Round()
bounds = bounds.Intersect(op.key.bounds)
size := bounds.Size()
alloc, fits := g.atlasAlloc(allocQuery{
atlas: atlas,
size: size.Add(padding),
format: driver.TextureFormatRGBA8,
bindings: combinedBindings,
})
if !fits {
break
}
if atlas == nil {
allocStart = len(alloc.atlas.allocs)
}
atlas = alloc.atlas
alloc.cpu = g.useCPU
offsetf := layout.FPt(bounds.Min.Mul(-1))
scale := f32.Pt(float32(size.X), float32(size.Y))
for i := range quad {
// Position quad to match place.
quad[i].posX += offsetf.X
quad[i].posY += offsetf.Y
// Scale to match viewport [0, 1].
quad[i].posX /= scale.X
quad[i].posY /= scale.Y
}
// Draw quad as two triangles.
m.quads = append(m.quads, quad[0], quad[1], quad[3], quad[3], quad[1], quad[2])
if m.allocs == nil {
m.allocs = make(map[textureKey]materialAlloc)
}
atlasAlloc := materialAlloc{
alloc: &alloc,
offset: bounds.Min.Mul(-1),
}
atlas.allocs = append(atlas.allocs, atlasAlloc.alloc)
m.allocs[op.key] = atlasAlloc
op.matAlloc = atlasAlloc
texOps = texOps[1:]
}
if len(m.quads) == 0 {
break
}
realized := atlas.realized
if err := g.realizeAtlas(atlas, g.useCPU, atlas.packer.sizes[0]); err != nil {
return err
}
// Transform to clip space: [-1, -1] - [1, 1].
*m.uniforms.u = materialUniforms{
scale: [2]float32{2, 2},
pos: [2]float32{-1, -1},
}
if !g.srgb {
m.uniforms.u.emulatesRGB = 1.0
}
m.uniforms.buf.Upload(byteslice.Struct(m.uniforms.u))
vertexData := byteslice.Slice(m.quads)
n := pow2Ceil(len(vertexData))
m.buffer.ensureCapacity(false, g.ctx, driver.BufferBindingVertices, n)