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
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
|
/**
* @file llmeshrepository.cpp
* @brief Mesh repository implementation.
*
* $LicenseInfo:firstyear=2005&license=viewerlgpl$
* Second Life Viewer Source Code
* Copyright (C) 2010-2014, 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 "apr_pools.h"
#include "apr_dso.h"
#include "llhttpstatuscodes.h"
#include "llmeshrepository.h"
#include "llagent.h"
#include "llappviewer.h"
#include "llbufferstream.h"
#include "llcallbacklist.h"
#include "llcurl.h"
#include "lldatapacker.h"
#include "lldeadmantimer.h"
#include "llfloatermodelpreview.h"
#include "llfloaterperms.h"
#include "lleconomy.h"
#include "llimagej2c.h"
#include "llhost.h"
#include "llmath.h"
#include "llnotificationsutil.h"
#include "llsd.h"
#include "llsdutil_math.h"
#include "llsdserialize.h"
#include "llthread.h"
#include "llvfile.h"
#include "llviewercontrol.h"
#include "llviewerinventory.h"
#include "llviewermenufile.h"
#include "llviewermessage.h"
#include "llviewerobjectlist.h"
#include "llviewerregion.h"
#include "llviewertexturelist.h"
#include "llvolume.h"
#include "llvolumemgr.h"
#include "llvovolume.h"
#include "llworld.h"
#include "material_codes.h"
#include "pipeline.h"
#include "llinventorymodel.h"
#include "llfoldertype.h"
#include "llviewerparcelmgr.h"
#include "lluploadfloaterobservers.h"
#include "bufferarray.h"
#include "bufferstream.h"
#include "llfasttimer.h"
#include "boost/lexical_cast.hpp"
#ifndef LL_WINDOWS
#include "netdb.h"
#endif
// Purpose
//
// The purpose of this module is to provide access between the viewer
// and the asset system as regards to mesh objects.
//
// * High-throughput download of mesh assets from servers while
// following best industry practices for network profile.
// * Reliable expensing and upload of new mesh assets.
// * Recovery and retry from errors when appropriate.
// * Decomposition of mesh assets for preview and uploads.
// * And most important: all of the above without exposing the
// main thread to stalls due to deep processing or thread
// locking actions. In particular, the following operations
// on LLMeshRepository are very averse to any stalls:
// * loadMesh
// * getMeshHeader (For structural details, see:
// http://wiki.secondlife.com/wiki/Mesh/Mesh_Asset_Format)
// * notifyLoadedMeshes
// * getSkinInfo
//
// Threads
//
// main Main rendering thread, very sensitive to locking and other stalls
// repo Overseeing worker thread associated with the LLMeshRepoThread class
// decom Worker thread for mesh decomposition requests
// core HTTP worker thread: does the work but doesn't intrude here
// uploadN 0-N temporary mesh upload threads (0-1 in practice)
//
// Sequence of Operations
//
// What follows is a description of the retrieval of one LOD for
// a new mesh object. Work is performed by a series of short, quick
// actions distributed over a number of threads. Each is meant
// to proceed without stalling and the whole forms a deep request
// pipeline to achieve throughput. Ellipsis indicates a return
// or break in processing which is resumed elsewhere.
//
// main thread repo thread (run() method)
//
// loadMesh() invoked to request LOD
// append LODRequest to mPendingRequests
// ...
// other mesh requests may be made
// ...
// notifyLoadedMeshes() invoked to stage work
// append HeaderRequest to mHeaderReqQ
// ...
// scan mHeaderReqQ
// issue 4096-byte GET for header
// ...
// onCompleted() invoked for GET
// data copied
// headerReceived() invoked
// LLSD parsed
// mMeshHeader, mMeshHeaderSize updated
// scan mPendingLOD for LOD request
// push LODRequest to mLODReqQ
// ...
// scan mLODReqQ
// fetchMeshLOD() invoked
// issue Byte-Range GET for LOD
// ...
// onCompleted() invoked for GET
// data copied
// lodReceived() invoked
// unpack data into LLVolume
// append LoadedMesh to mLoadedQ
// ...
// notifyLoadedMeshes() invoked again
// scan mLoadedQ
// notifyMeshLoaded() for LOD
// setMeshAssetLoaded() invoked for system volume
// notifyMeshLoaded() invoked for each interested object
// ...
//
// Mutexes
//
// LLMeshRepository::mMeshMutex
// LLMeshRepoThread::mMutex
// LLMeshRepoThread::mHeaderMutex
// LLMeshRepoThread::mSignal (LLCondition)
// LLPhysicsDecomp::mSignal (LLCondition)
// LLPhysicsDecomp::mMutex
// LLMeshUploadThread::mMutex
//
// Mutex Order Rules
//
// 1. LLMeshRepoThread::mMutex before LLMeshRepoThread::mHeaderMutex
// 2. LLMeshRepository::mMeshMutex before LLMeshRepoThread::mMutex
// (There are more rules, haven't been extracted.)
//
// Data Member Access/Locking
//
// Description of how shared access to static and instance data
// members is performed. Each member is followed by the name of
// the mutex, if any, covering the data and then a list of data
// access models each of which is a triplet of the following form:
//
// {ro, wo, rw}.{main, repo, any}.{mutex, none}
// Type of access: read-only, write-only, read-write.
// Accessing thread or 'any'
// Relevant mutex held during access (several may be held) or 'none'
//
// A careful eye will notice some unsafe operations. Many of these
// have an alibi of some form. Several types of alibi are identified
// and listed here:
//
// [0] No alibi. Probably unsafe.
// [1] Single-writer, self-consistent readers. Old data must
// be tolerated by any reader but data will come true eventually.
// [2] Like [1] but provides a hint about thread state. These
// may be unsafe.
// [3] empty() check outside of lock. Can me made safish when
// done in double-check lock style. But this depends on
// std:: implementation and memory model.
// [4] Appears to be covered by a mutex but doesn't need one.
// [5] Read of a double-checked lock.
//
// So, in addition to documentation, take this as a to-do/review
// list and see if you can improve things. For porters to non-x86
// architectures, the weaker memory models will make these platforms
// probabilistically more susceptible to hitting race conditions.
// True here and in other multi-thread code such as texture fetching.
// (Strong memory models make weak programmers. Weak memory models
// make strong programmers. Ref: arm, ppc, mips, alpha)
//
// LLMeshRepository:
//
// sBytesReceived none rw.repo.none, ro.main.none [1]
// sMeshRequestCount "
// sHTTPRequestCount "
// sHTTPLargeRequestCount "
// sHTTPRetryCount "
// sHTTPErrorCount "
// sLODPending mMeshMutex [4] rw.main.mMeshMutex
// sLODProcessing Repo::mMutex rw.any.Repo::mMutex
// sCacheBytesRead none rw.repo.none, ro.main.none [1]
// sCacheBytesWritten "
// sCacheReads "
// sCacheWrites "
// mLoadingMeshes mMeshMutex [4] rw.main.none, rw.any.mMeshMutex
// mSkinMap none rw.main.none
// mDecompositionMap none rw.main.none
// mPendingRequests mMeshMutex [4] rw.main.mMeshMutex
// mLoadingSkins mMeshMutex [4] rw.main.mMeshMutex
// mPendingSkinRequests mMeshMutex [4] rw.main.mMeshMutex
// mLoadingDecompositions mMeshMutex [4] rw.main.mMeshMutex
// mPendingDecompositionRequests mMeshMutex [4] rw.main.mMeshMutex
// mLoadingPhysicsShapes mMeshMutex [4] rw.main.mMeshMutex
// mPendingPhysicsShapeRequests mMeshMutex [4] rw.main.mMeshMutex
// mUploads none rw.main.none (upload thread accessing objects)
// mUploadWaitList none rw.main.none (upload thread accessing objects)
// mInventoryQ mMeshMutex [4] rw.main.mMeshMutex, ro.main.none [5]
// mUploadErrorQ mMeshMutex rw.main.mMeshMutex, rw.any.mMeshMutex
// mGetMeshVersion none rw.main.none
//
// LLMeshRepoThread:
//
// sActiveHeaderRequests mMutex rw.any.mMutex, ro.repo.none [1]
// sActiveLODRequests mMutex rw.any.mMutex, ro.repo.none [1]
// sMaxConcurrentRequests mMutex wo.main.none, ro.repo.none, ro.main.mMutex
// mMeshHeader mHeaderMutex rw.repo.mHeaderMutex, ro.main.mHeaderMutex, ro.main.none [0]
// mMeshHeaderSize mHeaderMutex rw.repo.mHeaderMutex
// mSkinRequests mMutex rw.repo.mMutex, ro.repo.none [5]
// mSkinInfoQ mMutex rw.repo.mMutex, rw.main.mMutex [5] (was: [0])
// mDecompositionRequests mMutex rw.repo.mMutex, ro.repo.none [5]
// mPhysicsShapeRequests mMutex rw.repo.mMutex, ro.repo.none [5]
// mDecompositionQ mMutex rw.repo.mMutex, rw.main.mMutex [5] (was: [0])
// mHeaderReqQ mMutex ro.repo.none [5], rw.repo.mMutex, rw.any.mMutex
// mLODReqQ mMutex ro.repo.none [5], rw.repo.mMutex, rw.any.mMutex
// mUnavailableQ mMutex rw.repo.none [0], ro.main.none [5], rw.main.mMutex
// mLoadedQ mMutex rw.repo.mMutex, ro.main.none [5], rw.main.mMutex
// mPendingLOD mMutex rw.repo.mMutex, rw.any.mMutex
// mGetMeshCapability mMutex rw.main.mMutex, ro.repo.mMutex (was: [0])
// mGetMesh2Capability mMutex rw.main.mMutex, ro.repo.mMutex (was: [0])
// mGetMeshVersion mMutex rw.main.mMutex, ro.repo.mMutex
// mHttp* none rw.repo.none
//
// LLMeshUploadThread:
//
// mDiscarded mMutex rw.main.mMutex, ro.uploadN.none [1]
// ... more ...
//
// QA/Development Testing
//
// Debug variable 'MeshUploadFakeErrors' takes a mask of bits that will
// simulate an error on fee query or upload. Defined bits are:
//
// 0x01 Simulate application error on fee check reading
// response body from file "fake_upload_error.xml"
// 0x02 Same as 0x01 but for actual upload attempt.
// 0x04 Simulate a transport problem on fee check with a
// locally-generated 500 status.
// 0x08 As with 0x04 but for the upload operation.
//
// For major changes, see the LL_MESH_FASTTIMER_ENABLE below and
// instructions for looking for frame stalls using fast timers.
//
// *TODO: Work list for followup actions:
// * Review anything marked as unsafe above, verify if there are real issues.
// * See if we can put ::run() into a hard sleep. May not actually perform better
// than the current scheme so be prepared for disappointment. You'll likely
// need to introduce a condition variable class that references a mutex in
// methods rather than derives from mutex which isn't correct.
// * On upload failures, make more information available to the alerting
// dialog. Get the structured information going into the log into a
// tree there.
// * Header parse failures come without much explanation. Elaborate.
// * Work queue for uploads? Any need for this or is the current scheme good
// enough?
// * Various temp buffers used in VFS I/O might be allocated once or even
// statically. Look for some wins here.
// * Move data structures holding mesh data used by main thread into main-
// thread-only access so that no locking is needed. May require duplication
// of some data so that worker thread has a minimal data set to guide
// operations.
//
// --------------------------------------------------------------------------
// Development/Debug/QA Tools
//
// Enable here or in build environment to get fasttimer data on mesh fetches.
//
// Typically, this is used to perform A/B testing using the
// fasttimer console (shift-ctrl-9). This is done by looking
// for stalls due to lock contention between the main thread
// and the repository and HTTP code. In a release viewer,
// these appear as ping-time or worse spikes in frame time.
// With this instrumentation enabled, a stall will appear
// under the 'Mesh Fetch' timer which will be either top-level
// or under 'Render' time.
#ifndef LL_MESH_FASTTIMER_ENABLE
#define LL_MESH_FASTTIMER_ENABLE 1
#endif
#if LL_MESH_FASTTIMER_ENABLE
static LLFastTimer::DeclareTimer FTM_MESH_FETCH("Mesh Fetch");
#define MESH_FASTTIMER_DEFBLOCK LLFastTimer meshtimer(FTM_MESH_FETCH)
#else
#define MESH_FASTTIMER_DEFBLOCK
#endif // LL_MESH_FASTTIMER_ENABLE
// Random failure testing for development/QA.
//
// Set the MESH_*_FAILED macros to either 'false' or to
// an invocation of MESH_RANDOM_NTH_TRUE() with some
// suitable number. In production, all must be false.
//
// Example:
// #define MESH_HTTP_RESPONSE_FAILED MESH_RANDOM_NTH_TRUE(9)
// 1-in-N calls will test true
#define MESH_RANDOM_NTH_TRUE(_N) ( ll_rand(S32(_N)) == 0 )
#define MESH_HTTP_RESPONSE_FAILED false
#define MESH_HEADER_PROCESS_FAILED false
#define MESH_LOD_PROCESS_FAILED false
#define MESH_SKIN_INFO_PROCESS_FAILED false
#define MESH_DECOMP_PROCESS_FAILED false
#define MESH_PHYS_SHAPE_PROCESS_FAILED false
// --------------------------------------------------------------------------
LLMeshRepository gMeshRepo;
const S32 MESH_HEADER_SIZE = 4096; // Important: assumption is that headers fit in this space
const S32 REQUEST_HIGH_WATER_MIN = 32; // Limits for GetMesh regions
const S32 REQUEST_HIGH_WATER_MAX = 150; // Should remain under 2X throttle
const S32 REQUEST_LOW_WATER_MIN = 16;
const S32 REQUEST_LOW_WATER_MAX = 75;
const S32 REQUEST2_HIGH_WATER_MIN = 32; // Limits for GetMesh2 regions
const S32 REQUEST2_HIGH_WATER_MAX = 80;
const S32 REQUEST2_LOW_WATER_MIN = 16;
const S32 REQUEST2_LOW_WATER_MAX = 40;
const U32 LARGE_MESH_FETCH_THRESHOLD = 1U << 21; // Size at which requests goes to narrow/slow queue
const long SMALL_MESH_XFER_TIMEOUT = 120L; // Seconds to complete xfer, small mesh downloads
const long LARGE_MESH_XFER_TIMEOUT = 600L; // Seconds to complete xfer, large downloads
// Would normally like to retry on uploads as some
// retryable failures would be recoverable. Unfortunately,
// the mesh service is using 500 (retryable) rather than
// 400/bad request (permanent) for a bad payload and
// retrying that just leads to revocation of the one-shot
// cap which then produces a 404 on retry destroying some
// (occasionally) useful error information. We'll leave
// upload retries to the user as in the past. SH-4667.
const long UPLOAD_RETRY_LIMIT = 0L;
// Maximum mesh version to support. Three least significant digits are reserved for the minor version,
// with major version changes indicating a format change that is not backwards compatible and should not
// be parsed by viewers that don't specifically support that version. For example, if the integer "1" is
// present, the version is 0.001. A viewer that can parse version 0.001 can also parse versions up to 0.999,
// but not 1.0 (integer 1000).
// See wiki at https://wiki.secondlife.com/wiki/Mesh/Mesh_Asset_Format
const S32 MAX_MESH_VERSION = 999;
U32 LLMeshRepository::sBytesReceived = 0;
U32 LLMeshRepository::sMeshRequestCount = 0;
U32 LLMeshRepository::sHTTPRequestCount = 0;
U32 LLMeshRepository::sHTTPLargeRequestCount = 0;
U32 LLMeshRepository::sHTTPRetryCount = 0;
U32 LLMeshRepository::sHTTPErrorCount = 0;
U32 LLMeshRepository::sLODProcessing = 0;
U32 LLMeshRepository::sLODPending = 0;
U32 LLMeshRepository::sCacheBytesRead = 0;
U32 LLMeshRepository::sCacheBytesWritten = 0;
U32 LLMeshRepository::sCacheReads = 0;
U32 LLMeshRepository::sCacheWrites = 0;
U32 LLMeshRepository::sMaxLockHoldoffs = 0;
LLDeadmanTimer LLMeshRepository::sQuiescentTimer(15.0, false); // true -> gather cpu metrics
static S32 dump_num = 0;
std::string make_dump_name(std::string prefix, S32 num)
{
return prefix + boost::lexical_cast<std::string>(num) + std::string(".xml");
}
void dump_llsd_to_file(const LLSD& content, std::string filename);
LLSD llsd_from_file(std::string filename);
const std::string header_lod[] =
{
"lowest_lod",
"low_lod",
"medium_lod",
"high_lod"
};
const char * const LOG_MESH = "Mesh";
// Static data and functions to measure mesh load
// time metrics for a new region scene.
static unsigned int metrics_teleport_start_count = 0;
boost::signals2::connection metrics_teleport_started_signal;
static void teleport_started();
//get the number of bytes resident in memory for given volume
U32 get_volume_memory_size(const LLVolume* volume)
{
U32 indices = 0;
U32 vertices = 0;
for (U32 i = 0; i < volume->getNumVolumeFaces(); ++i)
{
const LLVolumeFace& face = volume->getVolumeFace(i);
indices += face.mNumIndices;
vertices += face.mNumVertices;
}
return indices*2+vertices*11+sizeof(LLVolume)+sizeof(LLVolumeFace)*volume->getNumVolumeFaces();
}
void get_vertex_buffer_from_mesh(LLCDMeshData& mesh, LLModel::PhysicsMesh& res, F32 scale = 1.f)
{
res.mPositions.clear();
res.mNormals.clear();
const F32* v = mesh.mVertexBase;
if (mesh.mIndexType == LLCDMeshData::INT_16)
{
U16* idx = (U16*) mesh.mIndexBase;
for (S32 j = 0; j < mesh.mNumTriangles; ++j)
{
F32* mp0 = (F32*) ((U8*)v+idx[0]*mesh.mVertexStrideBytes);
F32* mp1 = (F32*) ((U8*)v+idx[1]*mesh.mVertexStrideBytes);
F32* mp2 = (F32*) ((U8*)v+idx[2]*mesh.mVertexStrideBytes);
idx = (U16*) (((U8*)idx)+mesh.mIndexStrideBytes);
LLVector3 v0(mp0);
LLVector3 v1(mp1);
LLVector3 v2(mp2);
LLVector3 n = (v1-v0)%(v2-v0);
n.normalize();
res.mPositions.push_back(v0*scale);
res.mPositions.push_back(v1*scale);
res.mPositions.push_back(v2*scale);
res.mNormals.push_back(n);
res.mNormals.push_back(n);
res.mNormals.push_back(n);
}
}
else
{
U32* idx = (U32*) mesh.mIndexBase;
for (S32 j = 0; j < mesh.mNumTriangles; ++j)
{
F32* mp0 = (F32*) ((U8*)v+idx[0]*mesh.mVertexStrideBytes);
F32* mp1 = (F32*) ((U8*)v+idx[1]*mesh.mVertexStrideBytes);
F32* mp2 = (F32*) ((U8*)v+idx[2]*mesh.mVertexStrideBytes);
idx = (U32*) (((U8*)idx)+mesh.mIndexStrideBytes);
LLVector3 v0(mp0);
LLVector3 v1(mp1);
LLVector3 v2(mp2);
LLVector3 n = (v1-v0)%(v2-v0);
n.normalize();
res.mPositions.push_back(v0*scale);
res.mPositions.push_back(v1*scale);
res.mPositions.push_back(v2*scale);
res.mNormals.push_back(n);
res.mNormals.push_back(n);
res.mNormals.push_back(n);
}
}
}
volatile S32 LLMeshRepoThread::sActiveHeaderRequests = 0;
volatile S32 LLMeshRepoThread::sActiveLODRequests = 0;
U32 LLMeshRepoThread::sMaxConcurrentRequests = 1;
S32 LLMeshRepoThread::sRequestLowWater = REQUEST2_LOW_WATER_MIN;
S32 LLMeshRepoThread::sRequestHighWater = REQUEST2_HIGH_WATER_MIN;
S32 LLMeshRepoThread::sRequestWaterLevel = 0;
// Base handler class for all mesh users of llcorehttp.
// This is roughly equivalent to a Responder class in
// traditional LL code. The base is going to perform
// common response/data handling in the inherited
// onCompleted() method. Derived classes, one for each
// type of HTTP action, define processData() and
// processFailure() methods to customize handling and
// error messages.
//
// LLCore::HttpHandler
// LLMeshHandlerBase
// LLMeshHeaderHandler
// LLMeshLODHandler
// LLMeshSkinInfoHandler
// LLMeshDecompositionHandler
// LLMeshPhysicsShapeHandler
// LLMeshUploadThread
class LLMeshHandlerBase : public LLCore::HttpHandler
{
public:
LLMeshHandlerBase()
: LLCore::HttpHandler(),
mMeshParams(),
mProcessed(false),
mHttpHandle(LLCORE_HTTP_HANDLE_INVALID)
{}
virtual ~LLMeshHandlerBase()
{}
protected:
LLMeshHandlerBase(const LLMeshHandlerBase &); // Not defined
void operator=(const LLMeshHandlerBase &); // Not defined
public:
virtual void onCompleted(LLCore::HttpHandle handle, LLCore::HttpResponse * response);
virtual void processData(LLCore::BufferArray * body, U8 * data, S32 data_size) = 0;
virtual void processFailure(LLCore::HttpStatus status) = 0;
public:
LLVolumeParams mMeshParams;
bool mProcessed;
LLCore::HttpHandle mHttpHandle;
};
// Subclass for header fetches.
//
// Thread: repo
class LLMeshHeaderHandler : public LLMeshHandlerBase
{
public:
LLMeshHeaderHandler(const LLVolumeParams & mesh_params)
: LLMeshHandlerBase()
{
mMeshParams = mesh_params;
LLMeshRepoThread::incActiveHeaderRequests();
}
virtual ~LLMeshHeaderHandler();
protected:
LLMeshHeaderHandler(const LLMeshHeaderHandler &); // Not defined
void operator=(const LLMeshHeaderHandler &); // Not defined
public:
virtual void processData(LLCore::BufferArray * body, U8 * data, S32 data_size);
virtual void processFailure(LLCore::HttpStatus status);
};
// Subclass for LOD fetches.
//
// Thread: repo
class LLMeshLODHandler : public LLMeshHandlerBase
{
public:
LLMeshLODHandler(const LLVolumeParams & mesh_params, S32 lod, U32 offset, U32 requested_bytes)
: LLMeshHandlerBase(),
mLOD(lod),
mRequestedBytes(requested_bytes),
mOffset(offset)
{
mMeshParams = mesh_params;
LLMeshRepoThread::incActiveLODRequests();
}
virtual ~LLMeshLODHandler();
protected:
LLMeshLODHandler(const LLMeshLODHandler &); // Not defined
void operator=(const LLMeshLODHandler &); // Not defined
public:
virtual void processData(LLCore::BufferArray * body, U8 * data, S32 data_size);
virtual void processFailure(LLCore::HttpStatus status);
public:
S32 mLOD;
U32 mRequestedBytes;
U32 mOffset;
};
// Subclass for skin info fetches.
//
// Thread: repo
class LLMeshSkinInfoHandler : public LLMeshHandlerBase
{
public:
LLMeshSkinInfoHandler(const LLUUID& id, U32 offset, U32 size)
: LLMeshHandlerBase(),
mMeshID(id),
mRequestedBytes(size),
mOffset(offset)
{}
virtual ~LLMeshSkinInfoHandler();
protected:
LLMeshSkinInfoHandler(const LLMeshSkinInfoHandler &); // Not defined
void operator=(const LLMeshSkinInfoHandler &); // Not defined
public:
virtual void processData(LLCore::BufferArray * body, U8 * data, S32 data_size);
virtual void processFailure(LLCore::HttpStatus status);
public:
LLUUID mMeshID;
U32 mRequestedBytes;
U32 mOffset;
};
// Subclass for decomposition fetches.
//
// Thread: repo
class LLMeshDecompositionHandler : public LLMeshHandlerBase
{
public:
LLMeshDecompositionHandler(const LLUUID& id, U32 offset, U32 size)
: LLMeshHandlerBase(),
mMeshID(id),
mRequestedBytes(size),
mOffset(offset)
{}
virtual ~LLMeshDecompositionHandler();
protected:
LLMeshDecompositionHandler(const LLMeshDecompositionHandler &); // Not defined
void operator=(const LLMeshDecompositionHandler &); // Not defined
public:
virtual void processData(LLCore::BufferArray * body, U8 * data, S32 data_size);
virtual void processFailure(LLCore::HttpStatus status);
public:
LLUUID mMeshID;
U32 mRequestedBytes;
U32 mOffset;
};
// Subclass for physics shape fetches.
//
// Thread: repo
class LLMeshPhysicsShapeHandler : public LLMeshHandlerBase
{
public:
LLMeshPhysicsShapeHandler(const LLUUID& id, U32 offset, U32 size)
: LLMeshHandlerBase(),
mMeshID(id),
mRequestedBytes(size),
mOffset(offset)
{}
virtual ~LLMeshPhysicsShapeHandler();
protected:
LLMeshPhysicsShapeHandler(const LLMeshPhysicsShapeHandler &); // Not defined
void operator=(const LLMeshPhysicsShapeHandler &); // Not defined
public:
virtual void processData(LLCore::BufferArray * body, U8 * data, S32 data_size);
virtual void processFailure(LLCore::HttpStatus status);
public:
LLUUID mMeshID;
U32 mRequestedBytes;
U32 mOffset;
};
void log_upload_error(LLCore::HttpStatus status, const LLSD& content,
const char * const stage, const std::string & model_name)
{
// Add notification popup.
LLSD args;
std::string message = content["error"]["message"].asString();
std::string identifier = content["error"]["identifier"].asString();
args["MESSAGE"] = message;
args["IDENTIFIER"] = identifier;
args["LABEL"] = model_name;
gMeshRepo.uploadError(args);
// Log details.
LL_WARNS(LOG_MESH) << "Error in stage: " << stage
<< ", Reason: " << status.toString()
<< " (" << status.toTerseString() << ")" << LL_ENDL;
if (content.has("error"))
{
const LLSD& err = content["error"];
LL_WARNS(LOG_MESH) << "error: " << err << LL_ENDL;
LL_WARNS(LOG_MESH) << " mesh upload failed, stage '" << stage
<< "', error '" << err["error"].asString()
<< "', message '" << err["message"].asString()
<< "', id '" << err["identifier"].asString()
<< "'" << LL_ENDL;
if (err.has("errors"))
{
S32 error_num = 0;
const LLSD& err_list = err["errors"];
for (LLSD::array_const_iterator it = err_list.beginArray();
it != err_list.endArray();
++it)
{
const LLSD& err_entry = *it;
LL_WARNS(LOG_MESH) << " error[" << error_num << "]:" << LL_ENDL;
for (LLSD::map_const_iterator map_it = err_entry.beginMap();
map_it != err_entry.endMap();
++map_it)
{
LL_WARNS(LOG_MESH) << " " << map_it->first << ": "
<< map_it->second << LL_ENDL;
}
error_num++;
}
}
}
else
{
LL_WARNS(LOG_MESH) << "Bad response to mesh request, no additional error information available." << LL_ENDL;
}
}
LLMeshRepoThread::LLMeshRepoThread()
: LLThread("mesh repo"),
mHttpRequest(NULL),
mHttpOptions(NULL),
mHttpLargeOptions(NULL),
mHttpHeaders(NULL),
mHttpPolicyClass(LLCore::HttpRequest::DEFAULT_POLICY_ID),
mHttpLegacyPolicyClass(LLCore::HttpRequest::DEFAULT_POLICY_ID),
mHttpLargePolicyClass(LLCore::HttpRequest::DEFAULT_POLICY_ID),
mHttpPriority(0),
mGetMeshVersion(2)
{
mMutex = new LLMutex(NULL);
mHeaderMutex = new LLMutex(NULL);
mSignal = new LLCondition(NULL);
mHttpRequest = new LLCore::HttpRequest;
mHttpOptions = new LLCore::HttpOptions;
mHttpOptions->setTransferTimeout(SMALL_MESH_XFER_TIMEOUT);
mHttpOptions->setUseRetryAfter(gSavedSettings.getBOOL("MeshUseHttpRetryAfter"));
mHttpLargeOptions = new LLCore::HttpOptions;
mHttpLargeOptions->setTransferTimeout(LARGE_MESH_XFER_TIMEOUT);
mHttpLargeOptions->setUseRetryAfter(gSavedSettings.getBOOL("MeshUseHttpRetryAfter"));
mHttpHeaders = new LLCore::HttpHeaders;
mHttpHeaders->append("Accept", "application/vnd.ll.mesh");
mHttpPolicyClass = LLAppViewer::instance()->getAppCoreHttp().getPolicy(LLAppCoreHttp::AP_MESH2);
mHttpLegacyPolicyClass = LLAppViewer::instance()->getAppCoreHttp().getPolicy(LLAppCoreHttp::AP_MESH1);
mHttpLargePolicyClass = LLAppViewer::instance()->getAppCoreHttp().getPolicy(LLAppCoreHttp::AP_LARGE_MESH);
}
LLMeshRepoThread::~LLMeshRepoThread()
{
LL_INFOS(LOG_MESH) << "Small GETs issued: " << LLMeshRepository::sHTTPRequestCount
<< ", Large GETs issued: " << LLMeshRepository::sHTTPLargeRequestCount
<< ", Max Lock Holdoffs: " << LLMeshRepository::sMaxLockHoldoffs
<< LL_ENDL;
for (http_request_set::iterator iter(mHttpRequestSet.begin());
iter != mHttpRequestSet.end();
++iter)
{
delete *iter;
}
mHttpRequestSet.clear();
if (mHttpHeaders)
{
mHttpHeaders->release();
mHttpHeaders = NULL;
}
if (mHttpOptions)
{
mHttpOptions->release();
mHttpOptions = NULL;
}
if (mHttpLargeOptions)
{
mHttpLargeOptions->release();
mHttpLargeOptions = NULL;
}
delete mHttpRequest;
mHttpRequest = NULL;
delete mMutex;
mMutex = NULL;
delete mHeaderMutex;
mHeaderMutex = NULL;
delete mSignal;
mSignal = NULL;
}
void LLMeshRepoThread::run()
{
LLCDResult res = LLConvexDecomposition::initThread();
if (res != LLCD_OK)
{
LL_WARNS(LOG_MESH) << "Convex decomposition unable to be loaded. Expect severe problems." << LL_ENDL;
}
while (!LLApp::isQuitting())
{
// *TODO: Revise sleep/wake strategy and try to move away
// from polling operations in this thread. We can sleep
// this thread hard when:
// * All Http requests are serviced
// * LOD request queue empty
// * Header request queue empty
// * Skin info request queue empty
// * Decomposition request queue empty
// * Physics shape request queue empty
// We wake the thread when any of the above become untrue.
// Will likely need a correctly-implemented condition variable to do this.
// On the other hand, this may actually be an effective and efficient scheme...
mSignal->wait();
if (LLApp::isQuitting())
{
break;
}
if (! mHttpRequestSet.empty())
{
// Dispatch all HttpHandler notifications
mHttpRequest->update(0L);
}
sRequestWaterLevel = mHttpRequestSet.size(); // Stats data update
// NOTE: order of queue processing intentionally favors LOD requests over header requests
while (!mLODReqQ.empty() && mHttpRequestSet.size() < sRequestHighWater)
{
if (! mMutex)
{
break;
}
mMutex->lock();
LODRequest req = mLODReqQ.front();
mLODReqQ.pop();
LLMeshRepository::sLODProcessing--;
mMutex->unlock();
if (!fetchMeshLOD(req.mMeshParams, req.mLOD)) // failed, resubmit
{
mMutex->lock();
mLODReqQ.push(req) ;
++LLMeshRepository::sLODProcessing;
mMutex->unlock();
}
}
while (!mHeaderReqQ.empty() && mHttpRequestSet.size() < sRequestHighWater)
{
if (! mMutex)
{
break;
}
mMutex->lock();
HeaderRequest req = mHeaderReqQ.front();
mHeaderReqQ.pop();
mMutex->unlock();
if (!fetchMeshHeader(req.mMeshParams))//failed, resubmit
{
mMutex->lock();
mHeaderReqQ.push(req) ;
mMutex->unlock();
}
}
// For the final three request lists, similar goal to above but
// slightly different queue structures. Stay off the mutex when
// performing long-duration actions.
if (mHttpRequestSet.size() < sRequestHighWater
&& (! mSkinRequests.empty()
|| ! mDecompositionRequests.empty()
|| ! mPhysicsShapeRequests.empty()))
{
// Something to do probably, lock and double-check. We don't want
// to hold the lock long here. That will stall main thread activities
// so we bounce it.
mMutex->lock();
if (! mSkinRequests.empty() && mHttpRequestSet.size() < sRequestHighWater)
{
std::set<LLUUID> incomplete;
std::set<LLUUID>::iterator iter(mSkinRequests.begin());
while (iter != mSkinRequests.end() && mHttpRequestSet.size() < sRequestHighWater)
{
LLUUID mesh_id = *iter;
mSkinRequests.erase(iter);
mMutex->unlock();
if (! fetchMeshSkinInfo(mesh_id))
{
incomplete.insert(mesh_id);
}
mMutex->lock();
iter = mSkinRequests.begin();
}
if (! incomplete.empty())
{
mSkinRequests.insert(incomplete.begin(), incomplete.end());
}
}
// holding lock, try next list
// *TODO: For UI/debug-oriented lists, we might drop the fine-
// grained locking as there's a lowered expectation of smoothness
// in these cases.
if (! mDecompositionRequests.empty() && mHttpRequestSet.size() < sRequestHighWater)
{
std::set<LLUUID> incomplete;
std::set<LLUUID>::iterator iter(mDecompositionRequests.begin());
while (iter != mDecompositionRequests.end() && mHttpRequestSet.size() < sRequestHighWater)
{
LLUUID mesh_id = *iter;
mDecompositionRequests.erase(iter);
mMutex->unlock();
if (! fetchMeshDecomposition(mesh_id))
{
incomplete.insert(mesh_id);
}
mMutex->lock();
iter = mDecompositionRequests.begin();
}
if (! incomplete.empty())
{
mDecompositionRequests.insert(incomplete.begin(), incomplete.end());
}
}
// holding lock, final list
if (! mPhysicsShapeRequests.empty() && mHttpRequestSet.size() < sRequestHighWater)
{
std::set<LLUUID> incomplete;
std::set<LLUUID>::iterator iter(mPhysicsShapeRequests.begin());
while (iter != mPhysicsShapeRequests.end() && mHttpRequestSet.size() < sRequestHighWater)
{
LLUUID mesh_id = *iter;
mPhysicsShapeRequests.erase(iter);
mMutex->unlock();
if (! fetchMeshPhysicsShape(mesh_id))
{
incomplete.insert(mesh_id);
}
mMutex->lock();
iter = mPhysicsShapeRequests.begin();
}
if (! incomplete.empty())
{
mPhysicsShapeRequests.insert(incomplete.begin(), incomplete.end());
}
}
mMutex->unlock();
}
// For dev purposes only. A dynamic change could make this false
// and that shouldn't assert.
// llassert_always(mHttpRequestSet.size() <= sRequestHighWater);
}
if (mSignal->isLocked())
{ //make sure to let go of the mutex associated with the given signal before shutting down
mSignal->unlock();
}
res = LLConvexDecomposition::quitThread();
if (res != LLCD_OK)
{
LL_WARNS(LOG_MESH) << "Convex decomposition unable to be quit." << LL_ENDL;
}
}
// Mutex: LLMeshRepoThread::mMutex must be held on entry
void LLMeshRepoThread::loadMeshSkinInfo(const LLUUID& mesh_id)
{
mSkinRequests.insert(mesh_id);
}
// Mutex: LLMeshRepoThread::mMutex must be held on entry
void LLMeshRepoThread::loadMeshDecomposition(const LLUUID& mesh_id)
{
mDecompositionRequests.insert(mesh_id);
}
// Mutex: LLMeshRepoThread::mMutex must be held on entry
void LLMeshRepoThread::loadMeshPhysicsShape(const LLUUID& mesh_id)
{
mPhysicsShapeRequests.insert(mesh_id);
}
void LLMeshRepoThread::lockAndLoadMeshLOD(const LLVolumeParams& mesh_params, S32 lod)
{
if (!LLAppViewer::isQuitting())
{
loadMeshLOD(mesh_params, lod);
}
}
void LLMeshRepoThread::loadMeshLOD(const LLVolumeParams& mesh_params, S32 lod)
{ //could be called from any thread
LLMutexLock lock(mMutex);
mesh_header_map::iterator iter = mMeshHeader.find(mesh_params.getSculptID());
if (iter != mMeshHeader.end())
{ //if we have the header, request LOD byte range
LODRequest req(mesh_params, lod);
{
mLODReqQ.push(req);
LLMeshRepository::sLODProcessing++;
}
}
else
{
HeaderRequest req(mesh_params);
pending_lod_map::iterator pending = mPendingLOD.find(mesh_params);
if (pending != mPendingLOD.end())
{ //append this lod request to existing header request
pending->second.push_back(lod);
llassert(pending->second.size() <= LLModel::NUM_LODS)
}
else
{ //if no header request is pending, fetch header
mHeaderReqQ.push(req);
mPendingLOD[mesh_params].push_back(lod);
}
}
}
// Mutex: must be holding mMutex when called
void LLMeshRepoThread::setGetMeshCaps(const std::string & get_mesh1,
const std::string & get_mesh2,
int pref_version)
{
mGetMeshCapability = get_mesh1;
mGetMesh2Capability = get_mesh2;
mGetMeshVersion = pref_version;
}
// Constructs a Cap URL for the mesh. Prefers a GetMesh2 cap
// over a GetMesh cap.
//
// Mutex: acquires mMutex
void LLMeshRepoThread::constructUrl(LLUUID mesh_id, std::string * url, int * version)
{
std::string res_url;
int res_version(2);
if (gAgent.getRegion())
{
LLMutexLock lock(mMutex);
// Get a consistent pair of (cap string, version). The
// locking could be eliminated here without loss of safety
// by using a set of staging values in setGetMeshCaps().
if (! mGetMesh2Capability.empty() && mGetMeshVersion > 1)
{
res_url = mGetMesh2Capability;
res_version = 2;
}
else
{
res_url = mGetMeshCapability;
res_version = 1;
}
}
if (! res_url.empty())
{
res_url += "/?mesh_id=";
res_url += mesh_id.asString().c_str();
}
else
{
LL_WARNS_ONCE(LOG_MESH) << "Current region does not have GetMesh capability! Cannot load "
<< mesh_id << ".mesh" << LL_ENDL;
}
*url = res_url;
*version = res_version;
}
// Issue an HTTP GET request with byte range using the right
// policy class. Large requests go to the large request class.
// If the current region supports GetMesh2, we prefer that for
// smaller requests otherwise we try to use the traditional
// GetMesh capability and connection concurrency.
//
// @return Valid handle or LLCORE_HTTP_HANDLE_INVALID.
// If the latter, actual status is found in
// mHttpStatus member which is valid until the
// next call to this method.
//
// Thread: repo
LLCore::HttpHandle LLMeshRepoThread::getByteRange(const std::string & url, int cap_version,
size_t offset, size_t len,
LLCore::HttpHandler * handler)
{
LLCore::HttpHandle handle(LLCORE_HTTP_HANDLE_INVALID);
if (len < LARGE_MESH_FETCH_THRESHOLD)
{
handle = mHttpRequest->requestGetByteRange((2 == cap_version
? mHttpPolicyClass
: mHttpLegacyPolicyClass),
mHttpPriority,
url,
offset,
len,
mHttpOptions,
mHttpHeaders,
handler);
if (LLCORE_HTTP_HANDLE_INVALID != handle)
{
++LLMeshRepository::sHTTPRequestCount;
}
}
else
{
handle = mHttpRequest->requestGetByteRange(mHttpLargePolicyClass,
mHttpPriority,
url,
offset,
len,
mHttpLargeOptions,
mHttpHeaders,
handler);
if (LLCORE_HTTP_HANDLE_INVALID != handle)
{
++LLMeshRepository::sHTTPLargeRequestCount;
}
}
if (LLCORE_HTTP_HANDLE_INVALID == handle)
{
// Something went wrong, capture the error code for caller.
mHttpStatus = mHttpRequest->getStatus();
}
return handle;
}
bool LLMeshRepoThread::fetchMeshSkinInfo(const LLUUID& mesh_id)
{
if (!mHeaderMutex)
{
return false;
}
mHeaderMutex->lock();
if (mMeshHeader.find(mesh_id) == mMeshHeader.end())
{ //we have no header info for this mesh, do nothing
mHeaderMutex->unlock();
return false;
}
++LLMeshRepository::sMeshRequestCount;
bool ret = true;
U32 header_size = mMeshHeaderSize[mesh_id];
if (header_size > 0)
{
S32 version = mMeshHeader[mesh_id]["version"].asInteger();
S32 offset = header_size + mMeshHeader[mesh_id]["skin"]["offset"].asInteger();
S32 size = mMeshHeader[mesh_id]["skin"]["size"].asInteger();
mHeaderMutex->unlock();
if (version <= MAX_MESH_VERSION && offset >= 0 && size > 0)
{
//check VFS for mesh skin info
LLVFile file(gVFS, mesh_id, LLAssetType::AT_MESH);
if (file.getSize() >= offset+size)
{
LLMeshRepository::sCacheBytesRead += size;
++LLMeshRepository::sCacheReads;
file.seek(offset);
U8* buffer = new U8[size];
file.read(buffer, size);
//make sure buffer isn't all 0's by checking the first 1KB (reserved block but not written)
bool zero = true;
for (S32 i = 0; i < llmin(size, 1024) && zero; ++i)
{
zero = buffer[i] > 0 ? false : true;
}
if (!zero)
{ //attempt to parse
if (skinInfoReceived(mesh_id, buffer, size))
{
delete[] buffer;
return true;
}
}
delete[] buffer;
}
//reading from VFS failed for whatever reason, fetch from sim
int cap_version(2);
std::string http_url;
constructUrl(mesh_id, &http_url, &cap_version);
if (!http_url.empty())
{
LLMeshSkinInfoHandler * handler = new LLMeshSkinInfoHandler(mesh_id, offset, size);
LLCore::HttpHandle handle = getByteRange(http_url, cap_version, offset, size, handler);
if (LLCORE_HTTP_HANDLE_INVALID == handle)
{
LL_WARNS(LOG_MESH) << "HTTP GET request failed for skin info on mesh " << mID
<< ". Reason: " << mHttpStatus.toString()
<< " (" << mHttpStatus.toTerseString() << ")"
<< LL_ENDL;
delete handler;
ret = false;
}
else
{
handler->mHttpHandle = handle;
mHttpRequestSet.insert(handler);
}
}
}
}
else
{
mHeaderMutex->unlock();
}
//early out was not hit, effectively fetched
return ret;
}
bool LLMeshRepoThread::fetchMeshDecomposition(const LLUUID& mesh_id)
{
if (!mHeaderMutex)
{
return false;
}
mHeaderMutex->lock();
if (mMeshHeader.find(mesh_id) == mMeshHeader.end())
{ //we have no header info for this mesh, do nothing
mHeaderMutex->unlock();
return false;
}
++LLMeshRepository::sMeshRequestCount;
U32 header_size = mMeshHeaderSize[mesh_id];
bool ret = true;
if (header_size > 0)
{
S32 version = mMeshHeader[mesh_id]["version"].asInteger();
S32 offset = header_size + mMeshHeader[mesh_id]["physics_convex"]["offset"].asInteger();
S32 size = mMeshHeader[mesh_id]["physics_convex"]["size"].asInteger();
mHeaderMutex->unlock();
if (version <= MAX_MESH_VERSION && offset >= 0 && size > 0)
{
//check VFS for mesh skin info
LLVFile file(gVFS, mesh_id, LLAssetType::AT_MESH);
if (file.getSize() >= offset+size)
{
LLMeshRepository::sCacheBytesRead += size;
++LLMeshRepository::sCacheReads;
file.seek(offset);
U8* buffer = new U8[size];
file.read(buffer, size);
//make sure buffer isn't all 0's by checking the first 1KB (reserved block but not written)
bool zero = true;
for (S32 i = 0; i < llmin(size, 1024) && zero; ++i)
{
zero = buffer[i] > 0 ? false : true;
}
if (!zero)
{ //attempt to parse
if (decompositionReceived(mesh_id, buffer, size))
{
delete[] buffer;
return true;
}
}
delete[] buffer;
}
//reading from VFS failed for whatever reason, fetch from sim
int cap_version(2);
std::string http_url;
constructUrl(mesh_id, &http_url, &cap_version);
if (!http_url.empty())
{
LLMeshDecompositionHandler * handler = new LLMeshDecompositionHandler(mesh_id, offset, size);
LLCore::HttpHandle handle = getByteRange(http_url, cap_version, offset, size, handler);
if (LLCORE_HTTP_HANDLE_INVALID == handle)
{
LL_WARNS(LOG_MESH) << "HTTP GET request failed for decomposition mesh " << mID
<< ". Reason: " << mHttpStatus.toString()
<< " (" << mHttpStatus.toTerseString() << ")"
<< LL_ENDL;
delete handler;
ret = false;
}
else
{
handler->mHttpHandle = handle;
mHttpRequestSet.insert(handler);
}
}
}
}
else
{
mHeaderMutex->unlock();
}
//early out was not hit, effectively fetched
return ret;
}
bool LLMeshRepoThread::fetchMeshPhysicsShape(const LLUUID& mesh_id)
{
if (!mHeaderMutex)
{
return false;
}
mHeaderMutex->lock();
if (mMeshHeader.find(mesh_id) == mMeshHeader.end())
{ //we have no header info for this mesh, do nothing
mHeaderMutex->unlock();
return false;
}
++LLMeshRepository::sMeshRequestCount;
U32 header_size = mMeshHeaderSize[mesh_id];
bool ret = true;
if (header_size > 0)
{
S32 version = mMeshHeader[mesh_id]["version"].asInteger();
S32 offset = header_size + mMeshHeader[mesh_id]["physics_mesh"]["offset"].asInteger();
S32 size = mMeshHeader[mesh_id]["physics_mesh"]["size"].asInteger();
mHeaderMutex->unlock();
if (version <= MAX_MESH_VERSION && offset >= 0 && size > 0)
{
//check VFS for mesh physics shape info
LLVFile file(gVFS, mesh_id, LLAssetType::AT_MESH);
if (file.getSize() >= offset+size)
{
LLMeshRepository::sCacheBytesRead += size;
++LLMeshRepository::sCacheReads;
file.seek(offset);
U8* buffer = new U8[size];
file.read(buffer, size);
//make sure buffer isn't all 0's by checking the first 1KB (reserved block but not written)
bool zero = true;
for (S32 i = 0; i < llmin(size, 1024) && zero; ++i)
{
zero = buffer[i] > 0 ? false : true;
}
if (!zero)
{ //attempt to parse
if (physicsShapeReceived(mesh_id, buffer, size))
{
delete[] buffer;
return true;
}
}
delete[] buffer;
}
//reading from VFS failed for whatever reason, fetch from sim
int cap_version(2);
std::string http_url;
constructUrl(mesh_id, &http_url, &cap_version);
if (!http_url.empty())
{
LLMeshPhysicsShapeHandler * handler = new LLMeshPhysicsShapeHandler(mesh_id, offset, size);
LLCore::HttpHandle handle = getByteRange(http_url, cap_version, offset, size, handler);
if (LLCORE_HTTP_HANDLE_INVALID == handle)
{
LL_WARNS(LOG_MESH) << "HTTP GET request failed for physics shape on mesh " << mID
<< ". Reason: " << mHttpStatus.toString()
<< " (" << mHttpStatus.toTerseString() << ")"
<< LL_ENDL;
delete handler;
ret = false;
}
else
{
handler->mHttpHandle = handle;
mHttpRequestSet.insert(handler);
}
}
}
else
{ //no physics shape whatsoever, report back NULL
physicsShapeReceived(mesh_id, NULL, 0);
}
}
else
{
mHeaderMutex->unlock();
}
//early out was not hit, effectively fetched
return ret;
}
//static
void LLMeshRepoThread::incActiveLODRequests()
{
LLMutexLock lock(gMeshRepo.mThread->mMutex);
++LLMeshRepoThread::sActiveLODRequests;
}
//static
void LLMeshRepoThread::decActiveLODRequests()
{
LLMutexLock lock(gMeshRepo.mThread->mMutex);
--LLMeshRepoThread::sActiveLODRequests;
}
//static
void LLMeshRepoThread::incActiveHeaderRequests()
{
LLMutexLock lock(gMeshRepo.mThread->mMutex);
++LLMeshRepoThread::sActiveHeaderRequests;
}
//static
void LLMeshRepoThread::decActiveHeaderRequests()
{
LLMutexLock lock(gMeshRepo.mThread->mMutex);
--LLMeshRepoThread::sActiveHeaderRequests;
}
//return false if failed to get header
bool LLMeshRepoThread::fetchMeshHeader(const LLVolumeParams& mesh_params)
{
++LLMeshRepository::sMeshRequestCount;
{
//look for mesh in asset in vfs
LLVFile file(gVFS, mesh_params.getSculptID(), LLAssetType::AT_MESH);
S32 size = file.getSize();
if (size > 0)
{
// *NOTE: if the header size is ever more than 4KB, this will break
U8 buffer[MESH_HEADER_SIZE];
S32 bytes = llmin(size, MESH_HEADER_SIZE);
LLMeshRepository::sCacheBytesRead += bytes;
++LLMeshRepository::sCacheReads;
file.read(buffer, bytes);
if (headerReceived(mesh_params, buffer, bytes))
{
// Found mesh in VFS cache
return true;
}
}
}
//either cache entry doesn't exist or is corrupt, request header from simulator
bool retval = true;
int cap_version(2);
std::string http_url;
constructUrl(mesh_params.getSculptID(), &http_url, &cap_version);
if (!http_url.empty())
{
//grab first 4KB if we're going to bother with a fetch. Cache will prevent future fetches if a full mesh fits
//within the first 4KB
//NOTE -- this will break of headers ever exceed 4KB
LLMeshHeaderHandler * handler = new LLMeshHeaderHandler(mesh_params);
LLCore::HttpHandle handle = getByteRange(http_url, cap_version, 0, MESH_HEADER_SIZE, handler);
if (LLCORE_HTTP_HANDLE_INVALID == handle)
{
LL_WARNS(LOG_MESH) << "HTTP GET request failed for mesh header " << mID
<< ". Reason: " << mHttpStatus.toString()
<< " (" << mHttpStatus.toTerseString() << ")"
<< LL_ENDL;
delete handler;
retval = false;
}
else
{
handler->mHttpHandle = handle;
mHttpRequestSet.insert(handler);
}
}
return retval;
}
//return false if failed to get mesh lod.
bool LLMeshRepoThread::fetchMeshLOD(const LLVolumeParams& mesh_params, S32 lod)
{
if (!mHeaderMutex)
{
return false;
}
mHeaderMutex->lock();
++LLMeshRepository::sMeshRequestCount;
bool retval = true;
LLUUID mesh_id = mesh_params.getSculptID();
U32 header_size = mMeshHeaderSize[mesh_id];
if (header_size > 0)
{
S32 version = mMeshHeader[mesh_id]["version"].asInteger();
S32 offset = header_size + mMeshHeader[mesh_id][header_lod[lod]]["offset"].asInteger();
S32 size = mMeshHeader[mesh_id][header_lod[lod]]["size"].asInteger();
mHeaderMutex->unlock();
if (version <= MAX_MESH_VERSION && offset >= 0 && size > 0)
{
//check VFS for mesh asset
LLVFile file(gVFS, mesh_id, LLAssetType::AT_MESH);
if (file.getSize() >= offset+size)
{
LLMeshRepository::sCacheBytesRead += size;
++LLMeshRepository::sCacheReads;
file.seek(offset);
U8* buffer = new U8[size];
file.read(buffer, size);
//make sure buffer isn't all 0's by checking the first 1KB (reserved block but not written)
bool zero = true;
for (S32 i = 0; i < llmin(size, 1024) && zero; ++i)
{
zero = buffer[i] > 0 ? false : true;
}
if (!zero)
{ //attempt to parse
if (lodReceived(mesh_params, lod, buffer, size))
{
delete[] buffer;
return true;
}
}
delete[] buffer;
}
//reading from VFS failed for whatever reason, fetch from sim
int cap_version(2);
std::string http_url;
constructUrl(mesh_id, &http_url, &cap_version);
if (!http_url.empty())
{
LLMeshLODHandler * handler = new LLMeshLODHandler(mesh_params, lod, offset, size);
LLCore::HttpHandle handle = getByteRange(http_url, cap_version, offset, size, handler);
if (LLCORE_HTTP_HANDLE_INVALID == handle)
{
LL_WARNS(LOG_MESH) << "HTTP GET request failed for LOD on mesh " << mID
<< ". Reason: " << mHttpStatus.toString()
<< " (" << mHttpStatus.toTerseString() << ")"
<< LL_ENDL;
delete handler;
retval = false;
}
else
{
handler->mHttpHandle = handle;
mHttpRequestSet.insert(handler);
// *NOTE: Allowing a re-request, not marking as unavailable. Is that correct?
}
}
else
{
mUnavailableQ.push(LODRequest(mesh_params, lod));
}
}
else
{
mUnavailableQ.push(LODRequest(mesh_params, lod));
}
}
else
{
mHeaderMutex->unlock();
}
return retval;
}
bool LLMeshRepoThread::headerReceived(const LLVolumeParams& mesh_params, U8* data, S32 data_size)
{
const LLUUID mesh_id = mesh_params.getSculptID();
LLSD header;
U32 header_size = 0;
if (data_size > 0)
{
std::string res_str((char*) data, data_size);
std::string deprecated_header("<? LLSD/Binary ?>");
if (res_str.substr(0, deprecated_header.size()) == deprecated_header)
{
res_str = res_str.substr(deprecated_header.size()+1, data_size);
header_size = deprecated_header.size()+1;
}
data_size = res_str.size();
std::istringstream stream(res_str);
if (!LLSDSerialize::fromBinary(header, stream, data_size))
{
LL_WARNS(LOG_MESH) << "Mesh header parse error. Not a valid mesh asset! ID: " << mesh_id
<< LL_ENDL;
return false;
}
header_size += stream.tellg();
}
else
{
LL_INFOS(LOG_MESH) << "Non-positive data size. Marking header as non-existent, will not retry. ID: " << mesh_id
<< LL_ENDL;
header["404"] = 1;
}
{
{
LLMutexLock lock(mHeaderMutex);
mMeshHeaderSize[mesh_id] = header_size;
mMeshHeader[mesh_id] = header;
}
LLMutexLock lock(mMutex); // make sure only one thread access mPendingLOD at the same time.
//check for pending requests
pending_lod_map::iterator iter = mPendingLOD.find(mesh_params);
if (iter != mPendingLOD.end())
{
for (U32 i = 0; i < iter->second.size(); ++i)
{
LODRequest req(mesh_params, iter->second[i]);
mLODReqQ.push(req);
LLMeshRepository::sLODProcessing++;
}
mPendingLOD.erase(iter);
}
}
return true;
}
bool LLMeshRepoThread::lodReceived(const LLVolumeParams& mesh_params, S32 lod, U8* data, S32 data_size)
{
LLPointer<LLVolume> volume = new LLVolume(mesh_params, LLVolumeLODGroup::getVolumeScaleFromDetail(lod));
std::string mesh_string((char*) data, data_size);
std::istringstream stream(mesh_string);
if (volume->unpackVolumeFaces(stream, data_size))
{
if (volume->getNumFaces() > 0)
{
LoadedMesh mesh(volume, mesh_params, lod);
{
LLMutexLock lock(mMutex);
mLoadedQ.push(mesh);
}
return true;
}
}
return false;
}
bool LLMeshRepoThread::skinInfoReceived(const LLUUID& mesh_id, U8* data, S32 data_size)
{
LLSD skin;
if (data_size > 0)
{
std::string res_str((char*) data, data_size);
std::istringstream stream(res_str);
if (!unzip_llsd(skin, stream, data_size))
{
LL_WARNS(LOG_MESH) << "Mesh skin info parse error. Not a valid mesh asset! ID: " << mesh_id
<< LL_ENDL;
return false;
}
}
{
LLMeshSkinInfo info(skin);
info.mMeshID = mesh_id;
// LL_DEBUGS(LOG_MESH) << "info pelvis offset" << info.mPelvisOffset << LL_ENDL;
{
LLMutexLock lock(mMutex);
mSkinInfoQ.push_back(info);
}
}
return true;
}
bool LLMeshRepoThread::decompositionReceived(const LLUUID& mesh_id, U8* data, S32 data_size)
{
LLSD decomp;
if (data_size > 0)
{
std::string res_str((char*) data, data_size);
std::istringstream stream(res_str);
if (!unzip_llsd(decomp, stream, data_size))
{
LL_WARNS(LOG_MESH) << "Mesh decomposition parse error. Not a valid mesh asset! ID: " << mesh_id
<< LL_ENDL;
return false;
}
}
{
LLModel::Decomposition* d = new LLModel::Decomposition(decomp);
d->mMeshID = mesh_id;
{
LLMutexLock lock(mMutex);
mDecompositionQ.push_back(d);
}
}
return true;
}
bool LLMeshRepoThread::physicsShapeReceived(const LLUUID& mesh_id, U8* data, S32 data_size)
{
LLSD physics_shape;
LLModel::Decomposition* d = new LLModel::Decomposition();
d->mMeshID = mesh_id;
if (data == NULL)
{ //no data, no physics shape exists
d->mPhysicsShapeMesh.clear();
}
else
{
LLVolumeParams volume_params;
volume_params.setType(LL_PCODE_PROFILE_SQUARE, LL_PCODE_PATH_LINE);
volume_params.setSculptID(mesh_id, LL_SCULPT_TYPE_MESH);
LLPointer<LLVolume> volume = new LLVolume(volume_params,0);
std::string mesh_string((char*) data, data_size);
std::istringstream stream(mesh_string);
if (volume->unpackVolumeFaces(stream, data_size))
{
//load volume faces into decomposition buffer
S32 vertex_count = 0;
S32 index_count = 0;
for (S32 i = 0; i < volume->getNumVolumeFaces(); ++i)
{
const LLVolumeFace& face = volume->getVolumeFace(i);
vertex_count += face.mNumVertices;
index_count += face.mNumIndices;
}
d->mPhysicsShapeMesh.clear();
std::vector<LLVector3>& pos = d->mPhysicsShapeMesh.mPositions;
std::vector<LLVector3>& norm = d->mPhysicsShapeMesh.mNormals;
for (S32 i = 0; i < volume->getNumVolumeFaces(); ++i)
{
const LLVolumeFace& face = volume->getVolumeFace(i);
for (S32 i = 0; i < face.mNumIndices; ++i)
{
U16 idx = face.mIndices[i];
pos.push_back(LLVector3(face.mPositions[idx].getF32ptr()));
norm.push_back(LLVector3(face.mNormals[idx].getF32ptr()));
}
}
}
}
{
LLMutexLock lock(mMutex);
mDecompositionQ.push_back(d);
}
return true;
}
LLMeshUploadThread::LLMeshUploadThread(LLMeshUploadThread::instance_list& data, LLVector3& scale, bool upload_textures,
bool upload_skin, bool upload_joints, const std::string & upload_url, bool do_upload,
LLHandle<LLWholeModelFeeObserver> fee_observer,
LLHandle<LLWholeModelUploadObserver> upload_observer)
: LLThread("mesh upload"),
LLCore::HttpHandler(),
mDiscarded(false),
mDoUpload(do_upload),
mWholeModelUploadURL(upload_url),
mFeeObserverHandle(fee_observer),
mUploadObserverHandle(upload_observer)
{
mInstanceList = data;
mUploadTextures = upload_textures;
mUploadSkin = upload_skin;
mUploadJoints = upload_joints;
mMutex = new LLMutex(NULL);
mPendingUploads = 0;
mFinished = false;
mOrigin = gAgent.getPositionAgent();
mHost = gAgent.getRegionHost();
mWholeModelFeeCapability = gAgent.getRegion()->getCapability("NewFileAgentInventory");
mOrigin += gAgent.getAtAxis() * scale.magVec();
mMeshUploadTimeOut = gSavedSettings.getS32("MeshUploadTimeOut");
mHttpRequest = new LLCore::HttpRequest;
mHttpOptions = new LLCore::HttpOptions;
mHttpOptions->setTransferTimeout(mMeshUploadTimeOut);
mHttpOptions->setUseRetryAfter(gSavedSettings.getBOOL("MeshUseHttpRetryAfter"));
mHttpOptions->setRetries(UPLOAD_RETRY_LIMIT);
mHttpHeaders = new LLCore::HttpHeaders;
mHttpHeaders->append("Content-Type", "application/llsd+xml");
mHttpPolicyClass = LLAppViewer::instance()->getAppCoreHttp().getPolicy(LLAppCoreHttp::AP_UPLOADS);
mHttpPriority = 0;
}
LLMeshUploadThread::~LLMeshUploadThread()
{
if (mHttpHeaders)
{
mHttpHeaders->release();
mHttpHeaders = NULL;
}
if (mHttpOptions)
{
mHttpOptions->release();
mHttpOptions = NULL;
}
delete mHttpRequest;
mHttpRequest = NULL;
}
LLMeshUploadThread::DecompRequest::DecompRequest(LLModel* mdl, LLModel* base_model, LLMeshUploadThread* thread)
{
mStage = "single_hull";
mModel = mdl;
mDecompID = &mdl->mDecompID;
mBaseModel = base_model;
mThread = thread;
//copy out positions and indices
assignData(mdl) ;
mThread->mFinalDecomp = this;
mThread->mPhysicsComplete = false;
}
void LLMeshUploadThread::DecompRequest::completed()
{
if (mThread->mFinalDecomp == this)
{
mThread->mPhysicsComplete = true;
}
llassert(mHull.size() == 1);
mThread->mHullMap[mBaseModel] = mHull[0];
}
//called in the main thread.
void LLMeshUploadThread::preStart()
{
//build map of LLModel refs to instances for callbacks
for (instance_list::iterator iter = mInstanceList.begin(); iter != mInstanceList.end(); ++iter)
{
mInstance[iter->mModel].push_back(*iter);
}
}
void LLMeshUploadThread::discard()
{
LLMutexLock lock(mMutex);
mDiscarded = true;
}
bool LLMeshUploadThread::isDiscarded() const
{
LLMutexLock lock(mMutex);
return mDiscarded;
}
void LLMeshUploadThread::run()
{
if (mDoUpload)
{
doWholeModelUpload();
}
else
{
requestWholeModelFee();
}
}
void dump_llsd_to_file(const LLSD& content, std::string filename)
{
if (gSavedSettings.getBOOL("MeshUploadLogXML"))
{
std::ofstream of(filename.c_str());
LLSDSerialize::toPrettyXML(content,of);
}
}
LLSD llsd_from_file(std::string filename)
{
std::ifstream ifs(filename.c_str());
LLSD result;
LLSDSerialize::fromXML(result,ifs);
return result;
}
void LLMeshUploadThread::wholeModelToLLSD(LLSD& dest, bool include_textures)
{
LLSD result;
LLSD res;
result["folder_id"] = gInventory.findCategoryUUIDForType(LLFolderType::FT_OBJECT);
result["texture_folder_id"] = gInventory.findCategoryUUIDForType(LLFolderType::FT_TEXTURE);
result["asset_type"] = "mesh";
result["inventory_type"] = "object";
result["description"] = "(No Description)";
result["next_owner_mask"] = LLSD::Integer(LLFloaterPerms::getNextOwnerPerms());
result["group_mask"] = LLSD::Integer(LLFloaterPerms::getGroupPerms());
result["everyone_mask"] = LLSD::Integer(LLFloaterPerms::getEveryonePerms());
res["mesh_list"] = LLSD::emptyArray();
res["texture_list"] = LLSD::emptyArray();
res["instance_list"] = LLSD::emptyArray();
S32 mesh_num = 0;
S32 texture_num = 0;
std::set<LLViewerTexture* > textures;
std::map<LLViewerTexture*,S32> texture_index;
std::map<LLModel*,S32> mesh_index;
std::string model_name;
std::string model_metric;
S32 instance_num = 0;
for (instance_map::iterator iter = mInstance.begin(); iter != mInstance.end(); ++iter)
{
LLMeshUploadData data;
data.mBaseModel = iter->first;
LLModelInstance& first_instance = *(iter->second.begin());
for (S32 i = 0; i < 5; i++)
{
data.mModel[i] = first_instance.mLOD[i];
}
if (mesh_index.find(data.mBaseModel) == mesh_index.end())
{
// Have not seen this model before - create a new mesh_list entry for it.
if (model_name.empty())
{
model_name = data.mBaseModel->getName();
}
if (model_metric.empty())
{
model_metric = data.mBaseModel->getMetric();
}
std::stringstream ostr;
LLModel::Decomposition& decomp =
data.mModel[LLModel::LOD_PHYSICS].notNull() ?
data.mModel[LLModel::LOD_PHYSICS]->mPhysics :
data.mBaseModel->mPhysics;
decomp.mBaseHull = mHullMap[data.mBaseModel];
LLSD mesh_header = LLModel::writeModel(
ostr,
data.mModel[LLModel::LOD_PHYSICS],
data.mModel[LLModel::LOD_HIGH],
data.mModel[LLModel::LOD_MEDIUM],
data.mModel[LLModel::LOD_LOW],
data.mModel[LLModel::LOD_IMPOSTOR],
decomp,
mUploadSkin,
mUploadJoints);
data.mAssetData = ostr.str();
std::string str = ostr.str();
res["mesh_list"][mesh_num] = LLSD::Binary(str.begin(),str.end());
mesh_index[data.mBaseModel] = mesh_num;
mesh_num++;
}
// For all instances that use this model
for (instance_list::iterator instance_iter = iter->second.begin();
instance_iter != iter->second.end();
++instance_iter)
{
LLModelInstance& instance = *instance_iter;
LLSD instance_entry;
for (S32 i = 0; i < 5; i++)
{
data.mModel[i] = instance.mLOD[i];
}
LLVector3 pos, scale;
LLQuaternion rot;
LLMatrix4 transformation = instance.mTransform;
decomposeMeshMatrix(transformation,pos,rot,scale);
instance_entry["position"] = ll_sd_from_vector3(pos);
instance_entry["rotation"] = ll_sd_from_quaternion(rot);
instance_entry["scale"] = ll_sd_from_vector3(scale);
instance_entry["material"] = LL_MCODE_WOOD;
instance_entry["physics_shape_type"] = (U8)(LLViewerObject::PHYSICS_SHAPE_CONVEX_HULL);
instance_entry["mesh"] = mesh_index[data.mBaseModel];
instance_entry["face_list"] = LLSD::emptyArray();
S32 end = llmin((S32)data.mBaseModel->mMaterialList.size(), data.mBaseModel->getNumVolumeFaces()) ;
for (S32 face_num = 0; face_num < end; face_num++)
{
LLImportMaterial& material = instance.mMaterial[data.mBaseModel->mMaterialList[face_num]];
LLSD face_entry = LLSD::emptyMap();
LLViewerFetchedTexture *texture = material.mDiffuseMap.get();
if ((texture != NULL) &&
(textures.find(texture) == textures.end()))
{
textures.insert(texture);
}
std::stringstream texture_str;
if (texture != NULL && include_textures && mUploadTextures)
{
if(texture->hasSavedRawImage())
{
LLPointer<LLImageJ2C> upload_file =
LLViewerTextureList::convertToUploadFile(texture->getSavedRawImage());
texture_str.write((const char*) upload_file->getData(), upload_file->getDataSize());
}
}
if (texture != NULL &&
mUploadTextures &&
texture_index.find(texture) == texture_index.end())
{
texture_index[texture] = texture_num;
std::string str = texture_str.str();
res["texture_list"][texture_num] = LLSD::Binary(str.begin(),str.end());
texture_num++;
}
// Subset of TextureEntry fields.
if (texture != NULL && mUploadTextures)
{
face_entry["image"] = texture_index[texture];
face_entry["scales"] = 1.0;
face_entry["scalet"] = 1.0;
face_entry["offsets"] = 0.0;
face_entry["offsett"] = 0.0;
face_entry["imagerot"] = 0.0;
}
face_entry["diffuse_color"] = ll_sd_from_color4(material.mDiffuseColor);
face_entry["fullbright"] = material.mFullbright;
instance_entry["face_list"][face_num] = face_entry;
}
res["instance_list"][instance_num] = instance_entry;
instance_num++;
}
}
if (model_name.empty()) model_name = "mesh model";
result["name"] = model_name;
if (model_metric.empty()) model_metric = "MUT_Unspecified";
res["metric"] = model_metric;
result["asset_resources"] = res;
dump_llsd_to_file(result,make_dump_name("whole_model_",dump_num));
dest = result;
}
void LLMeshUploadThread::generateHulls()
{
bool has_valid_requests = false ;
for (instance_map::iterator iter = mInstance.begin(); iter != mInstance.end(); ++iter)
{
LLMeshUploadData data;
data.mBaseModel = iter->first;
LLModelInstance& instance = *(iter->second.begin());
for (S32 i = 0; i < 5; i++)
{
data.mModel[i] = instance.mLOD[i];
}
//queue up models for hull generation
LLModel* physics = NULL;
if (data.mModel[LLModel::LOD_PHYSICS].notNull())
{
physics = data.mModel[LLModel::LOD_PHYSICS];
}
else if (data.mModel[LLModel::LOD_LOW].notNull())
{
physics = data.mModel[LLModel::LOD_LOW];
}
else if (data.mModel[LLModel::LOD_MEDIUM].notNull())
{
physics = data.mModel[LLModel::LOD_MEDIUM];
}
else
{
physics = data.mModel[LLModel::LOD_HIGH];
}
llassert(physics != NULL);
DecompRequest* request = new DecompRequest(physics, data.mBaseModel, this);
if(request->isValid())
{
gMeshRepo.mDecompThread->submitRequest(request);
has_valid_requests = true ;
}
}
if (has_valid_requests)
{
// *NOTE: Interesting livelock condition on shutdown. If there
// is an upload request in generateHulls() when shutdown starts,
// the main thread isn't available to manage communication between
// the decomposition thread and the upload thread and this loop
// wouldn't complete in turn stalling the main thread. The check
// on isDiscarded() prevents that.
while (! mPhysicsComplete && ! isDiscarded())
{
apr_sleep(100);
}
}
}
void LLMeshUploadThread::doWholeModelUpload()
{
LL_DEBUGS(LOG_MESH) << "Starting model upload. Instances: " << mInstance.size() << LL_ENDL;
if (mWholeModelUploadURL.empty())
{
LL_WARNS(LOG_MESH) << "Missing mesh upload capability, unable to upload, fee request failed."
<< LL_ENDL;
}
else
{
generateHulls();
LL_DEBUGS(LOG_MESH) << "Hull generation completed." << LL_ENDL;
mModelData = LLSD::emptyMap();
wholeModelToLLSD(mModelData, true);
LLSD body = mModelData["asset_resources"];
dump_llsd_to_file(body, make_dump_name("whole_model_body_", dump_num));
LLCore::BufferArray * ba = new LLCore::BufferArray;
LLCore::BufferArrayStream bas(ba);
LLSDSerialize::toXML(body, bas);
// LLSDSerialize::toXML(mModelData, bas); // <- Enabling this will generate a convenient upload error
LLCore::HttpHandle handle = mHttpRequest->requestPost(mHttpPolicyClass,
mHttpPriority,
mWholeModelUploadURL,
ba,
mHttpOptions,
mHttpHeaders,
this);
ba->release();
if (LLCORE_HTTP_HANDLE_INVALID == handle)
{
mHttpStatus = mHttpRequest->getStatus();
LL_WARNS(LOG_MESH) << "Couldn't issue request for full model upload. Reason: " << mHttpStatus.toString()
<< " (" << mHttpStatus.toTerseString() << ")"
<< LL_ENDL;
}
else
{
U32 sleep_time(10);
LL_DEBUGS(LOG_MESH) << "POST request issued." << LL_ENDL;
mHttpRequest->update(0);
while (! LLApp::isQuitting() && ! finished() && ! isDiscarded())
{
ms_sleep(sleep_time);
sleep_time = llmin(250U, sleep_time + sleep_time);
mHttpRequest->update(0);
}
if (isDiscarded())
{
LL_DEBUGS(LOG_MESH) << "Mesh upload operation discarded." << LL_ENDL;
}
else
{
LL_DEBUGS(LOG_MESH) << "Mesh upload operation completed." << LL_ENDL;
}
}
}
}
void LLMeshUploadThread::requestWholeModelFee()
{
dump_num++;
generateHulls();
mModelData = LLSD::emptyMap();
wholeModelToLLSD(mModelData, false);
dump_llsd_to_file(mModelData, make_dump_name("whole_model_fee_request_", dump_num));
LLCore::BufferArray * ba = new LLCore::BufferArray;
LLCore::BufferArrayStream bas(ba);
LLSDSerialize::toXML(mModelData, bas);
LLCore::HttpHandle handle = mHttpRequest->requestPost(mHttpPolicyClass,
mHttpPriority,
mWholeModelFeeCapability,
ba,
mHttpOptions,
mHttpHeaders,
this);
ba->release();
if (LLCORE_HTTP_HANDLE_INVALID == handle)
{
mHttpStatus = mHttpRequest->getStatus();
LL_WARNS(LOG_MESH) << "Couldn't issue request for model fee. Reason: " << mHttpStatus.toString()
<< " (" << mHttpStatus.toTerseString() << ")"
<< LL_ENDL;
}
else
{
U32 sleep_time(10);
mHttpRequest->update(0);
while (! LLApp::isQuitting() && ! finished() && ! isDiscarded())
{
ms_sleep(sleep_time);
sleep_time = llmin(250U, sleep_time + sleep_time);
mHttpRequest->update(0);
}
if (isDiscarded())
{
LL_DEBUGS(LOG_MESH) << "Mesh fee query operation discarded." << LL_ENDL;
}
}
}
// Does completion duty for both fee queries and actual uploads.
void LLMeshUploadThread::onCompleted(LLCore::HttpHandle handle, LLCore::HttpResponse * response)
{
// QA/Devel: 0x2 to enable fake error import on upload, 0x1 on fee check
const S32 fake_error(gSavedSettings.getS32("MeshUploadFakeErrors") & (mDoUpload ? 0xa : 0x5));
LLCore::HttpStatus status(response->getStatus());
if (fake_error)
{
status = (fake_error & 0x0c) ? LLCore::HttpStatus(500) : LLCore::HttpStatus(200);
}
std::string reason(status.toString());
LLSD body;
mFinished = true;
if (mDoUpload)
{
// model upload case
LLWholeModelUploadObserver * observer(mUploadObserverHandle.get());
if (! status)
{
LL_WARNS(LOG_MESH) << "Upload failed. Reason: " << reason
<< " (" << status.toTerseString() << ")"
<< LL_ENDL;
// Build a fake body for the alert generator
body["error"] = LLSD::emptyMap();
body["error"]["message"] = reason;
body["error"]["identifier"] = "NetworkError"; // from asset-upload/upload_util.py
log_upload_error(status, body, "upload", mModelData["name"].asString());
if (observer)
{
doOnIdleOneTime(boost::bind(&LLWholeModelUploadObserver::onModelUploadFailure, observer));
}
}
else
{
if (fake_error & 0x2)
{
body = llsd_from_file("fake_upload_error.xml");
}
else
{
LLCore::BufferArray * ba(response->getBody());
if (ba && ba->size())
{
LLCore::BufferArrayStream bas(ba);
LLSDSerialize::fromXML(body, bas);
}
}
dump_llsd_to_file(body, make_dump_name("whole_model_upload_response_", dump_num));
if (body["state"].asString() == "complete")
{
// requested "mesh" asset type isn't actually the type
// of the resultant object, fix it up here.
mModelData["asset_type"] = "object";
gMeshRepo.updateInventory(LLMeshRepository::inventory_data(mModelData, body));
if (observer)
{
doOnIdleOneTime(boost::bind(&LLWholeModelUploadObserver::onModelUploadSuccess, observer));
}
}
else
{
LL_WARNS(LOG_MESH) << "Upload failed. Not in expected 'complete' state." << LL_ENDL;
log_upload_error(status, body, "upload", mModelData["name"].asString());
if (observer)
{
doOnIdleOneTime(boost::bind(&LLWholeModelUploadObserver::onModelUploadFailure, observer));
}
}
}
}
else
{
// model fee case
LLWholeModelFeeObserver* observer(mFeeObserverHandle.get());
mWholeModelUploadURL.clear();
if (! status)
{
LL_WARNS(LOG_MESH) << "Fee request failed. Reason: " << reason
<< " (" << status.toTerseString() << ")"
<< LL_ENDL;
// Build a fake body for the alert generator
body["error"] = LLSD::emptyMap();
body["error"]["message"] = reason;
body["error"]["identifier"] = "NetworkError"; // from asset-upload/upload_util.py
log_upload_error(status, body, "fee", mModelData["name"].asString());
if (observer)
{
observer->setModelPhysicsFeeErrorStatus(status.toULong(), reason);
}
}
else
{
if (fake_error & 0x1)
{
body = llsd_from_file("fake_upload_error.xml");
}
else
{
LLCore::BufferArray * ba(response->getBody());
if (ba && ba->size())
{
LLCore::BufferArrayStream bas(ba);
LLSDSerialize::fromXML(body, bas);
}
}
dump_llsd_to_file(body, make_dump_name("whole_model_fee_response_", dump_num));
if (body["state"].asString() == "upload")
{
mWholeModelUploadURL = body["uploader"].asString();
if (observer)
{
body["data"]["upload_price"] = body["upload_price"];
observer->onModelPhysicsFeeReceived(body["data"], mWholeModelUploadURL);
}
}
else
{
LL_WARNS(LOG_MESH) << "Fee request failed. Not in expected 'upload' state." << LL_ENDL;
log_upload_error(status, body, "fee", mModelData["name"].asString());
if (observer)
{
observer->setModelPhysicsFeeErrorStatus(status.toULong(), reason);
}
}
}
}
}
void LLMeshRepoThread::notifyLoadedMeshes()
{
bool update_metrics(false);
if (!mMutex)
{
return;
}
while (!mLoadedQ.empty())
{
mMutex->lock();
if (mLoadedQ.empty())
{
mMutex->unlock();
break;
}
LoadedMesh mesh = mLoadedQ.front();
mLoadedQ.pop();
mMutex->unlock();
update_metrics = true;
if (mesh.mVolume && mesh.mVolume->getNumVolumeFaces() > 0)
{
gMeshRepo.notifyMeshLoaded(mesh.mMeshParams, mesh.mVolume);
}
else
{
gMeshRepo.notifyMeshUnavailable(mesh.mMeshParams,
LLVolumeLODGroup::getVolumeDetailFromScale(mesh.mVolume->getDetail()));
}
}
while (!mUnavailableQ.empty())
{
mMutex->lock();
if (mUnavailableQ.empty())
{
mMutex->unlock();
break;
}
LODRequest req = mUnavailableQ.front();
mUnavailableQ.pop();
mMutex->unlock();
update_metrics = true;
gMeshRepo.notifyMeshUnavailable(req.mMeshParams, req.mLOD);
}
if (! mSkinInfoQ.empty() || ! mDecompositionQ.empty())
{
if (mMutex->trylock())
{
std::list<LLMeshSkinInfo> skin_info_q;
std::list<LLModel::Decomposition*> decomp_q;
if (! mSkinInfoQ.empty())
{
skin_info_q.swap(mSkinInfoQ);
}
if (! mDecompositionQ.empty())
{
decomp_q.swap(mDecompositionQ);
}
mMutex->unlock();
// Process the elements free of the lock
while (! skin_info_q.empty())
{
gMeshRepo.notifySkinInfoReceived(skin_info_q.front());
skin_info_q.pop_front();
}
while (! decomp_q.empty())
{
gMeshRepo.notifyDecompositionReceived(decomp_q.front());
decomp_q.pop_front();
}
}
}
if (update_metrics)
{
// Ping time-to-load metrics for mesh download operations.
LLMeshRepository::metricsProgress(0);
}
}
S32 LLMeshRepoThread::getActualMeshLOD(const LLVolumeParams& mesh_params, S32 lod)
{ //only ever called from main thread
LLMutexLock lock(mHeaderMutex);
mesh_header_map::iterator iter = mMeshHeader.find(mesh_params.getSculptID());
if (iter != mMeshHeader.end())
{
LLSD& header = iter->second;
return LLMeshRepository::getActualMeshLOD(header, lod);
}
return lod;
}
//static
S32 LLMeshRepository::getActualMeshLOD(LLSD& header, S32 lod)
{
lod = llclamp(lod, 0, 3);
S32 version = header["version"];
if (header.has("404") || version > MAX_MESH_VERSION)
{
return -1;
}
if (header[header_lod[lod]]["size"].asInteger() > 0)
{
return lod;
}
//search down to find the next available lower lod
for (S32 i = lod-1; i >= 0; --i)
{
if (header[header_lod[i]]["size"].asInteger() > 0)
{
return i;
}
}
//search up to find then ext available higher lod
for (S32 i = lod+1; i < 4; ++i)
{
if (header[header_lod[i]]["size"].asInteger() > 0)
{
return i;
}
}
//header exists and no good lod found, treat as 404
header["404"] = 1;
return -1;
}
void LLMeshRepository::cacheOutgoingMesh(LLMeshUploadData& data, LLSD& header)
{
mThread->mMeshHeader[data.mUUID] = header;
// we cache the mesh for default parameters
LLVolumeParams volume_params;
volume_params.setType(LL_PCODE_PROFILE_SQUARE, LL_PCODE_PATH_LINE);
volume_params.setSculptID(data.mUUID, LL_SCULPT_TYPE_MESH);
for (U32 i = 0; i < 4; i++)
{
if (data.mModel[i].notNull())
{
LLPointer<LLVolume> volume = new LLVolume(volume_params, LLVolumeLODGroup::getVolumeScaleFromDetail(i));
volume->copyVolumeFaces(data.mModel[i]);
volume->setMeshAssetLoaded(TRUE);
}
}
}
void LLMeshHandlerBase::onCompleted(LLCore::HttpHandle handle, LLCore::HttpResponse * response)
{
mProcessed = true;
unsigned int retries(0U);
response->getRetries(NULL, &retries);
LLMeshRepository::sHTTPRetryCount += retries;
LLCore::HttpStatus status(response->getStatus());
if (! status || MESH_HTTP_RESPONSE_FAILED)
{
processFailure(status);
++LLMeshRepository::sHTTPErrorCount;
}
else
{
// From texture fetch code and may apply here:
//
// A warning about partial (HTTP 206) data. Some grid services
// do *not* return a 'Content-Range' header in the response to
// Range requests with a 206 status. We're forced to assume
// we get what we asked for in these cases until we can fix
// the services.
//
// May also need to deal with 200 status (full asset returned
// rather than partial) and 416 (request completely unsatisfyable).
// Always been exposed to these but are less likely here where
// speculative loads aren't done.
static const LLCore::HttpStatus par_status(HTTP_PARTIAL_CONTENT);
if (par_status != status)
{
LL_WARNS_ONCE(LOG_MESH) << "Non-206 successful status received for fetch: "
<< status.toTerseString() << LL_ENDL;
}
LLCore::BufferArray * body(response->getBody());
S32 data_size(body ? body->size() : 0);
U8 * data(NULL);
if (data_size > 0)
{
// *TODO: Try to get rid of data copying and add interfaces
// that support BufferArray directly. Introduce a two-phase
// handler, optional first that takes a body, fallback second
// that requires a temporary allocation and data copy.
data = new U8[data_size];
body->read(0, (char *) data, data_size);
LLMeshRepository::sBytesReceived += data_size;
}
processData(body, data, data_size);
delete [] data;
}
// Release handler
gMeshRepo.mThread->mHttpRequestSet.erase(this);
delete this; // Must be last statement
}
LLMeshHeaderHandler::~LLMeshHeaderHandler()
{
if (!LLApp::isQuitting())
{
if (! mProcessed)
{
// something went wrong, retry
LL_WARNS(LOG_MESH) << "Mesh header fetch canceled unexpectedly, retrying." << LL_ENDL;
LLMeshRepoThread::HeaderRequest req(mMeshParams);
LLMutexLock lock(gMeshRepo.mThread->mMutex);
gMeshRepo.mThread->mHeaderReqQ.push(req);
}
LLMeshRepoThread::decActiveHeaderRequests();
}
}
void LLMeshHeaderHandler::processFailure(LLCore::HttpStatus status)
{
LL_WARNS(LOG_MESH) << "Error during mesh header handling. ID: " << mMeshParams.getSculptID()
<< ", Reason: " << status.toString()
<< " (" << status.toTerseString() << "). Not retrying."
<< LL_ENDL;
// Can't get the header so none of the LODs will be available
LLMutexLock lock(gMeshRepo.mThread->mMutex);
for (int i(0); i < 4; ++i)
{
gMeshRepo.mThread->mUnavailableQ.push(LLMeshRepoThread::LODRequest(mMeshParams, i));
}
}
void LLMeshHeaderHandler::processData(LLCore::BufferArray * body, U8 * data, S32 data_size)
{
LLUUID mesh_id = mMeshParams.getSculptID();
bool success = (! MESH_HEADER_PROCESS_FAILED) && gMeshRepo.mThread->headerReceived(mMeshParams, data, data_size);
llassert(success);
if (! success)
{
// *TODO: Get real reason for parse failure here. Might we want to retry?
LL_WARNS(LOG_MESH) << "Unable to parse mesh header. ID: " << mesh_id
<< ", Unknown reason. Not retrying."
<< LL_ENDL;
// Can't get the header so none of the LODs will be available
LLMutexLock lock(gMeshRepo.mThread->mMutex);
for (int i(0); i < 4; ++i)
{
gMeshRepo.mThread->mUnavailableQ.push(LLMeshRepoThread::LODRequest(mMeshParams, i));
}
}
else if (data && data_size > 0)
{
// header was successfully retrieved from sim, cache in vfs
LLSD header = gMeshRepo.mThread->mMeshHeader[mesh_id];
S32 version = header["version"].asInteger();
if (version <= MAX_MESH_VERSION)
{
std::stringstream str;
S32 lod_bytes = 0;
for (U32 i = 0; i < LLModel::LOD_PHYSICS; ++i)
{
// figure out how many bytes we'll need to reserve in the file
const std::string & lod_name = header_lod[i];
lod_bytes = llmax(lod_bytes, header[lod_name]["offset"].asInteger()+header[lod_name]["size"].asInteger());
}
// just in case skin info or decomposition is at the end of the file (which it shouldn't be)
lod_bytes = llmax(lod_bytes, header["skin"]["offset"].asInteger() + header["skin"]["size"].asInteger());
lod_bytes = llmax(lod_bytes, header["physics_convex"]["offset"].asInteger() + header["physics_convex"]["size"].asInteger());
S32 header_bytes = (S32) gMeshRepo.mThread->mMeshHeaderSize[mesh_id];
S32 bytes = lod_bytes + header_bytes;
// It's possible for the remote asset to have more data than is needed for the local cache
// only allocate as much space in the VFS as is needed for the local cache
data_size = llmin(data_size, bytes);
LLVFile file(gVFS, mesh_id, LLAssetType::AT_MESH, LLVFile::WRITE);
if (file.getMaxSize() >= bytes || file.setMaxSize(bytes))
{
LLMeshRepository::sCacheBytesWritten += data_size;
++LLMeshRepository::sCacheWrites;
file.write(data, data_size);
// zero out the rest of the file
U8 block[MESH_HEADER_SIZE];
memset(block, 0, sizeof(block));
while (bytes-file.tell() > sizeof(block))
{
file.write(block, sizeof(block));
}
S32 remaining = bytes-file.tell();
if (remaining > 0)
{
file.write(block, remaining);
}
}
}
}
}
LLMeshLODHandler::~LLMeshLODHandler()
{
if (! LLApp::isQuitting())
{
if (! mProcessed)
{
LL_WARNS(LOG_MESH) << "Mesh LOD fetch canceled unexpectedly, retrying." << LL_ENDL;
gMeshRepo.mThread->lockAndLoadMeshLOD(mMeshParams, mLOD);
}
LLMeshRepoThread::decActiveLODRequests();
}
}
void LLMeshLODHandler::processFailure(LLCore::HttpStatus status)
{
LL_WARNS(LOG_MESH) << "Error during mesh LOD handling. ID: " << mMeshParams.getSculptID()
<< ", Reason: " << status.toString()
<< " (" << status.toTerseString() << "). Not retrying."
<< LL_ENDL;
LLMutexLock lock(gMeshRepo.mThread->mMutex);
gMeshRepo.mThread->mUnavailableQ.push(LLMeshRepoThread::LODRequest(mMeshParams, mLOD));
}
void LLMeshLODHandler::processData(LLCore::BufferArray * body, U8 * data, S32 data_size)
{
if ((! MESH_LOD_PROCESS_FAILED) && gMeshRepo.mThread->lodReceived(mMeshParams, mLOD, data, data_size))
{
// good fetch from sim, write to VFS for caching
LLVFile file(gVFS, mMeshParams.getSculptID(), LLAssetType::AT_MESH, LLVFile::WRITE);
S32 offset = mOffset;
S32 size = mRequestedBytes;
if (file.getSize() >= offset+size)
{
file.seek(offset);
file.write(data, size);
LLMeshRepository::sCacheBytesWritten += size;
++LLMeshRepository::sCacheWrites;
}
}
else
{
LL_WARNS(LOG_MESH) << "Error during mesh LOD processing. ID: " << mMeshParams.getSculptID()
<< ", Unknown reason. Not retrying."
<< LL_ENDL;
LLMutexLock lock(gMeshRepo.mThread->mMutex);
gMeshRepo.mThread->mUnavailableQ.push(LLMeshRepoThread::LODRequest(mMeshParams, mLOD));
}
}
LLMeshSkinInfoHandler::~LLMeshSkinInfoHandler()
{
llassert(mProcessed);
}
void LLMeshSkinInfoHandler::processFailure(LLCore::HttpStatus status)
{
LL_WARNS(LOG_MESH) << "Error during mesh skin info handling. ID: " << mMeshID
<< ", Reason: " << status.toString()
<< " (" << status.toTerseString() << "). Not retrying."
<< LL_ENDL;
// *TODO: Mark mesh unavailable on error. For now, simply leave
// request unfulfilled rather than retry forever.
}
void LLMeshSkinInfoHandler::processData(LLCore::BufferArray * body, U8 * data, S32 data_size)
{
if ((! MESH_SKIN_INFO_PROCESS_FAILED) && gMeshRepo.mThread->skinInfoReceived(mMeshID, data, data_size))
{
// good fetch from sim, write to VFS for caching
LLVFile file(gVFS, mMeshID, LLAssetType::AT_MESH, LLVFile::WRITE);
S32 offset = mOffset;
S32 size = mRequestedBytes;
if (file.getSize() >= offset+size)
{
LLMeshRepository::sCacheBytesWritten += size;
++LLMeshRepository::sCacheWrites;
file.seek(offset);
file.write(data, size);
}
}
else
{
LL_WARNS(LOG_MESH) << "Error during mesh skin info processing. ID: " << mMeshID
<< ", Unknown reason. Not retrying."
<< LL_ENDL;
// *TODO: Mark mesh unavailable on error
}
}
LLMeshDecompositionHandler::~LLMeshDecompositionHandler()
{
llassert(mProcessed);
}
void LLMeshDecompositionHandler::processFailure(LLCore::HttpStatus status)
{
LL_WARNS(LOG_MESH) << "Error during mesh decomposition handling. ID: " << mMeshID
<< ", Reason: " << status.toString()
<< " (" << status.toTerseString() << "). Not retrying."
<< LL_ENDL;
// *TODO: Mark mesh unavailable on error. For now, simply leave
// request unfulfilled rather than retry forever.
}
void LLMeshDecompositionHandler::processData(LLCore::BufferArray * body, U8 * data, S32 data_size)
{
if ((! MESH_DECOMP_PROCESS_FAILED) && gMeshRepo.mThread->decompositionReceived(mMeshID, data, data_size))
{
// good fetch from sim, write to VFS for caching
LLVFile file(gVFS, mMeshID, LLAssetType::AT_MESH, LLVFile::WRITE);
S32 offset = mOffset;
S32 size = mRequestedBytes;
if (file.getSize() >= offset+size)
{
LLMeshRepository::sCacheBytesWritten += size;
++LLMeshRepository::sCacheWrites;
file.seek(offset);
file.write(data, size);
}
}
else
{
LL_WARNS(LOG_MESH) << "Error during mesh decomposition processing. ID: " << mMeshID
<< ", Unknown reason. Not retrying."
<< LL_ENDL;
// *TODO: Mark mesh unavailable on error
}
}
LLMeshPhysicsShapeHandler::~LLMeshPhysicsShapeHandler()
{
llassert(mProcessed);
}
void LLMeshPhysicsShapeHandler::processFailure(LLCore::HttpStatus status)
{
LL_WARNS(LOG_MESH) << "Error during mesh physics shape handling. ID: " << mMeshID
<< ", Reason: " << status.toString()
<< " (" << status.toTerseString() << "). Not retrying."
<< LL_ENDL;
// *TODO: Mark mesh unavailable on error
}
void LLMeshPhysicsShapeHandler::processData(LLCore::BufferArray * body, U8 * data, S32 data_size)
{
if ((! MESH_PHYS_SHAPE_PROCESS_FAILED) && gMeshRepo.mThread->physicsShapeReceived(mMeshID, data, data_size))
{
// good fetch from sim, write to VFS for caching
LLVFile file(gVFS, mMeshID, LLAssetType::AT_MESH, LLVFile::WRITE);
S32 offset = mOffset;
S32 size = mRequestedBytes;
if (file.getSize() >= offset+size)
{
LLMeshRepository::sCacheBytesWritten += size;
++LLMeshRepository::sCacheWrites;
file.seek(offset);
file.write(data, size);
}
}
else
{
LL_WARNS(LOG_MESH) << "Error during mesh physics shape processing. ID: " << mMeshID
<< ", Unknown reason. Not retrying."
<< LL_ENDL;
// *TODO: Mark mesh unavailable on error
}
}
LLMeshRepository::LLMeshRepository()
: mMeshMutex(NULL),
mMeshThreadCount(0),
mThread(NULL),
mGetMeshVersion(2)
{
}
void LLMeshRepository::init()
{
mMeshMutex = new LLMutex(NULL);
LLConvexDecomposition::getInstance()->initSystem();
mDecompThread = new LLPhysicsDecomp();
mDecompThread->start();
while (!mDecompThread->mInited)
{ //wait for physics decomp thread to init
apr_sleep(100);
}
metrics_teleport_started_signal = LLViewerMessage::getInstance()->setTeleportStartedCallback(teleport_started);
mThread = new LLMeshRepoThread();
mThread->start();
}
void LLMeshRepository::shutdown()
{
LL_INFOS(LOG_MESH) << "Shutting down mesh repository." << LL_ENDL;
metrics_teleport_started_signal.disconnect();
for (U32 i = 0; i < mUploads.size(); ++i)
{
LL_INFOS(LOG_MESH) << "Discard the pending mesh uploads." << LL_ENDL;
mUploads[i]->discard() ; //discard the uploading requests.
}
mThread->mSignal->signal();
while (!mThread->isStopped())
{
apr_sleep(10);
}
delete mThread;
mThread = NULL;
for (U32 i = 0; i < mUploads.size(); ++i)
{
LL_INFOS(LOG_MESH) << "Waiting for pending mesh upload " << (i + 1) << "/" << mUploads.size() << LL_ENDL;
while (!mUploads[i]->isStopped())
{
apr_sleep(10);
}
delete mUploads[i];
}
mUploads.clear();
delete mMeshMutex;
mMeshMutex = NULL;
LL_INFOS(LOG_MESH) << "Shutting down decomposition system." << LL_ENDL;
if (mDecompThread)
{
mDecompThread->shutdown();
delete mDecompThread;
mDecompThread = NULL;
}
LLConvexDecomposition::quitSystem();
}
//called in the main thread.
S32 LLMeshRepository::update()
{
// Conditionally log a mesh metrics event
metricsUpdate();
if(mUploadWaitList.empty())
{
return 0 ;
}
S32 size = mUploadWaitList.size() ;
for (S32 i = 0; i < size; ++i)
{
mUploads.push_back(mUploadWaitList[i]);
mUploadWaitList[i]->preStart() ;
mUploadWaitList[i]->start() ;
}
mUploadWaitList.clear() ;
return size ;
}
S32 LLMeshRepository::loadMesh(LLVOVolume* vobj, const LLVolumeParams& mesh_params, S32 detail, S32 last_lod)
{
MESH_FASTTIMER_DEFBLOCK;
// Manage time-to-load metrics for mesh download operations.
metricsProgress(1);
if (detail < 0 || detail >= 4)
{
return detail;
}
{
LLMutexLock lock(mMeshMutex);
//add volume to list of loading meshes
mesh_load_map::iterator iter = mLoadingMeshes[detail].find(mesh_params);
if (iter != mLoadingMeshes[detail].end())
{ //request pending for this mesh, append volume id to list
iter->second.insert(vobj->getID());
}
else
{
//first request for this mesh
mLoadingMeshes[detail][mesh_params].insert(vobj->getID());
mPendingRequests.push_back(LLMeshRepoThread::LODRequest(mesh_params, detail));
LLMeshRepository::sLODPending++;
}
}
//do a quick search to see if we can't display something while we wait for this mesh to load
LLVolume* volume = vobj->getVolume();
if (volume)
{
LLVolumeParams params = volume->getParams();
LLVolumeLODGroup* group = LLPrimitive::getVolumeManager()->getGroup(params);
if (group)
{
//first, see if last_lod is available (don't transition down to avoid funny popping a la SH-641)
if (last_lod >= 0)
{
LLVolume* lod = group->refLOD(last_lod);
if (lod && lod->isMeshAssetLoaded() && lod->getNumVolumeFaces() > 0)
{
group->derefLOD(lod);
return last_lod;
}
group->derefLOD(lod);
}
//next, see what the next lowest LOD available might be
for (S32 i = detail-1; i >= 0; --i)
{
LLVolume* lod = group->refLOD(i);
if (lod && lod->isMeshAssetLoaded() && lod->getNumVolumeFaces() > 0)
{
group->derefLOD(lod);
return i;
}
group->derefLOD(lod);
}
//no lower LOD is a available, is a higher lod available?
for (S32 i = detail+1; i < 4; ++i)
{
LLVolume* lod = group->refLOD(i);
if (lod && lod->isMeshAssetLoaded() && lod->getNumVolumeFaces() > 0)
{
group->derefLOD(lod);
return i;
}
group->derefLOD(lod);
}
}
}
return detail;
}
void LLMeshRepository::notifyLoadedMeshes()
{ //called from main thread
MESH_FASTTIMER_DEFBLOCK;
if (1 == mGetMeshVersion)
{
// Legacy GetMesh operation with high connection concurrency
LLMeshRepoThread::sMaxConcurrentRequests = gSavedSettings.getU32("MeshMaxConcurrentRequests");
LLMeshRepoThread::sRequestHighWater = llclamp(2 * S32(LLMeshRepoThread::sMaxConcurrentRequests),
REQUEST_HIGH_WATER_MIN,
REQUEST_HIGH_WATER_MAX);
LLMeshRepoThread::sRequestLowWater = llclamp(LLMeshRepoThread::sRequestHighWater / 2,
REQUEST_LOW_WATER_MIN,
REQUEST_LOW_WATER_MAX);
}
else
{
// GetMesh2 operation with keepalives, etc. With pipelining,
// we'll increase this.
LLMeshRepoThread::sMaxConcurrentRequests = gSavedSettings.getU32("Mesh2MaxConcurrentRequests");
LLMeshRepoThread::sRequestHighWater = llclamp(5 * S32(LLMeshRepoThread::sMaxConcurrentRequests),
REQUEST2_HIGH_WATER_MIN,
REQUEST2_HIGH_WATER_MAX);
LLMeshRepoThread::sRequestLowWater = llclamp(LLMeshRepoThread::sRequestHighWater / 2,
REQUEST2_LOW_WATER_MIN,
REQUEST2_LOW_WATER_MAX);
}
//clean up completed upload threads
for (std::vector<LLMeshUploadThread*>::iterator iter = mUploads.begin(); iter != mUploads.end(); )
{
LLMeshUploadThread* thread = *iter;
if (thread->isStopped() && thread->finished())
{
iter = mUploads.erase(iter);
delete thread;
}
else
{
++iter;
}
}
//update inventory
if (!mInventoryQ.empty())
{
LLMutexLock lock(mMeshMutex);
while (!mInventoryQ.empty())
{
inventory_data& data = mInventoryQ.front();
LLAssetType::EType asset_type = LLAssetType::lookup(data.mPostData["asset_type"].asString());
LLInventoryType::EType inventory_type = LLInventoryType::lookup(data.mPostData["inventory_type"].asString());
// Handle addition of texture, if any.
if ( data.mResponse.has("new_texture_folder_id") )
{
const LLUUID& folder_id = data.mResponse["new_texture_folder_id"].asUUID();
if ( folder_id.notNull() )
{
LLUUID parent_id = gInventory.findCategoryUUIDForType(LLFolderType::FT_TEXTURE);
std::string name;
// Check if the server built a different name for the texture folder
if ( data.mResponse.has("new_texture_folder_name") )
{
name = data.mResponse["new_texture_folder_name"].asString();
}
else
{
name = data.mPostData["name"].asString();
}
// Add the category to the internal representation
LLPointer<LLViewerInventoryCategory> cat =
new LLViewerInventoryCategory(folder_id, parent_id,
LLFolderType::FT_NONE, name, gAgent.getID());
cat->setVersion(LLViewerInventoryCategory::VERSION_UNKNOWN);
LLInventoryModel::LLCategoryUpdate update(cat->getParentUUID(), 1);
gInventory.accountForUpdate(update);
gInventory.updateCategory(cat);
}
}
on_new_single_inventory_upload_complete(
asset_type,
inventory_type,
data.mPostData["asset_type"].asString(),
data.mPostData["folder_id"].asUUID(),
data.mPostData["name"],
data.mPostData["description"],
data.mResponse,
data.mResponse["upload_price"]);
//}
mInventoryQ.pop();
}
}
//call completed callbacks on finished decompositions
mDecompThread->notifyCompleted();
// For major operations, attempt to get the required locks
// without blocking and punt if they're not available. The
// longest run of holdoffs is kept in sMaxLockHoldoffs just
// to collect the data. In testing, I've never seen a value
// greater than 2 (written to log on exit).
{
LLMutexTrylock lock1(mMeshMutex);
LLMutexTrylock lock2(mThread->mMutex);
static U32 hold_offs(0);
if (! lock1.isLocked() || ! lock2.isLocked())
{
// If we can't get the locks, skip and pick this up later.
++hold_offs;
sMaxLockHoldoffs = llmax(sMaxLockHoldoffs, hold_offs);
return;
}
hold_offs = 0;
if (gAgent.getRegion())
{
// Update capability urls
static std::string region_name("never name a region this");
if (gAgent.getRegion()->getName() != region_name && gAgent.getRegion()->capabilitiesReceived())
{
region_name = gAgent.getRegion()->getName();
const bool use_v1(gSavedSettings.getBOOL("MeshUseGetMesh1"));
const std::string mesh1(gAgent.getRegion()->getCapability("GetMesh"));
const std::string mesh2(gAgent.getRegion()->getCapability("GetMesh2"));
mGetMeshVersion = (mesh2.empty() || use_v1) ? 1 : 2;
mThread->setGetMeshCaps(mesh1, mesh2, mGetMeshVersion);
LL_DEBUGS(LOG_MESH) << "Retrieving caps for region '" << region_name
<< "', GetMesh2: " << mesh2
<< ", GetMesh: " << mesh1
<< ", using version: " << mGetMeshVersion
<< LL_ENDL;
}
}
//popup queued error messages from background threads
while (!mUploadErrorQ.empty())
{
LLNotificationsUtil::add("MeshUploadError", mUploadErrorQ.front());
mUploadErrorQ.pop();
}
S32 active_count = LLMeshRepoThread::sActiveHeaderRequests + LLMeshRepoThread::sActiveLODRequests;
if (active_count < LLMeshRepoThread::sRequestLowWater)
{
S32 push_count = LLMeshRepoThread::sRequestHighWater - active_count;
if (mPendingRequests.size() > push_count)
{
// More requests than the high-water limit allows so
// sort and forward the most important.
//calculate "score" for pending requests
//create score map
std::map<LLUUID, F32> score_map;
for (U32 i = 0; i < 4; ++i)
{
for (mesh_load_map::iterator iter = mLoadingMeshes[i].begin(); iter != mLoadingMeshes[i].end(); ++iter)
{
F32 max_score = 0.f;
for (std::set<LLUUID>::iterator obj_iter = iter->second.begin(); obj_iter != iter->second.end(); ++obj_iter)
{
LLViewerObject* object = gObjectList.findObject(*obj_iter);
if (object)
{
LLDrawable* drawable = object->mDrawable;
if (drawable)
{
F32 cur_score = drawable->getRadius()/llmax(drawable->mDistanceWRTCamera, 1.f);
max_score = llmax(max_score, cur_score);
}
}
}
score_map[iter->first.getSculptID()] = max_score;
}
}
//set "score" for pending requests
for (std::vector<LLMeshRepoThread::LODRequest>::iterator iter = mPendingRequests.begin(); iter != mPendingRequests.end(); ++iter)
{
iter->mScore = score_map[iter->mMeshParams.getSculptID()];
}
//sort by "score"
std::partial_sort(mPendingRequests.begin(), mPendingRequests.begin() + push_count,
mPendingRequests.end(), LLMeshRepoThread::CompareScoreGreater());
}
while (!mPendingRequests.empty() && push_count > 0)
{
LLMeshRepoThread::LODRequest& request = mPendingRequests.front();
mThread->loadMeshLOD(request.mMeshParams, request.mLOD);
mPendingRequests.erase(mPendingRequests.begin());
LLMeshRepository::sLODPending--;
push_count--;
}
}
//send skin info requests
while (!mPendingSkinRequests.empty())
{
mThread->loadMeshSkinInfo(mPendingSkinRequests.front());
mPendingSkinRequests.pop();
}
//send decomposition requests
while (!mPendingDecompositionRequests.empty())
{
mThread->loadMeshDecomposition(mPendingDecompositionRequests.front());
mPendingDecompositionRequests.pop();
}
//send physics shapes decomposition requests
while (!mPendingPhysicsShapeRequests.empty())
{
mThread->loadMeshPhysicsShape(mPendingPhysicsShapeRequests.front());
mPendingPhysicsShapeRequests.pop();
}
mThread->notifyLoadedMeshes();
}
mThread->mSignal->signal();
}
void LLMeshRepository::notifySkinInfoReceived(LLMeshSkinInfo& info)
{
mSkinMap[info.mMeshID] = info;
skin_load_map::iterator iter = mLoadingSkins.find(info.mMeshID);
if (iter != mLoadingSkins.end())
{
for (std::set<LLUUID>::iterator obj_id = iter->second.begin(); obj_id != iter->second.end(); ++obj_id)
{
LLVOVolume* vobj = (LLVOVolume*) gObjectList.findObject(*obj_id);
if (vobj)
{
vobj->notifyMeshLoaded();
}
}
mLoadingSkins.erase(info.mMeshID);
}
}
void LLMeshRepository::notifyDecompositionReceived(LLModel::Decomposition* decomp)
{
decomposition_map::iterator iter = mDecompositionMap.find(decomp->mMeshID);
if (iter == mDecompositionMap.end())
{ //just insert decomp into map
mDecompositionMap[decomp->mMeshID] = decomp;
mLoadingDecompositions.erase(decomp->mMeshID);
}
else
{ //merge decomp with existing entry
iter->second->merge(decomp);
mLoadingDecompositions.erase(decomp->mMeshID);
delete decomp;
}
}
void LLMeshRepository::notifyMeshLoaded(const LLVolumeParams& mesh_params, LLVolume* volume)
{ //called from main thread
S32 detail = LLVolumeLODGroup::getVolumeDetailFromScale(volume->getDetail());
//get list of objects waiting to be notified this mesh is loaded
mesh_load_map::iterator obj_iter = mLoadingMeshes[detail].find(mesh_params);
if (volume && obj_iter != mLoadingMeshes[detail].end())
{
//make sure target volume is still valid
if (volume->getNumVolumeFaces() <= 0)
{
LL_WARNS(LOG_MESH) << "Mesh loading returned empty volume. ID: " << mesh_params.getSculptID()
<< LL_ENDL;
}
{ //update system volume
LLVolume* sys_volume = LLPrimitive::getVolumeManager()->refVolume(mesh_params, detail);
if (sys_volume)
{
sys_volume->copyVolumeFaces(volume);
sys_volume->setMeshAssetLoaded(TRUE);
LLPrimitive::getVolumeManager()->unrefVolume(sys_volume);
}
else
{
LL_WARNS(LOG_MESH) << "Couldn't find system volume for mesh " << mesh_params.getSculptID()
<< LL_ENDL;
}
}
//notify waiting LLVOVolume instances that their requested mesh is available
for (std::set<LLUUID>::iterator vobj_iter = obj_iter->second.begin(); vobj_iter != obj_iter->second.end(); ++vobj_iter)
{
LLVOVolume* vobj = (LLVOVolume*) gObjectList.findObject(*vobj_iter);
if (vobj)
{
vobj->notifyMeshLoaded();
}
}
mLoadingMeshes[detail].erase(mesh_params);
}
}
void LLMeshRepository::notifyMeshUnavailable(const LLVolumeParams& mesh_params, S32 lod)
{ //called from main thread
//get list of objects waiting to be notified this mesh is loaded
mesh_load_map::iterator obj_iter = mLoadingMeshes[lod].find(mesh_params);
F32 detail = LLVolumeLODGroup::getVolumeScaleFromDetail(lod);
if (obj_iter != mLoadingMeshes[lod].end())
{
for (std::set<LLUUID>::iterator vobj_iter = obj_iter->second.begin(); vobj_iter != obj_iter->second.end(); ++vobj_iter)
{
LLVOVolume* vobj = (LLVOVolume*) gObjectList.findObject(*vobj_iter);
if (vobj)
{
LLVolume* obj_volume = vobj->getVolume();
if (obj_volume &&
obj_volume->getDetail() == detail &&
obj_volume->getParams() == mesh_params)
{ //should force volume to find most appropriate LOD
vobj->setVolume(obj_volume->getParams(), lod);
}
}
}
mLoadingMeshes[lod].erase(mesh_params);
}
}
S32 LLMeshRepository::getActualMeshLOD(const LLVolumeParams& mesh_params, S32 lod)
{
return mThread->getActualMeshLOD(mesh_params, lod);
}
const LLMeshSkinInfo* LLMeshRepository::getSkinInfo(const LLUUID& mesh_id, const LLVOVolume* requesting_obj)
{
MESH_FASTTIMER_DEFBLOCK;
if (mesh_id.notNull())
{
skin_map::iterator iter = mSkinMap.find(mesh_id);
if (iter != mSkinMap.end())
{
return &(iter->second);
}
//no skin info known about given mesh, try to fetch it
{
LLMutexLock lock(mMeshMutex);
//add volume to list of loading meshes
skin_load_map::iterator iter = mLoadingSkins.find(mesh_id);
if (iter == mLoadingSkins.end())
{ //no request pending for this skin info
mPendingSkinRequests.push(mesh_id);
}
mLoadingSkins[mesh_id].insert(requesting_obj->getID());
}
}
return NULL;
}
void LLMeshRepository::fetchPhysicsShape(const LLUUID& mesh_id)
{
MESH_FASTTIMER_DEFBLOCK;
if (mesh_id.notNull())
{
LLModel::Decomposition* decomp = NULL;
decomposition_map::iterator iter = mDecompositionMap.find(mesh_id);
if (iter != mDecompositionMap.end())
{
decomp = iter->second;
}
//decomposition block hasn't been fetched yet
if (!decomp || decomp->mPhysicsShapeMesh.empty())
{
LLMutexLock lock(mMeshMutex);
//add volume to list of loading meshes
std::set<LLUUID>::iterator iter = mLoadingPhysicsShapes.find(mesh_id);
if (iter == mLoadingPhysicsShapes.end())
{ //no request pending for this skin info
// *FIXME: Nothing ever deletes entries, can't be right
mLoadingPhysicsShapes.insert(mesh_id);
mPendingPhysicsShapeRequests.push(mesh_id);
}
}
}
}
LLModel::Decomposition* LLMeshRepository::getDecomposition(const LLUUID& mesh_id)
{
MESH_FASTTIMER_DEFBLOCK;
LLModel::Decomposition* ret = NULL;
if (mesh_id.notNull())
{
decomposition_map::iterator iter = mDecompositionMap.find(mesh_id);
if (iter != mDecompositionMap.end())
{
ret = iter->second;
}
//decomposition block hasn't been fetched yet
if (!ret || ret->mBaseHullMesh.empty())
{
LLMutexLock lock(mMeshMutex);
//add volume to list of loading meshes
std::set<LLUUID>::iterator iter = mLoadingDecompositions.find(mesh_id);
if (iter == mLoadingDecompositions.end())
{ //no request pending for this skin info
mLoadingDecompositions.insert(mesh_id);
mPendingDecompositionRequests.push(mesh_id);
}
}
}
return ret;
}
void LLMeshRepository::buildHull(const LLVolumeParams& params, S32 detail)
{
LLVolume* volume = LLPrimitive::sVolumeManager->refVolume(params, detail);
if (!volume->mHullPoints)
{
//all default params
//execute first stage
//set simplify mode to retain
//set retain percentage to zero
//run second stage
}
LLPrimitive::sVolumeManager->unrefVolume(volume);
}
bool LLMeshRepository::hasPhysicsShape(const LLUUID& mesh_id)
{
LLSD mesh = mThread->getMeshHeader(mesh_id);
if (mesh.has("physics_mesh") && mesh["physics_mesh"].has("size") && (mesh["physics_mesh"]["size"].asInteger() > 0))
{
return true;
}
LLModel::Decomposition* decomp = getDecomposition(mesh_id);
if (decomp && !decomp->mHull.empty())
{
return true;
}
return false;
}
LLSD& LLMeshRepository::getMeshHeader(const LLUUID& mesh_id)
{
MESH_FASTTIMER_DEFBLOCK;
return mThread->getMeshHeader(mesh_id);
}
LLSD& LLMeshRepoThread::getMeshHeader(const LLUUID& mesh_id)
{
static LLSD dummy_ret;
if (mesh_id.notNull())
{
LLMutexLock lock(mHeaderMutex);
mesh_header_map::iterator iter = mMeshHeader.find(mesh_id);
if (iter != mMeshHeader.end())
{
return iter->second;
}
}
return dummy_ret;
}
void LLMeshRepository::uploadModel(std::vector<LLModelInstance>& data, LLVector3& scale, bool upload_textures,
bool upload_skin, bool upload_joints, std::string upload_url, bool do_upload,
LLHandle<LLWholeModelFeeObserver> fee_observer, LLHandle<LLWholeModelUploadObserver> upload_observer)
{
LLMeshUploadThread* thread = new LLMeshUploadThread(data, scale, upload_textures, upload_skin, upload_joints, upload_url,
do_upload, fee_observer, upload_observer);
mUploadWaitList.push_back(thread);
}
S32 LLMeshRepository::getMeshSize(const LLUUID& mesh_id, S32 lod)
{
if (mThread)
{
LLMeshRepoThread::mesh_header_map::iterator iter = mThread->mMeshHeader.find(mesh_id);
if (iter != mThread->mMeshHeader.end())
{
LLSD& header = iter->second;
if (header.has("404"))
{
return -1;
}
S32 size = header[header_lod[lod]]["size"].asInteger();
return size;
}
}
return -1;
}
void LLMeshUploadThread::decomposeMeshMatrix(LLMatrix4& transformation,
LLVector3& result_pos,
LLQuaternion& result_rot,
LLVector3& result_scale)
{
// check for reflection
BOOL reflected = (transformation.determinant() < 0);
// compute position
LLVector3 position = LLVector3(0, 0, 0) * transformation;
// compute scale
LLVector3 x_transformed = LLVector3(1, 0, 0) * transformation - position;
LLVector3 y_transformed = LLVector3(0, 1, 0) * transformation - position;
LLVector3 z_transformed = LLVector3(0, 0, 1) * transformation - position;
F32 x_length = x_transformed.normalize();
F32 y_length = y_transformed.normalize();
F32 z_length = z_transformed.normalize();
LLVector3 scale = LLVector3(x_length, y_length, z_length);
// adjust for "reflected" geometry
LLVector3 x_transformed_reflected = x_transformed;
if (reflected)
{
x_transformed_reflected *= -1.0;
}
// compute rotation
LLMatrix3 rotation_matrix;
rotation_matrix.setRows(x_transformed_reflected, y_transformed, z_transformed);
LLQuaternion quat_rotation = rotation_matrix.quaternion();
quat_rotation.normalize(); // the rotation_matrix might not have been orthoginal. make it so here.
LLVector3 euler_rotation;
quat_rotation.getEulerAngles(&euler_rotation.mV[VX], &euler_rotation.mV[VY], &euler_rotation.mV[VZ]);
result_pos = position + mOrigin;
result_scale = scale;
result_rot = quat_rotation;
}
bool LLImportMaterial::operator<(const LLImportMaterial &rhs) const
{
if (mDiffuseMap != rhs.mDiffuseMap)
{
return mDiffuseMap < rhs.mDiffuseMap;
}
if (mDiffuseMapFilename != rhs.mDiffuseMapFilename)
{
return mDiffuseMapFilename < rhs.mDiffuseMapFilename;
}
if (mDiffuseMapLabel != rhs.mDiffuseMapLabel)
{
return mDiffuseMapLabel < rhs.mDiffuseMapLabel;
}
if (mDiffuseColor != rhs.mDiffuseColor)
{
return mDiffuseColor < rhs.mDiffuseColor;
}
if (mBinding != rhs.mBinding)
{
return mBinding < rhs.mBinding;
}
return mFullbright < rhs.mFullbright;
}
void LLMeshRepository::updateInventory(inventory_data data)
{
LLMutexLock lock(mMeshMutex);
dump_llsd_to_file(data.mPostData,make_dump_name("update_inventory_post_data_",dump_num));
dump_llsd_to_file(data.mResponse,make_dump_name("update_inventory_response_",dump_num));
mInventoryQ.push(data);
}
void LLMeshRepository::uploadError(LLSD& args)
{
LLMutexLock lock(mMeshMutex);
mUploadErrorQ.push(args);
}
//static
F32 LLMeshRepository::getStreamingCost(LLSD& header, F32 radius, S32* bytes, S32* bytes_visible, S32 lod, F32 *unscaled_value)
{
F32 max_distance = 512.f;
F32 dlowest = llmin(radius/0.03f, max_distance);
F32 dlow = llmin(radius/0.06f, max_distance);
F32 dmid = llmin(radius/0.24f, max_distance);
F32 METADATA_DISCOUNT = (F32) gSavedSettings.getU32("MeshMetaDataDiscount"); //discount 128 bytes to cover the cost of LLSD tags and compression domain overhead
F32 MINIMUM_SIZE = (F32) gSavedSettings.getU32("MeshMinimumByteSize"); //make sure nothing is "free"
F32 bytes_per_triangle = (F32) gSavedSettings.getU32("MeshBytesPerTriangle");
S32 bytes_lowest = header["lowest_lod"]["size"].asInteger();
S32 bytes_low = header["low_lod"]["size"].asInteger();
S32 bytes_mid = header["medium_lod"]["size"].asInteger();
S32 bytes_high = header["high_lod"]["size"].asInteger();
if (bytes_high == 0)
{
return 0.f;
}
if (bytes_mid == 0)
{
bytes_mid = bytes_high;
}
if (bytes_low == 0)
{
bytes_low = bytes_mid;
}
if (bytes_lowest == 0)
{
bytes_lowest = bytes_low;
}
F32 triangles_lowest = llmax((F32) bytes_lowest-METADATA_DISCOUNT, MINIMUM_SIZE)/bytes_per_triangle;
F32 triangles_low = llmax((F32) bytes_low-METADATA_DISCOUNT, MINIMUM_SIZE)/bytes_per_triangle;
F32 triangles_mid = llmax((F32) bytes_mid-METADATA_DISCOUNT, MINIMUM_SIZE)/bytes_per_triangle;
F32 triangles_high = llmax((F32) bytes_high-METADATA_DISCOUNT, MINIMUM_SIZE)/bytes_per_triangle;
if (bytes)
{
*bytes = 0;
*bytes += header["lowest_lod"]["size"].asInteger();
*bytes += header["low_lod"]["size"].asInteger();
*bytes += header["medium_lod"]["size"].asInteger();
*bytes += header["high_lod"]["size"].asInteger();
}
if (bytes_visible)
{
lod = LLMeshRepository::getActualMeshLOD(header, lod);
if (lod >= 0 && lod <= 3)
{
*bytes_visible = header[header_lod[lod]]["size"].asInteger();
}
}
F32 max_area = 102932.f; //area of circle that encompasses region
F32 min_area = 1.f;
F32 high_area = llmin(F_PI*dmid*dmid, max_area);
F32 mid_area = llmin(F_PI*dlow*dlow, max_area);
F32 low_area = llmin(F_PI*dlowest*dlowest, max_area);
F32 lowest_area = max_area;
lowest_area -= low_area;
low_area -= mid_area;
mid_area -= high_area;
high_area = llclamp(high_area, min_area, max_area);
mid_area = llclamp(mid_area, min_area, max_area);
low_area = llclamp(low_area, min_area, max_area);
lowest_area = llclamp(lowest_area, min_area, max_area);
F32 total_area = high_area + mid_area + low_area + lowest_area;
high_area /= total_area;
mid_area /= total_area;
low_area /= total_area;
lowest_area /= total_area;
F32 weighted_avg = triangles_high*high_area +
triangles_mid*mid_area +
triangles_low*low_area +
triangles_lowest*lowest_area;
if (unscaled_value)
{
*unscaled_value = weighted_avg;
}
return weighted_avg/gSavedSettings.getU32("MeshTriangleBudget")*15000.f;
}
LLPhysicsDecomp::LLPhysicsDecomp()
: LLThread("Physics Decomp")
{
mInited = false;
mQuitting = false;
mDone = false;
mSignal = new LLCondition(NULL);
mMutex = new LLMutex(NULL);
}
LLPhysicsDecomp::~LLPhysicsDecomp()
{
shutdown();
delete mSignal;
mSignal = NULL;
delete mMutex;
mMutex = NULL;
}
void LLPhysicsDecomp::shutdown()
{
if (mSignal)
{
mQuitting = true;
mSignal->signal();
while (!isStopped())
{
apr_sleep(10);
}
}
}
void LLPhysicsDecomp::submitRequest(LLPhysicsDecomp::Request* request)
{
LLMutexLock lock(mMutex);
mRequestQ.push(request);
mSignal->signal();
}
//static
S32 LLPhysicsDecomp::llcdCallback(const char* status, S32 p1, S32 p2)
{
if (gMeshRepo.mDecompThread && gMeshRepo.mDecompThread->mCurRequest.notNull())
{
return gMeshRepo.mDecompThread->mCurRequest->statusCallback(status, p1, p2);
}
return 1;
}
void LLPhysicsDecomp::setMeshData(LLCDMeshData& mesh, bool vertex_based)
{
mesh.mVertexBase = mCurRequest->mPositions[0].mV;
mesh.mVertexStrideBytes = 12;
mesh.mNumVertices = mCurRequest->mPositions.size();
if(!vertex_based)
{
mesh.mIndexType = LLCDMeshData::INT_16;
mesh.mIndexBase = &(mCurRequest->mIndices[0]);
mesh.mIndexStrideBytes = 6;
mesh.mNumTriangles = mCurRequest->mIndices.size()/3;
}
if ((vertex_based || mesh.mNumTriangles > 0) && mesh.mNumVertices > 2)
{
LLCDResult ret = LLCD_OK;
if (LLConvexDecomposition::getInstance() != NULL)
{
ret = LLConvexDecomposition::getInstance()->setMeshData(&mesh, vertex_based);
}
if (ret)
{
LL_ERRS(LOG_MESH) << "Convex Decomposition thread valid but could not set mesh data." << LL_ENDL;
}
}
}
void LLPhysicsDecomp::doDecomposition()
{
LLCDMeshData mesh;
S32 stage = mStageID[mCurRequest->mStage];
if (LLConvexDecomposition::getInstance() == NULL)
{
// stub library. do nothing.
return;
}
//load data intoLLCD
if (stage == 0)
{
setMeshData(mesh, false);
}
//build parameter map
std::map<std::string, const LLCDParam*> param_map;
static const LLCDParam* params = NULL;
static S32 param_count = 0;
if (!params)
{
param_count = LLConvexDecomposition::getInstance()->getParameters(¶ms);
}
for (S32 i = 0; i < param_count; ++i)
{
param_map[params[i].mName] = params+i;
}
U32 ret = LLCD_OK;
//set parameter values
for (decomp_params::iterator iter = mCurRequest->mParams.begin(); iter != mCurRequest->mParams.end(); ++iter)
{
const std::string& name = iter->first;
const LLSD& value = iter->second;
const LLCDParam* param = param_map[name];
if (param == NULL)
{ //couldn't find valid parameter
continue;
}
if (param->mType == LLCDParam::LLCD_FLOAT)
{
ret = LLConvexDecomposition::getInstance()->setParam(param->mName, (F32) value.asReal());
}
else if (param->mType == LLCDParam::LLCD_INTEGER ||
param->mType == LLCDParam::LLCD_ENUM)
{
ret = LLConvexDecomposition::getInstance()->setParam(param->mName, value.asInteger());
}
else if (param->mType == LLCDParam::LLCD_BOOLEAN)
{
ret = LLConvexDecomposition::getInstance()->setParam(param->mName, value.asBoolean());
}
}
mCurRequest->setStatusMessage("Executing.");
if (LLConvexDecomposition::getInstance() != NULL)
{
ret = LLConvexDecomposition::getInstance()->executeStage(stage);
}
if (ret)
{
LL_WARNS(LOG_MESH) << "Convex Decomposition thread valid but could not execute stage " << stage << "."
<< LL_ENDL;
LLMutexLock lock(mMutex);
mCurRequest->mHull.clear();
mCurRequest->mHullMesh.clear();
mCurRequest->setStatusMessage("FAIL");
completeCurrent();
}
else
{
mCurRequest->setStatusMessage("Reading results");
S32 num_hulls =0;
if (LLConvexDecomposition::getInstance() != NULL)
{
num_hulls = LLConvexDecomposition::getInstance()->getNumHullsFromStage(stage);
}
{
LLMutexLock lock(mMutex);
mCurRequest->mHull.clear();
mCurRequest->mHull.resize(num_hulls);
mCurRequest->mHullMesh.clear();
mCurRequest->mHullMesh.resize(num_hulls);
}
for (S32 i = 0; i < num_hulls; ++i)
{
std::vector<LLVector3> p;
LLCDHull hull;
// if LLConvexDecomposition is a stub, num_hulls should have been set to 0 above, and we should not reach this code
LLConvexDecomposition::getInstance()->getHullFromStage(stage, i, &hull);
const F32* v = hull.mVertexBase;
for (S32 j = 0; j < hull.mNumVertices; ++j)
{
LLVector3 vert(v[0], v[1], v[2]);
p.push_back(vert);
v = (F32*) (((U8*) v) + hull.mVertexStrideBytes);
}
LLCDMeshData mesh;
// if LLConvexDecomposition is a stub, num_hulls should have been set to 0 above, and we should not reach this code
LLConvexDecomposition::getInstance()->getMeshFromStage(stage, i, &mesh);
get_vertex_buffer_from_mesh(mesh, mCurRequest->mHullMesh[i]);
{
LLMutexLock lock(mMutex);
mCurRequest->mHull[i] = p;
}
}
{
LLMutexLock lock(mMutex);
mCurRequest->setStatusMessage("FAIL");
completeCurrent();
}
}
}
void LLPhysicsDecomp::completeCurrent()
{
LLMutexLock lock(mMutex);
mCompletedQ.push(mCurRequest);
mCurRequest = NULL;
}
void LLPhysicsDecomp::notifyCompleted()
{
if (!mCompletedQ.empty())
{
LLMutexLock lock(mMutex);
while (!mCompletedQ.empty())
{
Request* req = mCompletedQ.front();
req->completed();
mCompletedQ.pop();
}
}
}
void make_box(LLPhysicsDecomp::Request * request)
{
LLVector3 min,max;
min = request->mPositions[0];
max = min;
for (U32 i = 0; i < request->mPositions.size(); ++i)
{
update_min_max(min, max, request->mPositions[i]);
}
request->mHull.clear();
LLModel::hull box;
box.push_back(LLVector3(min[0],min[1],min[2]));
box.push_back(LLVector3(max[0],min[1],min[2]));
box.push_back(LLVector3(min[0],max[1],min[2]));
box.push_back(LLVector3(max[0],max[1],min[2]));
box.push_back(LLVector3(min[0],min[1],max[2]));
box.push_back(LLVector3(max[0],min[1],max[2]));
box.push_back(LLVector3(min[0],max[1],max[2]));
box.push_back(LLVector3(max[0],max[1],max[2]));
request->mHull.push_back(box);
}
void LLPhysicsDecomp::doDecompositionSingleHull()
{
LLConvexDecomposition* decomp = LLConvexDecomposition::getInstance();
if (decomp == NULL)
{
//stub. do nothing.
return;
}
LLCDMeshData mesh;
setMeshData(mesh, true);
LLCDResult ret = decomp->buildSingleHull() ;
if (ret)
{
LL_WARNS(LOG_MESH) << "Could not execute decomposition stage when attempting to create single hull." << LL_ENDL;
make_box(mCurRequest);
}
else
{
{
LLMutexLock lock(mMutex);
mCurRequest->mHull.clear();
mCurRequest->mHull.resize(1);
mCurRequest->mHullMesh.clear();
}
std::vector<LLVector3> p;
LLCDHull hull;
// if LLConvexDecomposition is a stub, num_hulls should have been set to 0 above, and we should not reach this code
decomp->getSingleHull(&hull);
const F32* v = hull.mVertexBase;
for (S32 j = 0; j < hull.mNumVertices; ++j)
{
LLVector3 vert(v[0], v[1], v[2]);
p.push_back(vert);
v = (F32*) (((U8*) v) + hull.mVertexStrideBytes);
}
{
LLMutexLock lock(mMutex);
mCurRequest->mHull[0] = p;
}
}
{
completeCurrent();
}
}
void LLPhysicsDecomp::run()
{
LLConvexDecomposition* decomp = LLConvexDecomposition::getInstance();
if (decomp == NULL)
{
// stub library. Set init to true so the main thread
// doesn't wait for this to finish.
mInited = true;
return;
}
decomp->initThread();
mInited = true;
static const LLCDStageData* stages = NULL;
static S32 num_stages = 0;
if (!stages)
{
num_stages = decomp->getStages(&stages);
}
for (S32 i = 0; i < num_stages; i++)
{
mStageID[stages[i].mName] = i;
}
while (!mQuitting)
{
mSignal->wait();
while (!mQuitting && !mRequestQ.empty())
{
{
LLMutexLock lock(mMutex);
mCurRequest = mRequestQ.front();
mRequestQ.pop();
}
S32& id = *(mCurRequest->mDecompID);
if (id == -1)
{
decomp->genDecomposition(id);
}
decomp->bindDecomposition(id);
if (mCurRequest->mStage == "single_hull")
{
doDecompositionSingleHull();
}
else
{
doDecomposition();
}
}
}
decomp->quitThread();
if (mSignal->isLocked())
{ //let go of mSignal's associated mutex
mSignal->unlock();
}
mDone = true;
}
void LLPhysicsDecomp::Request::assignData(LLModel* mdl)
{
if (!mdl)
{
return ;
}
U16 index_offset = 0;
U16 tri[3] ;
mPositions.clear();
mIndices.clear();
mBBox[1] = LLVector3(F32_MIN, F32_MIN, F32_MIN) ;
mBBox[0] = LLVector3(F32_MAX, F32_MAX, F32_MAX) ;
//queue up vertex positions and indices
for (S32 i = 0; i < mdl->getNumVolumeFaces(); ++i)
{
const LLVolumeFace& face = mdl->getVolumeFace(i);
if (mPositions.size() + face.mNumVertices > 65535)
{
continue;
}
for (U32 j = 0; j < face.mNumVertices; ++j)
{
mPositions.push_back(LLVector3(face.mPositions[j].getF32ptr()));
for(U32 k = 0 ; k < 3 ; k++)
{
mBBox[0].mV[k] = llmin(mBBox[0].mV[k], mPositions[j].mV[k]) ;
mBBox[1].mV[k] = llmax(mBBox[1].mV[k], mPositions[j].mV[k]) ;
}
}
updateTriangleAreaThreshold() ;
for (U32 j = 0; j+2 < face.mNumIndices; j += 3)
{
tri[0] = face.mIndices[j] + index_offset ;
tri[1] = face.mIndices[j + 1] + index_offset ;
tri[2] = face.mIndices[j + 2] + index_offset ;
if(isValidTriangle(tri[0], tri[1], tri[2]))
{
mIndices.push_back(tri[0]);
mIndices.push_back(tri[1]);
mIndices.push_back(tri[2]);
}
}
index_offset += face.mNumVertices;
}
return ;
}
void LLPhysicsDecomp::Request::updateTriangleAreaThreshold()
{
F32 range = mBBox[1].mV[0] - mBBox[0].mV[0] ;
range = llmin(range, mBBox[1].mV[1] - mBBox[0].mV[1]) ;
range = llmin(range, mBBox[1].mV[2] - mBBox[0].mV[2]) ;
mTriangleAreaThreshold = llmin(0.0002f, range * 0.000002f) ;
}
//check if the triangle area is large enough to qualify for a valid triangle
bool LLPhysicsDecomp::Request::isValidTriangle(U16 idx1, U16 idx2, U16 idx3)
{
LLVector3 a = mPositions[idx2] - mPositions[idx1] ;
LLVector3 b = mPositions[idx3] - mPositions[idx1] ;
F32 c = a * b ;
return ((a*a) * (b*b) - c * c) > mTriangleAreaThreshold ;
}
void LLPhysicsDecomp::Request::setStatusMessage(const std::string& msg)
{
mStatusMessage = msg;
}
LLModelInstance::LLModelInstance(LLSD& data)
{
mLocalMeshID = data["mesh_id"].asInteger();
mLabel = data["label"].asString();
mTransform.setValue(data["transform"]);
for (U32 i = 0; i < data["material"].size(); ++i)
{
LLImportMaterial mat(data["material"][i]);
mMaterial[mat.mBinding] = mat;
}
}
LLSD LLModelInstance::asLLSD()
{
LLSD ret;
ret["mesh_id"] = mModel->mLocalID;
ret["label"] = mLabel;
ret["transform"] = mTransform.getValue();
U32 i = 0;
for (std::map<std::string, LLImportMaterial>::iterator iter = mMaterial.begin(); iter != mMaterial.end(); ++iter)
{
ret["material"][i++] = iter->second.asLLSD();
}
return ret;
}
LLImportMaterial::LLImportMaterial(LLSD& data)
{
mDiffuseMapFilename = data["diffuse"]["filename"].asString();
mDiffuseMapLabel = data["diffuse"]["label"].asString();
mDiffuseColor.setValue(data["diffuse"]["color"]);
mFullbright = data["fullbright"].asBoolean();
mBinding = data["binding"].asString();
}
LLSD LLImportMaterial::asLLSD()
{
LLSD ret;
ret["diffuse"]["filename"] = mDiffuseMapFilename;
ret["diffuse"]["label"] = mDiffuseMapLabel;
ret["diffuse"]["color"] = mDiffuseColor.getValue();
ret["fullbright"] = mFullbright;
ret["binding"] = mBinding;
return ret;
}
void LLMeshRepository::buildPhysicsMesh(LLModel::Decomposition& decomp)
{
decomp.mMesh.resize(decomp.mHull.size());
for (U32 i = 0; i < decomp.mHull.size(); ++i)
{
LLCDHull hull;
hull.mNumVertices = decomp.mHull[i].size();
hull.mVertexBase = decomp.mHull[i][0].mV;
hull.mVertexStrideBytes = 12;
LLCDMeshData mesh;
LLCDResult res = LLCD_OK;
if (LLConvexDecomposition::getInstance() != NULL)
{
res = LLConvexDecomposition::getInstance()->getMeshFromHull(&hull, &mesh);
}
if (res == LLCD_OK)
{
get_vertex_buffer_from_mesh(mesh, decomp.mMesh[i]);
}
}
if (!decomp.mBaseHull.empty() && decomp.mBaseHullMesh.empty())
{ //get mesh for base hull
LLCDHull hull;
hull.mNumVertices = decomp.mBaseHull.size();
hull.mVertexBase = decomp.mBaseHull[0].mV;
hull.mVertexStrideBytes = 12;
LLCDMeshData mesh;
LLCDResult res = LLCD_OK;
if (LLConvexDecomposition::getInstance() != NULL)
{
res = LLConvexDecomposition::getInstance()->getMeshFromHull(&hull, &mesh);
}
if (res == LLCD_OK)
{
get_vertex_buffer_from_mesh(mesh, decomp.mBaseHullMesh);
}
}
}
bool LLMeshRepository::meshUploadEnabled()
{
LLViewerRegion *region = gAgent.getRegion();
if(gSavedSettings.getBOOL("MeshEnabled") &&
region)
{
return region->meshUploadEnabled();
}
return false;
}
bool LLMeshRepository::meshRezEnabled()
{
LLViewerRegion *region = gAgent.getRegion();
if(gSavedSettings.getBOOL("MeshEnabled") &&
region)
{
return region->meshRezEnabled();
}
return false;
}
// Threading: main thread only
// static
void LLMeshRepository::metricsStart()
{
++metrics_teleport_start_count;
sQuiescentTimer.start(0);
}
// Threading: main thread only
// static
void LLMeshRepository::metricsStop()
{
sQuiescentTimer.stop(0);
}
// Threading: main thread only
// static
void LLMeshRepository::metricsProgress(unsigned int this_count)
{
static bool first_start(true);
if (first_start)
{
metricsStart();
first_start = false;
}
sQuiescentTimer.ringBell(0, this_count);
}
// Threading: main thread only
// static
void LLMeshRepository::metricsUpdate()
{
F64 started, stopped;
U64 total_count(U64L(0)), user_cpu(U64L(0)), sys_cpu(U64L(0));
if (sQuiescentTimer.isExpired(0, started, stopped, total_count, user_cpu, sys_cpu))
{
LLSD metrics;
metrics["reason"] = "Mesh Download Quiescent";
metrics["scope"] = metrics_teleport_start_count > 1 ? "Teleport" : "Login";
metrics["start"] = started;
metrics["stop"] = stopped;
metrics["fetches"] = LLSD::Integer(total_count);
metrics["teleports"] = LLSD::Integer(metrics_teleport_start_count);
metrics["user_cpu"] = double(user_cpu) / 1.0e6;
metrics["sys_cpu"] = double(sys_cpu) / 1.0e6;
LL_INFOS(LOG_MESH) << "EventMarker " << metrics << LL_ENDL;
}
}
// Threading: main thread only
// static
void teleport_started()
{
LLMeshRepository::metricsStart();
}
|