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
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
|
/*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
* The Original Code is Copyright (C) 2005 Blender Foundation.
* All rights reserved.
*/
/** \file
* \ingroup gpu
*
* Convert material node-trees to GLSL.
*/
#include "MEM_guardedalloc.h"
#include "DNA_customdata_types.h"
#include "DNA_image_types.h"
#include "DNA_material_types.h"
#include "DNA_node_types.h"
#include "BLI_blenlib.h"
#include "BLI_hash_mm2a.h"
#include "BLI_link_utils.h"
#include "BLI_utildefines.h"
#include "BLI_dynstr.h"
#include "BLI_ghash.h"
#include "BLI_threads.h"
#include "BKE_material.h"
#include "PIL_time.h"
#include "GPU_extensions.h"
#include "GPU_glew.h"
#include "GPU_material.h"
#include "GPU_shader.h"
#include "GPU_uniformbuffer.h"
#include "GPU_vertex_format.h"
#include "BLI_sys_types.h" /* for intptr_t support */
#include "gpu_codegen.h"
#include "gpu_material_library.h"
#include <string.h>
#include <stdarg.h>
extern char datatoc_gpu_shader_material_glsl[];
extern char datatoc_gpu_shader_geometry_glsl[];
extern char datatoc_gpu_shader_common_obinfos_lib_glsl[];
extern char datatoc_common_view_lib_glsl[];
/* -------------------- GPUPass Cache ------------------ */
/**
* Internal shader cache: This prevent the shader recompilation / stall when
* using undo/redo AND also allows for GPUPass reuse if the Shader code is the
* same for 2 different Materials. Unused GPUPasses are free by Garbage collection.
*/
/* Only use one linklist that contains the GPUPasses grouped by hash. */
static GPUPass *pass_cache = NULL;
static SpinLock pass_cache_spin;
static uint32_t gpu_pass_hash(const char *frag_gen, const char *defs, GPUVertAttrLayers *attrs)
{
BLI_HashMurmur2A hm2a;
BLI_hash_mm2a_init(&hm2a, 0);
BLI_hash_mm2a_add(&hm2a, (uchar *)frag_gen, strlen(frag_gen));
if (attrs) {
for (int att_idx = 0; att_idx < attrs->totlayer; att_idx++) {
char *name = attrs->layer[att_idx].name;
BLI_hash_mm2a_add(&hm2a, (uchar *)name, strlen(name));
}
}
if (defs) {
BLI_hash_mm2a_add(&hm2a, (uchar *)defs, strlen(defs));
}
return BLI_hash_mm2a_end(&hm2a);
}
/* Search by hash only. Return first pass with the same hash.
* There is hash collision if (pass->next && pass->next->hash == hash) */
static GPUPass *gpu_pass_cache_lookup(uint32_t hash)
{
BLI_spin_lock(&pass_cache_spin);
/* Could be optimized with a Lookup table. */
for (GPUPass *pass = pass_cache; pass; pass = pass->next) {
if (pass->hash == hash) {
BLI_spin_unlock(&pass_cache_spin);
return pass;
}
}
BLI_spin_unlock(&pass_cache_spin);
return NULL;
}
/* Check all possible passes with the same hash. */
static GPUPass *gpu_pass_cache_resolve_collision(GPUPass *pass,
const char *vert,
const char *geom,
const char *frag,
const char *defs,
uint32_t hash)
{
BLI_spin_lock(&pass_cache_spin);
/* Collision, need to strcmp the whole shader. */
for (; pass && (pass->hash == hash); pass = pass->next) {
if ((defs != NULL) && (strcmp(pass->defines, defs) != 0)) { /* Pass */
}
else if ((geom != NULL) && (strcmp(pass->geometrycode, geom) != 0)) { /* Pass */
}
else if ((strcmp(pass->fragmentcode, frag) == 0) && (strcmp(pass->vertexcode, vert) == 0)) {
BLI_spin_unlock(&pass_cache_spin);
return pass;
}
}
BLI_spin_unlock(&pass_cache_spin);
return NULL;
}
/* -------------------- GPU Codegen ------------------ */
/* type definitions and constants */
#define MAX_FUNCTION_NAME 64
#define MAX_PARAMETER 32
typedef enum {
FUNCTION_QUAL_IN,
FUNCTION_QUAL_OUT,
FUNCTION_QUAL_INOUT,
} GPUFunctionQual;
typedef struct GPUFunction {
char name[MAX_FUNCTION_NAME];
eGPUType paramtype[MAX_PARAMETER];
GPUFunctionQual paramqual[MAX_PARAMETER];
int totparam;
GPUMaterialLibrary *library;
} GPUFunction;
/* Indices match the eGPUType enum */
static const char *GPU_DATATYPE_STR[17] = {
"",
"float",
"vec2",
"vec3",
"vec4",
NULL,
NULL,
NULL,
NULL,
"mat3",
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
"mat4",
};
/* GLSL code parsing for finding function definitions.
* These are stored in a hash for lookup when creating a material. */
static GHash *FUNCTION_HASH = NULL;
#if 0
static char *FUNCTION_PROTOTYPES = NULL;
static GPUShader *FUNCTION_LIB = NULL;
#endif
static int gpu_str_prefix(const char *str, const char *prefix)
{
while (*str && *prefix) {
if (*str != *prefix) {
return 0;
}
str++;
prefix++;
}
return (*prefix == '\0');
}
static char *gpu_str_skip_token(char *str, char *token, int max)
{
int len = 0;
/* skip a variable/function name */
while (*str) {
if (ELEM(*str, ' ', '(', ')', ',', ';', '\t', '\n', '\r')) {
break;
}
else {
if (token && len < max - 1) {
*token = *str;
token++;
len++;
}
str++;
}
}
if (token) {
*token = '\0';
}
/* skip the next special characters:
* note the missing ')' */
while (*str) {
if (ELEM(*str, ' ', '(', ',', ';', '\t', '\n', '\r')) {
str++;
}
else {
break;
}
}
return str;
}
static void gpu_parse_material_library(GHash *hash, GPUMaterialLibrary *library)
{
GPUFunction *function;
eGPUType type;
GPUFunctionQual qual;
int i;
char *code = library->code;
while ((code = strstr(code, "void "))) {
function = MEM_callocN(sizeof(GPUFunction), "GPUFunction");
function->library = library;
code = gpu_str_skip_token(code, NULL, 0);
code = gpu_str_skip_token(code, function->name, MAX_FUNCTION_NAME);
/* get parameters */
while (*code && *code != ')') {
/* test if it's an input or output */
qual = FUNCTION_QUAL_IN;
if (gpu_str_prefix(code, "out ")) {
qual = FUNCTION_QUAL_OUT;
}
if (gpu_str_prefix(code, "inout ")) {
qual = FUNCTION_QUAL_INOUT;
}
if ((qual != FUNCTION_QUAL_IN) || gpu_str_prefix(code, "in ")) {
code = gpu_str_skip_token(code, NULL, 0);
}
/* test for type */
type = GPU_NONE;
for (i = 1; i < ARRAY_SIZE(GPU_DATATYPE_STR); i++) {
if (GPU_DATATYPE_STR[i] && gpu_str_prefix(code, GPU_DATATYPE_STR[i])) {
type = i;
break;
}
}
if (!type && gpu_str_prefix(code, "samplerCube")) {
type = GPU_TEXCUBE;
}
if (!type && gpu_str_prefix(code, "sampler2DShadow")) {
type = GPU_SHADOW2D;
}
if (!type && gpu_str_prefix(code, "sampler1DArray")) {
type = GPU_TEX1D_ARRAY;
}
if (!type && gpu_str_prefix(code, "sampler2DArray")) {
type = GPU_TEX2D_ARRAY;
}
if (!type && gpu_str_prefix(code, "sampler2D")) {
type = GPU_TEX2D;
}
if (!type && gpu_str_prefix(code, "sampler3D")) {
type = GPU_TEX3D;
}
if (!type && gpu_str_prefix(code, "Closure")) {
type = GPU_CLOSURE;
}
if (type) {
/* add parameter */
code = gpu_str_skip_token(code, NULL, 0);
code = gpu_str_skip_token(code, NULL, 0);
function->paramqual[function->totparam] = qual;
function->paramtype[function->totparam] = type;
function->totparam++;
}
else {
fprintf(stderr, "GPU invalid function parameter in %s.\n", function->name);
break;
}
}
if (function->name[0] == '\0' || function->totparam == 0) {
fprintf(stderr, "GPU functions parse error.\n");
MEM_freeN(function);
break;
}
BLI_ghash_insert(hash, function->name, function);
}
}
#if 0
static char *gpu_generate_function_prototyps(GHash *hash)
{
DynStr *ds = BLI_dynstr_new();
GHashIterator *ghi;
GPUFunction *function;
char *name, *prototypes;
int a;
/* automatically generate function prototypes to add to the top of the
* generated code, to avoid have to add the actual code & recompile all */
ghi = BLI_ghashIterator_new(hash);
for (; !BLI_ghashIterator_done(ghi); BLI_ghashIterator_step(ghi)) {
name = BLI_ghashIterator_getValue(ghi);
function = BLI_ghashIterator_getValue(ghi);
BLI_dynstr_appendf(ds, "void %s(", name);
for (a = 0; a < function->totparam; a++) {
if (function->paramqual[a] == FUNCTION_QUAL_OUT) {
BLI_dynstr_append(ds, "out ");
}
else if (function->paramqual[a] == FUNCTION_QUAL_INOUT) {
BLI_dynstr_append(ds, "inout ");
}
if (function->paramtype[a] == GPU_TEX2D) {
BLI_dynstr_append(ds, "sampler2D");
}
else if (function->paramtype[a] == GPU_SHADOW2D) {
BLI_dynstr_append(ds, "sampler2DShadow");
}
else {
BLI_dynstr_append(ds, GPU_DATATYPE_STR[function->paramtype[a]]);
}
# if 0
BLI_dynstr_appendf(ds, " param%d", a);
# endif
if (a != function->totparam - 1) {
BLI_dynstr_append(ds, ", ");
}
}
BLI_dynstr_append(ds, ");\n");
}
BLI_dynstr_append(ds, "\n");
prototypes = BLI_dynstr_get_cstring(ds);
BLI_dynstr_free(ds);
return prototypes;
}
#endif
static GPUFunction *gpu_lookup_function(const char *name)
{
return BLI_ghash_lookup(FUNCTION_HASH, (const void *)name);
}
void gpu_codegen_init(void)
{
GPU_code_generate_glsl_lib();
}
void gpu_codegen_exit(void)
{
BKE_material_defaults_free_gpu();
if (FUNCTION_HASH) {
BLI_ghash_free(FUNCTION_HASH, NULL, MEM_freeN);
FUNCTION_HASH = NULL;
}
GPU_shader_free_builtin_shaders();
#if 0
if (FUNCTION_PROTOTYPES) {
MEM_freeN(FUNCTION_PROTOTYPES);
FUNCTION_PROTOTYPES = NULL;
}
if (FUNCTION_LIB) {
GPU_shader_free(FUNCTION_LIB);
FUNCTION_LIB = NULL;
}
#endif
}
/* GLSL code generation */
static void codegen_convert_datatype(DynStr *ds, int from, int to, const char *tmp, int id)
{
char name[1024];
BLI_snprintf(name, sizeof(name), "%s%d", tmp, id);
if (from == to) {
BLI_dynstr_append(ds, name);
}
else if (to == GPU_FLOAT) {
if (from == GPU_VEC4) {
BLI_dynstr_appendf(ds, "dot(%s.rgb, vec3(0.2126, 0.7152, 0.0722))", name);
}
else if (from == GPU_VEC3) {
BLI_dynstr_appendf(ds, "(%s.r + %s.g + %s.b) / 3.0", name, name, name);
}
else if (from == GPU_VEC2) {
BLI_dynstr_appendf(ds, "%s.r", name);
}
}
else if (to == GPU_VEC2) {
if (from == GPU_VEC4) {
BLI_dynstr_appendf(ds, "vec2((%s.r + %s.g + %s.b) / 3.0, %s.a)", name, name, name, name);
}
else if (from == GPU_VEC3) {
BLI_dynstr_appendf(ds, "vec2((%s.r + %s.g + %s.b) / 3.0, 1.0)", name, name, name);
}
else if (from == GPU_FLOAT) {
BLI_dynstr_appendf(ds, "vec2(%s, 1.0)", name);
}
}
else if (to == GPU_VEC3) {
if (from == GPU_VEC4) {
BLI_dynstr_appendf(ds, "%s.rgb", name);
}
else if (from == GPU_VEC2) {
BLI_dynstr_appendf(ds, "vec3(%s.r, %s.r, %s.r)", name, name, name);
}
else if (from == GPU_FLOAT) {
BLI_dynstr_appendf(ds, "vec3(%s, %s, %s)", name, name, name);
}
}
else if (to == GPU_VEC4) {
if (from == GPU_VEC3) {
BLI_dynstr_appendf(ds, "vec4(%s, 1.0)", name);
}
else if (from == GPU_VEC2) {
BLI_dynstr_appendf(ds, "vec4(%s.r, %s.r, %s.r, %s.g)", name, name, name, name);
}
else if (from == GPU_FLOAT) {
BLI_dynstr_appendf(ds, "vec4(%s, %s, %s, 1.0)", name, name, name);
}
}
else if (to == GPU_CLOSURE) {
if (from == GPU_VEC4) {
BLI_dynstr_appendf(ds, "closure_emission(%s.rgb)", name);
}
else if (from == GPU_VEC3) {
BLI_dynstr_appendf(ds, "closure_emission(%s.rgb)", name);
}
else if (from == GPU_VEC2) {
BLI_dynstr_appendf(ds, "closure_emission(%s.rrr)", name);
}
else if (from == GPU_FLOAT) {
BLI_dynstr_appendf(ds, "closure_emission(vec3(%s, %s, %s))", name, name, name);
}
}
else {
BLI_dynstr_append(ds, name);
}
}
static void codegen_print_datatype(DynStr *ds, const eGPUType type, float *data)
{
int i;
BLI_dynstr_appendf(ds, "%s(", GPU_DATATYPE_STR[type]);
for (i = 0; i < type; i++) {
BLI_dynstr_appendf(ds, "%.12f", data[i]);
if (i == type - 1) {
BLI_dynstr_append(ds, ")");
}
else {
BLI_dynstr_append(ds, ", ");
}
}
}
static int codegen_input_has_texture(GPUInput *input)
{
if (input->link) {
return 0;
}
else {
return (input->source == GPU_SOURCE_TEX);
}
}
const char *GPU_builtin_name(eGPUBuiltin builtin)
{
if (builtin == GPU_VIEW_MATRIX) {
return "unfviewmat";
}
else if (builtin == GPU_OBJECT_MATRIX) {
return "unfobmat";
}
else if (builtin == GPU_INVERSE_VIEW_MATRIX) {
return "unfinvviewmat";
}
else if (builtin == GPU_INVERSE_OBJECT_MATRIX) {
return "unfinvobmat";
}
else if (builtin == GPU_LOC_TO_VIEW_MATRIX) {
return "unflocaltoviewmat";
}
else if (builtin == GPU_INVERSE_LOC_TO_VIEW_MATRIX) {
return "unfinvlocaltoviewmat";
}
else if (builtin == GPU_VIEW_POSITION) {
return "varposition";
}
else if (builtin == GPU_WORLD_NORMAL) {
return "varwnormal";
}
else if (builtin == GPU_VIEW_NORMAL) {
return "varnormal";
}
else if (builtin == GPU_OBJECT_COLOR) {
return "unfobjectcolor";
}
else if (builtin == GPU_AUTO_BUMPSCALE) {
return "unfobautobumpscale";
}
else if (builtin == GPU_CAMERA_TEXCO_FACTORS) {
return "unfcameratexfactors";
}
else if (builtin == GPU_PARTICLE_SCALAR_PROPS) {
return "unfparticlescalarprops";
}
else if (builtin == GPU_PARTICLE_LOCATION) {
return "unfparticleco";
}
else if (builtin == GPU_PARTICLE_VELOCITY) {
return "unfparticlevel";
}
else if (builtin == GPU_PARTICLE_ANG_VELOCITY) {
return "unfparticleangvel";
}
else if (builtin == GPU_OBJECT_INFO) {
return "unfobjectinfo";
}
else if (builtin == GPU_VOLUME_DENSITY) {
return "sampdensity";
}
else if (builtin == GPU_VOLUME_FLAME) {
return "sampflame";
}
else if (builtin == GPU_VOLUME_TEMPERATURE) {
return "unftemperature";
}
else if (builtin == GPU_BARYCENTRIC_TEXCO) {
return "unfbarycentrictex";
}
else if (builtin == GPU_BARYCENTRIC_DIST) {
return "unfbarycentricdist";
}
else {
return "";
}
}
/* assign only one texid per buffer to avoid sampling the same texture twice */
static void codegen_set_texid(GHash *bindhash, GPUInput *input, int *texid, void *key1, int key2)
{
GHashPair pair = {key1, POINTER_FROM_INT(key2)};
if (BLI_ghash_haskey(bindhash, &pair)) {
/* Reuse existing texid */
input->texid = POINTER_AS_INT(BLI_ghash_lookup(bindhash, &pair));
}
else {
/* Allocate new texid */
input->texid = *texid;
(*texid)++;
input->bindtex = true;
void *key = BLI_ghashutil_pairalloc(key1, POINTER_FROM_INT(key2));
BLI_ghash_insert(bindhash, key, POINTER_FROM_INT(input->texid));
}
}
static void codegen_set_unique_ids(ListBase *nodes)
{
GHash *bindhash;
GPUNode *node;
GPUInput *input;
GPUOutput *output;
int id = 1, texid = 0;
bindhash = BLI_ghash_pair_new("codegen_set_unique_ids1 gh");
for (node = nodes->first; node; node = node->next) {
for (input = node->inputs.first; input; input = input->next) {
/* set id for unique names of uniform variables */
input->id = id++;
/* set texid used for settings texture slot */
if (codegen_input_has_texture(input)) {
input->bindtex = false;
if (input->ima) {
/* input is texture from image */
codegen_set_texid(bindhash, input, &texid, input->ima, input->type);
}
else if (input->coba) {
/* input is color band texture, check coba pointer */
codegen_set_texid(bindhash, input, &texid, input->coba, 0);
}
else {
/* Either input->ima or input->coba should be non-NULL. */
BLI_assert(0);
}
}
}
for (output = node->outputs.first; output; output = output->next) {
/* set id for unique names of tmp variables storing output */
output->id = id++;
}
}
BLI_ghash_free(bindhash, BLI_ghashutil_pairfree, NULL);
}
/**
* It will create an UBO for GPUMaterial if there is any GPU_DYNAMIC_UBO.
*/
static int codegen_process_uniforms_functions(GPUMaterial *material, DynStr *ds, ListBase *nodes)
{
GPUNode *node;
GPUInput *input;
const char *name;
int builtins = 0;
ListBase ubo_inputs = {NULL, NULL};
/* print uniforms */
for (node = nodes->first; node; node = node->next) {
for (input = node->inputs.first; input; input = input->next) {
if (input->source == GPU_SOURCE_TEX) {
/* create exactly one sampler for each texture */
if (codegen_input_has_texture(input) && input->bindtex) {
const char *type;
if (input->coba || input->type == GPU_TEX1D_ARRAY) {
type = "sampler1DArray";
}
else if (input->type == GPU_TEX2D_ARRAY) {
type = "sampler2DArray";
}
else {
BLI_assert(input->type == GPU_TEX2D);
type = "sampler2D";
}
BLI_dynstr_appendf(ds, "uniform %s samp%d;\n", type, input->texid);
}
}
else if (input->source == GPU_SOURCE_BUILTIN) {
/* only define each builtin uniform/varying once */
if (!(builtins & input->builtin)) {
builtins |= input->builtin;
name = GPU_builtin_name(input->builtin);
if (gpu_str_prefix(name, "samp")) {
if ((input->builtin == GPU_VOLUME_DENSITY) || (input->builtin == GPU_VOLUME_FLAME)) {
BLI_dynstr_appendf(ds, "uniform sampler3D %s;\n", name);
}
}
else if (gpu_str_prefix(name, "unf")) {
BLI_dynstr_appendf(ds, "uniform %s %s;\n", GPU_DATATYPE_STR[input->type], name);
}
else {
BLI_dynstr_appendf(ds, "in %s %s;\n", GPU_DATATYPE_STR[input->type], name);
}
}
}
else if (input->source == GPU_SOURCE_STRUCT) {
/* Add other struct here if needed. */
BLI_dynstr_appendf(ds, "Closure strct%d = CLOSURE_DEFAULT;\n", input->id);
}
else if (input->source == GPU_SOURCE_UNIFORM) {
if (!input->link) {
/* We handle the UBOuniforms separately. */
BLI_addtail(&ubo_inputs, BLI_genericNodeN(input));
}
}
else if (input->source == GPU_SOURCE_CONSTANT) {
BLI_dynstr_appendf(ds, "const %s cons%d = ", GPU_DATATYPE_STR[input->type], input->id);
codegen_print_datatype(ds, input->type, input->vec);
BLI_dynstr_append(ds, ";\n");
}
else if (input->source == GPU_SOURCE_ATTR && input->attr_first) {
BLI_dynstr_appendf(ds, "in %s var%d;\n", GPU_DATATYPE_STR[input->type], input->attr_id);
}
}
}
/* Handle the UBO block separately. */
if ((material != NULL) && !BLI_listbase_is_empty(&ubo_inputs)) {
GPU_material_uniform_buffer_create(material, &ubo_inputs);
/* Inputs are sorted */
BLI_dynstr_appendf(ds, "\nlayout (std140) uniform %s {\n", GPU_UBO_BLOCK_NAME);
for (LinkData *link = ubo_inputs.first; link; link = link->next) {
input = link->data;
BLI_dynstr_appendf(ds, "\t%s unf%d;\n", GPU_DATATYPE_STR[input->type], input->id);
}
BLI_dynstr_append(ds, "};\n");
BLI_freelistN(&ubo_inputs);
}
BLI_dynstr_append(ds, "\n");
return builtins;
}
static void codegen_declare_tmps(DynStr *ds, ListBase *nodes)
{
GPUNode *node;
GPUOutput *output;
for (node = nodes->first; node; node = node->next) {
/* declare temporary variables for node output storage */
for (output = node->outputs.first; output; output = output->next) {
if (output->type == GPU_CLOSURE) {
BLI_dynstr_appendf(ds, "\tClosure tmp%d;\n", output->id);
}
else {
BLI_dynstr_appendf(ds, "\t%s tmp%d;\n", GPU_DATATYPE_STR[output->type], output->id);
}
}
}
BLI_dynstr_append(ds, "\n");
}
static void codegen_call_functions(DynStr *ds, ListBase *nodes, GPUOutput *finaloutput)
{
GPUNode *node;
GPUInput *input;
GPUOutput *output;
for (node = nodes->first; node; node = node->next) {
BLI_dynstr_appendf(ds, "\t%s(", node->name);
for (input = node->inputs.first; input; input = input->next) {
if (input->source == GPU_SOURCE_TEX) {
BLI_dynstr_appendf(ds, "samp%d", input->texid);
}
else if (input->source == GPU_SOURCE_OUTPUT) {
codegen_convert_datatype(
ds, input->link->output->type, input->type, "tmp", input->link->output->id);
}
else if (input->source == GPU_SOURCE_BUILTIN) {
/* TODO(fclem) get rid of that. */
if (input->builtin == GPU_INVERSE_VIEW_MATRIX) {
BLI_dynstr_append(ds, "viewinv");
}
else if (input->builtin == GPU_VIEW_MATRIX) {
BLI_dynstr_append(ds, "viewmat");
}
else if (input->builtin == GPU_CAMERA_TEXCO_FACTORS) {
BLI_dynstr_append(ds, "camtexfac");
}
else if (input->builtin == GPU_LOC_TO_VIEW_MATRIX) {
BLI_dynstr_append(ds, "localtoviewmat");
}
else if (input->builtin == GPU_INVERSE_LOC_TO_VIEW_MATRIX) {
BLI_dynstr_append(ds, "invlocaltoviewmat");
}
else if (input->builtin == GPU_BARYCENTRIC_DIST) {
BLI_dynstr_append(ds, "barycentricDist");
}
else if (input->builtin == GPU_BARYCENTRIC_TEXCO) {
BLI_dynstr_append(ds, "barytexco");
}
else if (input->builtin == GPU_OBJECT_MATRIX) {
BLI_dynstr_append(ds, "objmat");
}
else if (input->builtin == GPU_OBJECT_INFO) {
BLI_dynstr_append(ds, "ObjectInfo");
}
else if (input->builtin == GPU_OBJECT_COLOR) {
BLI_dynstr_append(ds, "ObjectColor");
}
else if (input->builtin == GPU_INVERSE_OBJECT_MATRIX) {
BLI_dynstr_append(ds, "objinv");
}
else if (input->builtin == GPU_VIEW_POSITION) {
BLI_dynstr_append(ds, "viewposition");
}
else if (input->builtin == GPU_VIEW_NORMAL) {
BLI_dynstr_append(ds, "facingnormal");
}
else if (input->builtin == GPU_WORLD_NORMAL) {
BLI_dynstr_append(ds, "facingwnormal");
}
else {
BLI_dynstr_append(ds, GPU_builtin_name(input->builtin));
}
}
else if (input->source == GPU_SOURCE_STRUCT) {
BLI_dynstr_appendf(ds, "strct%d", input->id);
}
else if (input->source == GPU_SOURCE_UNIFORM) {
BLI_dynstr_appendf(ds, "unf%d", input->id);
}
else if (input->source == GPU_SOURCE_CONSTANT) {
BLI_dynstr_appendf(ds, "cons%d", input->id);
}
else if (input->source == GPU_SOURCE_ATTR) {
BLI_dynstr_appendf(ds, "var%d", input->attr_id);
}
BLI_dynstr_append(ds, ", ");
}
for (output = node->outputs.first; output; output = output->next) {
BLI_dynstr_appendf(ds, "tmp%d", output->id);
if (output->next) {
BLI_dynstr_append(ds, ", ");
}
}
BLI_dynstr_append(ds, ");\n");
}
BLI_dynstr_appendf(ds, "\n\treturn tmp%d", finaloutput->id);
BLI_dynstr_append(ds, ";\n");
}
static char *code_generate_fragment(GPUMaterial *material,
ListBase *nodes,
GPUOutput *output,
int *rbuiltins)
{
DynStr *ds = BLI_dynstr_new();
char *code;
int builtins;
#if 0
BLI_dynstr_append(ds, FUNCTION_PROTOTYPES);
#endif
codegen_set_unique_ids(nodes);
*rbuiltins = builtins = codegen_process_uniforms_functions(material, ds, nodes);
if (builtins & (GPU_OBJECT_INFO | GPU_OBJECT_COLOR)) {
BLI_dynstr_append(ds, datatoc_gpu_shader_common_obinfos_lib_glsl);
}
if (builtins & GPU_BARYCENTRIC_TEXCO) {
BLI_dynstr_append(ds, "in vec2 barycentricTexCo;\n");
}
if (builtins & GPU_BARYCENTRIC_DIST) {
BLI_dynstr_append(ds, "flat in vec3 barycentricDist;\n");
}
BLI_dynstr_append(ds, "Closure nodetree_exec(void)\n{\n");
if (builtins & GPU_BARYCENTRIC_TEXCO) {
BLI_dynstr_append(ds, "#ifdef HAIR_SHADER\n");
BLI_dynstr_append(ds,
"\tvec2 barytexco = vec2((fract(barycentricTexCo.y) != 0.0)\n"
"\t ? barycentricTexCo.x\n"
"\t : 1.0 - barycentricTexCo.x,\n"
"\t 0.0);\n");
BLI_dynstr_append(ds, "#else\n");
BLI_dynstr_append(ds, "\tvec2 barytexco = barycentricTexCo;\n");
BLI_dynstr_append(ds, "#endif\n");
}
/* TODO(fclem) get rid of that. */
if (builtins & GPU_VIEW_MATRIX) {
BLI_dynstr_append(ds, "\t#define viewmat ViewMatrix\n");
}
if (builtins & GPU_CAMERA_TEXCO_FACTORS) {
BLI_dynstr_append(ds, "\t#define camtexfac CameraTexCoFactors\n");
}
if (builtins & GPU_OBJECT_MATRIX) {
BLI_dynstr_append(ds, "\t#define objmat ModelMatrix\n");
}
if (builtins & GPU_INVERSE_OBJECT_MATRIX) {
BLI_dynstr_append(ds, "\t#define objinv ModelMatrixInverse\n");
}
if (builtins & GPU_INVERSE_VIEW_MATRIX) {
BLI_dynstr_append(ds, "\t#define viewinv ViewMatrixInverse\n");
}
if (builtins & GPU_LOC_TO_VIEW_MATRIX) {
BLI_dynstr_append(ds, "\t#define localtoviewmat (ViewMatrix * ModelMatrix)\n");
}
if (builtins & GPU_INVERSE_LOC_TO_VIEW_MATRIX) {
BLI_dynstr_append(ds,
"\t#define invlocaltoviewmat (ModelMatrixInverse * ViewMatrixInverse)\n");
}
if (builtins & GPU_VIEW_NORMAL) {
BLI_dynstr_append(ds, "#ifdef HAIR_SHADER\n");
BLI_dynstr_append(ds, "\tvec3 n;\n");
BLI_dynstr_append(ds, "\tworld_normals_get(n);\n");
BLI_dynstr_append(ds, "\tvec3 facingnormal = transform_direction(ViewMatrix, n);\n");
BLI_dynstr_append(ds, "#else\n");
BLI_dynstr_append(ds, "\tvec3 facingnormal = gl_FrontFacing ? viewNormal: -viewNormal;\n");
BLI_dynstr_append(ds, "#endif\n");
}
if (builtins & GPU_WORLD_NORMAL) {
BLI_dynstr_append(ds, "\tvec3 facingwnormal;\n");
if (builtins & GPU_VIEW_NORMAL) {
BLI_dynstr_append(ds, "#ifdef HAIR_SHADER\n");
BLI_dynstr_append(ds, "\tfacingwnormal = n;\n");
BLI_dynstr_append(ds, "#else\n");
BLI_dynstr_append(ds, "\tworld_normals_get(facingwnormal);\n");
BLI_dynstr_append(ds, "#endif\n");
}
else {
BLI_dynstr_append(ds, "\tworld_normals_get(facingwnormal);\n");
}
}
if (builtins & GPU_VIEW_POSITION) {
BLI_dynstr_append(ds, "\t#define viewposition viewPosition\n");
}
codegen_declare_tmps(ds, nodes);
codegen_call_functions(ds, nodes, output);
BLI_dynstr_append(ds, "}\n");
/* XXX This cannot go into gpu_shader_material.glsl because main()
* would be parsed and generate error */
/* Old glsl mode compat. */
/* TODO(fclem) This is only used by world shader now. get rid of it? */
BLI_dynstr_append(ds, "#ifndef NODETREE_EXEC\n");
BLI_dynstr_append(ds, "out vec4 fragColor;\n");
BLI_dynstr_append(ds, "void main()\n");
BLI_dynstr_append(ds, "{\n");
BLI_dynstr_append(ds, "\tClosure cl = nodetree_exec();\n");
BLI_dynstr_append(ds,
"\tfragColor = vec4(cl.radiance, "
"saturate(1.0 - avg(cl.transmittance)));\n");
BLI_dynstr_append(ds, "}\n");
BLI_dynstr_append(ds, "#endif\n\n");
/* create shader */
code = BLI_dynstr_get_cstring(ds);
BLI_dynstr_free(ds);
#if 0
if (G.debug & G_DEBUG) {
printf("%s\n", code);
}
#endif
return code;
}
static const char *attr_prefix_get(CustomDataType type)
{
switch (type) {
case CD_ORCO:
return "orco";
case CD_MTFACE:
return "u";
case CD_TANGENT:
return "t";
case CD_MCOL:
return "c";
case CD_AUTO_FROM_NAME:
return "a";
default:
BLI_assert(false && "GPUVertAttr Prefix type not found : This should not happen!");
return "";
}
}
static char *code_generate_vertex(ListBase *nodes, const char *vert_code, bool use_geom)
{
DynStr *ds = BLI_dynstr_new();
GPUNode *node;
GPUInput *input;
char *code;
int builtins = 0;
/* Hairs uv and col attributes are passed by bufferTextures. */
BLI_dynstr_append(ds,
"#ifdef HAIR_SHADER\n"
"#define DEFINE_ATTR(type, attr) uniform samplerBuffer attr\n"
"#else\n"
"#define DEFINE_ATTR(type, attr) in type attr\n"
"#endif\n");
for (node = nodes->first; node; node = node->next) {
for (input = node->inputs.first; input; input = input->next) {
if (input->source == GPU_SOURCE_BUILTIN) {
builtins |= input->builtin;
}
if (input->source == GPU_SOURCE_ATTR && input->attr_first) {
/* XXX FIXME : see notes in mesh_render_data_create() */
/* NOTE : Replicate changes to mesh_render_data_create() in draw_cache_impl_mesh.c */
if (input->attr_type == CD_ORCO) {
/* OPTI : orco is computed from local positions, but only if no modifier is present. */
BLI_dynstr_append(ds, datatoc_gpu_shader_common_obinfos_lib_glsl);
BLI_dynstr_append(ds, "DEFINE_ATTR(vec4, orco);\n");
}
else if (input->attr_name[0] == '\0') {
BLI_dynstr_appendf(ds,
"DEFINE_ATTR(%s, %s);\n",
GPU_DATATYPE_STR[input->type],
attr_prefix_get(input->attr_type));
BLI_dynstr_appendf(
ds, "#define att%d %s\n", input->attr_id, attr_prefix_get(input->attr_type));
}
else {
char attr_safe_name[GPU_MAX_SAFE_ATTRIB_NAME];
GPU_vertformat_safe_attrib_name(
input->attr_name, attr_safe_name, GPU_MAX_SAFE_ATTRIB_NAME);
BLI_dynstr_appendf(ds,
"DEFINE_ATTR(%s, %s%s);\n",
GPU_DATATYPE_STR[input->type],
attr_prefix_get(input->attr_type),
attr_safe_name);
BLI_dynstr_appendf(ds,
"#define att%d %s%s\n",
input->attr_id,
attr_prefix_get(input->attr_type),
attr_safe_name);
}
BLI_dynstr_appendf(ds,
"out %s var%d%s;\n",
GPU_DATATYPE_STR[input->type],
input->attr_id,
use_geom ? "g" : "");
}
}
}
if (builtins & GPU_BARYCENTRIC_TEXCO) {
BLI_dynstr_append(ds, "#ifdef HAIR_SHADER\n");
BLI_dynstr_appendf(ds, "out vec2 barycentricTexCo%s;\n", use_geom ? "g" : "");
BLI_dynstr_append(ds, "#endif\n");
}
if (builtins & GPU_BARYCENTRIC_DIST) {
BLI_dynstr_append(ds, "out vec3 barycentricPosg;\n");
}
BLI_dynstr_append(ds, "\n#define USE_ATTR\n");
/* Prototype, defined later (this is because of matrices definition). */
BLI_dynstr_append(ds, "void pass_attr(in vec3 position);\n");
BLI_dynstr_append(ds, "\n");
if (use_geom) {
/* XXX HACK: Eevee specific. */
char *vert_new, *vert_new2;
vert_new = BLI_str_replaceN(vert_code, "worldPosition", "worldPositiong");
vert_new2 = vert_new;
vert_new = BLI_str_replaceN(vert_new2, "viewPosition", "viewPositiong");
MEM_freeN(vert_new2);
vert_new2 = vert_new;
vert_new = BLI_str_replaceN(vert_new2, "worldNormal", "worldNormalg");
MEM_freeN(vert_new2);
vert_new2 = vert_new;
vert_new = BLI_str_replaceN(vert_new2, "viewNormal", "viewNormalg");
MEM_freeN(vert_new2);
BLI_dynstr_append(ds, vert_new);
MEM_freeN(vert_new);
}
else {
BLI_dynstr_append(ds, vert_code);
}
BLI_dynstr_append(ds, "\n");
BLI_dynstr_append(ds, use_geom ? "RESOURCE_ID_VARYING_GEOM\n" : "RESOURCE_ID_VARYING\n");
/* Prototype because defined later. */
BLI_dynstr_append(ds,
"vec2 hair_get_customdata_vec2(const samplerBuffer);\n"
"vec3 hair_get_customdata_vec3(const samplerBuffer);\n"
"vec4 hair_get_customdata_vec4(const samplerBuffer);\n"
"vec3 hair_get_strand_pos(void);\n"
"int hair_get_base_id(void);\n"
"\n");
BLI_dynstr_append(ds, "void pass_attr(in vec3 position) {\n");
BLI_dynstr_append(ds, use_geom ? "\tPASS_RESOURCE_ID_GEOM\n" : "\tPASS_RESOURCE_ID\n");
BLI_dynstr_append(ds, "#ifdef HAIR_SHADER\n");
if (builtins & GPU_BARYCENTRIC_TEXCO) {
/* To match cycles without breaking into individual segment we encode if we need to invert
* the first component into the second component. We invert if the barycentricTexCo.y
* is NOT 0.0 or 1.0. */
BLI_dynstr_append(ds, "\tint _base_id = hair_get_base_id();\n");
BLI_dynstr_appendf(
ds, "\tbarycentricTexCo%s.x = float((_base_id %% 2) == 1);\n", use_geom ? "g" : "");
BLI_dynstr_appendf(
ds, "\tbarycentricTexCo%s.y = float(((_base_id %% 4) %% 3) > 0);\n", use_geom ? "g" : "");
}
if (builtins & GPU_BARYCENTRIC_DIST) {
BLI_dynstr_append(ds, "\tbarycentricPosg = position;\n");
}
for (node = nodes->first; node; node = node->next) {
for (input = node->inputs.first; input; input = input->next) {
if (input->source == GPU_SOURCE_ATTR && input->attr_first) {
if (input->attr_type == CD_TANGENT) {
/* Not supported by hairs */
BLI_dynstr_appendf(ds, "\tvar%d%s = vec4(0.0);\n", input->attr_id, use_geom ? "g" : "");
}
else if (input->attr_type == CD_ORCO) {
BLI_dynstr_appendf(ds,
"\tvar%d%s = OrcoTexCoFactors[0].xyz + (ModelMatrixInverse * "
"vec4(hair_get_strand_pos(), 1.0)).xyz * OrcoTexCoFactors[1].xyz;\n",
input->attr_id,
use_geom ? "g" : "");
/* TODO: fix ORCO with modifiers. */
}
else {
BLI_dynstr_appendf(ds,
"\tvar%d%s = hair_get_customdata_%s(att%d);\n",
input->attr_id,
use_geom ? "g" : "",
GPU_DATATYPE_STR[input->type],
input->attr_id);
}
}
}
}
BLI_dynstr_append(ds, "#else /* MESH_SHADER */\n");
/* GPU_BARYCENTRIC_TEXCO cannot be computed based on gl_VertexID
* for MESH_SHADER because of indexed drawing. In this case a
* geometry shader is needed. */
if (builtins & GPU_BARYCENTRIC_DIST) {
BLI_dynstr_append(ds, "\tbarycentricPosg = (ModelMatrix * vec4(position, 1.0)).xyz;\n");
}
for (node = nodes->first; node; node = node->next) {
for (input = node->inputs.first; input; input = input->next) {
if (input->source == GPU_SOURCE_ATTR && input->attr_first) {
if (input->attr_type == CD_TANGENT) { /* silly exception */
BLI_dynstr_appendf(ds,
"\tvar%d%s.xyz = transpose(mat3(ModelMatrixInverse)) * att%d.xyz;\n",
input->attr_id,
use_geom ? "g" : "",
input->attr_id);
BLI_dynstr_appendf(
ds, "\tvar%d%s.w = att%d.w;\n", input->attr_id, use_geom ? "g" : "", input->attr_id);
/* Normalize only if vector is not null. */
BLI_dynstr_appendf(ds,
"\tfloat lvar%d = dot(var%d%s.xyz, var%d%s.xyz);\n",
input->attr_id,
input->attr_id,
use_geom ? "g" : "",
input->attr_id,
use_geom ? "g" : "");
BLI_dynstr_appendf(ds,
"\tvar%d%s.xyz *= (lvar%d > 0.0) ? inversesqrt(lvar%d) : 1.0;\n",
input->attr_id,
use_geom ? "g" : "",
input->attr_id,
input->attr_id);
}
else if (input->attr_type == CD_ORCO) {
BLI_dynstr_appendf(ds,
"\tvar%d%s = OrcoTexCoFactors[0].xyz + position *"
" OrcoTexCoFactors[1].xyz;\n",
input->attr_id,
use_geom ? "g" : "");
/* See mesh_create_loop_orco() for explanation. */
BLI_dynstr_appendf(ds,
"\tif (orco.w == 0.0) { var%d%s = orco.xyz * 0.5 + 0.5; }\n",
input->attr_id,
use_geom ? "g" : "");
}
else {
BLI_dynstr_appendf(
ds, "\tvar%d%s = att%d;\n", input->attr_id, use_geom ? "g" : "", input->attr_id);
}
}
}
}
BLI_dynstr_append(ds, "#endif /* HAIR_SHADER */\n");
BLI_dynstr_append(ds, "}\n");
code = BLI_dynstr_get_cstring(ds);
BLI_dynstr_free(ds);
#if 0
if (G.debug & G_DEBUG) {
printf("%s\n", code);
}
#endif
return code;
}
static char *code_generate_geometry(ListBase *nodes, const char *geom_code, const char *defines)
{
DynStr *ds = BLI_dynstr_new();
GPUNode *node;
GPUInput *input;
char *code;
int builtins = 0;
/* XXX we should not make specific eevee cases here. */
bool is_hair_shader = (strstr(defines, "HAIR_SHADER") != NULL);
/* Create prototype because attributes cannot be declared before layout. */
BLI_dynstr_append(ds, "void pass_attr(in int vert);\n");
BLI_dynstr_append(ds, "void calc_barycentric_distances(vec3 pos0, vec3 pos1, vec3 pos2);\n");
BLI_dynstr_append(ds, "#define USE_ATTR\n");
/* Generate varying declarations. */
for (node = nodes->first; node; node = node->next) {
for (input = node->inputs.first; input; input = input->next) {
if (input->source == GPU_SOURCE_BUILTIN) {
builtins |= input->builtin;
}
if (input->source == GPU_SOURCE_ATTR && input->attr_first) {
BLI_dynstr_appendf(ds, "in %s var%dg[];\n", GPU_DATATYPE_STR[input->type], input->attr_id);
BLI_dynstr_appendf(ds, "out %s var%d;\n", GPU_DATATYPE_STR[input->type], input->attr_id);
}
}
}
if (builtins & GPU_BARYCENTRIC_TEXCO) {
BLI_dynstr_append(ds, "#ifdef HAIR_SHADER\n");
BLI_dynstr_append(ds, "in vec2 barycentricTexCog[];\n");
BLI_dynstr_append(ds, "#endif\n");
BLI_dynstr_append(ds, "out vec2 barycentricTexCo;\n");
}
if (builtins & GPU_BARYCENTRIC_DIST) {
BLI_dynstr_append(ds, "in vec3 barycentricPosg[];\n");
BLI_dynstr_append(ds, "flat out vec3 barycentricDist;\n");
}
if (geom_code == NULL) {
/* Force geometry usage if GPU_BARYCENTRIC_DIST or GPU_BARYCENTRIC_TEXCO are used.
* Note: GPU_BARYCENTRIC_TEXCO only requires it if the shader is not drawing hairs. */
if ((builtins & (GPU_BARYCENTRIC_DIST | GPU_BARYCENTRIC_TEXCO)) == 0 || is_hair_shader) {
/* Early out */
BLI_dynstr_free(ds);
return NULL;
}
else {
/* Force geom shader usage */
/* TODO put in external file. */
BLI_dynstr_append(ds, "layout(triangles) in;\n");
BLI_dynstr_append(ds, "layout(triangle_strip, max_vertices=3) out;\n");
BLI_dynstr_append(ds, "in vec3 worldPositiong[];\n");
BLI_dynstr_append(ds, "in vec3 viewPositiong[];\n");
BLI_dynstr_append(ds, "in vec3 worldNormalg[];\n");
BLI_dynstr_append(ds, "in vec3 viewNormalg[];\n");
BLI_dynstr_append(ds, "out vec3 worldPosition;\n");
BLI_dynstr_append(ds, "out vec3 viewPosition;\n");
BLI_dynstr_append(ds, "out vec3 worldNormal;\n");
BLI_dynstr_append(ds, "out vec3 viewNormal;\n");
BLI_dynstr_append(ds, datatoc_common_view_lib_glsl);
BLI_dynstr_append(ds, "void main(){\n");
if (builtins & GPU_BARYCENTRIC_DIST) {
BLI_dynstr_append(ds,
"\tcalc_barycentric_distances(barycentricPosg[0], barycentricPosg[1], "
"barycentricPosg[2]);\n");
}
for (int i = 0; i < 3; i++) {
BLI_dynstr_appendf(ds, "\tgl_Position = gl_in[%d].gl_Position;\n", i);
BLI_dynstr_appendf(ds, "\tgl_ClipDistance[0] = gl_in[%d].gl_ClipDistance[0];\n", i);
BLI_dynstr_appendf(ds, "\tpass_attr(%d);\n", i);
BLI_dynstr_append(ds, "\tEmitVertex();\n");
}
BLI_dynstr_append(ds, "}\n");
}
}
else {
BLI_dynstr_append(ds, geom_code);
}
if (builtins & GPU_BARYCENTRIC_DIST) {
BLI_dynstr_append(ds, "void calc_barycentric_distances(vec3 pos0, vec3 pos1, vec3 pos2) {\n");
BLI_dynstr_append(ds, "\tvec3 edge21 = pos2 - pos1;\n");
BLI_dynstr_append(ds, "\tvec3 edge10 = pos1 - pos0;\n");
BLI_dynstr_append(ds, "\tvec3 edge02 = pos0 - pos2;\n");
BLI_dynstr_append(ds, "\tvec3 d21 = normalize(edge21);\n");
BLI_dynstr_append(ds, "\tvec3 d10 = normalize(edge10);\n");
BLI_dynstr_append(ds, "\tvec3 d02 = normalize(edge02);\n");
BLI_dynstr_append(ds, "\tfloat d = dot(d21, edge02);\n");
BLI_dynstr_append(ds, "\tbarycentricDist.x = sqrt(dot(edge02, edge02) - d * d);\n");
BLI_dynstr_append(ds, "\td = dot(d02, edge10);\n");
BLI_dynstr_append(ds, "\tbarycentricDist.y = sqrt(dot(edge10, edge10) - d * d);\n");
BLI_dynstr_append(ds, "\td = dot(d10, edge21);\n");
BLI_dynstr_append(ds, "\tbarycentricDist.z = sqrt(dot(edge21, edge21) - d * d);\n");
BLI_dynstr_append(ds, "}\n");
}
BLI_dynstr_append(ds, "RESOURCE_ID_VARYING\n");
/* Generate varying assignments. */
BLI_dynstr_append(ds, "void pass_attr(in int vert) {\n");
BLI_dynstr_append(ds, "\tPASS_RESOURCE_ID(vert)\n");
/* XXX HACK: Eevee specific. */
if (geom_code == NULL) {
BLI_dynstr_append(ds, "\tworldPosition = worldPositiong[vert];\n");
BLI_dynstr_append(ds, "\tviewPosition = viewPositiong[vert];\n");
BLI_dynstr_append(ds, "\tworldNormal = worldNormalg[vert];\n");
BLI_dynstr_append(ds, "\tviewNormal = viewNormalg[vert];\n");
}
if (builtins & GPU_BARYCENTRIC_TEXCO) {
BLI_dynstr_append(ds, "#ifdef HAIR_SHADER\n");
BLI_dynstr_append(ds, "\tbarycentricTexCo = barycentricTexCog[vert];\n");
BLI_dynstr_append(ds, "#else\n");
BLI_dynstr_append(ds, "\tbarycentricTexCo.x = float((vert % 3) == 0);\n");
BLI_dynstr_append(ds, "\tbarycentricTexCo.y = float((vert % 3) == 1);\n");
BLI_dynstr_append(ds, "#endif\n");
}
for (node = nodes->first; node; node = node->next) {
for (input = node->inputs.first; input; input = input->next) {
if (input->source == GPU_SOURCE_ATTR && input->attr_first) {
/* TODO let shader choose what to do depending on what the attribute is. */
BLI_dynstr_appendf(ds, "\tvar%d = var%dg[vert];\n", input->attr_id, input->attr_id);
}
}
}
BLI_dynstr_append(ds, "}\n");
code = BLI_dynstr_get_cstring(ds);
BLI_dynstr_free(ds);
return code;
}
void GPU_code_generate_glsl_lib(void)
{
/* Only parse GLSL shader files once. */
if (FUNCTION_HASH) {
return;
}
FUNCTION_HASH = BLI_ghash_str_new("GPU_lookup_function gh");
for (int i = 0; gpu_material_libraries[i]; i++) {
gpu_parse_material_library(FUNCTION_HASH, gpu_material_libraries[i]);
}
}
/* GPU pass binding/unbinding */
GPUShader *GPU_pass_shader_get(GPUPass *pass)
{
return pass->shader;
}
void GPU_nodes_extract_dynamic_inputs(GPUShader *shader, ListBase *inputs, ListBase *nodes)
{
GPUNode *node;
GPUInput *next, *input;
BLI_listbase_clear(inputs);
if (!shader) {
return;
}
for (node = nodes->first; node; node = node->next) {
int z = 0;
for (input = node->inputs.first; input; input = next, z++) {
next = input->next;
/* attributes don't need to be bound, they already have
* an id that the drawing functions will use. Builtins have
* constant names. */
if (ELEM(input->source, GPU_SOURCE_ATTR, GPU_SOURCE_BUILTIN)) {
continue;
}
if (input->source == GPU_SOURCE_TEX) {
BLI_snprintf(input->shadername, sizeof(input->shadername), "samp%d", input->texid);
}
else {
BLI_snprintf(input->shadername, sizeof(input->shadername), "unf%d", input->id);
}
if (input->source == GPU_SOURCE_TEX) {
if (input->bindtex) {
input->shaderloc = GPU_shader_get_uniform_ensure(shader, input->shadername);
/* extract nodes */
BLI_remlink(&node->inputs, input);
BLI_addtail(inputs, input);
}
}
}
}
}
/* Node Link Functions */
static GPUNodeLink *GPU_node_link_create(void)
{
GPUNodeLink *link = MEM_callocN(sizeof(GPUNodeLink), "GPUNodeLink");
link->users++;
return link;
}
static void gpu_node_link_free(GPUNodeLink *link)
{
link->users--;
if (link->users < 0) {
fprintf(stderr, "GPU_node_link_free: negative refcount\n");
}
if (link->users == 0) {
if (link->output) {
link->output->link = NULL;
}
MEM_freeN(link);
}
}
/* Node Functions */
static GPUNode *GPU_node_begin(const char *name)
{
GPUNode *node = MEM_callocN(sizeof(GPUNode), "GPUNode");
node->name = name;
return node;
}
static void gpu_node_input_link(GPUNode *node, GPUNodeLink *link, const eGPUType type)
{
GPUInput *input;
GPUNode *outnode;
const char *name;
if (link->link_type == GPU_NODE_LINK_OUTPUT) {
outnode = link->output->node;
name = outnode->name;
input = outnode->inputs.first;
if ((STR_ELEM(name, "set_value", "set_rgb", "set_rgba")) && (input->type == type)) {
input = MEM_dupallocN(outnode->inputs.first);
if (input->link) {
input->link->users++;
}
BLI_addtail(&node->inputs, input);
return;
}
}
input = MEM_callocN(sizeof(GPUInput), "GPUInput");
input->node = node;
input->type = type;
switch (link->link_type) {
case GPU_NODE_LINK_BUILTIN:
input->source = GPU_SOURCE_BUILTIN;
input->builtin = link->builtin;
break;
case GPU_NODE_LINK_OUTPUT:
input->source = GPU_SOURCE_OUTPUT;
input->link = link;
link->users++;
break;
case GPU_NODE_LINK_COLORBAND:
input->source = GPU_SOURCE_TEX;
input->coba = link->coba;
break;
case GPU_NODE_LINK_IMAGE_BLENDER:
case GPU_NODE_LINK_IMAGE_TILEMAP:
input->source = GPU_SOURCE_TEX;
input->ima = link->ima;
input->iuser = link->iuser;
break;
case GPU_NODE_LINK_ATTR:
input->source = GPU_SOURCE_ATTR;
input->attr_type = link->attr_type;
BLI_strncpy(input->attr_name, link->attr_name, sizeof(input->attr_name));
break;
case GPU_NODE_LINK_CONSTANT:
input->source = (type == GPU_CLOSURE) ? GPU_SOURCE_STRUCT : GPU_SOURCE_CONSTANT;
break;
case GPU_NODE_LINK_UNIFORM:
input->source = GPU_SOURCE_UNIFORM;
break;
default:
break;
}
if (ELEM(input->source, GPU_SOURCE_CONSTANT, GPU_SOURCE_UNIFORM)) {
memcpy(input->vec, link->data, type * sizeof(float));
}
if (link->link_type != GPU_NODE_LINK_OUTPUT) {
MEM_freeN(link);
}
BLI_addtail(&node->inputs, input);
}
static const char *gpu_uniform_set_function_from_type(eNodeSocketDatatype type)
{
switch (type) {
/* For now INT is supported as float. */
case SOCK_INT:
case SOCK_FLOAT:
return "set_value";
case SOCK_VECTOR:
return "set_rgb";
case SOCK_RGBA:
return "set_rgba";
default:
BLI_assert(!"No gpu function for non-supported eNodeSocketDatatype");
return NULL;
}
}
/**
* Link stack uniform buffer.
* This is called for the input/output sockets that are note connected.
*/
static GPUNodeLink *gpu_uniformbuffer_link(GPUMaterial *mat,
bNode *node,
GPUNodeStack *stack,
const int index,
const eNodeSocketInOut in_out)
{
bNodeSocket *socket;
if (in_out == SOCK_IN) {
socket = BLI_findlink(&node->inputs, index);
}
else {
socket = BLI_findlink(&node->outputs, index);
}
BLI_assert(socket != NULL);
BLI_assert(socket->in_out == in_out);
if ((socket->flag & SOCK_HIDE_VALUE) == 0) {
GPUNodeLink *link;
switch (socket->type) {
case SOCK_FLOAT: {
bNodeSocketValueFloat *socket_data = socket->default_value;
link = GPU_uniform(&socket_data->value);
break;
}
case SOCK_VECTOR: {
bNodeSocketValueVector *socket_data = socket->default_value;
link = GPU_uniform(socket_data->value);
break;
}
case SOCK_RGBA: {
bNodeSocketValueRGBA *socket_data = socket->default_value;
link = GPU_uniform(socket_data->value);
break;
}
default:
return NULL;
break;
}
if (in_out == SOCK_IN) {
GPU_link(mat, gpu_uniform_set_function_from_type(socket->type), link, &stack->link);
}
return link;
}
return NULL;
}
static void gpu_node_input_socket(
GPUMaterial *material, bNode *bnode, GPUNode *node, GPUNodeStack *sock, const int index)
{
if (sock->link) {
gpu_node_input_link(node, sock->link, sock->type);
}
else if ((material != NULL) &&
(gpu_uniformbuffer_link(material, bnode, sock, index, SOCK_IN) != NULL)) {
gpu_node_input_link(node, sock->link, sock->type);
}
else {
gpu_node_input_link(node, GPU_constant(sock->vec), sock->type);
}
}
static void gpu_node_output(GPUNode *node, const eGPUType type, GPUNodeLink **link)
{
GPUOutput *output = MEM_callocN(sizeof(GPUOutput), "GPUOutput");
output->type = type;
output->node = node;
if (link) {
*link = output->link = GPU_node_link_create();
output->link->link_type = GPU_NODE_LINK_OUTPUT;
output->link->output = output;
/* note: the caller owns the reference to the link, GPUOutput
* merely points to it, and if the node is destroyed it will
* set that pointer to NULL */
}
BLI_addtail(&node->outputs, output);
}
void GPU_inputs_free(ListBase *inputs)
{
GPUInput *input;
for (input = inputs->first; input; input = input->next) {
if (input->link) {
gpu_node_link_free(input->link);
}
}
BLI_freelistN(inputs);
}
static void gpu_node_free(GPUNode *node)
{
GPUOutput *output;
GPU_inputs_free(&node->inputs);
for (output = node->outputs.first; output; output = output->next) {
if (output->link) {
output->link->output = NULL;
gpu_node_link_free(output->link);
}
}
BLI_freelistN(&node->outputs);
MEM_freeN(node);
}
static void gpu_nodes_free(ListBase *nodes)
{
GPUNode *node;
while ((node = BLI_pophead(nodes))) {
gpu_node_free(node);
}
}
/* vertex attributes */
void GPU_nodes_get_vertex_attrs(ListBase *nodes, GPUVertAttrLayers *attrs)
{
GPUNode *node;
GPUInput *input;
int a;
/* convert attributes requested by node inputs to an array of layers,
* checking for duplicates and assigning id's starting from zero. */
memset(attrs, 0, sizeof(*attrs));
for (node = nodes->first; node; node = node->next) {
for (input = node->inputs.first; input; input = input->next) {
if (input->source == GPU_SOURCE_ATTR) {
for (a = 0; a < attrs->totlayer; a++) {
if (attrs->layer[a].type == input->attr_type &&
STREQ(attrs->layer[a].name, input->attr_name)) {
break;
}
}
if (a < GPU_MAX_ATTR) {
if (a == attrs->totlayer) {
input->attr_id = attrs->totlayer++;
input->attr_first = true;
attrs->layer[a].type = input->attr_type;
attrs->layer[a].attr_id = input->attr_id;
BLI_strncpy(attrs->layer[a].name, input->attr_name, sizeof(attrs->layer[a].name));
}
else {
input->attr_id = attrs->layer[a].attr_id;
}
}
}
}
}
}
/* varargs linking */
GPUNodeLink *GPU_attribute(const CustomDataType type, const char *name)
{
GPUNodeLink *link = GPU_node_link_create();
link->link_type = GPU_NODE_LINK_ATTR;
link->attr_name = name;
/* Fall back to the UV layer, which matches old behavior. */
if (type == CD_AUTO_FROM_NAME && name[0] == '\0') {
link->attr_type = CD_MTFACE;
}
else {
link->attr_type = type;
}
return link;
}
GPUNodeLink *GPU_constant(float *num)
{
GPUNodeLink *link = GPU_node_link_create();
link->link_type = GPU_NODE_LINK_CONSTANT;
link->data = num;
return link;
}
GPUNodeLink *GPU_uniform(float *num)
{
GPUNodeLink *link = GPU_node_link_create();
link->link_type = GPU_NODE_LINK_UNIFORM;
link->data = num;
return link;
}
GPUNodeLink *GPU_image(Image *ima, ImageUser *iuser)
{
GPUNodeLink *link = GPU_node_link_create();
link->link_type = GPU_NODE_LINK_IMAGE_BLENDER;
link->ima = ima;
link->iuser = iuser;
return link;
}
GPUNodeLink *GPU_color_band(GPUMaterial *mat, int size, float *pixels, float *row)
{
GPUNodeLink *link = GPU_node_link_create();
link->link_type = GPU_NODE_LINK_COLORBAND;
link->coba = gpu_material_ramp_texture_row_set(mat, size, pixels, row);
MEM_freeN(pixels);
return link;
}
GPUNodeLink *GPU_builtin(eGPUBuiltin builtin)
{
GPUNodeLink *link = GPU_node_link_create();
link->link_type = GPU_NODE_LINK_BUILTIN;
link->builtin = builtin;
return link;
}
static void gpu_material_use_library_with_dependencies(GSet *used_libraries,
GPUMaterialLibrary *library)
{
if (BLI_gset_add(used_libraries, library->code)) {
for (int i = 0; library->dependencies[i]; i++) {
gpu_material_use_library_with_dependencies(used_libraries, library->dependencies[i]);
}
}
}
static void gpu_material_use_library(GPUMaterial *material, GPUMaterialLibrary *library)
{
GSet *used_libraries = gpu_material_used_libraries(material);
gpu_material_use_library_with_dependencies(used_libraries, library);
}
bool GPU_link(GPUMaterial *mat, const char *name, ...)
{
GPUNode *node;
GPUFunction *function;
GPUNodeLink *link, **linkptr;
va_list params;
int i;
function = gpu_lookup_function(name);
if (!function) {
fprintf(stderr, "GPU failed to find function %s\n", name);
return false;
}
gpu_material_use_library(mat, function->library);
node = GPU_node_begin(name);
va_start(params, name);
for (i = 0; i < function->totparam; i++) {
if (function->paramqual[i] != FUNCTION_QUAL_IN) {
linkptr = va_arg(params, GPUNodeLink **);
gpu_node_output(node, function->paramtype[i], linkptr);
}
else {
link = va_arg(params, GPUNodeLink *);
gpu_node_input_link(node, link, function->paramtype[i]);
}
}
va_end(params);
gpu_material_add_node(mat, node);
return true;
}
bool GPU_stack_link(GPUMaterial *material,
bNode *bnode,
const char *name,
GPUNodeStack *in,
GPUNodeStack *out,
...)
{
GPUNode *node;
GPUFunction *function;
GPUNodeLink *link, **linkptr;
va_list params;
int i, totin, totout;
function = gpu_lookup_function(name);
if (!function) {
fprintf(stderr, "GPU failed to find function %s\n", name);
return false;
}
gpu_material_use_library(material, function->library);
node = GPU_node_begin(name);
totin = 0;
totout = 0;
if (in) {
for (i = 0; !in[i].end; i++) {
if (in[i].type != GPU_NONE) {
gpu_node_input_socket(material, bnode, node, &in[i], i);
totin++;
}
}
}
if (out) {
for (i = 0; !out[i].end; i++) {
if (out[i].type != GPU_NONE) {
gpu_node_output(node, out[i].type, &out[i].link);
totout++;
}
}
}
va_start(params, out);
for (i = 0; i < function->totparam; i++) {
if (function->paramqual[i] != FUNCTION_QUAL_IN) {
if (totout == 0) {
linkptr = va_arg(params, GPUNodeLink **);
gpu_node_output(node, function->paramtype[i], linkptr);
}
else {
totout--;
}
}
else {
if (totin == 0) {
link = va_arg(params, GPUNodeLink *);
if (link->socket) {
gpu_node_input_socket(NULL, NULL, node, link->socket, -1);
}
else {
gpu_node_input_link(node, link, function->paramtype[i]);
}
}
else {
totin--;
}
}
}
va_end(params);
gpu_material_add_node(material, node);
return true;
}
GPUNodeLink *GPU_uniformbuffer_link_out(GPUMaterial *mat,
bNode *node,
GPUNodeStack *stack,
const int index)
{
return gpu_uniformbuffer_link(mat, node, stack, index, SOCK_OUT);
}
/* Pass create/free */
static void gpu_nodes_tag(GPUNodeLink *link)
{
GPUNode *node;
GPUInput *input;
if (!link->output) {
return;
}
node = link->output->node;
if (node->tag) {
return;
}
node->tag = true;
for (input = node->inputs.first; input; input = input->next) {
if (input->link) {
gpu_nodes_tag(input->link);
}
}
}
void GPU_nodes_prune(ListBase *nodes, GPUNodeLink *outlink)
{
GPUNode *node, *next;
for (node = nodes->first; node; node = node->next) {
node->tag = false;
}
gpu_nodes_tag(outlink);
for (node = nodes->first; node; node = next) {
next = node->next;
if (!node->tag) {
BLI_remlink(nodes, node);
gpu_node_free(node);
}
}
}
static bool gpu_pass_is_valid(GPUPass *pass)
{
/* Shader is not null if compilation is successful. */
return (pass->compiled == false || pass->shader != NULL);
}
static char *code_generate_material_library(GPUMaterial *material, const char *frag_lib)
{
DynStr *ds = BLI_dynstr_new();
if (frag_lib) {
BLI_dynstr_append(ds, frag_lib);
}
GSet *used_libraries = gpu_material_used_libraries(material);
/* Always include those because they may be needed by the execution function. */
gpu_material_use_library_with_dependencies(used_libraries,
&gpu_shader_material_world_normals_library);
/* Add library code in order, for dependencies. */
for (int i = 0; gpu_material_libraries[i]; i++) {
GPUMaterialLibrary *library = gpu_material_libraries[i];
if (BLI_gset_haskey(used_libraries, library->code)) {
BLI_dynstr_append(ds, library->code);
}
}
char *result = BLI_dynstr_get_cstring(ds);
BLI_dynstr_free(ds);
return result;
}
GPUPass *GPU_generate_pass(GPUMaterial *material,
GPUNodeLink *frag_outlink,
struct GPUVertAttrLayers *attrs,
ListBase *nodes,
int *builtins,
const char *vert_code,
const char *geom_code,
const char *frag_lib,
const char *defines)
{
char *vertexcode, *geometrycode, *fragmentcode;
GPUPass *pass = NULL, *pass_hash = NULL;
/* prune unused nodes */
GPU_nodes_prune(nodes, frag_outlink);
GPU_nodes_get_vertex_attrs(nodes, attrs);
/* generate code */
char *fragmentgen = code_generate_fragment(material, nodes, frag_outlink->output, builtins);
/* Cache lookup: Reuse shaders already compiled */
uint32_t hash = gpu_pass_hash(fragmentgen, defines, attrs);
pass_hash = gpu_pass_cache_lookup(hash);
if (pass_hash && (pass_hash->next == NULL || pass_hash->next->hash != hash)) {
/* No collision, just return the pass. */
MEM_freeN(fragmentgen);
if (!gpu_pass_is_valid(pass_hash)) {
/* Shader has already been created but failed to compile. */
return NULL;
}
pass_hash->refcount += 1;
return pass_hash;
}
/* Either the shader is not compiled or there is a hash collision...
* continue generating the shader strings. */
char *tmp = code_generate_material_library(material, frag_lib);
geometrycode = code_generate_geometry(nodes, geom_code, defines);
vertexcode = code_generate_vertex(nodes, vert_code, (geometrycode != NULL));
fragmentcode = BLI_strdupcat(tmp, fragmentgen);
MEM_freeN(fragmentgen);
MEM_freeN(tmp);
if (pass_hash) {
/* Cache lookup: Reuse shaders already compiled */
pass = gpu_pass_cache_resolve_collision(
pass_hash, vertexcode, geometrycode, fragmentcode, defines, hash);
}
if (pass) {
/* Cache hit. Reuse the same GPUPass and GPUShader. */
if (!gpu_pass_is_valid(pass)) {
/* Shader has already been created but failed to compile. */
return NULL;
}
MEM_SAFE_FREE(vertexcode);
MEM_SAFE_FREE(fragmentcode);
MEM_SAFE_FREE(geometrycode);
pass->refcount += 1;
}
else {
/* We still create a pass even if shader compilation
* fails to avoid trying to compile again and again. */
pass = MEM_callocN(sizeof(GPUPass), "GPUPass");
pass->shader = NULL;
pass->refcount = 1;
pass->hash = hash;
pass->vertexcode = vertexcode;
pass->fragmentcode = fragmentcode;
pass->geometrycode = geometrycode;
pass->defines = (defines) ? BLI_strdup(defines) : NULL;
pass->compiled = false;
BLI_spin_lock(&pass_cache_spin);
if (pass_hash != NULL) {
/* Add after the first pass having the same hash. */
pass->next = pass_hash->next;
pass_hash->next = pass;
}
else {
/* No other pass have same hash, just prepend to the list. */
BLI_LINKS_PREPEND(pass_cache, pass);
}
BLI_spin_unlock(&pass_cache_spin);
}
return pass;
}
static int count_active_texture_sampler(GPUShader *shader, char *source)
{
char *code = source;
/* Remember this is per stage. */
GSet *sampler_ids = BLI_gset_int_new(__func__);
int num_samplers = 0;
while ((code = strstr(code, "uniform "))) {
/* Move past "uniform". */
code += 7;
/* Skip following spaces. */
while (*code == ' ') {
code++;
}
/* Skip "i" from potential isamplers. */
if (*code == 'i') {
code++;
}
/* Skip following spaces. */
if (gpu_str_prefix(code, "sampler")) {
/* Move past "uniform". */
code += 7;
/* Skip sampler type suffix. */
while (*code != ' ' && *code != '\0') {
code++;
}
/* Skip following spaces. */
while (*code == ' ') {
code++;
}
if (*code != '\0') {
char sampler_name[64];
code = gpu_str_skip_token(code, sampler_name, sizeof(sampler_name));
int id = GPU_shader_get_uniform_ensure(shader, sampler_name);
if (id == -1) {
continue;
}
/* Catch duplicates. */
if (BLI_gset_add(sampler_ids, POINTER_FROM_INT(id))) {
num_samplers++;
}
}
}
}
BLI_gset_free(sampler_ids, NULL);
return num_samplers;
}
static bool gpu_pass_shader_validate(GPUPass *pass, GPUShader *shader)
{
if (shader == NULL) {
return false;
}
/* NOTE: The only drawback of this method is that it will count a sampler
* used in the fragment shader and only declared (but not used) in the vertex
* shader as used by both. But this corner case is not happening for now. */
int vert_samplers_len = count_active_texture_sampler(shader, pass->vertexcode);
int frag_samplers_len = count_active_texture_sampler(shader, pass->fragmentcode);
int total_samplers_len = vert_samplers_len + frag_samplers_len;
/* Validate against opengl limit. */
if ((frag_samplers_len > GPU_max_textures_frag()) ||
(vert_samplers_len > GPU_max_textures_vert())) {
return false;
}
if (pass->geometrycode) {
int geom_samplers_len = count_active_texture_sampler(shader, pass->geometrycode);
total_samplers_len += geom_samplers_len;
if (geom_samplers_len > GPU_max_textures_geom()) {
return false;
}
}
return (total_samplers_len <= GPU_max_textures());
}
bool GPU_pass_compile(GPUPass *pass, const char *shname)
{
bool success = true;
if (!pass->compiled) {
GPUShader *shader = GPU_shader_create(
pass->vertexcode, pass->fragmentcode, pass->geometrycode, NULL, pass->defines, shname);
/* NOTE: Some drivers / gpu allows more active samplers than the opengl limit.
* We need to make sure to count active samplers to avoid undefined behavior. */
if (!gpu_pass_shader_validate(pass, shader)) {
success = false;
if (shader != NULL) {
fprintf(stderr, "GPUShader: error: too many samplers in shader.\n");
GPU_shader_free(shader);
shader = NULL;
}
}
else if (!BLI_thread_is_main() && GPU_context_local_shaders_workaround()) {
pass->binary.content = GPU_shader_get_binary(
shader, &pass->binary.format, &pass->binary.len);
GPU_shader_free(shader);
shader = NULL;
}
pass->shader = shader;
pass->compiled = true;
}
else if (pass->binary.content && BLI_thread_is_main()) {
pass->shader = GPU_shader_load_from_binary(
pass->binary.content, pass->binary.format, pass->binary.len, shname);
MEM_SAFE_FREE(pass->binary.content);
}
return success;
}
void GPU_pass_release(GPUPass *pass)
{
BLI_assert(pass->refcount > 0);
pass->refcount--;
}
static void gpu_pass_free(GPUPass *pass)
{
BLI_assert(pass->refcount == 0);
if (pass->shader) {
GPU_shader_free(pass->shader);
}
MEM_SAFE_FREE(pass->fragmentcode);
MEM_SAFE_FREE(pass->geometrycode);
MEM_SAFE_FREE(pass->vertexcode);
MEM_SAFE_FREE(pass->defines);
if (pass->binary.content) {
MEM_freeN(pass->binary.content);
}
MEM_freeN(pass);
}
void GPU_pass_free_nodes(ListBase *nodes)
{
gpu_nodes_free(nodes);
}
void GPU_pass_cache_garbage_collect(void)
{
static int lasttime = 0;
const int shadercollectrate = 60; /* hardcoded for now. */
int ctime = (int)PIL_check_seconds_timer();
if (ctime < shadercollectrate + lasttime) {
return;
}
lasttime = ctime;
BLI_spin_lock(&pass_cache_spin);
GPUPass *next, **prev_pass = &pass_cache;
for (GPUPass *pass = pass_cache; pass; pass = next) {
next = pass->next;
if (pass->refcount == 0) {
/* Remove from list */
*prev_pass = next;
gpu_pass_free(pass);
}
else {
prev_pass = &pass->next;
}
}
BLI_spin_unlock(&pass_cache_spin);
}
void GPU_pass_cache_init(void)
{
BLI_spin_init(&pass_cache_spin);
}
void GPU_pass_cache_free(void)
{
BLI_spin_lock(&pass_cache_spin);
while (pass_cache) {
GPUPass *next = pass_cache->next;
gpu_pass_free(pass_cache);
pass_cache = next;
}
BLI_spin_unlock(&pass_cache_spin);
BLI_spin_end(&pass_cache_spin);
}
|