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
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
|
/**
* @file llmaterialeditor.cpp
* @brief Implementation of the gltf material editor
*
* $LicenseInfo:firstyear=2022&license=viewerlgpl$
* Second Life Viewer Source Code
* Copyright (C) 2010, Linden Research, Inc.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation;
* version 2.1 of the License only.
*
* This library 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*
* Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA
* $/LicenseInfo$
*/
#include "llviewerprecompiledheaders.h"
#include "llmaterialeditor.h"
#include "llagent.h"
#include "llagentbenefits.h"
#include "llappviewer.h"
#include "llcombobox.h"
#include "llfloaterreg.h"
#include "llfilesystem.h"
#include "llgltfmateriallist.h"
#include "llinventorymodel.h"
#include "llnotificationsutil.h"
#include "lltexturectrl.h"
#include "lltrans.h"
#include "llviewermenufile.h"
#include "llviewertexture.h"
#include "llsdutil.h"
#include "llselectmgr.h"
#include "llstatusbar.h" // can_afford_transaction()
#include "llviewerinventory.h"
#include "llinventory.h"
#include "llviewerregion.h"
#include "llvovolume.h"
#include "roles_constants.h"
#include "llviewerobjectlist.h"
#include "llsdserialize.h"
#include "llimagej2c.h"
#include "llviewertexturelist.h"
#include "llfloaterperms.h"
#include "tinygltf/tiny_gltf.h"
#include "lltinygltfhelper.h"
#include <strstream>
const std::string MATERIAL_BASE_COLOR_DEFAULT_NAME = "Base Color";
const std::string MATERIAL_NORMAL_DEFAULT_NAME = "Normal";
const std::string MATERIAL_METALLIC_DEFAULT_NAME = "Metallic Roughness";
const std::string MATERIAL_EMISSIVE_DEFAULT_NAME = "Emissive";
// Don't use ids here, LLPreview will attempt to use it as an inventory item
static const std::string LIVE_MATERIAL_EDITOR_KEY = "Live Editor";
// Dirty flags
static const U32 MATERIAL_BASE_COLOR_DIRTY = 0x1 << 0;
static const U32 MATERIAL_BASE_TRANSPARENCY_DIRTY = 0x1 << 1;
static const U32 MATERIAL_BASE_COLOR_TEX_DIRTY = 0x1 << 2;
static const U32 MATERIAL_NORMAL_TEX_DIRTY = 0x1 << 3;
static const U32 MATERIAL_METALLIC_ROUGHTNESS_TEX_DIRTY = 0x1 << 4;
static const U32 MATERIAL_METALLIC_ROUGHTNESS_METALNESS_DIRTY = 0x1 << 5;
static const U32 MATERIAL_METALLIC_ROUGHTNESS_ROUGHNESS_DIRTY = 0x1 << 6;
static const U32 MATERIAL_EMISIVE_COLOR_DIRTY = 0x1 << 7;
static const U32 MATERIAL_EMISIVE_TEX_DIRTY = 0x1 << 8;
static const U32 MATERIAL_DOUBLE_SIDED_DIRTY = 0x1 << 9;
static const U32 MATERIAL_ALPHA_MODE_DIRTY = 0x1 << 10;
static const U32 MATERIAL_ALPHA_CUTOFF_DIRTY = 0x1 << 11;
LLUUID LLMaterialEditor::mOverrideObjectId;
S32 LLMaterialEditor::mOverrideObjectTE = -1;
LLFloaterComboOptions::LLFloaterComboOptions()
: LLFloater(LLSD())
{
buildFromFile("floater_combobox_ok_cancel.xml");
}
LLFloaterComboOptions::~LLFloaterComboOptions()
{
}
BOOL LLFloaterComboOptions::postBuild()
{
mConfirmButton = getChild<LLButton>("combo_ok", TRUE);
mCancelButton = getChild<LLButton>("combo_cancel", TRUE);
mComboOptions = getChild<LLComboBox>("combo_options", TRUE);
mComboText = getChild<LLTextBox>("combo_text", TRUE);
mConfirmButton->setCommitCallback([this](LLUICtrl* ctrl, const LLSD& param) {onConfirm(); });
mCancelButton->setCommitCallback([this](LLUICtrl* ctrl, const LLSD& param) {onCancel(); });
return TRUE;
}
LLFloaterComboOptions* LLFloaterComboOptions::showUI(
combo_callback callback,
const std::string &title,
const std::string &description,
const std::list<std::string> &options)
{
LLFloaterComboOptions* combo_picker = new LLFloaterComboOptions();
if (combo_picker)
{
combo_picker->mCallback = callback;
combo_picker->setTitle(title);
combo_picker->mComboText->setText(description);
std::list<std::string>::const_iterator iter = options.begin();
std::list<std::string>::const_iterator end = options.end();
for (; iter != end; iter++)
{
combo_picker->mComboOptions->addSimpleElement(*iter);
}
combo_picker->mComboOptions->selectFirstItem();
combo_picker->openFloater(LLSD(title));
combo_picker->setFocus(TRUE);
combo_picker->center();
}
return combo_picker;
}
LLFloaterComboOptions* LLFloaterComboOptions::showUI(
combo_callback callback,
const std::string &title,
const std::string &description,
const std::string &ok_text,
const std::string &cancel_text,
const std::list<std::string> &options)
{
LLFloaterComboOptions* combo_picker = showUI(callback, title, description, options);
if (combo_picker)
{
combo_picker->mConfirmButton->setLabel(ok_text);
combo_picker->mCancelButton->setLabel(cancel_text);
}
return combo_picker;
}
void LLFloaterComboOptions::onConfirm()
{
mCallback(mComboOptions->getSimple(), mComboOptions->getCurrentIndex());
closeFloater();
}
void LLFloaterComboOptions::onCancel()
{
mCallback(std::string(), -1);
closeFloater();
}
class LLMaterialEditorCopiedCallback : public LLInventoryCallback
{
public:
LLMaterialEditorCopiedCallback(
const std::string &buffer,
const LLSD &old_key,
bool has_unsaved_changes)
: mBuffer(buffer),
mOldKey(old_key),
mHasUnsavedChanges(has_unsaved_changes)
{}
LLMaterialEditorCopiedCallback(
const LLSD &old_key,
const std::string &new_name)
: mOldKey(old_key),
mNewName(new_name),
mHasUnsavedChanges(false)
{}
virtual void fire(const LLUUID& inv_item_id)
{
if (!mNewName.empty())
{
// making a copy from a notecard doesn't change name, do it now
LLViewerInventoryItem* item = gInventory.getItem(inv_item_id);
if (item->getName() != mNewName)
{
LLSD updates;
updates["name"] = mNewName;
update_inventory_item(inv_item_id, updates, NULL);
}
}
LLMaterialEditor::finishSaveAs(mOldKey, inv_item_id, mBuffer, mHasUnsavedChanges);
}
private:
std::string mBuffer;
LLSD mOldKey;
std::string mNewName;
bool mHasUnsavedChanges;
};
///----------------------------------------------------------------------------
/// Class LLSelectedTEGetMatData
/// For finding selected applicable inworld material
///----------------------------------------------------------------------------
struct LLSelectedTEGetMatData : public LLSelectedTEFunctor
{
LLSelectedTEGetMatData(bool for_override);
bool apply(LLViewerObject* objectp, S32 te_index);
bool mIsOverride;
bool mIdenticalTexColor;
bool mIdenticalTexMetal;
bool mIdenticalTexEmissive;
bool mIdenticalTexNormal;
bool mFirst;
LLUUID mTexColorId;
LLUUID mTexMetalId;
LLUUID mTexEmissiveId;
LLUUID mTexNormalId;
LLUUID mObjectId;
S32 mObjectTE;
LLPointer<LLGLTFMaterial> mMaterial;
};
LLSelectedTEGetMatData::LLSelectedTEGetMatData(bool for_override)
: mIsOverride(for_override)
, mIdenticalTexColor(true)
, mIdenticalTexMetal(true)
, mIdenticalTexEmissive(true)
, mIdenticalTexNormal(true)
, mObjectTE(-1)
, mFirst(true)
{}
bool LLSelectedTEGetMatData::apply(LLViewerObject* objectp, S32 te_index)
{
if (!objectp)
{
return false;
}
LLUUID mat_id = objectp->getRenderMaterialID(te_index);
bool can_use = mIsOverride ? objectp->permModify() : objectp->permCopy();
LLTextureEntry *tep = objectp->getTE(te_index);
// We might want to disable this entirely if at least
// something in selection is no-copy or no modify
// or has no base material
if (can_use && tep && mat_id.notNull())
{
LLPointer<LLGLTFMaterial> mat = tep->getGLTFRenderMaterial();
LLUUID tex_color_id;
LLUUID tex_metal_id;
LLUUID tex_emissive_id;
LLUUID tex_normal_id;
llassert(mat.notNull()); // by this point shouldn't be null
if (mat.notNull())
{
tex_color_id = mat->mBaseColorId;
tex_metal_id = mat->mMetallicRoughnessId;
tex_emissive_id = mat->mEmissiveId;
tex_normal_id = mat->mNormalId;
}
if (mFirst)
{
mMaterial = mat;
mTexColorId = tex_color_id;
mTexMetalId = tex_metal_id;
mTexEmissiveId = tex_emissive_id;
mTexNormalId = tex_normal_id;
mObjectTE = te_index;
mObjectId = objectp->getID();
mFirst = false;
}
else
{
if (mTexColorId != tex_color_id)
{
mIdenticalTexColor = false;
}
if (mTexMetalId != tex_metal_id)
{
mIdenticalTexMetal = false;
}
if (mTexEmissiveId != tex_emissive_id)
{
mIdenticalTexEmissive = false;
}
if (mTexNormalId != tex_normal_id)
{
mIdenticalTexNormal = false;
}
}
}
return true;
}
///----------------------------------------------------------------------------
/// Class LLMaterialEditor
///----------------------------------------------------------------------------
// Default constructor
LLMaterialEditor::LLMaterialEditor(const LLSD& key)
: LLPreview(key)
, mUnsavedChanges(0)
, mExpectedUploadCost(0)
, mUploadingTexturesCount(0)
{
const LLInventoryItem* item = getItem();
if (item)
{
mAssetID = item->getAssetUUID();
}
// if this is a 'live editor' instance, it uses live overrides
mIsOverride = key.asString() == LIVE_MATERIAL_EDITOR_KEY;
}
void LLMaterialEditor::setObjectID(const LLUUID& object_id)
{
LLPreview::setObjectID(object_id);
const LLInventoryItem* item = getItem();
if (item)
{
mAssetID = item->getAssetUUID();
}
}
void LLMaterialEditor::setAuxItem(const LLInventoryItem* item)
{
LLPreview::setAuxItem(item);
if (item)
{
mAssetID = item->getAssetUUID();
}
}
BOOL LLMaterialEditor::postBuild()
{
mBaseColorTextureCtrl = getChild<LLTextureCtrl>("base_color_texture");
mMetallicTextureCtrl = getChild<LLTextureCtrl>("metallic_roughness_texture");
mEmissiveTextureCtrl = getChild<LLTextureCtrl>("emissive_texture");
mNormalTextureCtrl = getChild<LLTextureCtrl>("normal_texture");
mBaseColorTextureCtrl->setCommitCallback(boost::bind(&LLMaterialEditor::onCommitBaseColorTexture, this, _1, _2));
mMetallicTextureCtrl->setCommitCallback(boost::bind(&LLMaterialEditor::onCommitMetallicTexture, this, _1, _2));
mEmissiveTextureCtrl->setCommitCallback(boost::bind(&LLMaterialEditor::onCommitEmissiveTexture, this, _1, _2));
mNormalTextureCtrl->setCommitCallback(boost::bind(&LLMaterialEditor::onCommitNormalTexture, this, _1, _2));
childSetAction("save", boost::bind(&LLMaterialEditor::onClickSave, this));
childSetAction("save_as", boost::bind(&LLMaterialEditor::onClickSaveAs, this));
childSetAction("cancel", boost::bind(&LLMaterialEditor::onClickCancel, this));
S32 upload_cost = LLAgentBenefitsMgr::current().getTextureUploadCost();
getChild<LLUICtrl>("base_color_upload_fee")->setTextArg("[FEE]", llformat("%d", upload_cost));
getChild<LLUICtrl>("metallic_upload_fee")->setTextArg("[FEE]", llformat("%d", upload_cost));
getChild<LLUICtrl>("emissive_upload_fee")->setTextArg("[FEE]", llformat("%d", upload_cost));
getChild<LLUICtrl>("normal_upload_fee")->setTextArg("[FEE]", llformat("%d", upload_cost));
boost::function<void(LLUICtrl*, void*)> changes_callback = [this](LLUICtrl * ctrl, void* userData)
{
const U32 *flag = (const U32*)userData;
markChangesUnsaved(*flag);
// Apply changes to object live
applyToSelection();
};
childSetCommitCallback("double sided", changes_callback, (void*)&MATERIAL_DOUBLE_SIDED_DIRTY);
// BaseColor
childSetCommitCallback("base color", changes_callback, (void*)&MATERIAL_BASE_COLOR_DIRTY);
childSetCommitCallback("transparency", changes_callback, (void*)&MATERIAL_BASE_TRANSPARENCY_DIRTY);
childSetCommitCallback("alpha mode", changes_callback, (void*)&MATERIAL_ALPHA_MODE_DIRTY);
childSetCommitCallback("alpha cutoff", changes_callback, (void*)&MATERIAL_ALPHA_CUTOFF_DIRTY);
// Metallic-Roughness
childSetCommitCallback("metalness factor", changes_callback, (void*)&MATERIAL_METALLIC_ROUGHTNESS_METALNESS_DIRTY);
childSetCommitCallback("roughness factor", changes_callback, (void*)&MATERIAL_METALLIC_ROUGHTNESS_ROUGHNESS_DIRTY);
// Emissive
childSetCommitCallback("emissive color", changes_callback, (void*)&MATERIAL_EMISIVE_COLOR_DIRTY);
childSetVisible("unsaved_changes", mUnsavedChanges && !mIsOverride);
getChild<LLUICtrl>("total_upload_fee")->setTextArg("[FEE]", llformat("%d", 0));
// Todo:
// Disable/enable setCanApplyImmediately() based on
// working from inventory, upload or editing inworld
return LLPreview::postBuild();
}
void LLMaterialEditor::onClickCloseBtn(bool app_quitting)
{
if (app_quitting)
{
closeFloater(app_quitting);
}
else
{
onClickCancel();
}
}
void LLMaterialEditor::onClose(bool app_quitting)
{
if (mSelectionUpdateSlot.connected())
{
mSelectionUpdateSlot.disconnect();
}
LLPreview::onClose(app_quitting);
}
LLUUID LLMaterialEditor::getBaseColorId()
{
return mBaseColorTextureCtrl->getValue().asUUID();
}
void LLMaterialEditor::setBaseColorId(const LLUUID& id)
{
mBaseColorTextureCtrl->setValue(id);
mBaseColorTextureCtrl->setDefaultImageAssetID(id);
mBaseColorTextureCtrl->setTentative(FALSE);
}
void LLMaterialEditor::setBaseColorUploadId(const LLUUID& id)
{
// Might be better to use local textures and
// assign a fee in case of a local texture
if (id.notNull())
{
// todo: this does not account for posibility of texture
// being from inventory, need to check that
childSetValue("base_color_upload_fee", getString("upload_fee_string"));
// Only set if we will need to upload this texture
mBaseColorTextureUploadId = id;
}
markChangesUnsaved(MATERIAL_BASE_COLOR_TEX_DIRTY);
}
LLColor4 LLMaterialEditor::getBaseColor()
{
LLColor4 ret = linearColor4(LLColor4(childGetValue("base color")));
ret.mV[3] = getTransparency();
return ret;
}
void LLMaterialEditor::setBaseColor(const LLColor4& color)
{
childSetValue("base color", srgbColor4(color).getValue());
setTransparency(color.mV[3]);
}
F32 LLMaterialEditor::getTransparency()
{
return childGetValue("transparency").asReal();
}
void LLMaterialEditor::setTransparency(F32 transparency)
{
childSetValue("transparency", transparency);
}
std::string LLMaterialEditor::getAlphaMode()
{
return childGetValue("alpha mode").asString();
}
void LLMaterialEditor::setAlphaMode(const std::string& alpha_mode)
{
childSetValue("alpha mode", alpha_mode);
}
F32 LLMaterialEditor::getAlphaCutoff()
{
return childGetValue("alpha cutoff").asReal();
}
void LLMaterialEditor::setAlphaCutoff(F32 alpha_cutoff)
{
childSetValue("alpha cutoff", alpha_cutoff);
}
void LLMaterialEditor::setMaterialName(const std::string &name)
{
setTitle(name);
mMaterialName = name;
}
LLUUID LLMaterialEditor::getMetallicRoughnessId()
{
return mMetallicTextureCtrl->getValue().asUUID();
}
void LLMaterialEditor::setMetallicRoughnessId(const LLUUID& id)
{
mMetallicTextureCtrl->setValue(id);
mMetallicTextureCtrl->setDefaultImageAssetID(id);
mMetallicTextureCtrl->setTentative(FALSE);
}
void LLMaterialEditor::setMetallicRoughnessUploadId(const LLUUID& id)
{
if (id.notNull())
{
// todo: this does not account for posibility of texture
// being from inventory, need to check that
childSetValue("metallic_upload_fee", getString("upload_fee_string"));
mMetallicTextureUploadId = id;
}
markChangesUnsaved(MATERIAL_METALLIC_ROUGHTNESS_TEX_DIRTY);
}
F32 LLMaterialEditor::getMetalnessFactor()
{
return childGetValue("metalness factor").asReal();
}
void LLMaterialEditor::setMetalnessFactor(F32 factor)
{
childSetValue("metalness factor", factor);
}
F32 LLMaterialEditor::getRoughnessFactor()
{
return childGetValue("roughness factor").asReal();
}
void LLMaterialEditor::setRoughnessFactor(F32 factor)
{
childSetValue("roughness factor", factor);
}
LLUUID LLMaterialEditor::getEmissiveId()
{
return mEmissiveTextureCtrl->getValue().asUUID();
}
void LLMaterialEditor::setEmissiveId(const LLUUID& id)
{
mEmissiveTextureCtrl->setValue(id);
mEmissiveTextureCtrl->setDefaultImageAssetID(id);
mEmissiveTextureCtrl->setTentative(FALSE);
}
void LLMaterialEditor::setEmissiveUploadId(const LLUUID& id)
{
if (id.notNull())
{
// todo: this does not account for posibility of texture
// being from inventory, need to check that
childSetValue("emissive_upload_fee", getString("upload_fee_string"));
mEmissiveTextureUploadId = id;
}
markChangesUnsaved(MATERIAL_EMISIVE_TEX_DIRTY);
}
LLColor4 LLMaterialEditor::getEmissiveColor()
{
return linearColor4(LLColor4(childGetValue("emissive color")));
}
void LLMaterialEditor::setEmissiveColor(const LLColor4& color)
{
childSetValue("emissive color", srgbColor4(color).getValue());
}
LLUUID LLMaterialEditor::getNormalId()
{
return mNormalTextureCtrl->getValue().asUUID();
}
void LLMaterialEditor::setNormalId(const LLUUID& id)
{
mNormalTextureCtrl->setValue(id);
mNormalTextureCtrl->setDefaultImageAssetID(id);
mNormalTextureCtrl->setTentative(FALSE);
}
void LLMaterialEditor::setNormalUploadId(const LLUUID& id)
{
if (id.notNull())
{
// todo: this does not account for posibility of texture
// being from inventory, need to check that
childSetValue("normal_upload_fee", getString("upload_fee_string"));
mNormalTextureUploadId = id;
}
markChangesUnsaved(MATERIAL_NORMAL_TEX_DIRTY);
}
bool LLMaterialEditor::getDoubleSided()
{
return childGetValue("double sided").asBoolean();
}
void LLMaterialEditor::setDoubleSided(bool double_sided)
{
childSetValue("double sided", double_sided);
}
void LLMaterialEditor::resetUnsavedChanges()
{
mUnsavedChanges = 0;
childSetVisible("unsaved_changes", false);
setCanSave(false);
mExpectedUploadCost = 0;
getChild<LLUICtrl>("total_upload_fee")->setTextArg("[FEE]", llformat("%d", mExpectedUploadCost));
}
void LLMaterialEditor::markChangesUnsaved(U32 dirty_flag)
{
mUnsavedChanges |= dirty_flag;
// at the moment live editing (mIsOverride) applies everything 'live'
childSetVisible("unsaved_changes", mUnsavedChanges && !mIsOverride);
if (mUnsavedChanges)
{
const LLInventoryItem* item = getItem();
if (item)
{
LLPermissions perm(item->getPermissions());
bool allow_modify = canModify(mObjectUUID, item);
bool source_library = mObjectUUID.isNull() && gInventory.isObjectDescendentOf(mItemUUID, gInventory.getLibraryRootFolderID());
bool source_notecard = mNotecardInventoryID.notNull();
setCanSave(allow_modify && !source_library && !source_notecard);
}
}
else
{
setCanSave(false);
}
S32 upload_texture_count = 0;
if (mBaseColorTextureUploadId.notNull() && mBaseColorTextureUploadId == getBaseColorId())
{
upload_texture_count++;
}
if (mMetallicTextureUploadId.notNull() && mMetallicTextureUploadId == getMetallicRoughnessId())
{
upload_texture_count++;
}
if (mEmissiveTextureUploadId.notNull() && mEmissiveTextureUploadId == getEmissiveId())
{
upload_texture_count++;
}
if (mNormalTextureUploadId.notNull() && mNormalTextureUploadId == getNormalId())
{
upload_texture_count++;
}
mExpectedUploadCost = upload_texture_count * LLAgentBenefitsMgr::current().getTextureUploadCost();
getChild<LLUICtrl>("total_upload_fee")->setTextArg("[FEE]", llformat("%d", mExpectedUploadCost));
}
void LLMaterialEditor::setCanSaveAs(bool value)
{
childSetEnabled("save_as", value);
}
void LLMaterialEditor::setCanSave(bool value)
{
childSetEnabled("save", value);
}
void LLMaterialEditor::setEnableEditing(bool can_modify)
{
childSetEnabled("double sided", can_modify);
// BaseColor
childSetEnabled("base color", can_modify);
childSetEnabled("transparency", can_modify);
childSetEnabled("alpha mode", can_modify);
childSetEnabled("alpha cutoff", can_modify);
// Metallic-Roughness
childSetEnabled("metalness factor", can_modify);
childSetEnabled("roughness factor", can_modify);
// Metallic-Roughness
childSetEnabled("metalness factor", can_modify);
childSetEnabled("roughness factor", can_modify);
// Emissive
childSetEnabled("emissive color", can_modify);
mBaseColorTextureCtrl->setEnabled(can_modify);
mMetallicTextureCtrl->setEnabled(can_modify);
mEmissiveTextureCtrl->setEnabled(can_modify);
mNormalTextureCtrl->setEnabled(can_modify);
}
void LLMaterialEditor::onCommitBaseColorTexture(LLUICtrl * ctrl, const LLSD & data)
{
// might be better to use arrays, to have a single callback
// and not to repeat the same thing for each tecture control
LLUUID new_val = mBaseColorTextureCtrl->getValue().asUUID();
if (new_val == mBaseColorTextureUploadId && mBaseColorTextureUploadId.notNull())
{
childSetValue("base_color_upload_fee", getString("upload_fee_string"));
}
else
{
// Texture picker has 'apply now' with 'cancel' support.
// Keep mBaseColorJ2C and mBaseColorFetched, it's our storage in
// case user decides to cancel changes.
// Without mBaseColorFetched, viewer will eventually cleanup
// the texture that is not in use
childSetValue("base_color_upload_fee", getString("no_upload_fee_string"));
}
markChangesUnsaved(MATERIAL_BASE_COLOR_TEX_DIRTY);
applyToSelection();
}
void LLMaterialEditor::onCommitMetallicTexture(LLUICtrl * ctrl, const LLSD & data)
{
LLUUID new_val = mMetallicTextureCtrl->getValue().asUUID();
if (new_val == mMetallicTextureUploadId && mMetallicTextureUploadId.notNull())
{
childSetValue("metallic_upload_fee", getString("upload_fee_string"));
}
else
{
childSetValue("metallic_upload_fee", getString("no_upload_fee_string"));
}
markChangesUnsaved(MATERIAL_METALLIC_ROUGHTNESS_TEX_DIRTY);
applyToSelection();
}
void LLMaterialEditor::onCommitEmissiveTexture(LLUICtrl * ctrl, const LLSD & data)
{
LLUUID new_val = mEmissiveTextureCtrl->getValue().asUUID();
if (new_val == mEmissiveTextureUploadId && mEmissiveTextureUploadId.notNull())
{
childSetValue("emissive_upload_fee", getString("upload_fee_string"));
}
else
{
childSetValue("emissive_upload_fee", getString("no_upload_fee_string"));
}
markChangesUnsaved(MATERIAL_EMISIVE_TEX_DIRTY);
applyToSelection();
}
void LLMaterialEditor::onCommitNormalTexture(LLUICtrl * ctrl, const LLSD & data)
{
LLUUID new_val = mNormalTextureCtrl->getValue().asUUID();
if (new_val == mNormalTextureUploadId && mNormalTextureUploadId.notNull())
{
childSetValue("normal_upload_fee", getString("upload_fee_string"));
}
else
{
childSetValue("normal_upload_fee", getString("no_upload_fee_string"));
}
markChangesUnsaved(MATERIAL_NORMAL_TEX_DIRTY);
applyToSelection();
}
static void write_color(const LLColor4& color, std::vector<double>& c)
{
for (int i = 0; i < c.size(); ++i) // NOTE -- use c.size because some gltf colors are 3-component
{
c[i] = color.mV[i];
}
}
static U32 write_texture(const LLUUID& id, tinygltf::Model& model)
{
tinygltf::Image image;
image.uri = id.asString();
model.images.push_back(image);
U32 image_idx = model.images.size() - 1;
tinygltf::Texture texture;
texture.source = image_idx;
model.textures.push_back(texture);
U32 texture_idx = model.textures.size() - 1;
return texture_idx;
}
void LLMaterialEditor::onClickSave()
{
if (!can_afford_transaction(mExpectedUploadCost))
{
LLSD args;
args["COST"] = llformat("%d", mExpectedUploadCost);
LLNotificationsUtil::add("ErrorCannotAffordUpload", args);
return;
}
applyToSelection();
saveIfNeeded();
}
std::string LLMaterialEditor::getGLTFJson(bool prettyprint)
{
tinygltf::Model model;
getGLTFModel(model);
std::ostringstream str;
tinygltf::TinyGLTF gltf;
gltf.WriteGltfSceneToStream(&model, str, prettyprint, false);
std::string dump = str.str();
return dump;
}
void LLMaterialEditor::getGLBData(std::vector<U8>& data)
{
tinygltf::Model model;
getGLTFModel(model);
std::ostringstream str;
tinygltf::TinyGLTF gltf;
gltf.WriteGltfSceneToStream(&model, str, false, true);
std::string dump = str.str();
data.resize(dump.length());
memcpy(&data[0], dump.c_str(), dump.length());
}
void LLMaterialEditor::getGLTFModel(tinygltf::Model& model)
{
model.materials.resize(1);
tinygltf::PbrMetallicRoughness& pbrMaterial = model.materials[0].pbrMetallicRoughness;
// write base color
LLColor4 base_color = getBaseColor();
base_color.mV[3] = getTransparency();
write_color(base_color, pbrMaterial.baseColorFactor);
model.materials[0].alphaCutoff = getAlphaCutoff();
model.materials[0].alphaMode = getAlphaMode();
LLUUID base_color_id = getBaseColorId();
if (base_color_id.notNull())
{
U32 texture_idx = write_texture(base_color_id, model);
pbrMaterial.baseColorTexture.index = texture_idx;
}
// write metallic/roughness
F32 metalness = getMetalnessFactor();
F32 roughness = getRoughnessFactor();
pbrMaterial.metallicFactor = metalness;
pbrMaterial.roughnessFactor = roughness;
LLUUID mr_id = getMetallicRoughnessId();
if (mr_id.notNull())
{
U32 texture_idx = write_texture(mr_id, model);
pbrMaterial.metallicRoughnessTexture.index = texture_idx;
}
//write emissive
LLColor4 emissive_color = getEmissiveColor();
model.materials[0].emissiveFactor.resize(3);
write_color(emissive_color, model.materials[0].emissiveFactor);
LLUUID emissive_id = getEmissiveId();
if (emissive_id.notNull())
{
U32 idx = write_texture(emissive_id, model);
model.materials[0].emissiveTexture.index = idx;
}
//write normal
LLUUID normal_id = getNormalId();
if (normal_id.notNull())
{
U32 idx = write_texture(normal_id, model);
model.materials[0].normalTexture.index = idx;
}
//write doublesided
model.materials[0].doubleSided = getDoubleSided();
model.asset.version = "2.0";
}
std::string LLMaterialEditor::getEncodedAsset()
{
LLSD asset;
asset["version"] = "1.0";
asset["type"] = "GLTF 2.0";
asset["data"] = getGLTFJson(false);
std::ostringstream str;
LLSDSerialize::serialize(asset, str, LLSDSerialize::LLSD_BINARY);
return str.str();
}
bool LLMaterialEditor::decodeAsset(const std::vector<char>& buffer)
{
LLSD asset;
std::istrstream str(&buffer[0], buffer.size());
if (LLSDSerialize::deserialize(asset, str, buffer.size()))
{
if (asset.has("version") && asset["version"] == "1.0")
{
if (asset.has("type") && asset["type"] == "GLTF 2.0")
{
if (asset.has("data") && asset["data"].isString())
{
std::string data = asset["data"];
tinygltf::TinyGLTF gltf;
tinygltf::TinyGLTF loader;
std::string error_msg;
std::string warn_msg;
tinygltf::Model model_in;
if (loader.LoadASCIIFromString(&model_in, &error_msg, &warn_msg, data.c_str(), data.length(), ""))
{
// assets are only supposed to have one item
return setFromGltfModel(model_in, 0, true);
}
else
{
LL_WARNS("MaterialEditor") << "Floater " << getKey() << " Failed to decode material asset: " << LL_NEWLINE
<< warn_msg << LL_NEWLINE
<< error_msg << LL_ENDL;
}
}
}
}
else
{
LL_WARNS("MaterialEditor") << "Invalid LLSD content "<< asset << " for flaoter " << getKey() << LL_ENDL;
}
}
else
{
LL_WARNS("MaterialEditor") << "Failed to deserialize material LLSD for flaoter " << getKey() << LL_ENDL;
}
return false;
}
/**
* Build a description of the material we just imported.
* Currently this means a list of the textures present but we
* may eventually want to make it more complete - will be guided
* by what the content creators say they need.
*/
const std::string LLMaterialEditor::buildMaterialDescription()
{
std::ostringstream desc;
desc << LLTrans::getString("Material Texture Name Header");
// add the texture names for each just so long as the material
// we loaded has an entry for it (i think testing the texture
// control UUI for NULL is a valid metric for if it was loaded
// or not but I suspect this code will change a lot so may need
// to revisit
if (!mBaseColorTextureCtrl->getValue().asUUID().isNull())
{
desc << mBaseColorName;
desc << ", ";
}
if (!mMetallicTextureCtrl->getValue().asUUID().isNull())
{
desc << mMetallicRoughnessName;
desc << ", ";
}
if (!mEmissiveTextureCtrl->getValue().asUUID().isNull())
{
desc << mEmissiveName;
desc << ", ";
}
if (!mNormalTextureCtrl->getValue().asUUID().isNull())
{
desc << mNormalName;
}
// trim last char if it's a ',' in case there is no normal texture
// present and the code above inserts one
// (no need to check for string length - always has initial string)
std::string::iterator iter = desc.str().end() - 1;
if (*iter == ',')
{
desc.str().erase(iter);
}
// sanitize the material description so that it's compatible with the inventory
// note: split this up because clang doesn't like operating directly on the
// str() - error: lvalue reference to type 'basic_string<...>' cannot bind to a
// temporary of type 'basic_string<...>'
std::string inv_desc = desc.str();
LLInventoryObject::correctInventoryName(inv_desc);
return inv_desc;
}
bool LLMaterialEditor::saveIfNeeded()
{
if (mUploadingTexturesCount > 0)
{
// upload already in progress
// wait until textures upload
// will retry saving on callback
return true;
}
if (saveTextures() > 0)
{
// started texture upload
setEnabled(false);
return true;
}
std::string buffer = getEncodedAsset();
const LLInventoryItem* item = getItem();
// save it out to database
if (item)
{
if (!updateInventoryItem(buffer, mItemUUID, mObjectUUID))
{
return false;
}
if (mCloseAfterSave)
{
closeFloater();
}
else
{
mAssetStatus = PREVIEW_ASSET_LOADING;
setEnabled(false);
}
}
else
{
//make a new inventory item
std::string res_desc = buildMaterialDescription();
createInventoryItem(buffer, mMaterialName, res_desc);
// We do not update floater with uploaded asset yet, so just close it.
closeFloater();
}
return true;
}
// static
bool LLMaterialEditor::updateInventoryItem(const std::string &buffer, const LLUUID &item_id, const LLUUID &task_id)
{
const LLViewerRegion* region = gAgent.getRegion();
if (!region)
{
LL_WARNS("MaterialEditor") << "Not connected to a region, cannot save material." << LL_ENDL;
return false;
}
std::string agent_url = region->getCapability("UpdateMaterialAgentInventory");
std::string task_url = region->getCapability("UpdateMaterialTaskInventory");
if (!agent_url.empty() && !task_url.empty())
{
std::string url;
LLResourceUploadInfo::ptr_t uploadInfo;
if (task_id.isNull() && !agent_url.empty())
{
uploadInfo = std::make_shared<LLBufferedAssetUploadInfo>(item_id, LLAssetType::AT_MATERIAL, buffer,
[](LLUUID itemId, LLUUID newAssetId, LLUUID newItemId, LLSD) {
LLMaterialEditor::finishInventoryUpload(itemId, newAssetId, newItemId);
});
url = agent_url;
}
else if (!task_id.isNull() && !task_url.empty())
{
LLUUID object_uuid(task_id);
uploadInfo = std::make_shared<LLBufferedAssetUploadInfo>(task_id, item_id, LLAssetType::AT_MATERIAL, buffer,
[object_uuid](LLUUID itemId, LLUUID, LLUUID newAssetId, LLSD) {
LLMaterialEditor::finishTaskUpload(itemId, newAssetId, object_uuid);
});
url = task_url;
}
if (!url.empty() && uploadInfo)
{
LLViewerAssetUpload::EnqueueInventoryUpload(url, uploadInfo);
}
else
{
return false;
}
}
else // !gAssetStorage
{
LL_WARNS("MaterialEditor") << "Not connected to an materials capable region." << LL_ENDL;
return false;
}
// todo: apply permissions from textures here if server doesn't
// if any texture is 'no transfer', material should be 'no transfer' as well
return true;
}
void LLMaterialEditor::createInventoryItem(const std::string &buffer, const std::string &name, const std::string &desc)
{
// gen a new uuid for this asset
LLTransactionID tid;
tid.generate(); // timestamp-based randomization + uniquification
LLAssetID new_asset_id = tid.makeAssetID(gAgent.getSecureSessionID());
U32 next_owner_perm = LLFloaterPerms::getNextOwnerPerms("Materials");
LLUUID parent = gInventory.findUserDefinedCategoryUUIDForType(LLFolderType::FT_MATERIAL);
const U8 subtype = NO_INV_SUBTYPE; // TODO maybe use AT_SETTINGS and LLSettingsType::ST_MATERIAL ?
create_inventory_item(gAgent.getID(), gAgent.getSessionID(), parent, tid, name, desc,
LLAssetType::AT_MATERIAL, LLInventoryType::IT_MATERIAL, subtype, next_owner_perm,
new LLBoostFuncInventoryCallback([output = buffer](LLUUID const& inv_item_id)
{
LLViewerInventoryItem* item = gInventory.getItem(inv_item_id);
if (item)
{
// create_inventory_item doesn't allow presetting some permissions, fix it now
LLPermissions perm = item->getPermissions();
if (perm.getMaskEveryone() != LLFloaterPerms::getEveryonePerms("Materials")
|| perm.getMaskGroup() != LLFloaterPerms::getGroupPerms("Materials"))
{
perm.setMaskEveryone(LLFloaterPerms::getEveryonePerms("Materials"));
perm.setMaskGroup(LLFloaterPerms::getGroupPerms("Materials"));
item->setPermissions(perm);
item->updateServer(FALSE);
gInventory.updateItem(item);
gInventory.notifyObservers();
}
}
// from reference in LLSettingsVOBase::createInventoryItem()/updateInventoryItem()
LLResourceUploadInfo::ptr_t uploadInfo =
std::make_shared<LLBufferedAssetUploadInfo>(
inv_item_id,
LLAssetType::AT_MATERIAL,
output,
[](LLUUID item_id, LLUUID new_asset_id, LLUUID new_item_id, LLSD response) {
LL_INFOS("Material") << "inventory item uploaded. item: " << item_id << " asset: " << new_asset_id << " new_item_id: " << new_item_id << " response: " << response << LL_ENDL;
LLSD params = llsd::map("ASSET_ID", new_asset_id);
LLNotificationsUtil::add("MaterialCreated", params);
});
// todo: apply permissions from textures here if server doesn't
// if any texture is 'no transfer', material should be 'no transfer' as well
const LLViewerRegion* region = gAgent.getRegion();
if (region)
{
std::string agent_url(region->getCapability("UpdateMaterialAgentInventory"));
if (agent_url.empty())
{
LL_ERRS("MaterialEditor") << "missing required agent inventory cap url" << LL_ENDL;
}
LLViewerAssetUpload::EnqueueInventoryUpload(agent_url, uploadInfo);
}
})
);
}
void LLMaterialEditor::finishInventoryUpload(LLUUID itemId, LLUUID newAssetId, LLUUID newItemId)
{
// Update the UI with the new asset.
LLMaterialEditor* me = LLFloaterReg::findTypedInstance<LLMaterialEditor>("material_editor", LLSD(itemId));
if (me)
{
if (newItemId.isNull())
{
me->setAssetId(newAssetId);
me->refreshFromInventory();
}
else if (newItemId.notNull())
{
// Not supposed to happen?
me->refreshFromInventory(newItemId);
}
else
{
me->refreshFromInventory(itemId);
}
}
}
void LLMaterialEditor::finishTaskUpload(LLUUID itemId, LLUUID newAssetId, LLUUID taskId)
{
LLSD floater_key;
floater_key["taskid"] = taskId;
floater_key["itemid"] = itemId;
LLMaterialEditor* me = LLFloaterReg::findTypedInstance<LLMaterialEditor>("material_editor", floater_key);
if (me)
{
me->setAssetId(newAssetId);
me->refreshFromInventory();
me->setEnabled(true);
}
}
void LLMaterialEditor::finishSaveAs(
const LLSD &oldKey,
const LLUUID &newItemId,
const std::string &buffer,
bool has_unsaved_changes)
{
LLMaterialEditor* me = LLFloaterReg::findTypedInstance<LLMaterialEditor>("material_editor", oldKey);
LLViewerInventoryItem* item = gInventory.getItem(newItemId);
if (item)
{
if (me)
{
me->mItemUUID = newItemId;
me->mObjectUUID = LLUUID::null;
me->mNotecardInventoryID = LLUUID::null;
me->mNotecardObjectID = LLUUID::null;
me->mAuxItem = nullptr;
me->setKey(LLSD(newItemId)); // for findTypedInstance
me->setMaterialName(item->getName());
if (has_unsaved_changes)
{
if (!updateInventoryItem(buffer, newItemId, LLUUID::null))
{
me->setEnabled(true);
}
}
else
{
me->loadAsset();
me->setEnabled(true);
}
}
else if(has_unsaved_changes)
{
updateInventoryItem(buffer, newItemId, LLUUID::null);
}
}
else if (me)
{
me->setEnabled(true);
LL_WARNS("MaterialEditor") << "Item does not exist, floater " << me->getKey() << LL_ENDL;
}
}
void LLMaterialEditor::refreshFromInventory(const LLUUID& new_item_id)
{
if (mIsOverride)
{
// refreshFromInventory shouldn't be called for overrides,
// but just in case.
LL_WARNS("MaterialEditor") << "Tried to refresh from inventory for live editor" << LL_ENDL;
return;
}
LLSD old_key = getKey();
if (new_item_id.notNull())
{
mItemUUID = new_item_id;
if (mNotecardInventoryID.notNull())
{
LLSD floater_key;
floater_key["objectid"] = mNotecardObjectID;
floater_key["notecardid"] = mNotecardInventoryID;
setKey(floater_key);
}
else if (mObjectUUID.notNull())
{
LLSD floater_key;
floater_key["taskid"] = new_item_id;
floater_key["itemid"] = mObjectUUID;
setKey(floater_key);
}
else
{
setKey(LLSD(new_item_id));
}
}
LL_DEBUGS("MaterialEditor") << "New floater key: " << getKey() << " Old key: " << old_key << LL_ENDL;
loadAsset();
}
void LLMaterialEditor::onClickSaveAs()
{
if (!can_afford_transaction(mExpectedUploadCost))
{
LLSD args;
args["COST"] = llformat("%d", mExpectedUploadCost);
LLNotificationsUtil::add("ErrorCannotAffordUpload", args);
return;
}
LLSD args;
args["DESC"] = mMaterialName;
LLNotificationsUtil::add("SaveMaterialAs", args, LLSD(), boost::bind(&LLMaterialEditor::onSaveAsMsgCallback, this, _1, _2));
}
void LLMaterialEditor::onSaveAsMsgCallback(const LLSD& notification, const LLSD& response)
{
S32 option = LLNotificationsUtil::getSelectedOption(notification, response);
if (0 == option)
{
std::string new_name = response["message"].asString();
LLInventoryObject::correctInventoryName(new_name);
if (!new_name.empty())
{
const LLInventoryItem* item;
if (mNotecardInventoryID.notNull())
{
item = mAuxItem.get();
}
else
{
item = getItem();
}
if (item)
{
const LLUUID &marketplacelistings_id = gInventory.findCategoryUUIDForType(LLFolderType::FT_MARKETPLACE_LISTINGS, false);
LLUUID parent_id = item->getParentUUID();
if (mObjectUUID.notNull() || marketplacelistings_id == parent_id || gInventory.isObjectDescendentOf(item->getUUID(), gInventory.getLibraryRootFolderID()))
{
parent_id = gInventory.findCategoryUUIDForType(LLFolderType::FT_MATERIAL);
}
// A two step process, first copy an existing item, then create new asset
if (mNotecardInventoryID.notNull())
{
LLPointer<LLInventoryCallback> cb = new LLMaterialEditorCopiedCallback(getKey(), new_name);
copy_inventory_from_notecard(parent_id,
mNotecardObjectID,
mNotecardInventoryID,
mAuxItem.get(),
gInventoryCallbacks.registerCB(cb));
}
else
{
std::string buffer = getEncodedAsset();
LLPointer<LLInventoryCallback> cb = new LLMaterialEditorCopiedCallback(buffer, getKey(), mUnsavedChanges);
copy_inventory_item(
gAgent.getID(),
item->getPermissions().getOwner(),
item->getUUID(),
parent_id,
new_name,
cb);
}
mAssetStatus = PREVIEW_ASSET_LOADING;
setEnabled(false);
}
else
{
setMaterialName(new_name);
onClickSave();
}
}
else
{
LLNotificationsUtil::add("InvalidMaterialName");
}
}
}
void LLMaterialEditor::onClickCancel()
{
if (mUnsavedChanges)
{
LLNotificationsUtil::add("UsavedMaterialChanges", LLSD(), LLSD(), boost::bind(&LLMaterialEditor::onCancelMsgCallback, this, _1, _2));
}
else
{
closeFloater();
}
}
void LLMaterialEditor::onCancelMsgCallback(const LLSD& notification, const LLSD& response)
{
S32 option = LLNotificationsUtil::getSelectedOption(notification, response);
if (0 == option)
{
if (mIsOverride && !mObjectOverridesSavedValues.empty())
{
// Reapply ids back onto selection.
// TODO: monitor selection changes and resave on selection changes
struct g : public LLSelectedObjectFunctor
{
g(LLMaterialEditor* me) : mEditor(me) {}
virtual bool apply(LLViewerObject* objectp)
{
if (!objectp || !objectp->permModify())
{
return false;
}
U32 local_id = objectp->getLocalID();
if (mEditor->mObjectOverridesSavedValues.find(local_id) == mEditor->mObjectOverridesSavedValues.end())
{
return false;
}
S32 num_tes = llmin((S32)objectp->getNumTEs(), (S32)objectp->getNumFaces());
for (U8 te = 0; te < num_tes; te++)
{
if (mEditor->mObjectOverridesSavedValues[local_id].size() > te
&& objectp->getTE(te)->isSelected())
{
objectp->setRenderMaterialID(
te,
mEditor->mObjectOverridesSavedValues[local_id][te],
false /*wait for bulk update*/);
}
}
return true;
}
LLMaterialEditor* mEditor;
} restorefunc(this);
LLSelectMgr::getInstance()->getSelection()->applyToObjects(&restorefunc);
struct f : public LLSelectedObjectFunctor
{
virtual bool apply(LLViewerObject* object)
{
if (object && !object->permModify())
{
return false;
}
LLRenderMaterialParams* param_block = (LLRenderMaterialParams*)object->getParameterEntry(LLNetworkData::PARAMS_RENDER_MATERIAL);
if (param_block)
{
if (param_block->isEmpty())
{
object->setHasRenderMaterialParams(false);
}
else
{
object->parameterChanged(LLNetworkData::PARAMS_RENDER_MATERIAL, true);
}
}
object->sendTEUpdate();
return true;
}
} sendfunc;
LLSelectMgr::getInstance()->getSelection()->applyToObjects(&sendfunc);
}
closeFloater();
}
}
static void pack_textures(
LLPointer<LLImageRaw>& base_color_img,
LLPointer<LLImageRaw>& normal_img,
LLPointer<LLImageRaw>& mr_img,
LLPointer<LLImageRaw>& emissive_img,
LLPointer<LLImageRaw>& occlusion_img,
LLPointer<LLImageJ2C>& base_color_j2c,
LLPointer<LLImageJ2C>& normal_j2c,
LLPointer<LLImageJ2C>& mr_j2c,
LLPointer<LLImageJ2C>& emissive_j2c)
{
// NOTE : remove log spam and lossless vs lossy comparisons when the logs are no longer useful
if (base_color_img)
{
base_color_j2c = LLViewerTextureList::convertToUploadFile(base_color_img);
LL_DEBUGS("MaterialEditor") << "BaseColor: " << base_color_j2c->getDataSize() << LL_ENDL;
}
if (normal_img)
{
normal_j2c = LLViewerTextureList::convertToUploadFile(normal_img);
LLPointer<LLImageJ2C> test;
test = LLViewerTextureList::convertToUploadFile(normal_img, 1024, true);
S32 lossy_bytes = normal_j2c->getDataSize();
S32 lossless_bytes = test->getDataSize();
LL_DEBUGS("MaterialEditor") << llformat("Lossless vs Lossy: (%d/%d) = %.2f", lossless_bytes, lossy_bytes, (F32)lossless_bytes / lossy_bytes) << LL_ENDL;
normal_j2c = test;
}
if (mr_img)
{
mr_j2c = LLViewerTextureList::convertToUploadFile(mr_img);
LL_DEBUGS("MaterialEditor") << "Metallic/Roughness: " << mr_j2c->getDataSize() << LL_ENDL;
}
if (emissive_img)
{
emissive_j2c = LLViewerTextureList::convertToUploadFile(emissive_img);
LL_DEBUGS("MaterialEditor") << "Emissive: " << emissive_j2c->getDataSize() << LL_ENDL;
}
}
void LLMaterialEditor::loadMaterialFromFile(const std::string& filename, S32 index)
{
tinygltf::TinyGLTF loader;
std::string error_msg;
std::string warn_msg;
bool loaded = false;
tinygltf::Model model_in;
std::string filename_lc = filename;
LLStringUtil::toLower(filename_lc);
// Load a tinygltf model fom a file. Assumes that the input filename has already been
// been sanitized to one of (.gltf , .glb) extensions, so does a simple find to distinguish.
if (std::string::npos == filename_lc.rfind(".gltf"))
{ // file is binary
loaded = loader.LoadBinaryFromFile(&model_in, &error_msg, &warn_msg, filename);
}
else
{ // file is ascii
loaded = loader.LoadASCIIFromFile(&model_in, &error_msg, &warn_msg, filename);
}
if (!loaded)
{
LLNotificationsUtil::add("CannotUploadMaterial");
return;
}
if (model_in.materials.empty())
{
// materials are missing
LLNotificationsUtil::add("CannotUploadMaterial");
return;
}
if (index >= 0 && model_in.materials.size() <= index)
{
// material is missing
LLNotificationsUtil::add("CannotUploadMaterial");
return;
}
LLMaterialEditor* me = (LLMaterialEditor*)LLFloaterReg::getInstance("material_editor");
if (index >= 0)
{
// Prespecified material
me->loadMaterial(model_in, filename_lc, index);
}
else if (model_in.materials.size() == 1)
{
// Only one, just load it
me->loadMaterial(model_in, filename_lc, 0);
}
else
{
// Promt user to select material
std::list<std::string> material_list;
std::vector<tinygltf::Material>::const_iterator mat_iter = model_in.materials.begin();
std::vector<tinygltf::Material>::const_iterator mat_end = model_in.materials.end();
for (; mat_iter != mat_end; mat_iter++)
{
std::string mat_name = mat_iter->name;
if (mat_name.empty())
{
material_list.push_back("Material " + std::to_string(material_list.size()));
}
else
{
material_list.push_back(mat_name);
}
}
LLFloaterComboOptions::showUI(
[me, model_in, filename_lc](const std::string& option, S32 index)
{
me->loadMaterial(model_in, filename_lc, index);
},
me->getString("material_selection_title"),
me->getString("material_selection_text"),
material_list
);
}
}
void LLMaterialEditor::onSelectionChanged()
{
// This won't get deletion or deselectAll()
// Might need to handle that separately
// Drop selection updates if we are waiting for
// overrides to finish aplying to not reset values
// (might need a timeout)
if (!mOverrideInProgress)
{
clearTextures();
setFromSelection();
}
// At the moment all cahges are 'live' so don't reset dirty flags
// saveLiveValues(); todo
}
void LLMaterialEditor::saveLiveValues()
{
// Collect ids to be able to revert overrides.
// TODO: monitor selection changes and resave on selection changes
mObjectOverridesSavedValues.clear();
struct g : public LLSelectedObjectFunctor
{
g(LLMaterialEditor* me) : mEditor(me) {}
virtual bool apply(LLViewerObject* objectp)
{
if (!objectp)
{
return false;
}
U32 local_id = objectp->getLocalID();
S32 num_tes = llmin((S32)objectp->getNumTEs(), (S32)objectp->getNumFaces());
for (U8 te = 0; te < num_tes; te++)
{
// Todo: fix this, overrides don't care about ids,
// we will have to save actual values or materials
LLUUID mat_id = objectp->getRenderMaterialID(te);
mEditor->mObjectOverridesSavedValues[local_id].push_back(mat_id);
}
return true;
}
LLMaterialEditor* mEditor;
} savefunc(this);
LLSelectMgr::getInstance()->getSelection()->applyToObjects(&savefunc);
}
void LLMaterialEditor::updateLive()
{
const LLSD floater_key(LIVE_MATERIAL_EDITOR_KEY);
LLFloater* instance = LLFloaterReg::findInstance("material_editor", floater_key);
if (instance && LLFloater::isVisible(instance))
{
LLMaterialEditor* me = (LLMaterialEditor*)instance;
if (me)
{
me->mOverrideInProgress = false;
me->clearTextures();
me->setFromSelection();
}
}
}
void LLMaterialEditor::updateLive(const LLUUID &object_id, S32 te)
{
if (mOverrideObjectId != object_id
|| mOverrideObjectTE != te)
{
// Not an update we are waiting for
return;
}
const LLSD floater_key(LIVE_MATERIAL_EDITOR_KEY);
LLFloater* instance = LLFloaterReg::findInstance("material_editor", floater_key);
if (instance && LLFloater::isVisible(instance))
{
LLMaterialEditor* me = (LLMaterialEditor*)instance;
if (me)
{
me->mOverrideInProgress = false;
me->clearTextures();
me->setFromSelection();
}
}
}
void LLMaterialEditor::loadLive()
{
// Allow only one 'live' instance
const LLSD floater_key(LIVE_MATERIAL_EDITOR_KEY);
LLMaterialEditor* me = (LLMaterialEditor*)LLFloaterReg::getInstance("material_editor", floater_key);
if (me)
{
me->mOverrideInProgress = false;
me->setFromSelection();
me->setTitle(me->getString("material_override_title"));
me->childSetVisible("save", false);
me->childSetVisible("save_as", false);
// Set up for selection changes updates
if (!me->mSelectionUpdateSlot.connected())
{
me->mSelectionUpdateSlot = LLSelectMgr::instance().mUpdateSignal.connect(boost::bind(&LLMaterialEditor::onSelectionChanged, me));
}
// Collect ids to be able to revert overrides on cancel.
me->saveLiveValues();
me->openFloater(floater_key);
me->setFocus(TRUE);
}
}
void LLMaterialEditor::saveObjectsMaterialAs()
{
LLSD args;
args["DESC"] = LLTrans::getString("New Material");
LLSD payload;
// Find an applicable material.
// Do this before showing message, because
// message is going to drop selection.
LLSelectedTEGetMatData func(false);
LLSelectMgr::getInstance()->getSelection()->applyToTEs(&func);
if (func.mMaterial.notNull())
{
func.mMaterial;
payload["data"] = func.mMaterial->asJSON();
}
else
{
// Menu shouldn't allow this, but as a fallback
// pick defaults from a blank material
LLGLTFMaterial blank_mat;
payload["data"] = blank_mat.asJSON();
LL_WARNS() << "Got no material when trying to save material" << LL_ENDL;
}
LLNotificationsUtil::add("SaveMaterialAs", args, payload, boost::bind(&LLMaterialEditor::onSaveObjectsMaterialAsMsgCallback, _1, _2));
}
void LLMaterialEditor::onSaveObjectsMaterialAsMsgCallback(const LLSD& notification, const LLSD& response)
{
S32 option = LLNotificationsUtil::getSelectedOption(notification, response);
if (0 == option)
{
LLSD asset;
asset["version"] = "1.0";
asset["type"] = "GLTF 2.0";
asset["data"] = notification["payload"]["data"];
std::ostringstream str;
LLSDSerialize::serialize(asset, str, LLSDSerialize::LLSD_BINARY);
std::string new_name = response["message"].asString();
createInventoryItem(str.str(), new_name, std::string());
}
}
void LLMaterialEditor::loadFromGLTFMaterial(LLUUID &asset_id)
{
if (asset_id.isNull())
{
LL_WARNS("MaterialEditor") << "Trying to open material with null id" << LL_ENDL;
return;
}
LLMaterialEditor* me = (LLMaterialEditor*)LLFloaterReg::getInstance("material_editor");
me->mMaterialName = LLTrans::getString("New Material");
me->setTitle(me->mMaterialName);
me->setFromGLTFMaterial(gGLTFMaterialList.getMaterial(asset_id));
me->openFloater();
me->setFocus(TRUE);
}
void LLMaterialEditor::loadMaterial(const tinygltf::Model &model_in, const std::string &filename_lc, S32 index)
{
if (model_in.materials.size() <= index)
{
return;
}
std::string folder = gDirUtilp->getDirName(filename_lc);
tinygltf::Material material_in = model_in.materials[index];
tinygltf::Model model_out;
model_out.asset.version = "2.0";
model_out.materials.resize(1);
// get base color texture
LLPointer<LLImageRaw> base_color_img = LLTinyGLTFHelper::getTexture(folder, model_in, material_in.pbrMetallicRoughness.baseColorTexture.index, mBaseColorName);
// get normal map
LLPointer<LLImageRaw> normal_img = LLTinyGLTFHelper::getTexture(folder, model_in, material_in.normalTexture.index, mNormalName);
// get metallic-roughness texture
LLPointer<LLImageRaw> mr_img = LLTinyGLTFHelper::getTexture(folder, model_in, material_in.pbrMetallicRoughness.metallicRoughnessTexture.index, mMetallicRoughnessName);
// get emissive texture
LLPointer<LLImageRaw> emissive_img = LLTinyGLTFHelper::getTexture(folder, model_in, material_in.emissiveTexture.index, mEmissiveName);
// get occlusion map if needed
LLPointer<LLImageRaw> occlusion_img;
if (material_in.occlusionTexture.index != material_in.pbrMetallicRoughness.metallicRoughnessTexture.index)
{
std::string tmp;
occlusion_img = LLTinyGLTFHelper::getTexture(folder, model_in, material_in.occlusionTexture.index, tmp);
}
LLTinyGLTFHelper::initFetchedTextures(material_in, base_color_img, normal_img, mr_img, emissive_img, occlusion_img,
mBaseColorFetched, mNormalFetched, mMetallicRoughnessFetched, mEmissiveFetched);
pack_textures(base_color_img, normal_img, mr_img, emissive_img, occlusion_img,
mBaseColorJ2C, mNormalJ2C, mMetallicRoughnessJ2C, mEmissiveJ2C);
LLUUID base_color_id;
if (mBaseColorFetched.notNull())
{
mBaseColorFetched->forceToSaveRawImage(0, F32_MAX);
base_color_id = mBaseColorFetched->getID();
if (mBaseColorName.empty())
{
mBaseColorName = MATERIAL_BASE_COLOR_DEFAULT_NAME;
}
}
LLUUID normal_id;
if (mNormalFetched.notNull())
{
mNormalFetched->forceToSaveRawImage(0, F32_MAX);
normal_id = mNormalFetched->getID();
if (mNormalName.empty())
{
mNormalName = MATERIAL_NORMAL_DEFAULT_NAME;
}
}
LLUUID mr_id;
if (mMetallicRoughnessFetched.notNull())
{
mMetallicRoughnessFetched->forceToSaveRawImage(0, F32_MAX);
mr_id = mMetallicRoughnessFetched->getID();
if (mMetallicRoughnessName.empty())
{
mMetallicRoughnessName = MATERIAL_METALLIC_DEFAULT_NAME;
}
}
LLUUID emissive_id;
if (mEmissiveFetched.notNull())
{
mEmissiveFetched->forceToSaveRawImage(0, F32_MAX);
emissive_id = mEmissiveFetched->getID();
if (mEmissiveName.empty())
{
mEmissiveName = MATERIAL_EMISSIVE_DEFAULT_NAME;
}
}
setBaseColorId(base_color_id);
setBaseColorUploadId(base_color_id);
setMetallicRoughnessId(mr_id);
setMetallicRoughnessUploadId(mr_id);
setEmissiveId(emissive_id);
setEmissiveUploadId(emissive_id);
setNormalId(normal_id);
setNormalUploadId(normal_id);
setFromGltfModel(model_in, index);
setFromGltfMetaData(filename_lc, model_in, index);
markChangesUnsaved(U32_MAX);
openFloater();
setFocus(TRUE);
applyToSelection();
}
bool LLMaterialEditor::setFromGltfModel(const tinygltf::Model& model, S32 index, bool set_textures)
{
if (model.materials.size() > index)
{
const tinygltf::Material& material_in = model.materials[index];
if (set_textures)
{
S32 index;
LLUUID id;
// get base color texture
index = material_in.pbrMetallicRoughness.baseColorTexture.index;
if (index >= 0)
{
id.set(model.images[index].uri);
setBaseColorId(id);
}
else
{
setBaseColorId(LLUUID::null);
}
// get normal map
index = material_in.normalTexture.index;
if (index >= 0)
{
id.set(model.images[index].uri);
setNormalId(id);
}
else
{
setNormalId(LLUUID::null);
}
// get metallic-roughness texture
index = material_in.pbrMetallicRoughness.metallicRoughnessTexture.index;
if (index >= 0)
{
id.set(model.images[index].uri);
setMetallicRoughnessId(id);
}
else
{
setMetallicRoughnessId(LLUUID::null);
}
// get emissive texture
index = material_in.emissiveTexture.index;
if (index >= 0)
{
id.set(model.images[index].uri);
setEmissiveId(id);
}
else
{
setEmissiveId(LLUUID::null);
}
}
setAlphaMode(material_in.alphaMode);
setAlphaCutoff(material_in.alphaCutoff);
setBaseColor(LLTinyGLTFHelper::getColor(material_in.pbrMetallicRoughness.baseColorFactor));
setEmissiveColor(LLTinyGLTFHelper::getColor(material_in.emissiveFactor));
setMetalnessFactor(material_in.pbrMetallicRoughness.metallicFactor);
setRoughnessFactor(material_in.pbrMetallicRoughness.roughnessFactor);
setDoubleSided(material_in.doubleSided);
}
return true;
}
/**
* Build a texture name from the contents of the (in tinyGLFT parlance)
* Image URI. This often is filepath to the original image on the users'
* local file system.
*/
const std::string LLMaterialEditor::getImageNameFromUri(std::string image_uri, const std::string texture_type)
{
// getBaseFileName() works differently on each platform and file patchs
// can contain both types of delimiter so unify them then extract the
// base name (no path or extension)
std::replace(image_uri.begin(), image_uri.end(), '\\', gDirUtilp->getDirDelimiter()[0]);
std::replace(image_uri.begin(), image_uri.end(), '/', gDirUtilp->getDirDelimiter()[0]);
const bool strip_extension = true;
std::string stripped_uri = gDirUtilp->getBaseFileName(image_uri, strip_extension);
// sometimes they can be really long and unwieldy - 64 chars is enough for anyone :)
const int max_texture_name_length = 64;
if (stripped_uri.length() > max_texture_name_length)
{
stripped_uri = stripped_uri.substr(0, max_texture_name_length - 1);
}
// We intend to append the type of texture (base color, emissive etc.) to the
// name of the texture but sometimes the creator already did that. To try
// to avoid repeats (not perfect), we look for the texture type in the name
// and if we find it, do not append the type, later on. One way this fails
// (and it's fine for now) is I see some texture/image uris have a name like
// "metallic roughness" and of course, that doesn't match our predefined
// name "metallicroughness" - consider fix later..
bool name_includes_type = false;
std::string stripped_uri_lower = stripped_uri;
LLStringUtil::toLower(stripped_uri_lower);
stripped_uri_lower.erase(std::remove_if(stripped_uri_lower.begin(), stripped_uri_lower.end(), isspace), stripped_uri_lower.end());
std::string texture_type_lower = texture_type;
LLStringUtil::toLower(texture_type_lower);
texture_type_lower.erase(std::remove_if(texture_type_lower.begin(), texture_type_lower.end(), isspace), texture_type_lower.end());
if (stripped_uri_lower.find(texture_type_lower) != std::string::npos)
{
name_includes_type = true;
}
// uri doesn't include the type at all
if (name_includes_type == false)
{
// uri doesn't include the type and the uri is not empty
// so we can include everything
if (stripped_uri.length() > 0)
{
// example "DamagedHelmet: base layer"
return STRINGIZE(
mMaterialNameShort <<
": " <<
stripped_uri <<
" (" <<
texture_type <<
")"
);
}
else
// uri doesn't include the type (because the uri is empty)
// so we must reorganize the string a bit to include the name
// and an explicit name type
{
// example "DamagedHelmet: (Emissive)"
return STRINGIZE(
mMaterialNameShort <<
" (" <<
texture_type <<
")"
);
}
}
else
// uri includes the type so just use it directly with the
// name of the material
{
return STRINGIZE(
// example: AlienBust: normal_layer
mMaterialNameShort <<
": " <<
stripped_uri
);
}
}
/**
* Update the metadata for the material based on what we find in the loaded
* file (along with some assumptions and interpretations...). Fields include
* the name of the material, a material description and the names of the
* composite textures.
*/
void LLMaterialEditor::setFromGltfMetaData(const std::string& filename, const tinygltf::Model& model, S32 index)
{
// Use the name (without any path/extension) of the file that was
// uploaded as the base of the material name. Then if the name of the
// scene is present and not blank, append that and use the result as
// the name of the material. This is a first pass at creating a
// naming scheme that is useful to real content creators and hopefully
// avoid 500 materials in your inventory called "scene" or "Default"
const bool strip_extension = true;
std::string base_filename = gDirUtilp->getBaseFileName(filename, strip_extension);
// Extract the name of the scene. Note it is often blank or some very
// generic name like "Scene" or "Default" so using this in the name
// is less useful than you might imagine.
std::string material_name;
if (model.materials.size() > index && !model.materials[index].name.empty())
{
material_name = model.materials[index].name;
}
else if (model.scenes.size() > 0)
{
const tinygltf::Scene& scene_in = model.scenes[0];
if (scene_in.name.length())
{
material_name = scene_in.name;
}
else
{
// scene name is empty so no point using it
}
}
else
{
// scene name isn't present so no point using it
}
// If we have a valid material or scene name, use it to build the short and
// long versions of the material name. The long version is used
// as you might expect, for the material name. The short version is
// used as part of the image/texture name - the theory is that will
// allow content creators to track the material and the corresponding
// textures
if (material_name.length())
{
mMaterialNameShort = base_filename;
mMaterialName = STRINGIZE(
base_filename <<
" " <<
"(" <<
material_name <<
")"
);
}
else
// otherwise, just use the trimmed filename as is
{
mMaterialNameShort = base_filename;
mMaterialName = base_filename;
}
// sanitize the material name so that it's compatible with the inventory
LLInventoryObject::correctInventoryName(mMaterialName);
LLInventoryObject::correctInventoryName(mMaterialNameShort);
// We also set the title of the floater to match the
// name of the material
setTitle(mMaterialName);
/**
* Extract / derive the names of each composite texture. For each, the
* index is used to to determine which of the "Images" is used. If the index
* is -1 then that texture type is not present in the material (Seems to be
* quite common that a material is missing 1 or more types of texture)
*/
if (model.materials.size() > index)
{
const tinygltf::Material& first_material = model.materials[index];
mBaseColorName = MATERIAL_BASE_COLOR_DEFAULT_NAME;
// note: unlike the other textures, base color doesn't have its own entry
// in the tinyGLTF Material struct. Rather, it is taken from a
// sub-texture in the pbrMetallicRoughness member
int index = first_material.pbrMetallicRoughness.baseColorTexture.index;
if (index > -1 && index < model.images.size())
{
// sanitize the name we decide to use for each texture
std::string texture_name = getImageNameFromUri(model.images[index].uri, MATERIAL_BASE_COLOR_DEFAULT_NAME);
LLInventoryObject::correctInventoryName(texture_name);
mBaseColorName = texture_name;
}
mEmissiveName = MATERIAL_EMISSIVE_DEFAULT_NAME;
index = first_material.emissiveTexture.index;
if (index > -1 && index < model.images.size())
{
std::string texture_name = getImageNameFromUri(model.images[index].uri, MATERIAL_EMISSIVE_DEFAULT_NAME);
LLInventoryObject::correctInventoryName(texture_name);
mEmissiveName = texture_name;
}
mMetallicRoughnessName = MATERIAL_METALLIC_DEFAULT_NAME;
index = first_material.pbrMetallicRoughness.metallicRoughnessTexture.index;
if (index > -1 && index < model.images.size())
{
std::string texture_name = getImageNameFromUri(model.images[index].uri, MATERIAL_METALLIC_DEFAULT_NAME);
LLInventoryObject::correctInventoryName(texture_name);
mMetallicRoughnessName = texture_name;
}
mNormalName = MATERIAL_NORMAL_DEFAULT_NAME;
index = first_material.normalTexture.index;
if (index > -1 && index < model.images.size())
{
std::string texture_name = getImageNameFromUri(model.images[index].uri, MATERIAL_NORMAL_DEFAULT_NAME);
LLInventoryObject::correctInventoryName(texture_name);
mNormalName = texture_name;
}
}
}
void LLMaterialEditor::importMaterial()
{
LLFilePickerReplyThread::startPicker(
[](const std::vector<std::string>& filenames, LLFilePicker::ELoadFilter load_filter, LLFilePicker::ESaveFilter save_filter)
{
if (LLAppViewer::instance()->quitRequested())
{
return;
}
if (filenames.size() > 0)
{
LLMaterialEditor::loadMaterialFromFile(filenames[0], -1);
}
},
LLFilePicker::FFLOAD_MATERIAL,
true);
}
class LLRenderMaterialFunctor : public LLSelectedTEFunctor
{
public:
LLRenderMaterialFunctor(const LLUUID &id)
: mMatId(id)
{
}
bool apply(LLViewerObject* objectp, S32 te) override
{
if (objectp && objectp->permModify() && objectp->getVolume())
{
LLVOVolume* vobjp = (LLVOVolume*)objectp;
vobjp->setRenderMaterialID(te, mMatId, false /*preview only*/);
vobjp->updateTEMaterialTextures(te);
}
return true;
}
private:
LLUUID mMatId;
};
class LLRenderMaterialOverrideFunctor : public LLSelectedTEFunctor
{
public:
LLRenderMaterialOverrideFunctor(LLMaterialEditor * me, std::string const & url)
: mEditor(me), mCapUrl(url)
{
}
bool apply(LLViewerObject* objectp, S32 te) override
{
// post override from given object and te to the simulator
// requestData should have:
// object_id - UUID of LLViewerObject
// side - S32 index of texture entry
// gltf_json - String of GLTF json for override data
if (objectp && objectp->permModify() && objectp->getVolume())
{
// Get material from object
// Selection can cover multiple objects, and live editor is
// supposed to overwrite changed values only
LLTextureEntry* tep = objectp->getTE(te);
LLPointer<LLGLTFMaterial> material = tep->getGLTFRenderMaterial();
if (material.isNull())
{
// overrides are not supposed to work or apply if
// there is no base material to work from
return false;
}
// make a copy to not invalidate existing
// material for multiple objects
material = new LLGLTFMaterial(*material);
// Override object's values with values from editor where appropriate
if (mEditor->getUnsavedChangesFlags() & MATERIAL_BASE_COLOR_DIRTY)
{
material->mBaseColor = mEditor->getBaseColor();
}
if (mEditor->getUnsavedChangesFlags() & MATERIAL_BASE_TRANSPARENCY_DIRTY)
{
material->mBaseColor.mV[3] = mEditor->getTransparency();
}
if (mEditor->getUnsavedChangesFlags() & MATERIAL_BASE_COLOR_TEX_DIRTY)
{
material->mBaseColorId = mEditor->getBaseColorId();
}
if (mEditor->getUnsavedChangesFlags() & MATERIAL_NORMAL_TEX_DIRTY)
{
material->mNormalId = mEditor->getNormalId();
}
if (mEditor->getUnsavedChangesFlags() & MATERIAL_METALLIC_ROUGHTNESS_TEX_DIRTY)
{
material->mMetallicRoughnessId = mEditor->getMetallicRoughnessId();
}
if (mEditor->getUnsavedChangesFlags() & MATERIAL_METALLIC_ROUGHTNESS_METALNESS_DIRTY)
{
material->mMetallicFactor = mEditor->getMetalnessFactor();
}
if (mEditor->getUnsavedChangesFlags() & MATERIAL_METALLIC_ROUGHTNESS_ROUGHNESS_DIRTY)
{
material->mRoughnessFactor = mEditor->getRoughnessFactor();
}
if (mEditor->getUnsavedChangesFlags() & MATERIAL_EMISIVE_COLOR_DIRTY)
{
material->mEmissiveColor = mEditor->getEmissiveColor();
}
if (mEditor->getUnsavedChangesFlags() & MATERIAL_EMISIVE_TEX_DIRTY)
{
material->mEmissiveId = mEditor->getEmissiveId();
}
if (mEditor->getUnsavedChangesFlags() & MATERIAL_DOUBLE_SIDED_DIRTY)
{
material->mDoubleSided = mEditor->getDoubleSided();
}
if (mEditor->getUnsavedChangesFlags() & MATERIAL_ALPHA_MODE_DIRTY)
{
material->setAlphaMode(mEditor->getAlphaMode());
}
if (mEditor->getUnsavedChangesFlags() & MATERIAL_ALPHA_CUTOFF_DIRTY)
{
material->mAlphaCutoff = mEditor->getAlphaCutoff();
}
std::string overrides_json = material->asJSON();
LLSD overrides = llsd::map(
"object_id", objectp->getID(),
"side", te,
"gltf_json", overrides_json
);
LLCoros::instance().launch("modifyMaterialCoro", std::bind(&LLGLTFMaterialList::modifyMaterialCoro, mCapUrl, overrides, modifyCallback));
}
return true;
}
static void modifyCallback(bool success)
{
if (!success)
{
// something went wrong update selection
LLMaterialEditor::updateLive();
}
// else we will get updateLive(obj, id) from aplied overrides
}
private:
LLMaterialEditor * mEditor;
std::string mCapUrl;
};
void LLMaterialEditor::applyToSelection()
{
if (!mIsOverride)
{
// Only apply if working with 'live' materials
// Might need a better way to distinguish 'live' mode.
// But only one live edit is supposed to work at a time
// as a pair to tools floater.
return;
}
std::string url = gAgent.getRegionCapability("ModifyMaterialParams");
if (!url.empty())
{
// Don't send data if there is nothing to send.
// Some UI elements will cause multiple commits,
// like spin ctrls on click and on down
if (mUnsavedChanges != 0)
{
mOverrideInProgress = true;
LLObjectSelectionHandle selected_objects = LLSelectMgr::getInstance()->getSelection();
LLRenderMaterialOverrideFunctor override_func(this, url);
if (!selected_objects->applyToTEs(&override_func))
{
mOverrideInProgress = false;
}
// we posted all changes
mUnsavedChanges = 0;
}
}
else
{
LL_WARNS("MaterialEditor") << "Not connected to materials capable region, missing ModifyMaterialParams cap" << LL_ENDL;
// Fallback local preview. Will be removed once override systems is finished and new cap is deployed everywhere.
LLPointer<LLFetchedGLTFMaterial> mat = new LLFetchedGLTFMaterial();
getGLTFMaterial(mat);
static const LLUUID placeholder("984e183e-7811-4b05-a502-d79c6f978a98");
gGLTFMaterialList.addMaterial(placeholder, mat);
LLRenderMaterialFunctor mat_func(placeholder);
LLObjectSelectionHandle selected_objects = LLSelectMgr::getInstance()->getSelection();
selected_objects->applyToTEs(&mat_func);
}
}
void LLMaterialEditor::getGLTFMaterial(LLGLTFMaterial* mat)
{
mat->mBaseColor = getBaseColor();
mat->mBaseColor.mV[3] = getTransparency();
mat->mBaseColorId = getBaseColorId();
mat->mNormalId = getNormalId();
mat->mMetallicRoughnessId = getMetallicRoughnessId();
mat->mMetallicFactor = getMetalnessFactor();
mat->mRoughnessFactor = getRoughnessFactor();
mat->mEmissiveColor = getEmissiveColor();
mat->mEmissiveId = getEmissiveId();
mat->mDoubleSided = getDoubleSided();
mat->setAlphaMode(getAlphaMode());
mat->mAlphaCutoff = getAlphaCutoff();
}
void LLMaterialEditor::setFromGLTFMaterial(LLGLTFMaterial* mat)
{
setBaseColor(mat->mBaseColor);
setBaseColorId(mat->mBaseColorId);
setNormalId(mat->mNormalId);
setMetallicRoughnessId(mat->mMetallicRoughnessId);
setMetalnessFactor(mat->mMetallicFactor);
setRoughnessFactor(mat->mRoughnessFactor);
setEmissiveColor(mat->mEmissiveColor);
setEmissiveId(mat->mEmissiveId);
setDoubleSided(mat->mDoubleSided);
setAlphaMode(mat->getAlphaMode());
setAlphaCutoff(mat->mAlphaCutoff);
}
bool LLMaterialEditor::setFromSelection()
{
LLSelectedTEGetMatData func(mIsOverride);
LLSelectMgr::getInstance()->getSelection()->applyToTEs(&func);
if (func.mMaterial.notNull())
{
setFromGLTFMaterial(func.mMaterial);
setEnableEditing(true);
}
else
{
// pick defaults from a blank material;
LLGLTFMaterial blank_mat;
setFromGLTFMaterial(&blank_mat);
if (mIsOverride)
{
setEnableEditing(false);
}
}
if (mIsOverride)
{
mBaseColorTextureCtrl->setTentative(!func.mIdenticalTexColor);
mMetallicTextureCtrl->setTentative(!func.mIdenticalTexMetal);
mEmissiveTextureCtrl->setTentative(!func.mIdenticalTexEmissive);
mNormalTextureCtrl->setTentative(!func.mIdenticalTexNormal);
// Memorize selection data for filtering further updates
mOverrideObjectId = func.mObjectId;
mOverrideObjectTE = func.mObjectTE;
}
return func.mMaterial.notNull();
}
void LLMaterialEditor::loadAsset()
{
const LLInventoryItem* item;
if (mNotecardInventoryID.notNull())
{
item = mAuxItem.get();
}
else
{
item = getItem();
}
bool fail = false;
if (item)
{
LLPermissions perm(item->getPermissions());
bool allow_copy = gAgent.allowOperation(PERM_COPY, perm, GP_OBJECT_MANIPULATE);
bool allow_modify = canModify(mObjectUUID, item);
bool source_library = mObjectUUID.isNull() && gInventory.isObjectDescendentOf(mItemUUID, gInventory.getLibraryRootFolderID());
setCanSaveAs(allow_copy);
setMaterialName(item->getName());
{
mAssetID = item->getAssetUUID();
if (mAssetID.isNull())
{
mAssetStatus = PREVIEW_ASSET_LOADED;
loadDefaults();
resetUnsavedChanges();
setEnableEditing(allow_modify && !source_library);
}
else
{
LLHost source_sim = LLHost();
LLSD* user_data = new LLSD();
if (mNotecardInventoryID.notNull())
{
user_data->with("objectid", mNotecardObjectID).with("notecardid", mNotecardInventoryID);
}
else if (mObjectUUID.notNull())
{
LLViewerObject* objectp = gObjectList.findObject(mObjectUUID);
if (objectp && objectp->getRegion())
{
source_sim = objectp->getRegion()->getHost();
}
else
{
// The object that we're trying to look at disappeared, bail.
LL_WARNS("MaterialEditor") << "Can't find object " << mObjectUUID << " associated with material." << LL_ENDL;
mAssetID.setNull();
mAssetStatus = PREVIEW_ASSET_LOADED;
resetUnsavedChanges();
setEnableEditing(allow_modify && !source_library);
return;
}
user_data->with("taskid", mObjectUUID).with("itemid", mItemUUID);
}
else
{
user_data = new LLSD(mItemUUID);
}
setEnableEditing(false); // wait for it to load
// request the asset.
gAssetStorage->getInvItemAsset(source_sim,
gAgent.getID(),
gAgent.getSessionID(),
item->getPermissions().getOwner(),
mObjectUUID,
item->getUUID(),
item->getAssetUUID(),
item->getType(),
&onLoadComplete,
(void*)user_data,
TRUE);
mAssetStatus = PREVIEW_ASSET_LOADING;
}
}
}
else if (mObjectUUID.notNull() && mItemUUID.notNull())
{
LLViewerObject* objectp = gObjectList.findObject(mObjectUUID);
if (objectp && (objectp->isInventoryPending() || objectp->isInventoryDirty()))
{
// It's a material in object's inventory and we failed to get it because inventory is not up to date.
// Subscribe for callback and retry at inventoryChanged()
registerVOInventoryListener(objectp, NULL); //removes previous listener
if (objectp->isInventoryDirty())
{
objectp->requestInventory();
}
}
else
{
fail = true;
}
}
else
{
fail = true;
}
if (fail)
{
/*editor->setText(LLStringUtil::null);
editor->makePristine();
editor->setEnabled(TRUE);*/
// Don't set asset status here; we may not have set the item id yet
// (e.g. when this gets called initially)
//mAssetStatus = PREVIEW_ASSET_LOADED;
}
}
// static
void LLMaterialEditor::onLoadComplete(const LLUUID& asset_uuid,
LLAssetType::EType type,
void* user_data, S32 status, LLExtStat ext_status)
{
LLSD* floater_key = (LLSD*)user_data;
LL_DEBUGS("MaterialEditor") << "loading " << asset_uuid << " for " << *floater_key << LL_ENDL;
LLMaterialEditor* editor = LLFloaterReg::findTypedInstance<LLMaterialEditor>("material_editor", *floater_key);
if (editor)
{
if (asset_uuid != editor->mAssetID)
{
LL_WARNS() << "Asset id mismatch, expected: " << editor->mAssetID << " got: " << asset_uuid << LL_ENDL;
}
if (0 == status)
{
LLFileSystem file(asset_uuid, type, LLFileSystem::READ);
S32 file_length = file.getSize();
std::vector<char> buffer(file_length + 1);
file.read((U8*)&buffer[0], file_length);
editor->decodeAsset(buffer);
BOOL allow_modify = editor->canModify(editor->mObjectUUID, editor->getItem());
BOOL source_library = editor->mObjectUUID.isNull() && gInventory.isObjectDescendentOf(editor->mItemUUID, gInventory.getLibraryRootFolderID());
editor->setEnableEditing(allow_modify && !source_library);
editor->resetUnsavedChanges();
editor->mAssetStatus = PREVIEW_ASSET_LOADED;
editor->setEnabled(true); // ready for use
}
else
{
if (LL_ERR_ASSET_REQUEST_NOT_IN_DATABASE == status ||
LL_ERR_FILE_EMPTY == status)
{
LLNotificationsUtil::add("MaterialMissing");
}
else if (LL_ERR_INSUFFICIENT_PERMISSIONS == status)
{
LLNotificationsUtil::add("MaterialNoPermissions");
}
else
{
LLNotificationsUtil::add("UnableToLoadMaterial");
}
editor->setEnableEditing(false);
LL_WARNS() << "Problem loading material: " << status << LL_ENDL;
editor->mAssetStatus = PREVIEW_ASSET_ERROR;
}
}
else
{
LL_DEBUGS("MaterialEditor") << "Floater " << *floater_key << " does not exist." << LL_ENDL;
}
delete floater_key;
}
void LLMaterialEditor::inventoryChanged(LLViewerObject* object,
LLInventoryObject::object_list_t* inventory,
S32 serial_num,
void* user_data)
{
removeVOInventoryListener();
loadAsset();
}
void LLMaterialEditor::saveTexture(LLImageJ2C* img, const std::string& name, const LLUUID& asset_id, upload_callback_f cb)
{
if (asset_id.isNull()
|| img == nullptr
|| img->getDataSize() == 0)
{
return;
}
// copy image bytes into string
std::string buffer;
buffer.assign((const char*) img->getData(), img->getDataSize());
U32 expected_upload_cost = LLAgentBenefitsMgr::current().getTextureUploadCost();
LLResourceUploadInfo::ptr_t uploadInfo(std::make_shared<LLNewBufferedResourceUploadInfo>(
buffer,
asset_id,
name,
name,
0,
LLFolderType::FT_TEXTURE,
LLInventoryType::IT_TEXTURE,
LLAssetType::AT_TEXTURE,
LLFloaterPerms::getNextOwnerPerms("Uploads"),
LLFloaterPerms::getGroupPerms("Uploads"),
LLFloaterPerms::getEveryonePerms("Uploads"),
expected_upload_cost,
false,
cb));
upload_new_resource(uploadInfo);
}
S32 LLMaterialEditor::saveTextures()
{
S32 work_count = 0;
LLSD key = getKey(); // must be locally declared for lambda's capture to work
if (mBaseColorTextureUploadId == getBaseColorId() && mBaseColorTextureUploadId.notNull())
{
mUploadingTexturesCount++;
work_count++;
saveTexture(mBaseColorJ2C, mBaseColorName, mBaseColorTextureUploadId, [key](LLUUID newAssetId, LLSD response)
{
LLMaterialEditor* me = LLFloaterReg::findTypedInstance<LLMaterialEditor>("material_editor", key);
if (me)
{
if (response["success"].asBoolean())
{
me->setBaseColorId(newAssetId);
}
else
{
// To make sure that we won't retry (some failures can cb immediately)
me->setBaseColorId(LLUUID::null);
}
me->mUploadingTexturesCount--;
// try saving
me->saveIfNeeded();
}
});
}
if (mNormalTextureUploadId == getNormalId() && mNormalTextureUploadId.notNull())
{
mUploadingTexturesCount++;
work_count++;
saveTexture(mNormalJ2C, mNormalName, mNormalTextureUploadId, [key](LLUUID newAssetId, LLSD response)
{
LLMaterialEditor* me = LLFloaterReg::findTypedInstance<LLMaterialEditor>("material_editor", key);
if (me)
{
if (response["success"].asBoolean())
{
me->setNormalId(newAssetId);
}
else
{
me->setNormalId(LLUUID::null);
}
me->setNormalId(newAssetId);
me->mUploadingTexturesCount--;
// try saving
me->saveIfNeeded();
}
});
}
if (mMetallicTextureUploadId == getMetallicRoughnessId() && mMetallicTextureUploadId.notNull())
{
mUploadingTexturesCount++;
work_count++;
saveTexture(mMetallicRoughnessJ2C, mMetallicRoughnessName, mMetallicTextureUploadId, [key](LLUUID newAssetId, LLSD response)
{
LLMaterialEditor* me = LLFloaterReg::findTypedInstance<LLMaterialEditor>("material_editor", key);
if (me)
{
if (response["success"].asBoolean())
{
me->setMetallicRoughnessId(newAssetId);
}
else
{
me->setMetallicRoughnessId(LLUUID::null);
}
me->mUploadingTexturesCount--;
// try saving
me->saveIfNeeded();
}
});
}
if (mEmissiveTextureUploadId == getEmissiveId() && mEmissiveTextureUploadId.notNull())
{
mUploadingTexturesCount++;
work_count++;
saveTexture(mEmissiveJ2C, mEmissiveName, mEmissiveTextureUploadId, [key](LLUUID newAssetId, LLSD response)
{
LLMaterialEditor* me = LLFloaterReg::findTypedInstance<LLMaterialEditor>("material_editor", LLSD(key));
if (me)
{
if (response["success"].asBoolean())
{
me->setEmissiveId(newAssetId);
}
else
{
me->setEmissiveId(LLUUID::null);
}
me->mUploadingTexturesCount--;
// try saving
me->saveIfNeeded();
}
});
}
// discard upload buffers once textures have been saved
clearTextures();
// asset storage can callback immediately, causing a decrease
// of mUploadingTexturesCount, report amount of work scheduled
// not amount of work remaining
return work_count;
}
void LLMaterialEditor::clearTextures()
{
mBaseColorJ2C = nullptr;
mNormalJ2C = nullptr;
mEmissiveJ2C = nullptr;
mMetallicRoughnessJ2C = nullptr;
mBaseColorFetched = nullptr;
mNormalFetched = nullptr;
mMetallicRoughnessFetched = nullptr;
mEmissiveFetched = nullptr;
mBaseColorTextureUploadId.setNull();
mNormalTextureUploadId.setNull();
mMetallicTextureUploadId.setNull();
mEmissiveTextureUploadId.setNull();
}
void LLMaterialEditor::loadDefaults()
{
tinygltf::Model model_in;
model_in.materials.resize(1);
setFromGltfModel(model_in, 0, true);
}
|