rev: 21c5e6d2f665d0e8b4ff917a51b664c895dab2ed tukan/tukan/csgpainter.sc -rw-r--r-- 69.8 KiB View raw Log this file
21c5e6d2f665 — Leonard Ritter * renamed project from Liminal to Tukan 2 years ago
                                                                                
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
# todo:
    vec3 Geoffrey(float t)
    {
        vec3 r = t * 2.1 - vec3(1.8, 1.14, 0.3);
        return 1.0 - r * r;
    }

#
    idea for improvement:
    - start at 1/8 resolution
    - raster OBB's conservatively
    - resolve pixels directly in fragment shader, conservatively
        - how to do it conservatively?
    - first optimal resolve for interior zbuffer

# with newton-raphson iteration

#
    using "none.libc"
    var system
        require "liminal.system"
    var window
        require "liminal.window"
    using "GLEW"
    using "liminal.imgui"
    using "liminal.screen"
    using "liminal.gl"
    using "liminal.bitmath"
    using "liminal.rotation"
    using "liminal.gltimer"
    using "liminal.utils"
    using "liminal.projection"
    using "liminal.vecmath"

    import-from "glsl" shader-compile

using import glm
using import .projection

# idea: transform brushes into view space so points save rotation effort

struct ComputeDispatchArgs
    num_groups_x : u32
    num_groups_y : u32
    num_groups_z : u32

struct LinkFragment
    objectid : i32
    t_init : f32
    next : i32

struct LinkBufferArray
    count : i32
    fragments : (array LinkFragment 0:usize)

struct ContourElement
    # 2x16
    fragcoord : u32
    first : i32

struct ContourMapArray
    count : i32
    fragcoords : (array ContourElement 0:usize)

struct Shape
    size : vec3
    radius : vec3

    method 'repr (self)
        .. "<size="
            repr self.size.x
            \ " " (repr self.size.y)
            \ " " (repr self.size.z)
            \ " " (repr self.radius.z)
            " radius="
            repr self.radius.x
            \ " " (repr self.radius.y)
            ">"

    # (Shape vec4 vec2)
    method 'shape (cls size radius)
        'structof cls
            size = size.xyz
            radius = (vec3 radius size.w)

    # ('box Shape vec3)
    method 'box (cls size)
        'shape cls (vec4 size 0) (vec2 0)

    # ('rounded-box Shape vec3 float)
    method 'rounded-box (cls size corner)
        'shape cls (vec4 size 0) (vec2 corner)

    # ('cube Shape float)
    method 'cube (cls size)
        'box cls (vec3 size)

    # ('rounded-cube Shape float float)
    method 'rounded-cube (cls size corner)
        'rounded-box cls (vec3 size) corner

    # ('sphere Shape float)
    method 'sphere (cls radius)
        'shape cls (vec4 radius radius radius 0) (vec2 radius)

    # ('cylinder Shape float float)
    method 'cylinder (cls radius height)
        'shape cls (vec4 radius radius height 0) (vec2 radius 0)

    # ('rounded-cylinder Shape float float float)
    method 'cylinder (cls radius height corner)
        'shape cls (vec4 radius radius height 0) (vec2 radius corner)

    # ('capsule Shape float float)
    method 'capsule (cls radius height)
        'shape cls (vec4 radius radius (radius + height) 0) (vec2 radius)

    # ('cone Shape float float)
    method 'cone (cls radius height)
        'shape cls (vec4 0 0 height radius) (vec2 0 0)

    # ('capped-cone Shape float float float)
    method 'capped-cone (cls radius1 radius2 height)
        'shape cls
            vec4 radius2 radius2 height (radius1 - radius2)
            vec2 radius2 0

struct Brush
    rotation : vec4
    origin : vec3
    shape : Shape

    method 'repr (self)
        .. "< " (repr self.shape) " origin=" (repr self.origin) " rotation=" (repr self.rotation) ">"

    method 'apply-type (cls shape origin rotation)
        'structof cls
            rotation =
                do
                    if (none? rotation)
                        vec4 0 0 0 1
                    else rotation
            origin =
                do
                    if (none? origin)
                        vec3 0
                    else origin

            shape =
                do
                    if (none? shape)
                        'cube Shape 1
                    else shape

struct BrushArray
    brushes : (array Brush 0:usize)

struct BrushMaterial
    albedo : vec3

struct BrushMaterialArray
    materials : (array BrushMaterial 0:usize)

struct ShaderGlobals
    time : f32
    frame : i32
    numbrushes : i32
    sunzoom : f32
    sundir : vec3
    viewsundir : vec3

struct ViewParams
    rotation : mat3
    projection : ProjectionSetup
    origin : vec3
    screensize : ivec2
    obbtexsize : ivec2
    surfacetexsize : ivec2
    #screensizepow2 : ivec2
    #screenbits : i32

let BUFFER_COUNT = 4
#let NUM_GROUPS = 13
let NUM_GROUPS = 128
let NUM_THREADS = 8
let NUM_GROUP_THREADS = (NUM_GROUPS * NUM_THREADS)

let NUM_RAYMARCH_STEPS = 8
let MAX_LINK_FRAGS_PP = 128

let WORK_FACTOR = 8

let NUM_LINK_FRAGMENTS =
    1024 * 1024 * 2
let NUM_CONTOUR_PIXELS =
    1920 * 1080

let USE_SUN = false

let NR_EPS =
    #1e-5
    1e-4

# factor by which to reduce the abuffer resolution
let ABUFFER_DIV = 4

let SMIN_R = 0.5

let MAX_BRUSHES = 65535
let SUNMAP_BITS = 9
let SUNMAP_SIZE =
    1 << SUNMAP_BITS

let SS_SRC_BRUSHES = 0
let SS_SRC_BRUSH_MATERIALS = 1
let SS_SRC_LINK_FRAGMENTS = 2
let SS_DST_LINK_FRAGMENTS = 3
let SS_SRC_CONTOUR_MAP = 4
let SS_DST_CONTOUR_MAP = 5
let SS_DST_COMPUTE_ARGS = 6

let IMG_SRC_START_OFFSETS = 0
let IMG_DST_START_OFFSETS = 1
let IMG_SRC_ID = 2
let IMG_DST_ID = 3

let UB_GLOBALS = 0
let UB_VIEWPARAMS = 1
let UB_SUNPARAMS = 2

let U_REFINE_LEVEL = 0
let U_DEBUG_VIZ_MODE = 1

let SMP_AABB_ZBUFFER = 0
let SMP_VIEW_GBUFFER = 1
let SMP_DEPTH_GBUFFER = 2
let SMP_ID_GBUFFER = 3

let CENTER = 5
let NEAR = 0.01
let FAR = 400.0

fn shaders ()
    import .screen
    using import glsl
    using import .csg
    using import .derivative
    using import .rotation
    using import .normal
    using import .hash
    using import .ssao
    using import .fog
    using import .color
    #
        syntax-import "glsl"
        using "glsl.builtin"
        using "glsl.projection"
        import-from "glsl.rotation"
            versor
            matrotation rotation
            versor-rotate
        using "glsl.color"
        using "glsl.derivative"
        using "glsl.bitmath"
        using "glsl.hash"
        ;using "glsl.random"
        ;using "glsl.compaction"
        using "glsl.math"
        using "glsl.csg"
        using "glsl.normal"
        using "glsl.ssao"
        using "glsl.fog"

    xvar out out_fragment-color : vec4
        location = 0
    xvar in in_fragment-color : vec4
        location = 0
    xvar out out_screen_uv : vec2
        location = 1
    xvar in in_screen_uv : vec2
        location = 1
    xvar out out_ndc_uv : vec2
        location = 2
    xvar in in_ndc_uv : vec2
        location = 2
    xvar out out_aabb-objectid : i32
        location = 3
    xvar in in_aabb-objectid : i32
        location = 3

    xvar buffer dst_dispatch_args : ComputeDispatchArgs
        binding = SS_DST_COMPUTE_ARGS
        \ coherent writeonly restrict

    xvar buffer src_brushes : BrushArray
        binding = SS_SRC_BRUSHES
        \ coherent readonly restrict
    xvar buffer src_brush_materials : BrushMaterialArray
        binding = SS_SRC_BRUSH_MATERIALS
        \ coherent readonly restrict

    let iimagetype = (iimage2D 'R32i)
    xvar uniform src_start_offsets : iimagetype
        binding = IMG_SRC_START_OFFSETS
        \ coherent readonly restrict
    xvar uniform dst_start_offsets : iimagetype
        binding = IMG_DST_START_OFFSETS
        \ coherent restrict
    xvar uniform dst_start_offsets_w : iimagetype
        binding = IMG_DST_START_OFFSETS
        \ coherent writeonly restrict

    let uimagetype = (uimage2D 'Rg32ui)
    xvar uniform src_id : uimagetype
        binding = IMG_SRC_ID
        \ coherent readonly restrict
    xvar uniform dst_id : uimagetype
        binding = IMG_DST_ID
        \ coherent writeonly restrict

    xvar buffer src_link_offsets : LinkBufferArray
        binding = SS_SRC_LINK_FRAGMENTS
        \ coherent readonly restrict
    xvar buffer dst_link_offsets : LinkBufferArray
        binding = SS_DST_LINK_FRAGMENTS
        \ coherent restrict

    xvar buffer src_contour_map : ContourMapArray
        binding = SS_SRC_CONTOUR_MAP
        \ coherent readonly restrict
    xvar buffer dst_contour_map : ContourMapArray
        binding = SS_DST_CONTOUR_MAP
        \ coherent restrict

    xvar uniform globals : ShaderGlobals
        binding = UB_GLOBALS
    xvar uniform viewparams : ViewParams
        binding = UB_VIEWPARAMS
    xvar uniform sunparams : ViewParams
        binding = UB_SUNPARAMS

    xvar uniform smp_aabb_zbuffer : sampler2DArray
        binding = SMP_AABB_ZBUFFER
    xvar uniform smp_view_gbuffer : sampler2D
        binding = SMP_VIEW_GBUFFER
    xvar uniform smp_depth_gbuffer : sampler2D
        binding = SMP_DEPTH_GBUFFER
    xvar uniform smp_id_gbuffer : isampler2DArray
        binding = SMP_ID_GBUFFER

    xvar uniform refine_level : i32
        location = U_REFINE_LEVEL

    xvar uniform debug_viz_mode : i32
        location = U_DEBUG_VIZ_MODE

    # (i32 f32) <- u32
    fn unpack_objectid_tinit (pval)
        "unpacks objectid and t_init from packed value"
        return
            i32 (pval & 0xffff:u32)
            (unpackHalf2x16 pval) . y

    # u32 <- (i32 f32)
    fn pack_objectid_tinit (objectid t_init)
        |
            u32 objectid
            packHalf2x16 (vec2 0 t_init)

    fn count_depth (start_frag)
        let loop (i fragref) = (unconst 0) start_frag
        if ((i == 128) | (fragref == 0))
            return i
        let fraginfo =
            src_link_offsets.fragments @ fragref
        loop (i + 1) (load fraginfo.next)

    # da3_float <- (i32 da3_vec3)
    fn eval_brush_gradient (brushid p)
        let brush = (src_brushes.brushes @ brushid)
        let invrot = brush.rotation
        let invrot = (vec4 invrot.xyz (- invrot.w))
        da_uberprim_convex
            da_versor_rotate invrot
                da_sub p brush.origin
            brush.size.xyz
            brush.radius

    # no change in performance when using this version over the one above
        even though the derivatives are not perfect, we don't hit singularities
        close to the surface.
    # vec3 <- (i32 vec3)
    fn eval_brush_gradient_cd (brushid p)
        let brush = (src_brushes.brushes @ brushid)
        let invrot = brush.rotation
        let invrot = (vec4 invrot.xyz (- invrot.w))
        let e = (0.0001 * (vec2 0.5 -0.5))
        let d0 =
            uberprim_convex
                versor-rotate invrot
                    - (p + e.xyy) brush.origin
                brush.size.xyz
                brush.radius
        let d1 =
            uberprim_convex
                versor-rotate invrot
                    - (p + e.yxy) brush.origin
                brush.size.xyz
                brush.radius
        let d2 =
            uberprim_convex
                versor-rotate invrot
                    - (p + e.yyx) brush.origin
                brush.size.xyz
                brush.radius
        let d3 =
            uberprim_convex
                versor-rotate invrot
                    - (p + e.xxx) brush.origin
                brush.size.xyz
                brush.radius
        normalize
            +
                e.xyy * d0
                e.yxy * d1
                e.yyx * d2
                e.xxx * d3

    let PIXEL_RADIUS = 0.70710678118655

    # f32 <- (i32 vec3 vec3 f32 f32 f32)
    fn eval_brush_distance (brushid ro rd tmin tmax aperture)
        let brush = (src_brushes.brushes @ brushid)
        let invrot = brush.rotation
        let invrot = (vec4 invrot.xyz (- invrot.w))
        let loop (k t) = (unconst 0) (unconst tmin)
        label break (t)
            return t
        if (k == NUM_RAYMARCH_STEPS)
            break t
        let td = (da3_f32 1 0 0 t)
        let pd = (da_add ro (da_mul rd td))
        let d =
            da_uberprim_convex
                da_versor_rotate invrot
                    da_sub pd brush.origin
                brush.size.xyz
                brush.radius
        let d =
            da_sub d
                da_mul
                    da_add
                        da_mul td
                            viewparams.projection.w_coeffs.x
                        viewparams.projection.w_coeffs.y
                    aperture
        if ((abs d.w) < NR_EPS)
            break t
        if ((d.x >= 0.0) | (t >= tmax))
            break tmax
        loop (k + 1)
            d.w / (max (- d.x) 0.0)

    # (f32 i32) <- (i32 vec3 vec3 f32 float)
    fn eval_distance (start_frag ro rd tmax aperture)
        var tmax = tmax
        var brushid = 0
        let loop (i fragref) = (unconst 0) (unconst start_frag)
        label break ()
            return (load tmax) (load brushid)
        if (i == MAX_LINK_FRAGS_PP)
            break;
        let fraginfo = (src_link_offsets.fragments @ fragref)
        let fragref = fraginfo.next
        let objid = fraginfo.objectid
        let t_init = fraginfo.t_init
        if (t_init < tmax)
            let t =
                eval_brush_distance objid ro rd t_init (load tmax) aperture
            if (t < tmax)
                tmax = t
                brushid = objid
        if (fragref == 0)
            break;
        loop (i + 1) fragref

    # (vec2 i32) <- (i32 vec3 vec3 f32 f32 i32)
    fn eval_distance_shadow (start_frag ro rd t0 t1 startbrush)
        return (vec2 0) 0

    #---------------------------------------------------------------------------

    fn map-quad ()
        let ndc = (screen.set-vertex-position)
        out_ndc_uv = ndc
        out_screen_uv = (ndc * 0.5 + 0.5)
        return;

    #---------------------------------------------------------------------------

    fn do-raymarch ()
        let fragcoord = (ivec2 (in_screen_uv * viewparams.surfacetexsize))
        let srcdata = ((imageLoad src_id fragcoord) . rg)
        let brushid = (i32 srcdata.r)
        let t_init = (bitcast srcdata.g f32)

        if (brushid != 0)
            let uv = (load in_ndc_uv)
            let v0 = ('project-inverse viewparams.projection (vec4 uv 1 1))
            let vnormal = (normalize v0.xyz)
            let vdir = (vnormal * viewparams.rotation)

            let origin = viewparams.origin

            let screensizef = (vec2 viewparams.screensize)
            let pixel = (1.0 / (min screensizef.x screensizef.y))
            let tmax = inf
            let iters = 0
            let t =
                eval_brush_distance
                    brushid
                    origin
                    vdir
                    t_init
                    tmax
                    PIXEL_RADIUS * pixel

            if (t >= tmax)
                discard!;

            let p = (origin + (vdir * (t * 0.99999)))

            let normal =
                #eval_brush_gradient_cd brushid p
                .
                    eval_brush_gradient brushid
                        da3_vec3
                            da3_f32 1 0 0 p.x
                            da3_f32 0 1 0 p.y
                            da3_f32 0 0 1 p.z
                    xyz
            let viewnormal = ((viewparams.rotation * normal) . xyz)

            let viewpos = (vnormal * t)
            let clippos = ('project viewparams.projection (vec4 viewpos 1))
            let depth = (clippos.z / clippos.w)
            gl_FragDepth = depth
            out_fragment-color =
                vec4
                    ### normhue
                        kt.x / (float 10)
                    #vec3hash (float brushid)
                    ### normhue
                        (float iters) / (float NUM_RAYMARCH_STEPS)
                    #(normalize normal.xyz) * 0.5 + 0.5
                    #viewnormal.xy * 0.5 + 0.5
                    pack_normal_snorm
                        vec3 viewnormal.xy (- viewnormal.z)
                    #viewpos
                    0
                    0
        return;

    #---------------------------------------------------------------------------

    # start from surface, trace towards light
    fn do-sun-raymarch (worldpos normal bias startbrush)
        "(f32 vec3) <- (vec3 vec3 f32 i32)"
        let viewpos =
            (sunparams.rotation * (worldpos - sunparams.origin)) . xyz
        let clippos =
            'project sunparams.projection (vec4 viewpos 1)
        let ndcpos = (clippos / clippos.w)

        let ndclimits =
            abs
                vec3
                    ndcpos.xy
                    ndcpos.z * 2.0 - 1.0

        if ((max ndclimits.x ndclimits.y ndclimits.z) > 1.0)
            return
                unconst 1.0
                unconst (vec3 1 0 0)
        let fragcoord =
            ivec2
                (ndcpos.xy * 0.5 + 0.5) * sunparams.surfacetexsize
        let start_frag =
            (imageLoad src_start_offsets fragcoord) . r
        let nearz =
            #(texelFetch smp_aabb_zbuffer (ivec3 fragcoord 0) 0) . r
            1.0
        let uv = ndcpos.xy
        let v0 =
            'project-inverse sunparams.projection (vec4 uv nearz 1)

        if ((start_frag == 0) | ((v0.z + bias) > viewpos.z))
            return
                unconst 1.0
                unconst
                    vec3 (? (start_frag == 0) 1.0 0.0) 1 0
        let v1 = viewpos
        let p0 = (v0.xyz * sunparams.rotation)
        let p1 = (v1.xyz * sunparams.rotation)
        let vdist = (p0 - p1)
        let vlen = (length vdist)
        let vdir = (vdist / vlen)
        let origin = (sunparams.origin + p1)
        let brushid = 0
        let t0 = 0.0
        let kt brushid =
            eval_distance_shadow start_frag origin vdir t0 vlen startbrush
        if (brushid == 0)
            return
                unconst 1.0
                unconst
                    vec3 0 0 1
        let fragviewpos =
            v1.xyz + (v0.xyz - v1.xyz) * (kt.x / vlen)
        if (fragviewpos.z > viewpos.z)
            return
                unconst 1.0
                unconst (vec3 1)
        return
            unconst 0.0
            unconst (vec3 0)

    #---------------------------------------------------------------------------

    fn do-abuffer-viz ()
        let fc =
            ivec2 (in_screen_uv * viewparams.surfacetexsize)
            #(ivec2 gl_FragCoord.xy) / 2
        let k = ((imageLoad src_start_offsets fc) . r)
        let kid = (i32 ((imageLoad src_id fc) . r))
        let loop (i k colors levels) = (unconst 0) k (unconst (vec3 0)) (unconst 0)
        if ((i < 128) & (k != 0))
            let fraginfo = (src_link_offsets.fragments @ k)
            let objid = fraginfo.objectid
            loop (i + 1)
                load fraginfo.next
                colors +
                    ? (objid == 0) (vec3 1 0 0) (vec3hash (f32 objid))
                levels + 1
        out_fragment-color =
            vec4
                if (levels == 1)
                    vec3 1 0 0
                elseif (levels == 0)
                    vec3hash (f32 kid)
                else
                    colors / (f32 levels)
                ### normhue
                    (f32 levels) / 8.0
                1.0
        return;

    #---------------------------------------------------------------------------

    fn ssao_sample_depth (vp)
        "f32 <- (vec3)"
        let clippos = ('project viewparams.projection (vec4 vp 1))
        let clippos = (vec4 (clippos.xyz / clippos.w) 1.0)
        #if ((max (abs clippos.x) (abs clippos.y)) >= 1.0)
        #   1.0 / 0.0
        let fragcoord =
            ivec2
                (clippos.xy * 0.5 + 0.5) * viewparams.screensize
        let depth =
            (texelFetch smp_depth_gbuffer fragcoord 0) . r
        let viewpos =
            'project-inverse viewparams.projection (vec4 clippos.xy depth 1)
        viewpos.z

    #-------------------------------------------------------------------------------

    let ssao_occlusion = (SSAO (sample_depth = ssao_sample_depth))

    fn do-gbuffer-viz ()
        let fragcoord = (ivec2 (in_screen_uv * viewparams.screensize))
        let depth =
            #(texelFetch smp_aabb_zbuffer (ivec3 fragcoord 0) 0) . r
            (texelFetch smp_depth_gbuffer fragcoord 0) . r
        let brushid =
            (texelFetch smp_id_gbuffer (ivec3 fragcoord 0) 0) . r
        let viewpos =
            'project-inverse viewparams.projection (vec4 in_ndc_uv depth 1)

        let normal =
            unpack_normal_snorm ((texelFetch smp_view_gbuffer fragcoord 0) . xy)
        let normal =
            vec3 normal.xy (- normal.z)
        let color =
            if (depth == 0.0)
                vec3 0 0 0.1
            else
                let cos_Ol = (dot normal (- globals.viewsundir))

                let albedo =
                    (src_brush_materials.materials @ brushid) . albedo
                    #vec3hash (f32 brushid)
                    ### hue2rgb
                        (float brushid) / (float globals.numbrushes)
                    #vec3 1
                let lambert = (max 0.0 cos_Ol)

                # half lambert term
                # see http://www.valvesoftware.com/publications/2007/NPAR07_IllustrativeRenderingInTeamFortress2.pdf
                let half_lambert = (0.5 + 0.5 * cos_Ol)

                let occ = (ssao_occlusion viewpos.xyz normal globals.time)
                let shadowterm =
                    if (USE_SUN and (lambert > 0.0))
                        do-sun-raymarch
                            viewpos.xyz * viewparams.rotation + viewparams.origin
                            \ normal 0.1 brushid
                    else 1.0
                #vec3 occ
                * albedo
                    +
                        * lambert
                            shadowterm
                            vec3 1 0.9 0.8
                        *
                            half_lambert * 0.2 + 0.1
                            exp2 (occ * -4.0)
                            vec3 0.8 0.9 1.0

        let distsq = (dot viewpos viewpos)
        let color =
            mix
                vec3 0.01 0.1 1
                color
                fogterm
                    fog_setup 500.0
                    distsq

        out_fragment-color =
            vec4
                # linear_srgb
                tonemap color
                #color
                1
        return;

    fn do-znearfar-viz ()
        let fc = (ivec2 (in_screen_uv * viewparams.surfacetexsize))
            #(ivec2 gl_FragCoord.xy) / 2
        let k =
            (imageLoad src_start_offsets fc) . r
        let loop (i k tmax) = (unconst 0) (unconst k) (unconst inf)
        if ((i < 128) & (k != 0))
            let fraginfo = (src_link_offsets.fragments @ k)
            let objid = fraginfo.objectid
            let t_init = fraginfo.t_init
            loop (i + 1)
                load fraginfo.next
                min tmax t_init
        out_fragment-color =
            vec4
                hue2rgb tmax
                ### vec3
                    tmax / (float 10)
                1
        return;

    #---------------------------------------------------------------------------

    fn do-debug-viz ()
        match debug_viz_mode
            0
                do-abuffer-viz;
            1
                do-znearfar-viz;
            2
                do-gbuffer-viz;
        return;

    #---------------------------------------------------------------------------

    let cube-vertices =
        arrayof vec3
            vec3 -1 -1 -1
            vec3 -1 -1  1
            vec3 -1  1 -1
            vec3 -1  1  1
            vec3  1 -1 -1
            vec3  1 -1  1
            vec3  1  1 -1
            vec3  1  1  1

    ;---------------------------------------------------------------------------

    fn transform-aabb-vertex (brush mp)
        vec4 <- (Brush vec3)
        var p
            .
                * viewparams.rotation
                    +
                        versor-rotate brush.rotation mp
                        brush.origin - viewparams.origin
                xyz
        var cp
            projection viewparams.projection (vec4 p 1)


shaders;

#

    function shaders ()




        shader transform-aabb-vertex-conservative (brush cv offset depth_offset) :
            vec4 <- (Brush vec3 float float)

            var cp
                transform-aabb-vertex brush cv
            var cpx
                transform-aabb-vertex brush
                    vec3 (- cv.x) cv.y cv.z
            var cpy
                transform-aabb-vertex brush
                    vec3 cv.x (- cv.y) cv.z
            var cpz
                transform-aabb-vertex brush
                    vec3 cv.x cv.y (- cv.z)

            var nx
                cpx.xyw - cp.xyw
            var ny
                cpy.xyw - cp.xyw
            var nz
                cpz.xyw - cp.xyw
            var eps
                1e-5
            var dxy
                if ((dot cp.xyw (cross nx ny)) < eps) 0 1
            var dyz
                if ((dot cp.xyw (cross ny nz)) < eps) 0 1
            var dzx
                if ((dot cp.xyw (cross nz nx)) < eps) 0 1
            var ux
                dxy ^ dzx
            var uy
                dyz ^ dxy
            var uz
                dzx ^ dyz
            do-if ((ux + uy + uz) == 2)
                var plane0 : vec3
                var plane1 : vec3
                if (ux == 1)
                    do
                        plane0 = nx
                        plane1 =
                            if (uy == 1) ny nz
                    do
                        plane0 = ny
                        plane1 = nz

                var ds
                    sign
                        dot cp.xyw (cross plane1 plane0)

                plane0 =
                    cross cp.xyw plane0
                plane1 =
                    cross plane1 cp.xyw

                var hpixel
                    offset / (vec2 viewparams.obbtexsize)

                plane0.z -=
                    ds *
                        dot hpixel
                            abs plane0.xy
                plane1.z -=
                    ds *
                        dot hpixel
                            abs plane1.xy

                var xp
                    cross plane0 plane1

                do-if (xp.z != (float 0))
                    cp.xy = (xp.xy / xp.z) * cp.w

            cp

        shader map-aabb () :
            void <- ()
            var brushid
                gl_InstanceID + 1
            var brush : Brush
                src_brushes.brushes # brushid
            var cv
                cube-vertices # gl_VertexID
            cv =
                cv * (brush.size.xyz + (vec3 brush.radius.zz 0))
            aabb-objectid = brushid
            gl_Position =
                transform-aabb-vertex-conservative brush cv 1 0

        shader map-aabb-debug () :
            void <- ()
            var brushid
                gl_InstanceID + 1
            var brush : Brush
                src_brushes.brushes # brushid
            var cv
                cube-vertices # gl_VertexID
            cv =
                cv * (brush.size.xyz + (vec3 brush.radius.zz 0))
            aabb-objectid = brushid
            gl_Position =
                transform-aabb-vertex brush cv

        var RCORNERZ
            ;0.28867513459481
            0.5 * 0.57735026918963
        var RCORNERXY
            0.5 * 0.70710678118655
        shader map-inner-aabb () :
            void <- ()
            var brushid
                gl_InstanceID + 1
            var brush : Brush
                src_brushes.brushes # brushid
            var cv
                cube-vertices # gl_VertexID
            var minl
                min brush.size.x brush.size.y brush.size.z
            var r
                vec2
                    (length brush.radius.xyz) * RCORNERZ
                    (length brush.radius.xyz) * RCORNERZ
            cv =
                cv * (max (brush.size.xyz - r.xxy) (float 0))
            gl_Position =
                transform-aabb-vertex-conservative brush cv -1 -1

        shader render-aabb-raymarch () :
            void <- ()
            var screensizef
                vec2 viewparams.obbtexsize
            var uv
                (gl_FragCoord.xy / screensizef) * (float 2) - (float 1)

            var v0
                inverse_projection viewparams.projection
                    vec4 uv 1 1
            var vnormal
                normalize v0.xyz
            var vdir
                vnormal * viewparams.rotation

            var pixel
                (float 1) / (min screensizef.x screensizef.y)

            var tmax
                (float 1) / (float 0)
            var t
                eval_brush_distance
                    aabb-objectid
                    viewparams.origin
                    vdir
                    float 0
                    tmax
                    PIXEL_RADIUS * pixel

            do-if (t < tmax)
                var viewpos
                    vnormal * t
                var clippos
                    projection viewparams.projection
                        vec4 viewpos 1
                var depth
                    clippos.z / clippos.w

                var fragcoord
                    ivec2 gl_FragCoord.xy
                var nearz
                    (texelFetch smp_aabb_zbuffer (ivec3 fragcoord 0) 0) . r
                do-if (depth > nearz)
                    ; get new fragment index
                    var newidx
                        atomicAdd dst_link_offsets.count 1
                    do-if (newidx < NUM_LINK_FRAGMENTS)
                        ; exchange previous stored link with new link
                        var oldidx
                            imageAtomicExchange dst_start_offsets fragcoord newidx
                        ; new link points to old link
                        dst_link_offsets.fragments # newidx . next = oldidx
                        dst_link_offsets.fragments # newidx . objectid = aabb-objectid
                        dst_link_offsets.fragments # newidx . t_init = t

        shader render-aabb-z-raymarch () :
            void <- ()
            var screensizef
                vec2 viewparams.obbtexsize
            var uv
                (gl_FragCoord.xy / screensizef) * (float 2) - (float 1)

            var v0
                inverse_projection viewparams.projection
                    vec4 uv 1 1
            var vnormal
                normalize v0.xyz
            var vdir
                vnormal * viewparams.rotation

            var pixel
                (float 1) / (min screensizef.x screensizef.y)

            var tmax
                (float 1) / (float 0)
            var t
                eval_brush_distance
                    aabb-objectid
                    viewparams.origin
                    vdir
                    float 0
                    tmax
                    (- PIXEL_RADIUS) * pixel

            do-if (t >= tmax)
                discard ;

            var viewpos
                vnormal * t
            var clippos
                projection viewparams.projection
                    vec4 viewpos 1
            var depth
                clippos.z / clippos.w
            gl_FragDepth =
                depth

        ### shader render-aabb () :
            void <- ()
            var st
                ivec2 gl_FragCoord.xy
            ; get new fragment index
            var newidx
                atomicAdd dst_link_offsets.count 1
            do-if (newidx < NUM_LINK_FRAGMENTS)
                ; exchange previous stored link with new link
                var oldidx
                    imageAtomicExchange dst_start_offsets st newidx
                ; new link points to old link
                dst_link_offsets.fragments # newidx . next = oldidx
                dst_link_offsets.fragments # newidx . objectid = aabb-objectid
                dst_link_offsets.fragments # newidx . t_init =
                    float 0

        shader render-aabb-z () :
            void <- ()
            fragment-color =
                vec4 0.5

        shader render-aabb-debug () :
            void <- ()
            fragment-color =
                vec4 1 0 0 1

        ;---------------------------------------------------------------------------

        shader init-id-buffer () :
            void <- ()
            var fragcoord
                ivec2
                    screen_uv * viewparams.obbtexsize
            var start_frag
                (imageLoad src_start_offsets fragcoord) . r
            do-if (start_frag != 0)
                var fraginfo
                    src_link_offsets.fragments # start_frag
                ; single fragment?
                do-if (fraginfo.next == 0)
                    var objid
                        fraginfo.objectid
                    var t_init
                        fraginfo.t_init
                    imageStore dst_id fragcoord
                        uvec4
                            uint objid
                            floatBitsToUint t_init
                            \ 0 0

        shader init-contour-map () :
            void <- ()
            var fragcoord
                ivec2
                    screen_uv * viewparams.obbtexsize
            var start_frag
                (imageLoad src_start_offsets fragcoord) . r
            do-if (start_frag != 0)
                var fraginfo
                    src_link_offsets.fragments # start_frag
                ; multiple fragments?
                do-if (fraginfo.next != 0)
                    ; get new contour pixel index
                    var newidx
                        atomicAdd dst_contour_map.count 1
                    dst_contour_map.fragcoords # newidx . first = start_frag
                    dst_contour_map.fragcoords # newidx . fragcoord =
                        |
                            (uint fragcoord.x) & (uint 0xffff)
                            (uint fragcoord.y) << 16

        ;---------------------------------------------------------------------------

        shader setup-refine-dispatch () :
            void <- ()
            var pixelcount : uint
                uint src_contour_map.count
            dst_dispatch_args.num_groups_x = (uint 1)
            dst_dispatch_args.num_groups_y = (uint 1)
            dst_dispatch_args.num_groups_z =
                min
                    uint 65535
                    ceildiv pixelcount (uint WORK_FACTOR)
            ; initialize
            ; child_cell_counter.count = (uint 0)

        shader refine-surface () :
            void <- ()
            var fragindex
                int gl_GlobalInvocationID.z
            do-if (fragindex < src_contour_map.count)
                var fragelement
                    src_contour_map.fragcoords # fragindex
                var src_fragcoord
                    ivec2
                        fragelement.fragcoord & (uint 0xffff)
                        fragelement.fragcoord >> 16
                var dst_fragcoord
                    (src_fragcoord << 2) + (ivec2 gl_LocalInvocationID.xy)
                var screensize
                    viewparams.screensize >> refine_level
                var screensizef
                    vec2 screensize
                var screen_uv
                    ((vec2 dst_fragcoord) + 0.5) / screensizef
                var start_frag
                    fragelement.first

                var uv
                    screen_uv * (float 2) - (float 1)

                var v0
                    inverse_projection viewparams.projection
                        vec4 uv 1 1
                var vnormal
                    normalize v0.xyz
                var vdir
                    vnormal * viewparams.rotation

                var origin
                    viewparams.origin

                var pixel
                    (float 1) / (min screensizef.x screensizef.y)

                var brushid 0
                var tmax
                    (float 1) / (float 0)
                tmax =
                    eval_distance
                        start_frag
                        origin
                        vdir
                        tmax
                        brushid
                        (- PIXEL_RADIUS) * pixel

                var aperture
                    PIXEL_RADIUS * pixel
                var fragref
                    start_frag
                var head 0
                var headobj 0
                var count 0
                var nearest tmax
                cloop i (0 MAX_LINK_FRAGS_PP)
                    var fraginfo
                        src_link_offsets.fragments # fragref
                    fragref = fraginfo.next
                    var objid
                        fraginfo.objectid
                    var t_init
                        fraginfo.t_init
                    do-if (t_init < tmax)
                        var t
                            eval_brush_distance
                                \ objid origin vdir t_init tmax aperture

                        do-if (t < tmax)
                            do-if (t < nearest)
                                nearest = t
                                headobj = objid
                            ; get new fragment index
                            var newidx
                                atomicAdd dst_link_offsets.count 1
                            do-if (newidx < NUM_LINK_FRAGMENTS)
                                ; new link points to old link
                                dst_link_offsets.fragments # newidx . objectid = objid
                                dst_link_offsets.fragments # newidx . t_init = t
                                dst_link_offsets.fragments # newidx . next = head
                                head = newidx
                                ++ count

                    if (fragref == 0)
                        break ;

                if (count > 1)
                    do
                        ; get new contour pixel index
                        var newidx
                            atomicAdd dst_contour_map.count 1
                        dst_contour_map.fragcoords # newidx . first = head
                        dst_contour_map.fragcoords # newidx . fragcoord =
                            |
                                (uint dst_fragcoord.x) & (uint 0xffff)
                                (uint dst_fragcoord.y) << 16
                    imageStore dst_id dst_fragcoord
                        uvec4
                            uint headobj
                            floatBitsToUint nearest
                            \ 0 0

        shader refine-surface-final () :
            void <- ()
            var fragindex
                int gl_GlobalInvocationID.z
            do-if (fragindex < src_contour_map.count)
                var fragelement
                    src_contour_map.fragcoords # fragindex
                var src_fragcoord
                    ivec2
                        fragelement.fragcoord & (uint 0xffff)
                        fragelement.fragcoord >> 16
                var dst_fragcoord
                    (src_fragcoord << 2) + (ivec2 gl_LocalInvocationID.xy)
                var screensize
                    viewparams.screensize
                var screensizef
                    vec2 screensize
                var screen_uv
                    ((vec2 dst_fragcoord) + 0.5) / screensizef
                var start_frag
                    fragelement.first

                var uv
                    screen_uv * (float 2) - (float 1)

                var v0
                    inverse_projection viewparams.projection
                        vec4 uv 1 1
                var vnormal
                    normalize v0.xyz
                var vdir
                    vnormal * viewparams.rotation

                var origin
                    viewparams.origin

                var pixel
                    (float 1) / (min screensizef.x screensizef.y)

                var brushid 0
                var tmax
                    (float 1) / (float 0)

                var aperture
                    PIXEL_RADIUS * pixel
                var fragref
                    start_frag
                var head 0
                var headobj 0
                var count 0
                var nearest tmax
                cloop i (0 MAX_LINK_FRAGS_PP)
                    var fraginfo
                        src_link_offsets.fragments # fragref
                    fragref = fraginfo.next
                    var objid
                        fraginfo.objectid
                    var t_init
                        fraginfo.t_init
                    do-if (t_init < nearest)
                        var t
                            eval_brush_distance
                                \ objid origin vdir t_init tmax aperture

                        do-if (t < nearest)
                            nearest = t
                            headobj = objid

                    if (fragref == 0)
                        break ;

                imageStore dst_id dst_fragcoord
                    uvec4
                        uint headobj
                        floatBitsToUint nearest
                        \ 0 0

        ;---------------------------------------------------------------------------

        function build-program (opts)
            var pg (ManagedProgram)
            shader-compile pg opts
            pg

        ;----

        var pg-debug-viz
            build-program
                table-do
                    var vertex-stage map-quad
                    var fragment-stage do-debug-viz
        var set-debug-viz-mode
            .bind debug_viz_mode pg-debug-viz

        ;----

        var pg-refine-surface
            build-program
                table-do
                    var compute-stage refine-surface
                    shader
                        layout
                            local_size_x 4
                            local_size_y 4
                            local_size_z WORK_FACTOR
                        \ bridge compute-in
        var set-refine-level
            .bind refine_level pg-refine-surface

        var pg-refine-surface-final
            build-program
                table-do
                    var compute-stage refine-surface-final
                    shader
                        layout
                            local_size_x 4
                            local_size_y 4
                            local_size_z WORK_FACTOR
                        \ bridge compute-in

        ;----

        .= ($)
            render-aabb
                build-program
                    table-do
                        var vertex-stage map-aabb
                        var fragment-stage
                            ;render-aabb
                            render-aabb-raymarch
                        ### shader
                            layout
                                early_fragment_tests
                            \ bridge fragment-in
                        ;var verbose true
            render-aabb-z
                build-program
                    table-do
                        var vertex-stage map-aabb
                        var fragment-stage render-aabb-z
                        ;var verbose true
            render-aabb-debug
                build-program
                    table-do
                        var vertex-stage map-aabb-debug
                        var fragment-stage render-aabb-debug
                        ;var verbose true
            init-id-buffer
                build-program
                    table-do
                        var vertex-stage map-quad
                        var fragment-stage init-id-buffer
                        ;var verbose true
            init-contour-map
                build-program
                    table-do
                        var vertex-stage map-quad
                        var fragment-stage init-contour-map
                        ;var verbose true
            setup-refine-dispatch
                build-program
                    table-do
                        var compute-stage setup-refine-dispatch
                        shader
                            layout
                                local_size_x 1
                                local_size_y 1
                                local_size_z 1
                            \ bridge compute-in
            refine-surface pg-refine-surface
            set-refine-level
            refine-surface-final pg-refine-surface-final
            raymarch
                build-program
                    table-do
                        var vertex-stage map-quad
                        var fragment-stage do-raymarch
                        ;var verbose true
            debug-viz pg-debug-viz
            set-debug-viz-mode

    shaders =
        memoize shaders

    ;-------------------------------------------------------------------------------

    class GBuffer
        function init (self)
            var screen-size
                window.get-largest-screen-size ;

            var txcolor
                setup-texture (ManagedTexture GL_TEXTURE_2D) screen-size
                    .= ($)
                        format GL_RGB16F

            var txdepth
                setup-texture (ManagedTexture GL_TEXTURE_2D) screen-size
                    .= ($)
                        format GL_DEPTH_COMPONENT32F

            var fb
                setup-framebuffer (ManagedFramebuffer)
                    .= ($)
                        color txcolor
                        depth txdepth

            .= self
                size screen-size
                color-texture txcolor
                depth-texture txdepth
                fb-color-depth fb

    ;-------------------------------------------------------------------------------

    function CSGPainter (opts)
        opts = opts or ($)
        opts =#
            "show-lightmap" false
        opts =#
            "lightmap-size" 512

        var UBO_ALIGN
            gl-get-int GL_UNIFORM_BUFFER_OFFSET_ALIGNMENT
        var SSBO_ALIGN
            gl-get-int GL_SHADER_STORAGE_BUFFER_OFFSET_ALIGNMENT

        var screen-size
            window.get-largest-screen-size ;

        var screen-bits
            ceilpow2bits
                max screen-size.x screen-size.y
        var screen-bit-size
            ivec2
                1 << screen-bits
        var screen-levels
            screen-bits + 1

        var present-texture
            setup-texture (ManagedTexture GL_TEXTURE_2D) screen-size
                .= ($)
                    format GL_SRGB8
        var fb-present
            setup-framebuffer (ManagedFramebuffer)
                .= ($)
                    color present-texture

        var aabb-zbuffer
            setup-texture (ManagedTexture GL_TEXTURE_2D_ARRAY) screen-size
                .= ($)
                    format GL_DEPTH_COMPONENT32F
                    layers 2

        const fb-aabb-near-zbuffer : (uint # 2)
            setup-framebuffer (ManagedFramebuffer)
                .= ($)
                    depth aabb-zbuffer
                    depth_layer 0
            setup-framebuffer (ManagedFramebuffer)
                .= ($)
                    depth aabb-zbuffer
                    depth_layer 1

        var start-offset-abuffer
            setup-texture (ManagedTexture GL_TEXTURE_2D_ARRAY) screen-size
                .= ($)
                    format GL_R32I
                    layers 2

        const fb-start-offset-abuffer : (uint # 2)
            setup-framebuffer (ManagedFramebuffer)
                .= ($)
                    color start-offset-abuffer
                    color_layer 0
            setup-framebuffer (ManagedFramebuffer)
                .= ($)
                    color start-offset-abuffer
                    color_layer 1

        var id-buffer
            setup-texture (ManagedTexture GL_TEXTURE_2D_ARRAY) screen-size
                .= ($)
                    format GL_RG32UI
                    layers 2

        const fb-id-buffer : (uint # 2)
            setup-framebuffer (ManagedFramebuffer)
                .= ($)
                    color id-buffer
                    color_layer 0
            setup-framebuffer (ManagedFramebuffer)
                .= ($)
                    color id-buffer
                    color_layer 1

        var LINK_FRAGMENT_SIZE
            (sizeof LinkFragment) * NUM_LINK_FRAGMENTS + (sizeof int)
        var LINK_FRAGMENT_ALIGN
            align LINK_FRAGMENT_SIZE SSBO_ALIGN
        var link-fragments (ManagedBuffer)
        glNamedBufferData link-fragments (BUFFER_COUNT * LINK_FRAGMENT_ALIGN) null GL_STREAM_DRAW

        var CONTOUR_MAP_SIZE
            (sizeof ContourElement) * NUM_CONTOUR_PIXELS + ((sizeof int) * 4)
        var CONTOUR_MAP_ALIGN
            align CONTOUR_MAP_SIZE SSBO_ALIGN
        var contour-map (ManagedBuffer)
        glNamedBufferData contour-map (BUFFER_COUNT * CONTOUR_MAP_ALIGN) null GL_STREAM_DRAW

        var BRUSH_ARRAY_SIZE
            (sizeof Brush) * (MAX_BRUSHES + 1)
        var BRUSH_ARRAY_ALIGN
            align BRUSH_ARRAY_SIZE SSBO_ALIGN
        var brush-data (ManagedBuffer)
        glNamedBufferData brush-data (BUFFER_COUNT * BRUSH_ARRAY_ALIGN) null GL_STREAM_DRAW

        var BRUSH_MATERIAL_ARRAY_SIZE
            (sizeof BrushMaterial) * (MAX_BRUSHES + 1)
        var BRUSH_MATERIAL_ARRAY_ALIGN
            align BRUSH_MATERIAL_ARRAY_SIZE SSBO_ALIGN
        var brush-material-data (ManagedBuffer)
        glNamedBufferData brush-material-data (BUFFER_COUNT * BRUSH_MATERIAL_ARRAY_ALIGN) null GL_STREAM_DRAW

        var INDIRECT_PARAMS_SIZE
            (sizeof ComputeDispatchArgs)
        var INDIRECT_PARAMS_ALIGN
            align INDIRECT_PARAMS_SIZE SSBO_ALIGN
        var indirect-params (ManagedBuffer)
        glNamedBufferData indirect-params (BUFFER_COUNT * INDIRECT_PARAMS_ALIGN) null GL_STREAM_DRAW

        const brushes : (Brush # (MAX_BRUSHES + 1))

        const brush-materials : (BrushMaterial # (MAX_BRUSHES + 1))

        var HASHSCALE 0.1031
        static hash3 (p) :
            vec3 <- (float)
            var p3
                vector-mod
                    * (vec3 p)
                        vec3
                            HASHSCALE
                            HASHSCALE * 1.51
                            HASHSCALE * 2.53
                    1
            p3 +=
                dot p3
                    p3.yzx + 19.19
            vector-mod
                vec3
                    (p3.x + p3.y) * p3.z
                    (p3.x + p3.z) * p3.y
                    (p3.y + p3.z) * p3.x
                1
        ; init brush materials with random colors
        static-do
            cloop brushid (0 (MAX_BRUSHES + 1))
                .= (brush-materials # brushid)
                    albedo
                        hash3 (float brushid)

        var OBB_ELEMENTS_COUNT 14
        var OBB_ELEMENTS_SIZE
            (sizeof uint8) * OBB_ELEMENTS_COUNT

        const obb-indices : (uint8 # OBB_ELEMENTS_COUNT)
            ; \ 6 2 7 3 1 2 0 6 4 7 5 1 4 0
            \ 7 3 6 2 0 3 1 7 5 6 4 0 5 1

        var obb-elements (ManagedBuffer)
        glNamedBufferData obb-elements OBB_ELEMENTS_SIZE obb-indices GL_STATIC_DRAW

        var vao-obb (ManagedVertexArray)
        glVertexArrayElementBuffer vao-obb obb-elements

        var GLOBALS_SIZE
            (sizeof ShaderGlobals)
        var GLOBALS_ALIGN
            align GLOBALS_SIZE UBO_ALIGN

        var global-data (ManagedBuffer)
        glNamedBufferData global-data (BUFFER_COUNT * GLOBALS_ALIGN) null GL_STREAM_DRAW

        var VIEWPARAMS_SIZE
            (sizeof ViewParams)
        var VIEWPARAMS_ALIGN
            align VIEWPARAMS_SIZE UBO_ALIGN

        var view-data (ManagedBuffer)
        glNamedBufferData view-data (BUFFER_COUNT * VIEWPARAMS_ALIGN) null GL_STREAM_DRAW

        var sun-data (ManagedBuffer)
        glNamedBufferData sun-data (BUFFER_COUNT * VIEWPARAMS_ALIGN) null GL_STREAM_DRAW

        var gbuffer
            GBuffer ;

        var pg (shaders)

        ;----

        static swap_buffer_index : uint 0

        var timeropts
            .= ($)
                simulate false

        var obbtimer
            GLTimer timeropts
        var refinetimer
            GLTimer timeropts
        var raymarchtimer
            GLTimer timeropts
        var suntimer
            GLTimer timeropts
        var presenttimer
            GLTimer timeropts

        const depth_clearval_max : (uint # 1) 0
        const depth_clearval_min : (uint # 1) 1

        const link_clearval : (int # 1) 0
        const id_clearval : (int # 1) 0
        const frag_count_clearval : (int # 1) 1
        const contour_count_clearval : (int # 4)
            \ 0 1 1 0

        static globaltime : int 0

        const globals : ShaderGlobals
        const viewparams : ViewParams
        const sunparams : ViewParams

        .= globals
            sundir
                normalize
                    ;vec3 2 -10 3
                    vec3 1.3 -1.1 1.2
            sunzoom 16

        ;----

        static paint-obb-buffer () :
            void <- ()
            var rsize
                viewparams.obbtexsize

            obbtimer.begin-pass ;

            glDepthRangedNV -1 1

            glEnable GL_DEPTH_TEST
            glEnable GL_CULL_FACE
            glCullFace GL_FRONT
            glBindVertexArray vao-obb

            ; build near z-buffer for masking per-pixel list
            glDepthMask GL_TRUE
            glDepthFunc GL_GREATER
            glCullFace GL_FRONT
            glViewport 0 0 rsize.x rsize.y
            glBindFramebuffer GL_FRAMEBUFFER (fb-aabb-near-zbuffer # 0)
            glClearDepth 0
            glClear GL_DEPTH_BUFFER_BIT
            glUseProgram 0

            ; build per-pixel linked list of brush bounding boxes
            glDisable GL_DEPTH_TEST
            glClearTexSubImage start-offset-abuffer 0 0 0 0 rsize.x rsize.y 1 GL_RED_INTEGER GL_INT (link_clearval + 0)
            glClearNamedBufferSubData link-fragments GL_R32I (LINK_FRAGMENT_ALIGN * 0) (sizeof int) GL_RED_INTEGER GL_INT
                frag_count_clearval + 0
            glBindImageTexture IMG_DST_START_OFFSETS start-offset-abuffer 0 GL_FALSE 0 GL_READ_WRITE GL_R32I
            glBindBufferRange GL_SHADER_STORAGE_BUFFER SS_DST_LINK_FRAGMENTS link-fragments (LINK_FRAGMENT_ALIGN * 0) LINK_FRAGMENT_SIZE
            glCullFace GL_FRONT
            glDepthFunc GL_GEQUAL
            glUseProgram pg.render-aabb
            glDrawElementsInstanced GL_TRIANGLE_STRIP OBB_ELEMENTS_COUNT GL_UNSIGNED_BYTE NULL globals.numbrushes
            glUseProgram 0

            glDepthMask GL_TRUE
            glDisable GL_DEPTH_TEST
            glDisable GL_CULL_FACE
            glCullFace GL_BACK
            glBindVertexArray 0

            ; init id buffer
            glClearTexSubImage id-buffer 0 0 0 0 rsize.x rsize.y 1 GL_RED_INTEGER GL_INT (id_clearval + 0)
            glBindImageTexture IMG_SRC_START_OFFSETS start-offset-abuffer 0 GL_FALSE 0 GL_READ_ONLY GL_R32I
            glBindBufferRange GL_SHADER_STORAGE_BUFFER SS_SRC_LINK_FRAGMENTS link-fragments (LINK_FRAGMENT_ALIGN * 0) LINK_FRAGMENT_SIZE
            glBindImageTexture IMG_DST_ID id-buffer 0 GL_FALSE 0 GL_WRITE_ONLY GL_RG32UI
            glUseProgram pg.init-id-buffer
            draw-screen-quad ;
            glUseProgram 0

            ; init contour map
            glClearNamedBufferSubData contour-map GL_R32I (CONTOUR_MAP_ALIGN * 0) (sizeof int) GL_RED_INTEGER GL_INT
                contour_count_clearval + 0
            glBindBufferRange GL_SHADER_STORAGE_BUFFER SS_DST_CONTOUR_MAP contour-map (CONTOUR_MAP_ALIGN * 0) CONTOUR_MAP_SIZE
            glUseProgram pg.init-contour-map
            draw-screen-quad ;
            glUseProgram 0

            obbtimer.end-pass ;

            ### do
                var contour_count : ivec3
                glGetNamedBufferSubData contour-map (CONTOUR_MAP_ALIGN * 0) (3 * (sizeof int)) &contour_count
                print &contour_count

        static refine-surface-buffer (inidx outidx level) :
            void <- (int int int)
            var srcrsize
                viewparams.screensize >> (level + 2)
            var rsize
                viewparams.screensize >> level

            glDepthRangedNV -1 1

            glDisable GL_DEPTH_TEST

            glBlitNamedFramebuffer
                fb-id-buffer # inidx
                fb-id-buffer # outidx
                \ 0 0 srcrsize.x srcrsize.y
                \ 0 0 rsize.x rsize.y
                \ GL_COLOR_BUFFER_BIT GL_NEAREST

            glBindImageTexture IMG_SRC_ID id-buffer 0 GL_FALSE inidx GL_READ_ONLY GL_RG32UI
            glBindImageTexture IMG_DST_ID id-buffer 0 GL_FALSE outidx GL_WRITE_ONLY GL_RG32UI

            glBindImageTexture IMG_SRC_START_OFFSETS start-offset-abuffer 0 GL_FALSE inidx GL_READ_ONLY GL_R32I
            glBindBufferRange GL_SHADER_STORAGE_BUFFER SS_SRC_LINK_FRAGMENTS link-fragments (LINK_FRAGMENT_ALIGN * inidx) LINK_FRAGMENT_SIZE
            ;glBindTextureUnit SMP_AABB_ZBUFFER aabb-zbuffer

            glClearNamedBufferSubData contour-map GL_R32I (CONTOUR_MAP_ALIGN * outidx) (sizeof int) GL_RED_INTEGER GL_INT
                contour_count_clearval + 0
            glBindBufferRange GL_SHADER_STORAGE_BUFFER SS_SRC_CONTOUR_MAP contour-map (CONTOUR_MAP_ALIGN * inidx) CONTOUR_MAP_SIZE
            glBindBufferRange GL_SHADER_STORAGE_BUFFER SS_DST_CONTOUR_MAP contour-map (CONTOUR_MAP_ALIGN * outidx) CONTOUR_MAP_SIZE

            glBindBufferRange GL_SHADER_STORAGE_BUFFER SS_DST_COMPUTE_ARGS indirect-params (INDIRECT_PARAMS_ALIGN * outidx) INDIRECT_PARAMS_SIZE
            glUseProgram pg.setup-refine-dispatch
            glDispatchCompute 1 1 1
            glUseProgram 0

            ; glScissor 0 0 rsize.x rsize.y
            ; glEnable GL_SCISSOR_TEST
            ; refine per-pixel linked list of brush bounding boxes
            glClearTexSubImage start-offset-abuffer 0 0 0 outidx rsize.x rsize.y 1 GL_RED_INTEGER GL_INT (link_clearval + 0)
            glClearNamedBufferSubData link-fragments GL_R32I (LINK_FRAGMENT_ALIGN * outidx) (sizeof int) GL_RED_INTEGER GL_INT
                frag_count_clearval + 0
            glBindImageTexture IMG_DST_START_OFFSETS start-offset-abuffer 0 GL_FALSE outidx GL_WRITE_ONLY GL_R32I
            glBindBufferRange GL_SHADER_STORAGE_BUFFER SS_DST_LINK_FRAGMENTS link-fragments (LINK_FRAGMENT_ALIGN * outidx) LINK_FRAGMENT_SIZE
            pg.set-refine-level level


            glUseProgram
                if (level == 0)
                    pg.refine-surface-final
                    pg.refine-surface
            glBindBuffer GL_DISPATCH_INDIRECT_BUFFER indirect-params
            glDispatchComputeIndirect
                (INDIRECT_PARAMS_ALIGN * outidx)
            glUseProgram 0

            ### do
                var contour_count : ivec3
                var fragment_count : int
                glGetNamedBufferSubData contour-map (CONTOUR_MAP_ALIGN * inidx) (4 * (sizeof int)) &contour_count
                glGetNamedBufferSubData link-fragments (LINK_FRAGMENT_ALIGN * outidx) (sizeof int) &fragment_count
                print level &contour_count fragment_count



        static paint-sunmap-obb-buffer (inidx) :
            void <- (int)
            var rsize
                sunparams.obbtexsize

            suntimer.begin-pass ;

            glBindBufferRange GL_UNIFORM_BUFFER UB_VIEWPARAMS sun-data (VIEWPARAMS_ALIGN * inidx) VIEWPARAMS_SIZE

            glDepthRangedNV -1 1

            glEnable GL_DEPTH_TEST
            glEnable GL_CULL_FACE
            glCullFace GL_BACK
            glDepthMask GL_TRUE
            glBindVertexArray vao-obb

            var z_offset
                1

            glEnable GL_POLYGON_OFFSET_FILL
            glPolygonOffset -z_offset 0

            ; build near z-buffer for masking per-pixel list
            glDepthFunc GL_GREATER
            glViewport 0 0 rsize.x rsize.y
            glBindFramebuffer GL_FRAMEBUFFER (fb-aabb-near-zbuffer # 0)
            glClearDepth 0
            glClear GL_DEPTH_BUFFER_BIT
            glUseProgram 0

            glPolygonOffset 0 0

            ; build per-pixel linked list of brush bounding boxes
            glPolygonOffset z_offset 0
            glClearTexSubImage start-offset-abuffer 0 0 0 0 rsize.x rsize.y 1 GL_RED_INTEGER GL_INT (link_clearval + 0)
            glClearNamedBufferSubData link-fragments GL_R32I (LINK_FRAGMENT_ALIGN * inidx) (sizeof int) GL_RED_INTEGER GL_INT
                frag_count_clearval + 0
            glBindImageTexture IMG_DST_START_OFFSETS start-offset-abuffer 0 GL_FALSE 0 GL_READ_WRITE GL_R32I
            glBindBufferRange GL_SHADER_STORAGE_BUFFER SS_DST_LINK_FRAGMENTS link-fragments (LINK_FRAGMENT_ALIGN * inidx) LINK_FRAGMENT_SIZE
            glDepthMask GL_FALSE
            glDepthFunc GL_GEQUAL
            glUseProgram pg.render-aabb
            glDrawElementsInstanced GL_TRIANGLE_STRIP OBB_ELEMENTS_COUNT GL_UNSIGNED_BYTE NULL globals.numbrushes
            glUseProgram 0
            glDepthMask GL_TRUE
            glPolygonOffset 0 0

            glUseProgram pg.render-aabb-z

            ; build near z-buffer
            glPolygonOffset z_offset 0
            glDepthFunc GL_GREATER
            glCullFace GL_BACK
            glBindFramebuffer GL_FRAMEBUFFER (fb-aabb-near-zbuffer # 0)
            glClearDepth 0
            glClear GL_DEPTH_BUFFER_BIT
            glDrawElementsInstanced GL_TRIANGLE_STRIP OBB_ELEMENTS_COUNT GL_UNSIGNED_BYTE NULL globals.numbrushes

            glPolygonOffset 0 0
            glDisable GL_POLYGON_OFFSET_FILL
            glDisable GL_DEPTH_TEST
            glDisable GL_CULL_FACE
            glCullFace GL_BACK

            suntimer.end-pass ;

        static paint-raymarch (inidx) :
            void <- (int)
            var rsize
                viewparams.screensize

            glBindImageTexture IMG_SRC_ID id-buffer 0 GL_FALSE inidx GL_READ_ONLY GL_RG32UI
            glBindImageTexture IMG_SRC_START_OFFSETS start-offset-abuffer 0 GL_FALSE inidx GL_READ_ONLY GL_R32I
            glBindBufferRange GL_SHADER_STORAGE_BUFFER SS_SRC_LINK_FRAGMENTS link-fragments (LINK_FRAGMENT_ALIGN * inidx) LINK_FRAGMENT_SIZE

            raymarchtimer.begin-pass ;
            glBindFramebuffer GL_FRAMEBUFFER gbuffer.fb-color-depth
            glClearColor 0 0 0 1
            glClearDepth 0
            glDepthFunc GL_ALWAYS
            glEnable GL_DEPTH_TEST
            glDepthRangedNV -1 1
            glDepthMask GL_TRUE

            glClear
                if true
                    |
                        GL_DEPTH_BUFFER_BIT
                        GL_COLOR_BUFFER_BIT
                    GL_DEPTH_BUFFER_BIT

            glViewport 0 0 rsize.x rsize.y
            glDisable GL_BLEND

            glBindTextureUnit SMP_AABB_ZBUFFER aabb-zbuffer
            glUseProgram pg.raymarch
            draw-screen-quad ;

            glUseProgram 0

            raymarchtimer.end-pass ;

        static setup-sunparams () :
            void <- ()
            var sunrsize
                ivec2 opts.lightmap-size

            var sundir
                globals.sundir
            var sunrot
                look-at
                    - sundir
                    vec3 0 1 0

            .= sunparams
                screensize sunrsize
                obbtexsize sunrsize
                surfacetexsize sunrsize
                origin
                    vec3 0
                rotation
                    transpose
                        sunrot

            .orthographic sunparams.projection
                /
                    vec2 1
                    globals.sunzoom
                -1000
                1000

        .setinlined setup-sunparams false

        static paint-gbuffer (rsize) :
            void <- (ivec2)

            var rsizebits
                ceilpow2bits
                    max rsize.x rsize.y
            var rsizepow2
                ivec2
                    1 << rsizebits

            .= globals
                frame globaltime
                numbrushes
                    min globals.numbrushes
                        MAX_BRUSHES
                viewsundir
                    (viewparams.rotation * globals.sundir) . xyz

            .= viewparams
                screensize rsize
                obbtexsize
                    rsize >> ABUFFER_DIV
                surfacetexsize
                    rsize >> (ABUFFER_DIV - 4)

            .ifp-perspective viewparams.projection
                vec2
                    1
                    (float rsize.x) / rsize.y
                NEAR

            setup-sunparams ;

            ++ swap_buffer_index
            var inidx : int
                swap_buffer_index % BUFFER_COUNT
            var outidx : int
                (swap_buffer_index + 1) % BUFFER_COUNT

            var brush_array_size
                (sizeof Brush) * (globals.numbrushes + 1)
            var brush_material_array_size
                (sizeof BrushMaterial) * (globals.numbrushes + 1)

            ; upload brush data
            glNamedBufferSubData brush-data
                inidx * BRUSH_ARRAY_ALIGN
                brush_array_size
                brushes + 0
            ; upload brush material data
            glNamedBufferSubData brush-material-data
                inidx * BRUSH_MATERIAL_ARRAY_ALIGN
                brush_material_array_size
                brush-materials + 0

            ; upload globals
            glNamedBufferSubData global-data
                inidx * GLOBALS_ALIGN
                GLOBALS_SIZE
                &globals
            ; upload viewparams
            glNamedBufferSubData view-data
                inidx * VIEWPARAMS_ALIGN
                VIEWPARAMS_SIZE
                &viewparams
            ; upload sunparams
            glNamedBufferSubData sun-data
                inidx * VIEWPARAMS_ALIGN
                VIEWPARAMS_SIZE
                &sunparams

            glBindBufferRange GL_UNIFORM_BUFFER UB_GLOBALS global-data (GLOBALS_ALIGN * inidx) GLOBALS_SIZE
            glBindBufferRange GL_UNIFORM_BUFFER UB_VIEWPARAMS view-data (VIEWPARAMS_ALIGN * inidx) VIEWPARAMS_SIZE
            glBindBufferRange GL_UNIFORM_BUFFER UB_SUNPARAMS sun-data (VIEWPARAMS_ALIGN * inidx) VIEWPARAMS_SIZE

            glBindBufferRange GL_SHADER_STORAGE_BUFFER SS_SRC_BRUSHES brush-data
                BRUSH_ARRAY_ALIGN * inidx
                brush_array_size
            glBindBufferRange GL_SHADER_STORAGE_BUFFER SS_SRC_BRUSH_MATERIALS brush-material-data
                BRUSH_MATERIAL_ARRAY_ALIGN * inidx
                brush_material_array_size

            ++ globaltime

            paint-obb-buffer ;

            refinetimer.begin-pass ;
            ;refine-surface-buffer 0 1 3
            ;refine-surface-buffer 1 0 2
            ;refine-surface-buffer 0 1 1
            ;refine-surface-buffer 1 0 0

            refine-surface-buffer 0 1 2
            refine-surface-buffer 1 0 0

            refinetimer.end-pass ;

            paint-raymarch 0

            ; paint-sunmap-obb-buffer inidx

            glBindBufferRange GL_UNIFORM_BUFFER UB_VIEWPARAMS view-data (VIEWPARAMS_ALIGN * inidx) VIEWPARAMS_SIZE

        static blit-gbuffer (size fb) :
            void <- (ivec2 uint)
            presenttimer.begin-pass ;
            switch 1
                0
                    blit-framebuffer gbuffer.fb-color-depth fb viewparams.screensize size
                1
                    glBindFramebuffer GL_FRAMEBUFFER fb-present
                    glEnable GL_FRAMEBUFFER_SRGB
                    glBindTextureUnit SMP_AABB_ZBUFFER aabb-zbuffer
                    glBindTextureUnit SMP_VIEW_GBUFFER gbuffer.color-texture
                    glBindTextureUnit SMP_DEPTH_GBUFFER gbuffer.depth-texture
                    glBindTextureUnit SMP_ID_GBUFFER id-buffer
                    glViewport 0 0 size.x size.y
                    pg.set-debug-viz-mode 2
                    glUseProgram pg.debug-viz
                    draw-screen-quad ;
                    glDisable GL_FRAMEBUFFER_SRGB

                    glBindFramebuffer GL_FRAMEBUFFER fb
                    blit-framebuffer fb-present fb viewparams.screensize

                    do-if opts.show-lightmap
                        var inidx : int
                            swap_buffer_index % BUFFER_COUNT
                        glBindBufferRange GL_UNIFORM_BUFFER UB_VIEWPARAMS sun-data (VIEWPARAMS_ALIGN * inidx) VIEWPARAMS_SIZE
                        glViewport 0 0 opts.lightmap-size opts.lightmap-size
                        pg.set-debug-viz-mode 0
                        draw-screen-quad ;

                    glDisable GL_BLEND
                2
                    ;blit-framebuffer gbuffer.fb-color-depth fb viewparams.screensize size
                    glBindFramebuffer GL_FRAMEBUFFER fb
                    glBindTextureUnit SMP_AABB_ZBUFFER aabb-zbuffer
                    glBindTextureUnit SMP_VIEW_GBUFFER gbuffer.color-texture
                    glBindTextureUnit SMP_DEPTH_GBUFFER gbuffer.depth-texture
                    glBindTextureUnit SMP_ID_GBUFFER id-buffer
                    glViewport 0 0 size.x size.y
                    pg.set-debug-viz-mode 2
                    glUseProgram pg.debug-viz
                    draw-screen-quad ;

                    glEnable GL_BLEND
                    glBlendFunc GL_ONE GL_ONE
                    pg.set-debug-viz-mode 0
                    glUseProgram pg.debug-viz
                    draw-screen-quad ;
                    glDisable GL_BLEND

                    ###
                        glPolygonOffset 1 0
                        glEnable GL_POLYGON_OFFSET_FILL
                        glUseProgram pg.render-aabb-debug
                        glBindVertexArray vao-obb
                        glDisable GL_DEPTH_TEST
                        glEnable GL_CULL_FACE
                        glCullFace GL_FRONT
                        glEnable GL_BLEND
                        glBlendFunc GL_ONE GL_ONE
                        glDrawElementsInstanced GL_TRIANGLE_STRIP OBB_ELEMENTS_COUNT GL_UNSIGNED_BYTE NULL globals.numbrushes
                        glDisable GL_BLEND
                        glPolygonOffset 0 0
                        glEnable GL_POLYGON_OFFSET_FILL

            presenttimer.end-pass ;
            glUseProgram 0

        static define-ui () :
            void <- ()

            var obb
                obbtimer.time-ms ;
            var refine
                refinetimer.time-ms ;
            var raymarch
                raymarchtimer.time-ms ;
            var present
                presenttimer.time-ms ;
            var sun
                suntimer.time-ms ;

            Text "build OBB buffer: %.5fms" obb
            Text "refine surface: %.5fms" refine
            Text "raymarch: %.5fms" raymarch
            Text "render sun OBB map: %.5fms" sun
            Text "present: %.5fms" present
            Text "total: %.5fms"
                + obb refine raymarch sun present

        ;----

        .= ($)
            brushes
            brush-materials
            globals
            viewparams
            paint-gbuffer
            blit-gbuffer
            define-ui

    .= ($)
        CSGPainter
        MAX_BRUSHES
        Brush