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
//! Lazily-built cache of per-prim composition indices.
//!
//! The [`IndexCache`] is the primary interface between [`Stage`](crate::usd::Stage)
//! and the composition engine. It caches one [`PrimEntry`] per composed prim —
//! the [`PrimIndex`] plus the [`CompositionContext`] its children inherit — so
//! ancestor composition is never recomputed.
//!
//! Relocates (`layerRelocates`) are composed by the indexer as `ArcType::Relocate`
//! nodes; the cache applies each node's layer-stack relocates while folding the
//! child-name list (`compute_prim_child_names`), renaming or hiding relocated
//! sources and exposing targets in place.
use std::collections::{HashMap, HashSet};
use std::mem;
use anyhow::Result;
use crate::ar::ResolvedPath;
use crate::sdf;
use crate::sdf::schema::{ChildrenKey, FieldKey};
use crate::sdf::{LayerOffset, Path, SpecType, Value};
use crate::tf::Token;
use super::clip::{ClipCache, ClipQuery, ResolvedClipSet};
use super::dependencies::Dependencies;
use super::index_store::IndexStore;
use super::instancing::PrototypeRegistry;
use super::layer_graph::LayerGraph;
use super::load_rules::LoadRules;
use super::prim_graph::ArcType;
use super::prim_index::{
AncestorArc, CompositionContext, Demand, PrimIndex, PropertyTargetKind, TargetMemo, TargetMemoKey,
};
use super::prim_indexer::ExprVarDeps;
use super::prim_resolve::InvalidTargetKind;
use super::relocates::{apply_child_relocates, chain_through_relocates, effective_relocates};
use super::{Error, LayerId, MapFunction, StackIdentity, VariantFallbackMap};
/// What [`IndexCache::edit_target_node_info`] reports for an arc node: the target
/// layer's identifier, the node's spec-to-scene mapping, and the value identity
/// of the layer stack it composes in, so an edit target resolves the same
/// (possibly contextual) stack wherever it is installed.
type EditTargetNodeInfo = (String, MapFunction, StackIdentity);
/// Lazily-built composition graph.
///
/// Caches a [`PrimEntry`] per composed prim. When a prim is queried for the
/// first time, its index is built using the parent's cached context (if
/// available). During depth-first traversal, parents are always composed before
/// children, so the context chain is always populated.
///
/// An optional [`VariantFallbackMap`] provides fallback selections for variant
/// sets that have no authored opinion. Authored selections always take priority;
/// fallbacks are tried in order, and a set with no applicable fallback stays
/// unselected.
///
/// Recoverable composition errors are retained in
/// [`Self::composition_errors`], while operational failures are returned to the
/// caller.
pub struct IndexCache {
/// The per-prim composition index storage and its dependency map (see
/// [`IndexStore`]). The instancing pass and the builder reach composed
/// indices through [`Self::cached`] and the store's accessors.
store: IndexStore,
/// Variant fallback selections tried when no authored selection exists.
variant_fallbacks: VariantFallbackMap,
/// Per-path payload-inclusion policy (C++ `UsdStageLoadRules`), seeded at
/// construction from the stage's
/// [`InitialLoadSet`](crate::usd::InitialLoadSet) and mutated at runtime
/// through [`Self::set_load_rules`]. `IndexCache::build_index` consults it
/// per path, via [`Self::is_loaded`].
pub(super) load_rules: LoadRules,
/// Value-clip resolution and its layer cache ([`ClipCache`], spec 12.3.4) —
/// an independently-owned entity that the clip orchestration methods
/// ([`resolve_clip_value`](Self::resolve_clip_value) and friends) delegate
/// per-anchor clip work to once they have ensured the relevant indices.
clip_cache: ClipCache,
/// Shared-prototype registry for scene-graph instancing (spec 11.3.3),
/// internal machinery driven by the instancing glue in
/// [`super::instancing`] (a second `impl IndexCache`). Callers go through
/// the cache's facade methods (`is_instance` / `prototype_of` /
/// `is_prototype` / …), never this field. Affected entries are dropped by
/// [`Self::invalidate_prototypes`] on a prim-level change, or through
/// [`Self::invalidate_layers`] on a layer-stack edit.
pub(super) prototypes: PrototypeRegistry,
/// Memoized instance-proxy / prototype-descendant redirections (spec
/// 11.3.3): a prim path mapped to the path that actually composes it
/// ([`effective_path`](Self::effective_path) walks the namespace to find an
/// enclosing instance, which is otherwise repeated on every descendant
/// query). A non-redirected prim caches an identity entry, so the common
/// non-instanced case skips the walk too. An entry holds only while the
/// prototype registry that produced it is unchanged: it is cleared wholesale
/// when prototypes are invalidated ([`Self::invalidate_prototypes`]), and the
/// subtree under a freshly
/// minted `/__Prototype_N` is dropped at registration (a synthetic
/// descendant queried before the mint cached an identity that must now
/// redirect into the prototype namespace).
//
// TODO(rayon): a per-prim parallel composition driver would share this map
// read-mostly; the entries are write-once until invalidation, so a
// concurrent reader needs only a shared snapshot rather than a lock on the
// hot path. Keep population off the critical section when that lands.
pub(super) redirected_prims: HashMap<Path, Path>,
/// One-shot errors from layer collection that the [`LayerGraph`](super::layer_graph::LayerGraph)
/// cannot regenerate (e.g. `UnresolvedSublayer`). Set once at construction;
/// never cleared, since nothing recomputes them.
collection_errors: Vec<Error>,
/// Transient errors produced by on-demand target / property-stack queries
/// (invalid external targets, inconsistent property types). Cleared on any
/// index invalidation so they never go stale across an edit; they are
/// recomputed on the next query.
//
// A memoizable target query's invalid-target errors are memoized with its
// resolved targets (see
// [`PrimEntry::resolved_targets`](super::prim_index::PrimEntry)) and
// re-surfaced here, deduplicated, on a cache hit, so repeated reads of those
// properties no longer duplicate them. A non-memoizable target read (an
// instance proxy, the deleted-paths walk, or a resolution that read cross-prim
// instance state) still appends fresh each call.
//
// TODO: the `property_stack` inconsistent-property-type conflicts are still
// recomputed and re-appended on each call, so repeated stacks on the same
// conflicting property duplicate within a session. The per-pass double-report
// (one at prim build, one per `property_stack` query) is C++-faithful — the
// composition golden expects it — so a fix must preserve the per-pass count and
// collapse only the repeat `property_stack` calls. A `PrimEntry` memo (like the
// targets) would do that, but the conflict set depends on the prim's property
// specs, so it would need a property-add/remove invalidation branch in
// `classify_property_entry`; computing it eagerly at index build instead would
// add per-property work to every prim's build (a cost on Caldera-class stages).
// Deferred until a profile justifies one.
query_errors: Vec<Error>,
/// Paths whose [`ensure_index`](Self::ensure_index) call is still on the
/// stack. Pre-caching an inherit/specialize target (and that target's own
/// targets) re-enters `ensure_index`; a cyclic class hierarchy (e.g. two
/// prims that inherit each other) would otherwise recurse forever before any
/// of them is cached. Re-entry for an in-progress path
/// returns early, so the cycle-closing arc simply finds no cached target and
/// drops out of composition.
in_progress: HashSet<Path>,
/// [`Demand`]s a build raised for a target layer that is not yet loaded,
/// returned up from the indexer (via `BuildOutput`) and accumulated here
/// across the builds run in a pass. [`Stage::with_cache`](crate::usd::Stage)
/// drains it, opens the layers, and recomposes. A plain `Vec` mutated through
/// `&mut self` — pcp keeps no interior mutability. `pub(super)` so the
/// instancing pass can detect a demand fired mid-redirect (see
/// [`effective_path`](Self::effective_path)).
pub(super) pending_loads: Vec<Demand>,
/// Monotonic counter bumped once per applied change batch
/// ([`Changes::apply`](super::Changes::apply)), the single funnel every
/// authoring and layer-stack edit passes through. Cached views that resolve
/// values once and replay them (e.g. [`Stage::attribute_query`]) snapshot
/// this and rebuild when it advances, so an edit to any opinion — even a
/// value-only edit that leaves the prim index intact — invalidates them.
///
/// It does not capture lazy prototype materialization, which can change what
/// resolves under a synthetic `/__Prototype_N` path without an edit (see
/// [`register_prototype`](Self::register_prototype)). A cached view must not
/// rely on this counter alone for paths that may be empty pending such
/// materialization.
///
/// A single stage-wide counter is deliberately coarse: every edit rebuilds
/// every cached value view, even unaffected ones. A per-prim revision would
/// let an unrelated prim's view survive, but value-only edits skip change
/// classification today (no producer says which prim's value moved), so a
/// per-prim bump would risk a stale read where this coarse counter is always
/// safe. Refine only with a value-edit classifier and a profile showing the
/// blanket rebuild dominates.
///
/// [`Stage::attribute_query`]: crate::usd::Stage::attribute_query
revision: u64,
}
enum FieldValue {
NotAuthored,
Authored(Option<Value>),
}
/// The resolved source of an attribute's value at a time code, the cacheable
/// half of [`IndexCache::value_at`]. A cached view
/// ([`Stage::attribute_query`](crate::usd::Stage::attribute_query)) resolves
/// this once — paying the opinion walk and the one sample-map clone — then
/// replays it across many time codes.
pub(crate) enum AttributeValueSource {
/// A time-independent value: a `default` opinion (local or fallback), or
/// `None` when the attribute is unauthored, masked out, or blocked. The
/// same value resolves at every time code.
Static(Option<Value>),
/// A time-sampled source — the matched map and its node's layer offset.
/// Interpolated per query in layer time via `offset.inverse().apply(time)`,
/// matching [`PrimIndex::resolve_value_at`](super::PrimIndex::resolve_value_at).
TimeSamples {
samples: sdf::TimeSampleMap,
offset: LayerOffset,
},
/// Value clips are authoritative for this attribute (spec 12.3.4). Clip
/// resolution selects a different clip layer per time, so a cached view
/// falls back to [`IndexCache::value_at`] for every query rather than
/// snapshotting a single source.
Clips,
}
/// Collapses the spec sentinels for "no value" ([`Value::ValueBlock`] and
/// [`Value::None`]) to `None`, passing any real value through as `Some`. An
/// authored block stops fall-through to weaker sources yet presents as absent.
pub(super) fn block_to_none(value: Value) -> Option<Value> {
match value {
Value::ValueBlock | Value::None => None,
other => Some(other),
}
}
impl IndexCache {
/// Creates a new composition cache. The layer data lives in a separate
/// [`LayerGraph`] owned by the [`Stage`](crate::usd::Stage) and passed to each
/// query. `collection_errors` are the one-shot errors from layer collection
/// the graph cannot regenerate (e.g. `UnresolvedSublayer`); per-prim build
/// errors join them as indices are composed. The regenerable layer-graph
/// diagnostics (sublayer cycles, invalid relocates) live on the
/// [`LayerGraph`] and are read through [`LayerGraph::errors`].
pub(crate) fn new(
variant_fallbacks: VariantFallbackMap,
load_rules: LoadRules,
collection_errors: Vec<Error>,
) -> Self {
Self {
store: IndexStore::default(),
variant_fallbacks,
load_rules,
clip_cache: ClipCache::default(),
prototypes: PrototypeRegistry::default(),
redirected_prims: HashMap::new(),
collection_errors,
query_errors: Vec::new(),
in_progress: HashSet::new(),
pending_loads: Vec::new(),
revision: 0,
}
}
/// Hands the [`Demand`]s the builds run so far raised (for target layers not
/// yet loaded) to `buf`, taking `buf`'s storage in exchange. The stage's
/// query loop passes a buffer it reuses across passes, so the two queues
/// ping-pong without reallocating: it opens the returned layers and
/// recomposes until a pass demands nothing.
pub(crate) fn swap_pending_loads(&mut self, buf: &mut Vec<Demand>) {
mem::swap(&mut self.pending_loads, buf);
}
/// The current composition revision (see the [`revision`](Self::revision)
/// field). Advances once per applied change batch.
pub(crate) fn revision(&self) -> u64 {
self.revision
}
/// Advances the composition revision, invalidating cached views that
/// snapshot it. Called once per [`Changes::apply`](super::Changes::apply).
pub(super) fn bump_revision(&mut self) {
self.revision += 1;
}
/// Returns the recoverable composition errors encountered so far: the
/// one-shot collection errors, the current per-prim build errors, and the
/// transient query errors.
pub(crate) fn composition_errors(&self) -> Vec<Error> {
self.collection_errors
.iter()
.chain(self.store.errors())
.chain(&self.query_errors)
.cloned()
.collect()
}
/// Drops the one-shot collection errors that also appear in `superseded` —
/// open-time loader copies of diagnostics the layer graph has taken
/// ownership of as per-stack regenerable errors, which would otherwise
/// double-report and outlive a later fix. Collection keeps what the loader
/// alone knows, e.g. a failure under a branch muted at open, which the
/// graph derives no diagnostic for.
pub(crate) fn discard_collection_errors(&mut self, superseded: &[Error]) {
self.collection_errors.retain(|error| !superseded.contains(error));
}
#[cfg(test)]
fn take_composition_errors(&mut self) -> Vec<Error> {
let errors = self.composition_errors();
self.collection_errors.clear();
self.query_errors.clear();
self.store.clear_errors();
errors
}
/// Resolves an attribute's value at `time`, honoring value clips
/// (spec 12.3.4). Strength ordering:
///
/// 1. Local (`Root` arc) `timeSamples` win over clips.
/// 2. Value clips anchored on the attribute's prim or an ancestor.
/// 3. The strongest remaining `timeSamples` (across reference/payload arcs).
/// 4. The strongest authored `default`.
///
/// `interp` applies the stage's interpolation policy to a sample map at a
/// given time; it is supplied by the caller so this layer stays free of any
/// interpolation policy.
///
/// [`Self::resolve_value_source`] mirrors this strength order to cache the
/// winning source for replay; keep the two in sync when the order changes.
pub(crate) fn value_at(
&mut self,
graph: &LayerGraph,
attr_path: &Path,
time: f64,
interp: &dyn Fn(&sdf::TimeSampleMap, f64) -> Option<Value>,
) -> Result<Option<Value>> {
let Some((prim, suffix)) = self.ensure_attr_index(graph, attr_path)? else {
return Ok(None);
};
let local_layers = graph.local_layers();
// TODO: only the default-sourced returns below resolve their `asset`
// values (via `anchor_asset_paths`); values from time samples
// (`resolve_value_at`) and value clips (`resolve_clip_value`) are
// returned with `evaluated_path` and `resolved_path` unset. To close
// this, those resolvers must surface the contributing layer/node so it
// can be anchored and its expression variables composed — note a clip
// value anchors against the *clip layer*, not a host-stack opinion, so
// it cannot reuse `asset_context` directly. Asset-valued time samples
// and clips are rare in practice.
// 1) Local time samples take precedence over clip data.
if let Some(value) =
self.cached(&prim)
.resolve_value_at(graph, Some(&suffix), Some(&local_layers), time, interp)?
{
return Ok(value);
}
// 2) Local defaults also take precedence over clip data.
if let FieldValue::Authored(value) =
self.resolve_local_field_value(graph, &prim, &suffix, FieldKey::Default.as_str(), &local_layers)?
{
return Ok(self.anchor_asset_paths(graph, &prim, FieldKey::Default.as_str(), Some(&suffix), value));
}
// 3) Value clips, anchored on this prim or an ancestor. A clip set that
// owns the attribute resolves it authoritatively: an authored value
// block stops fall-through to weaker sources but presents as `None`,
// matching the local-default handling above and the default below.
if let Some(value) = self.resolve_clip_value(graph, &prim, &suffix, time, interp)? {
return Ok(block_to_none(value));
}
// 4) Remaining time samples (reference/payload arcs), retimed.
if let Some(value) = self
.cached(&prim)
.resolve_value_at(graph, Some(&suffix), None, time, interp)?
{
return Ok(value);
}
// 5) Fall back to the strongest authored default.
let default = self
.cached(&prim)
.resolve_field(FieldKey::Default.as_str(), graph, Some(&suffix))?;
let default = self.anchor_asset_paths(graph, &prim, FieldKey::Default.as_str(), Some(&suffix), default);
Ok(default.and_then(block_to_none))
}
/// Resolves the cacheable value source for an attribute (the source half of
/// [`Self::value_at`]), so a [`Stage::attribute_query`] can replay it across
/// time codes. Walks the same strength order as `value_at`, stopping at the
/// first authoritative source. When value clips claim the attribute the
/// source is [`AttributeValueSource::Clips`]: the query then falls back to
/// `value_at` per call, since clip resolution is time-dependent.
///
/// [`Stage::attribute_query`]: crate::usd::Stage::attribute_query
pub(crate) fn resolve_value_source(
&mut self,
graph: &LayerGraph,
attr_path: &Path,
) -> Result<AttributeValueSource> {
let Some((prim, suffix)) = self.ensure_attr_index(graph, attr_path)? else {
return Ok(AttributeValueSource::Static(None));
};
let local_layers = graph.local_layers();
// 1) Local time samples take precedence over clip data.
if let Some((samples, offset)) =
self.cached(&prim)
.resolve_time_samples_with_offset(graph, Some(&suffix), Some(&local_layers))?
{
return Ok(AttributeValueSource::TimeSamples { samples, offset });
}
// 2) Local defaults also take precedence over clip data.
if let FieldValue::Authored(value) =
self.resolve_local_field_value(graph, &prim, &suffix, FieldKey::Default.as_str(), &local_layers)?
{
let value = self.anchor_asset_paths(graph, &prim, FieldKey::Default.as_str(), Some(&suffix), value);
return Ok(AttributeValueSource::Static(value));
}
// 3) Value clips, anchored on this prim or an ancestor, resolve
// authoritatively but per-time; defer them to `value_at`. The gate is
// clip participation (`clip_sample_times` returns `Some` exactly when
// a set sources the attribute), so a clip-bearing prim's non-clip
// attributes fall through to the cached arc / default tiers below.
if self.clip_sample_times(graph, &prim, &suffix)?.is_some() {
return Ok(AttributeValueSource::Clips);
}
// 4) Remaining time samples (reference/payload arcs).
if let Some((samples, offset)) =
self.cached(&prim)
.resolve_time_samples_with_offset(graph, Some(&suffix), None)?
{
return Ok(AttributeValueSource::TimeSamples { samples, offset });
}
// 5) Fall back to the strongest authored default.
let default = self
.cached(&prim)
.resolve_field(FieldKey::Default.as_str(), graph, Some(&suffix))?;
let default = self.anchor_asset_paths(graph, &prim, FieldKey::Default.as_str(), Some(&suffix), default);
Ok(AttributeValueSource::Static(default.and_then(block_to_none)))
}
/// Resolves an attribute's composed sample times, retimed to stage time and
/// including value-clip contributions (the introspection counterpart of
/// [`Self::value_at`], spec 12.3.4). `None` when no source has samples or the
/// prim is masked out.
///
/// This MUST report the times of whichever source [`Self::value_at`] would
/// resolve the value from, so it walks the same precedence: local
/// `timeSamples`, then a local `default` (a constant — no sample times),
/// then clips, then arc `timeSamples`. Keep the tiers here in lockstep with
/// `value_at`; the `clip_*` / `has_local_default` checks mirror its branches
/// 1-4, and the consistency tests in `tests/stage.rs` pin the agreement.
pub(crate) fn time_sample_times(&mut self, graph: &LayerGraph, attr_path: &Path) -> Result<Option<Vec<f64>>> {
let Some((prim, suffix)) = self.ensure_attr_index(graph, attr_path)? else {
return Ok(None);
};
let local_layers = graph.local_layers();
if let Some(times) = self
.cached(&prim)
.resolve_time_sample_times(graph, Some(&suffix), Some(&local_layers))?
{
return Ok(Some(times));
}
// A local `default` opinion resolves to a constant value that shadows
// clips and arc time samples (`value_at` branch 2), so the attribute has
// no sample times.
if self.has_local_default(graph, &prim, &suffix, &local_layers)? {
return Ok(None);
}
// Value clips own the attribute when a set participates, reporting every
// active-window boundary so a held window's switch point agrees with
// where `value_at` changes. The participation rule (manifest declares,
// or manifest-less with an authored sample) is the same one `clip_value_at`
// applies per-time, but computed independently there — the two must stay
// in agreement; the consistency tests in `tests/stage.rs` pin it.
//
// TODO: a manifest-less set reports only its own boundaries/samples here,
// but `clip_value_at` falls through to weaker sources (arc `timeSamples`)
// inside a fully-empty active window. Arc samples landing in such a gap
// window are served by `value_at` yet absent from this list. Closing the
// gap means unioning weaker-source sample times that fall within active
// windows the clip set authors nothing for — a clip/arc tier crossing
// tied to the broader `clip_value_at` unification.
if let Some(times) = self.clip_sample_times(graph, &prim, &suffix)? {
return Ok(Some(times));
}
self.cached(&prim).resolve_time_sample_times(graph, Some(&suffix), None)
}
/// Resolves the number of composed sample times for an attribute, including
/// value-clip contributions. Mirrors [`Self::time_sample_times`]'s source
/// order; keeps the count-only fast path for the common `timeSamples` case
/// and only materializes the time list when value clips own the attribute.
/// Zero when no source has samples or the prim is masked out.
pub(crate) fn num_time_samples(&mut self, graph: &LayerGraph, attr_path: &Path) -> Result<usize> {
Ok(self.time_sample_summary(graph, attr_path)?.0)
}
/// Whether an attribute's value may vary over time, the introspection behind
/// [`Attribute::value_might_be_time_varying`]. True when the winning value
/// source has more than one composed sample, or when that source is a value-
/// clip set whose schedule alone can vary the value
/// ([`ClipSet::may_be_time_varying`]). Resolving the source first keeps a
/// constant local `default` / `timeSamples` from being reported as
/// time-varying merely because it shadows a multi-clip set.
///
/// [`Attribute::value_might_be_time_varying`]: crate::usd::Attribute::value_might_be_time_varying
pub(crate) fn value_might_be_time_varying(&mut self, graph: &LayerGraph, attr_path: &Path) -> Result<bool> {
let (count, clip_may_vary) = self.time_sample_summary(graph, attr_path)?;
Ok(count > 1 || clip_may_vary)
}
/// The composed sample-time count for an attribute plus, when the winning
/// source is a value-clip set, whether that set's schedule can vary the value
/// ([`ClipSet::may_be_time_varying`]). Walks [`Self::value_at`]'s source
/// precedence in one pass — local `timeSamples`, local `default` (constant),
/// clips, then arc `timeSamples` — so [`Self::num_time_samples`] and
/// [`Self::value_might_be_time_varying`] share a single resolution. `(0,
/// false)` when no source has samples or the prim is masked out.
fn time_sample_summary(&mut self, graph: &LayerGraph, attr_path: &Path) -> Result<(usize, bool)> {
let Some((prim, suffix)) = self.ensure_attr_index(graph, attr_path)? else {
return Ok((0, false));
};
let local_layers = graph.local_layers();
if let Some(count) = self
.cached(&prim)
.resolve_time_sample_count(graph, Some(&suffix), Some(&local_layers))?
{
return Ok((count, false));
}
// A local `default` shadows clips and arc samples (see
// [`Self::time_sample_times`]), so the attribute has no time samples.
if self.has_local_default(graph, &prim, &suffix, &local_layers)? {
return Ok((0, false));
}
if let Some((times, may_vary)) = self.clip_introspection(graph, &prim, &suffix)? {
return Ok((times.len(), may_vary));
}
let arc = self
.cached(&prim)
.resolve_time_sample_count(graph, Some(&suffix), None)?
.unwrap_or(0);
Ok((arc, false))
}
/// Whether a `default` opinion is authored for the attribute in the root
/// layer stack. Such a local default resolves to a constant value that
/// shadows weaker time-varying sources (clips, arc `timeSamples`), matching
/// [`Self::value_at`]'s branch 2 — so the attribute reports no sample times.
fn has_local_default(
&self,
graph: &LayerGraph,
prim: &Path,
suffix: &str,
local_layers: &HashSet<LayerId>,
) -> Result<bool> {
Ok(matches!(
self.resolve_local_field_value(graph, prim, suffix, FieldKey::Default.as_str(), local_layers)?,
FieldValue::Authored(_)
))
}
/// Resolves a clip value for `attr_path` at `time` by searching the
/// attribute's prim and then its ancestors, nearest first — a nearer clip
/// set overrides one on an ancestor (spec 12.3.4.5).
fn resolve_clip_value(
&mut self,
graph: &LayerGraph,
attr_prim: &Path,
suffix: &str,
time: f64,
interp: &dyn Fn(&sdf::TimeSampleMap, f64) -> Option<Value>,
) -> Result<Option<Value>> {
let mut anchor_prim = attr_prim.clone();
loop {
if let Some(value) = self.clip_value_at(graph, &anchor_prim, attr_prim, suffix, time, interp)? {
return Ok(Some(value));
}
match anchor_prim.parent() {
Some(parent) if !parent.is_abs_root() => anchor_prim = parent,
_ => return Ok(None),
}
}
}
/// Looks for a clip set anchored on `anchor_prim` that provides a value for
/// `attr_prim + suffix` at `time`, delegating the per-set resolution to the
/// [`ClipCache`].
fn clip_value_at(
&mut self,
graph: &LayerGraph,
anchor_prim: &Path,
attr_prim: &Path,
suffix: &str,
time: f64,
interp: &dyn Fn(&sdf::TimeSampleMap, f64) -> Option<Value>,
) -> Result<Option<Value>> {
let sets = self.clip_sets_for(graph, anchor_prim)?;
let query = ClipQuery {
anchor: anchor_prim,
attr_prim,
suffix,
};
self.clip_cache.value_in_sets(graph, &sets, &query, time, interp)
}
/// The value-clip introspection for `attr_prim + suffix` from the first
/// participating set, searching the attribute's prim and its ancestors
/// nearest-first: its stage sample times (spec 12.3.4) and whether its
/// schedule alone can vary the value ([`ClipSet::may_be_time_varying`]).
/// `None` when no clip set sources the attribute; `Some` exactly when a set
/// participates. The sample-time vector may be empty for a participating set
/// that contributes no discrete times. Delegates the per-set participation
/// check to the [`ClipCache`].
fn clip_introspection(
&mut self,
graph: &LayerGraph,
attr_prim: &Path,
suffix: &str,
) -> Result<Option<(Vec<f64>, bool)>> {
let mut anchor = attr_prim.clone();
loop {
let sets = self.clip_sets_for(graph, &anchor)?;
let query = ClipQuery {
anchor: &anchor,
attr_prim,
suffix,
};
if let Some(introspection) = self.clip_cache.clip_introspection_in_sets(graph, &sets, &query)? {
return Ok(Some(introspection));
}
match anchor.parent() {
Some(parent) if !parent.is_abs_root() => anchor = parent,
_ => return Ok(None),
}
}
}
/// The stage times a value-clip set contributes for `attr_prim + suffix`, or
/// `None` when no clip set sources the attribute. Drops the time-varying flag
/// from [`Self::clip_introspection`] for callers that need only the times.
/// `Some` exactly when a clip set participates, so this doubles as the clip
/// gate for [`Self::resolve_value_source`] (and `value_at`'s clip tier).
fn clip_sample_times(&mut self, graph: &LayerGraph, attr_prim: &Path, suffix: &str) -> Result<Option<Vec<f64>>> {
Ok(self
.clip_introspection(graph, attr_prim, suffix)?
.map(|(times, _)| times))
}
/// Ensures `anchor`'s index is composed and resolves its value-clip sets —
/// the shared preamble for the clip orchestration walks. Returns an owned
/// list so the cached-index borrow is released before the per-anchor
/// [`ClipCache`] query takes `&mut self.clip_cache`.
fn clip_sets_for(&mut self, graph: &LayerGraph, anchor: &Path) -> Result<Vec<ResolvedClipSet>> {
self.ensure_index(graph, anchor)?;
self.cached(anchor).resolve_clip_sets(graph)
}
/// Redirects `attr_path` through [`Self::effective_path`] and ensures the
/// owning prim's index is composed, returning the owned prim path and
/// property suffix for a subsequent [`Self::cached`] lookup. `None` when no
/// spec exists at the path (absent or masked out).
fn ensure_attr_index(&mut self, graph: &LayerGraph, attr_path: &Path) -> Result<Option<(Path, String)>> {
let attr_path = &self.effective_path(graph, attr_path)?;
if !self.has_spec_at(graph, attr_path)? {
return Ok(None);
}
let prim = attr_path.prim_path();
let suffix = attr_path.property_suffix().to_owned();
self.ensure_index(graph, &prim)?;
Ok(Some((prim, suffix)))
}
fn resolve_local_field_value(
&self,
graph: &LayerGraph,
prim: &Path,
suffix: &str,
field: &str,
local_layers: &HashSet<LayerId>,
) -> Result<FieldValue> {
let Some(index) = self.store.index_at(prim) else {
return Ok(FieldValue::NotAuthored);
};
for node in index.nodes() {
let query_path = Path::new(&format!("{}{suffix}", node.path))?;
for &(layer, _) in graph.layer_stack(node.layer_stack_id()).iter() {
if !local_layers.contains(&layer) {
continue;
}
let Some(value) = graph.layer(layer).data().try_field(&query_path, field)? else {
continue;
};
return Ok(FieldValue::Authored(block_to_none(value.into_owned())));
}
}
Ok(FieldValue::NotAuthored)
}
/// Read-only access to the dependency map for change-driven invalidation.
pub(super) fn dependencies(&self) -> &Dependencies {
self.store.dependencies()
}
/// Returns `true` if a composed prim index is currently cached at `path`.
pub fn is_indexed(&self, path: &Path) -> bool {
self.store.is_indexed(path)
}
/// Borrows the cached index at `path`.
///
/// Callers use this where composition has already guaranteed the index is
/// present (a prim's index is built before any query that reads it, and
/// children build after their parents). When the build was left uncached
/// because it demanded a not-yet-loaded layer, an empty index is returned:
/// the query reads empty results and the stage's query loop discards them,
/// recomposing once the demanded layer is loaded. Absence is therefore always
/// the transient demanded-layer case — never a logic error — under the
/// loop's guarantee that a demanded build is retried.
pub(super) fn cached(&self, path: &Path) -> &PrimIndex {
self.store.cached(path)
}
/// Number of cached prim indices.
pub fn indexed_count(&self) -> usize {
self.store.len()
}
/// Caches a fully composed `index` at `path` with the `context` its children
/// inherit, its recoverable build `errors`, and the per-stack
/// expression-variable names its build read (`expr_var_deps`), registering
/// its dependencies (see [`IndexStore::insert`]). Shared by the ordinary
/// [`build_index`](Self::build_index) path and the materialized-prototype path
/// (which has no spec to build from, so it passes no errors and no variable
/// dependencies — a variable edit evicts a prototype through its instances'
/// registrations).
pub(super) fn cache_index(
&mut self,
graph: &LayerGraph,
path: &Path,
index: PrimIndex,
context: CompositionContext,
errors: Vec<Error>,
expr_var_deps: ExprVarDeps,
) {
self.store.insert(graph, path, index, context, errors, expr_var_deps);
}
/// The composition context for a namespace-root prim: empty except for the
/// stage's variant fallbacks. Used to seed the root of an ordinary build and
/// of a materialized prototype. `load_payloads` is left at its `Default`
/// value — [`build_index`](Self::build_index) always overwrites it with a
/// per-path decision before the context is ever consumed, so the value
/// seeded here is never read.
pub(super) fn root_parent_context(&self) -> CompositionContext {
CompositionContext {
variant_fallbacks: self.variant_fallbacks.clone(),
..Default::default()
}
}
/// Drop a single prim's cached entry (its index, child context, and build
/// errors) along with its dependency registrations. The transient query
/// errors are cleared too — they may reference the dropped prim and are
/// recomputed on the next query.
pub(super) fn drop_index(&mut self, path: &Path) {
self.store.remove(path);
self.query_errors.clear();
}
/// Drops every cached index that recorded a
/// [`MalformedLayer`](Error::MalformedLayer) error so it recomposes and
/// re-demands the target. The arc to an unreadable target was dropped, so
/// these indices carry no dependency on it and an ordinary layer-stack
/// invalidation misses them; the stage calls this when an edit clears the
/// graph's recorded load failures, since the target may now be readable.
pub(crate) fn drop_load_failed_indices(&mut self) {
let failed = self.store.paths_with_malformed_layer();
if failed.is_empty() {
return;
}
for path in failed {
self.store.remove(&path);
}
self.query_errors.clear();
self.bump_revision();
}
/// Spec-tier change consumer (C++ `Pcp_RescanForSpecs`) for one change round's
/// inert spec adds and removes, each a `(layer, path)` site. The store
/// refreshes every affected index's `has_specs` flags in place per site,
/// partitioning the indices into those refreshed in place and those it cannot
/// refresh; the latter are dropped for rebuild. Each in-place-refreshed index
/// then finalizes its memoized spec stack once, however many of this round's
/// sites reached it. The transient query errors are cleared too — they may
/// reference a dropped prim.
pub(super) fn rescan_specs(&mut self, graph: &LayerGraph, sites: &[(LayerId, Path)]) {
let mut refreshed: HashSet<Path> = HashSet::new();
let mut rebuild: HashSet<Path> = HashSet::new();
for (layer, path) in sites {
self.store
.refresh_specs(graph, *layer, path, &mut refreshed, &mut rebuild);
}
for prim in &rebuild {
self.store.remove(prim);
}
// The rebuild set was just dropped from the store and `finalize_spec_stacks`
// skips a path with no cached entry, so an index that ended up in both sets
// is already excluded — the refreshed set needs no further filtering.
self.store.finalize_spec_stacks(graph, &refreshed);
self.query_errors.clear();
}
/// Drop a prim's cached index and every namespace descendant. Used by
/// [`change::Changes`](super::change::Changes) when a significant change
/// touches `prefix` — the topology may have changed for the entire subtree,
/// so every dependent index is invalidated. Clears the transient query errors
/// too, which may reference a dropped prim.
pub(super) fn drop_index_subtree(&mut self, prefix: &Path) {
self.store.remove_subtree(prefix);
self.query_errors.clear();
}
/// Drops one memoized `(prim, property)` resolved-target entry per item, for a
/// `targetPaths` / `connectionPaths` edit that leaves the graph intact (so the
/// index survives) but restales that property's composed targets. Keyed by the
/// edited property's [`TargetMemoKey`], so a prim's other relationships and
/// connections keep their memos. See
/// [`CacheChanges::did_change_targets`](super::change::CacheChanges).
pub(super) fn clear_target_memos<'p>(&mut self, memos: impl IntoIterator<Item = &'p (Path, TargetMemoKey)>) {
for (prim, key) in memos {
self.store.clear_target_memo(prim, key);
}
}
/// Invalidates the cache after a layer-set change restructures only some
/// prims: advances the composition revision (so cached value views rebuild)
/// and drops just the cached indices that read one of the `affected` layers,
/// via [`drop_indices_touching_layers`](Self::drop_indices_touching_layers).
/// Used for a layer-muting toggle, a
/// `subLayers`/offset/relocate/`timeCodesPerSecond`/`expressionVariables` edit
/// (see [`Changes::apply`](super::change::Changes::apply)), and a demanded
/// layer that introduces relocates; in each case the graph's precomputed
/// layer-stack state is rebuilt by the mutation first, so the cache is all that
/// remains. Drops exactly the cached indices whose composition reads an
/// `affected` layer, leaving the rest warm.
pub(crate) fn invalidate_layers(&mut self, affected: &HashSet<LayerId>) {
self.bump_revision();
self.drop_indices_touching_layers(affected);
}
/// Invalidates the cache after a layer-muting toggle of the layer with
/// canonical identifier `canonical`: advances the revision, then drops the
/// cached indices the toggle can restructure (see
/// [`Dependencies::indices_for_mute_toggle`](super::dependencies::Dependencies::indices_for_mute_toggle))
/// — those reading one of the `affected` layers, plus those that only skipped
/// the target and recorded `canonical` because it interned no reachable layer.
/// Unmuting such a target drops the referrer's stale index so it recomposes and
/// the load barrier finally opens the now-unmuted target.
pub(crate) fn invalidate_muting(&mut self, affected: &HashSet<LayerId>, canonical: &str) {
self.bump_revision();
let victims = self.store.dependencies().indices_for_mute_toggle(affected, canonical);
self.drop_index_victims(&victims);
}
/// Drop every cached prim index whose composition reads one of the `affected`
/// layers (per [`Dependencies::indices_for_layers`](super::dependencies::Dependencies::indices_for_layers))
/// — together with its namespace descendants and any prototype the drops touch —
/// leaving indices that read none of them cached. Editing a layer can only
/// restructure prims that compose against a layer stack containing it (C++
/// `PcpChanges` layer-stack fanout), so the rest of the cache stays warm.
fn drop_indices_touching_layers(&mut self, affected: &HashSet<LayerId>) {
if affected.is_empty() {
return;
}
let victims = self.store.dependencies().indices_for_layers(affected);
self.drop_index_victims(&victims);
}
/// Drops each victim prim index and the prototypes its drop touches — the tail
/// shared by [`drop_indices_touching_layers`](Self::drop_indices_touching_layers),
/// [`invalidate_muting`](Self::invalidate_muting),
/// [`set_load_rules`](Self::set_load_rules), and the `expressionVariables`
/// delta path (`change::apply_vars_deltas`).
pub(super) fn drop_index_victims(&mut self, victims: &[Path]) {
if victims.is_empty() {
return;
}
// Evict prototypes whose instances or roots are among the victims, as the
// prim-tier path in [`Changes::apply`](super::change::Changes::apply) does.
self.invalidate_prototypes(victims);
for path in victims {
self.drop_index_subtree(path);
}
}
/// Returns `true` if any layer has a spec at the given composed path.
///
/// For property paths (e.g. `/Prim.attr`), checks whether the property
/// exists in any layer contributing to the owning prim's composition index.
pub fn has_spec(&mut self, graph: &LayerGraph, path: &Path) -> Result<bool> {
let path = &self.effective_path(graph, path)?;
self.has_spec_at(graph, path)
}
/// Resolves a value over the composition nodes of a property's owning prim,
/// strongest first, reading each contributing layer live. `path` must be a
/// property path: it is re-anchored onto each node's prim (crossing the
/// `.` separator) and `probe` is called with that node's layer and the
/// re-anchored property path; the first `Some` wins.
///
/// Reading live — rather than from a property-keyed index — keeps results
/// correct after a property spec is authored, since authoring a property
/// never reshapes the owning prim's composition graph (the prim index
/// stays valid).
fn find_property_node<T>(
&mut self,
graph: &LayerGraph,
path: &Path,
mut probe: impl FnMut(&sdf::Layer, &Path) -> Option<T>,
) -> Result<Option<T>> {
let prim_path = path.prim_path();
self.ensure_index(graph, &prim_path)?;
let Some(index) = self.store.index_at(&prim_path) else {
return Ok(None);
};
for node in index.nodes() {
let Some(prop_path) = path.replace_prefix(&prim_path, &node.path) else {
continue;
};
for &(layer, _) in graph.layer_stack(node.layer_stack_id()).iter() {
if let Some(found) = probe(graph.layer(layer), &prop_path) {
return Ok(Some(found));
}
}
}
Ok(None)
}
/// Like [`Self::has_spec`], but assumes `path` has already been redirected
/// through [`Self::effective_path`]. Callers that redirected the path
/// themselves (e.g. [`Self::value_at`]) use this to avoid redirecting twice.
fn has_spec_at(&mut self, graph: &LayerGraph, path: &Path) -> Result<bool> {
if path.is_property_path() {
return Ok(self
.find_property_node(graph, path, |layer, p| layer.data().has_spec(p).then_some(()))?
.is_some());
}
self.ensure_index(graph, path)?;
Ok(self.store.index_at(path).is_some_and(|idx| !idx.is_empty()))
}
/// Returns the spec type at a composed path from the strongest contributing layer.
///
/// For a property path the type is read live from the owning prim's
/// composition nodes (see [`Self::find_property_node`]) rather than from a
/// property-keyed index, so a property spec added after this path was first
/// queried is picked up instead of a stale cached `None`.
pub fn spec_type(&mut self, graph: &LayerGraph, path: &Path) -> Result<Option<SpecType>> {
let path = &self.effective_path(graph, path)?;
if path.is_property_path() {
return self.find_property_node(graph, path, |layer, p| layer.data().spec_type(p));
}
self.ensure_index(graph, path)?;
let Some(index) = self.store.index_at(path) else {
return Ok(None);
};
for node in index.nodes() {
for &(layer, _) in graph.layer_stack(node.layer_stack_id()).iter() {
if let Some(ty) = graph.layer(layer).data().spec_type(&node.path) {
return Ok(Some(ty));
}
}
}
Ok(None)
}
/// Returns `true` if the composed prim index contains any non-local arc.
pub(crate) fn has_composition_arc(&mut self, graph: &LayerGraph, path: &Path) -> Result<bool> {
self.ensure_index(graph, path)?;
Ok(self
.store
.index_at(path)
.is_some_and(|index| index.has_composition_arc()))
}
/// Captures the target layer identifier and namespace mapping of the
/// strongest node on `prim_path` whose arc satisfies `matches`, for building
/// an arc-based edit target (C++ `UsdEditTarget(UsdPrim, ...)`).
///
/// Considers only nodes that author a spec and are not permission-denied, in
/// strength order. Returns `None` when none match. The mapping is the node's
/// `map_to_root`, and for a node whose site sits inside a variant it is
/// composed over the node-path qualifier pair `{site → stripped site}` (C++
/// `_ComposeMappingForNode`) — map functions never carry variant selections,
/// so the qualifier must be re-attached for the edit target to author at the
/// variant-qualified spec path. Oriented spec → scene, queried in reverse for
/// authoring.
///
/// An instance-proxy path redirects to its shared prototype (the same
/// [`effective_path`](Self::effective_path) redirection value resolution
/// uses), so the arc captured is the prototype's, not an instance-local
/// opinion that composition discards. The returned mapping is therefore
/// oriented in the prototype's namespace, not the proxy's.
pub(crate) fn edit_target_node_info(
&mut self,
graph: &LayerGraph,
prim_path: &Path,
matches: impl Fn(ArcType) -> bool,
) -> Result<Option<EditTargetNodeInfo>> {
let prim_path = self.effective_path(graph, prim_path)?.prim_path();
self.ensure_index(graph, &prim_path)?;
let Some(index) = self.store.index_at(&prim_path) else {
return Ok(None);
};
Ok(index.nodes().find_map(|node| {
(matches(node.arc) && node.has_specs()).then(|| {
// A node inside a variant stores its specs at the qualified site
// path; compose the qualifier onto the map so the edit target
// reaches it (C++ `_ComposeMappingForNode`). The qualifier pair
// adapts the storage location only, so the arc map's root
// identity survives the composition — composing would otherwise
// drop it, since the pair itself carries none — keeping paths
// outside the arc's explicit domain visible to the target, as
// they are for every other arc whose map has the root identity.
let mapping = if node.path.contains_prim_variant_selection() {
let composed = node.map_to_root.compose(&MapFunction::from_pair(
node.path.clone(),
node.path.strip_all_variant_selections(),
));
if node.map_to_root.has_root_identity() {
composed.with_root_identity()
} else {
composed
}
} else {
node.map_to_root.clone()
};
// The layer stack the node composes in, captured by value identity
// so the edit target authors into it exactly rather than
// re-inferring it from layer membership — a contextual instance's
// `${VAR}`-resolved members reach a relocate plan unchanged. The
// value form resolves on any equal-input stage, where a graph-local
// handle would name an unrelated instance.
(
graph.identifier(node.layer_id()).to_string(),
mapping,
graph.stack_identity(node.layer_stack_id()),
)
})
}))
}
/// Resolves a field value from the strongest opinion across all composition nodes.
///
/// Layer metadata authored on the pseudo-root is resolved directly from
/// the root layer and does not compose with sublayers or arcs. The
/// pseudo-root's `primChildren` field remains a child-list query and is
/// handled by normal composition.
pub fn resolve_field(&mut self, graph: &LayerGraph, path: &Path, field: &str) -> Result<Option<Value>> {
let path = &self.effective_path(graph, path)?;
if path.is_abs_root() && field != ChildrenKey::PrimChildren.as_str() {
return self.root_layer_field(graph, field);
}
if path.is_property_path() {
let prim_path = path.prim_path();
let prop_suffix = path.property_suffix();
self.ensure_index(graph, &prim_path)?;
let value = self.cached(&prim_path).resolve_field(field, graph, Some(prop_suffix))?;
Ok(self.anchor_asset_paths(graph, &prim_path, field, Some(prop_suffix), value))
} else {
self.ensure_index(graph, path)?;
let value = self.cached(path).resolve_field(field, graph, None)?;
Ok(self.anchor_asset_paths(graph, path, field, None, value))
}
}
/// Fills the resolved path on any `asset` / `asset[]` value just resolved,
/// anchoring each authored path against the layer of the strongest opinion
/// (C++ `UsdStage::_MakeResolvedAssetPaths`). Non-asset values pass through;
/// asset paths nested inside a dictionary value are not recursed into, only
/// top-level `asset` / `asset[]` fields are resolved.
///
/// TODO(perf): each asset read re-runs `Resolver::resolve` (a filesystem
/// hit); a per-(layer, path) resolution cache would avoid repeating it.
fn anchor_asset_paths(
&self,
graph: &LayerGraph,
prim_path: &Path,
field: &str,
prop_suffix: Option<&str>,
value: Option<Value>,
) -> Option<Value> {
match value? {
Value::AssetPath(asset) => {
let needs_expr = sdf::expr::is_expression(asset.as_str());
let (anchor, vars) = self.asset_context(graph, prim_path, field, prop_suffix, needs_expr);
Some(Value::AssetPath(Self::resolve_asset_path(
graph,
asset,
anchor.as_ref(),
vars,
)))
}
Value::AssetPathVec(assets) => {
let needs_expr = assets.iter().any(|a| sdf::expr::is_expression(a.as_str()));
let (anchor, vars) = self.asset_context(graph, prim_path, field, prop_suffix, needs_expr);
let resolved = assets
.into_iter()
.map(|asset| Self::resolve_asset_path(graph, asset, anchor.as_ref(), vars))
.collect();
Some(Value::AssetPathVec(resolved))
}
other => Some(other),
}
}
/// The inputs for resolving `field`'s asset value, taken from its strongest
/// opinion: the resolved location of that opinion's layer (the anchor for a
/// relative path) and, when `needs_expr` is set, the `expressionVariables`
/// in scope at that opinion's node — its own stack's composed set (C++
/// `node.GetLayerStack()->GetExpressionVariables()`). Computed once so
/// every element of an `asset[]` reuses it; the variables are read only
/// when an authored path is actually an expression.
fn asset_context<'g>(
&self,
graph: &'g LayerGraph,
prim_path: &Path,
field: &str,
prop_suffix: Option<&str>,
needs_expr: bool,
) -> (Option<ResolvedPath>, Option<&'g HashMap<String, Value>>) {
let Some(index) = self.store.index_at(prim_path) else {
return (None, None);
};
let Some((layer, node)) = index.strongest_opinion(field, graph, prop_suffix) else {
return (None, None);
};
let anchor = graph.anchor_location(Some(layer));
let vars = needs_expr.then(|| graph.stack_expression_variables(node.layer_stack_id()));
(anchor, vars)
}
/// Resolves `asset` against `anchor` (its source layer's resolved location)
/// and returns it with the evaluated and resolved paths recorded.
///
/// A variable expression is evaluated against `expr_vars` to the path used
/// as input to resolution (C++ `SdfAssetPath::GetAssetPath`); a malformed
/// or non-string expression — or an expression with no variables in scope
/// (`asset_context` found no composed index or no authoring site for the
/// field) — leaves both derived paths unset. Resolution owns the derived
/// paths: the result is rebuilt from the authored path so any prior
/// evaluated/resolved path is discarded.
///
/// TODO: a failed expression is dropped silently, unlike a reference/payload
/// arc asset-path expression which records `Error::InvalidExpression`
/// (`compose_site::resolve_arc_asset_path`). Surfacing it needs an error
/// channel through value resolution (`value_at` returns `Result<Option>` but
/// this runs after the value is produced).
fn resolve_asset_path(
graph: &LayerGraph,
asset: sdf::AssetPath,
anchor: Option<&ResolvedPath>,
expr_vars: Option<&HashMap<String, Value>>,
) -> sdf::AssetPath {
let mut asset = sdf::AssetPath::new(asset.into_string());
if asset.is_empty() {
return asset;
}
// The per-element `is_expression` is load-bearing for `asset[]`: the
// caller's `needs_expr` is true if *any* element is an expression, so a
// plain element in a mixed array must still skip evaluation.
let identifier = if sdf::expr::is_expression(asset.as_str()) {
let Some(vars) = expr_vars else { return asset };
let Some(evaluated) = sdf::expr::evaluate_string(asset.as_str(), vars).value else {
return asset;
};
let identifier = graph.layer_registry().create_identifier(&evaluated, anchor);
asset.set_evaluated_path(evaluated);
identifier
} else {
graph.layer_registry().create_identifier(asset.as_str(), anchor)
};
if let Some(resolved) = graph.layer_registry().resolve(&identifier) {
asset.set_resolved_path(resolved.to_string_lossy().into_owned());
}
asset
}
/// Returns the composed `apiSchemas` list for a prim.
pub fn api_schemas(&mut self, graph: &LayerGraph, path: &Path) -> Result<Vec<Token>> {
let path = self.effective_path(graph, &path.prim_path())?;
self.ensure_index(graph, &path)?;
self.cached(&path)
.resolve_token_list_op(FieldKey::ApiSchemas, graph, None)
}
/// Resolves the `clipSets` strength-ordering list-op on the prim at `path`,
/// folding the list-op edits across every contributing layer (spec 12.2.6).
/// `None` when `clipSets` is unauthored (clip sets fall back to name order).
pub fn clip_sets_list_op(&mut self, graph: &LayerGraph, path: &Path) -> Result<Option<sdf::StringListOp>> {
let path = self.effective_path(graph, &path.prim_path())?;
self.ensure_index(graph, &path)?;
self.cached(&path).clip_sets_list_op(graph)
}
/// Returns the composed `connectionPaths` list for an attribute path,
/// folding list-op edits (prepend / append / add / delete) across every
/// contributing layer. Non-property paths trivially return an empty list.
pub fn connection_paths(&mut self, graph: &LayerGraph, path: &Path) -> Result<Vec<Path>> {
self.property_targets(graph, path, FieldKey::ConnectionPaths)
}
/// Returns the composed raw `targetPaths` list for a relationship path,
/// folding list-op edits (prepend / append / add / delete) across every
/// contributing layer. Non-property paths trivially return an empty list.
///
/// These are the raw targets (the resolved `targetPaths` list op, spec
/// 12.4); target forwarding — recursively chasing relationship-to-
/// relationship chains — is not applied here.
pub fn relationship_targets(&mut self, graph: &LayerGraph, path: &Path) -> Result<Vec<Path>> {
self.property_targets(graph, path, FieldKey::TargetPaths)
}
/// Returns the forwarded `targetPaths` for a relationship (spec 12.4):
/// a target that resolves to a relationship is replaced, recursively, by
/// that relationship's own forwarded targets. Every other target is kept
/// as-is — prim paths, attribute paths, and any target that does not
/// resolve to a relationship (a dangling or unloaded path). This matches
/// C++ `UsdRelationship::GetForwardedTargets`, which forwards only through
/// live relationships. Cycles are broken (each relationship is followed
/// once) and duplicates collapse, keeping first occurrence.
///
/// The walk uses an explicit stack rather than recursion (mirroring
/// [`crate::usd::ConnectionGraph::resolve_chain`]) so a deep relationship
/// chain cannot overflow the call stack.
///
/// `is_populated` reports whether a prim is inside the stage's working set.
/// A target relationship on a prim outside the set is not followed — its
/// raw targets would be empty under the population mask anyway — so the
/// forwarded result never leaks scene the mask excludes (it stays
/// consistent with [`Self::relationship_targets`] on that path).
pub fn forwarded_relationship_targets(
&mut self,
graph: &LayerGraph,
path: &Path,
is_populated: &dyn Fn(&Path) -> bool,
) -> Result<Vec<Path>> {
let mut out = Vec::new();
let mut emitted = HashSet::new();
let mut followed = HashSet::new();
followed.insert(path.clone());
// Seed with the queried relationship's raw targets. Targets are pushed
// reversed so the strongest (first) target is popped and resolved
// first, preserving authored order in `out`.
let mut stack: Vec<Path> = self.relationship_targets(graph, path)?.into_iter().rev().collect();
while let Some(target) = stack.pop() {
// Only property targets can be relationships; a prim-path target is
// always terminal. Classify property targets by composed spec type.
let is_relationship =
target.is_property_path() && matches!(self.spec_type(graph, &target)?, Some(SpecType::Relationship));
if is_relationship {
// Don't follow a relationship the mask excludes; a masked-out
// prim contributes no composed targets.
if !is_populated(&target.prim_path()) {
continue;
}
if !followed.insert(target.clone()) {
continue; // already followed — break the cycle
}
stack.extend(self.relationship_targets(graph, &target)?.into_iter().rev());
} else if emitted.insert(target.clone()) {
out.push(target);
}
}
Ok(out)
}
/// Composes a path-list-op property field (`connectionPaths` or
/// `targetPaths`) by folding list-op edits across every contributing layer
/// and mapping targets through composition arcs into the stage namespace.
/// Both fields follow generic list-op value resolution (spec 12.2.6).
fn property_targets(&mut self, graph: &LayerGraph, path: &Path, field: FieldKey) -> Result<Vec<Path>> {
self.compose_property_paths(graph, path, field, false)
}
/// Composes a path-list-op property field into stage namespace. With
/// `deleted` it returns the field's deleted entries (the `delete`-op paths);
/// otherwise the resolved targets/connections. On an instance proxy both
/// resolve against the shared prototype's subtree and map the
/// prototype-namespace results back to the queried instance (spec 11.3.4
/// under 11.3.3).
fn compose_property_paths(
&mut self,
graph: &LayerGraph,
path: &Path,
field: FieldKey,
deleted: bool,
) -> Result<Vec<Path>> {
if !path.is_property_path() {
return Ok(Vec::new());
}
let prim = path.prim_path();
let prop_suffix = path.property_suffix().to_owned();
let anchor = self.redirect_anchor(graph, &prim)?;
let resolved_prim = match &anchor {
Some((origin, canonical)) => prim.replace_prefix(origin, canonical).unwrap_or_else(|| prim.clone()),
None => prim.clone(),
};
self.ensure_index(graph, &resolved_prim)?;
// A property whose prim composes in place (no instance redirect), read by
// the non-deleted walk, resolves into its own namespace, so its targets
// can memoize on the prim's own entry. Instance proxies map results back
// per instance and the deleted-paths walk is rare, so both resolve live.
// Whether the result is actually cacheable also turns on it not reading
// cross-prim instance state, decided once `compute_instance_targets` runs.
let is_connection = matches!(field, FieldKey::ConnectionPaths);
let memo_candidate = !deleted && anchor.is_none();
let memo_key = memo_candidate.then(|| TargetMemoKey {
kind: if is_connection {
PropertyTargetKind::Connection
} else {
PropertyTargetKind::Relationship
},
property_suffix: prop_suffix.clone(),
});
if let Some(key) = &memo_key {
if let Some(hit) = self.store.target_memo(&resolved_prim, key) {
let TargetMemo { targets, errors } = hit.clone();
// Re-surface the cached errors: an unrelated index invalidation may
// have cleared `query_errors` since, so push any it now lacks.
for error in errors {
if !self.query_errors.contains(&error) {
self.query_errors.push(error);
}
}
return Ok(targets);
}
}
// A connection/relationship target authored in a class that translates but
// names a different instance of that class is dropped from that class
// node's contribution (C++ `_TargetInClassAndTargetsInstance`). The cache
// precomputes the cross-prim instance set; the per-node target walk
// consults it so a valid stronger opinion for the same path survives.
let (instance_targets, read_cross_prim) = if deleted {
(HashSet::new(), false)
} else {
self.compute_instance_targets(graph, &resolved_prim, field, &prop_suffix)?
};
// The resolved-targets walk translates each target through its
// contributing node's map (relocates folded in), so it needs no separate
// relocate-chaining. The deleted-paths walk has no per-node origin, so it
// still chains every entry through the prim's effective relocates.
let index = self.cached(&resolved_prim);
let (mut targets, invalid) = if deleted {
(
index.resolve_path_list_op_deleted(field, graph, Some(&prop_suffix))?,
Vec::new(),
)
} else {
index.resolve_path_list_op_validated(field, graph, Some(&prop_suffix), &instance_targets)?
};
if deleted && graph.has_relocates() {
let relocates = effective_relocates(graph, &resolved_prim, self.store.entries());
for target in &mut targets {
*target = chain_through_relocates(target, &relocates, None);
}
}
// Targets dropped during composition are reported in authored order, the
// `invalid` list already honoring list-op composition (a target shadowed
// by a stronger explicit, or retracted by a delete, is not reported).
let mut errs: Vec<Error> = Vec::new();
for inv in invalid {
errs.push(match inv.kind {
InvalidTargetKind::External => Error::InvalidExternalTargetPath {
is_connection,
target: inv.target,
property: inv.property,
layer: graph.identifier(inv.layer).to_string(),
arc: inv.arc,
arc_root: inv.arc_root,
composing: prim.clone(),
},
InvalidTargetKind::Instance => Error::InvalidInstanceTargetPath {
is_connection,
target: inv.target,
property: inv.property,
layer: graph.identifier(inv.layer).to_string(),
composing: prim.clone(),
},
});
}
// Targets resolved in the shared prototype's namespace map back to the
// queried instance (spec 11.3.4 under 11.3.3).
if let Some((origin, target_prefix)) = &anchor {
for target in &mut targets {
if let Some(remapped) = target.replace_prefix(target_prefix, origin) {
*target = remapped;
}
}
}
// Cache the in-place result for repeat queries, the errors travelling with
// it so a later cache hit can re-surface them. A resolution that read
// cross-prim instance state is excluded: a target prim's later
// instance-status change is not tracked by this property's invalidation,
// so it must resolve live. The deleted walk and instance proxies (no
// `memo_key`) just append to the transient channel.
if let Some(key) = memo_key.filter(|_| !read_cross_prim) {
let memo = TargetMemo {
targets: targets.clone(),
errors: errs.clone(),
};
self.store.set_target_memo(&resolved_prim, key, memo);
}
self.query_errors.append(&mut errs);
Ok(targets)
}
/// Computes the cross-prim set of connection/relationship targets authored in
/// a class (an inherit node) that name a *different* instance of that class
/// (C++ `_TargetInClassAndTargetsInstance`), keyed by the `(target, property)`
/// node-namespace pair the target walk matches on.
///
/// This is the purely structural fact "is this class target an instance
/// target"; list-op composition (delete / explicit shadowing) and the actual
/// dropping/reporting are left to `resolve_path_list_op_validated`, which
/// consults this set per node contribution. A target inside the class itself
/// (`connectionPathInsideInheritedClass`) is never an instance target.
///
/// Returns the set paired with whether any candidate was gathered — i.e.
/// whether the resolution read cross-prim instance state by composing target
/// prims. The target memo is unsafe in that case (a target prim's later
/// instance-status change is not tracked by the property's own
/// `did_change_targets`), so the caller skips memoization when it is `true`.
fn compute_instance_targets(
&mut self,
graph: &LayerGraph,
resolved_prim: &Path,
field: FieldKey,
prop_suffix: &str,
) -> Result<(HashSet<(Path, Path)>, bool)> {
// Phase 1: gather candidates that translate, releasing the index borrow
// before the cross-prim composition in phase 2.
let mut candidates: Vec<InstanceCandidate> = Vec::new();
let mut seen: HashSet<(Path, Path)> = HashSet::new();
{
let index = self.cached(resolved_prim);
for (id, node) in index.nodes_with_ids() {
if node.arc != ArcType::Inherit || !node.has_specs() {
continue;
}
let class_path = index.graph().path_at_introduction(id);
// The selection-free form for the within-class test below: a
// class defined inside a variant has a qualified introduction
// path, while target paths compare selection-free.
let class_prefix = class_path.strip_all_variant_selections();
let members = graph.layer_stack(node.layer_stack_id());
let class_layers: Vec<LayerId> = members.iter().map(|(l, _)| *l).collect();
// The node's map to the root namespace (C++ `PcpNodeRef::GetMapToRoot`).
let map = &node.map_to_root;
let property = Path::new(&format!("{}{prop_suffix}", node.path))?;
for &(layer, _) in members.iter() {
let Some(value) = graph.layer(layer).data().try_field(&property, field.as_str())? else {
continue;
};
let list_op = match value.into_owned() {
Value::PathListOp(op) => op,
Value::PathVec(paths) => sdf::PathListOp::explicit(paths),
_ => continue,
};
for path in list_op.iter() {
let target = property.make_absolute(path);
// A target inside the class itself is a normal within-class
// target (C++ `connectionPathInsideInheritedClass`); only a
// target that translates can name an instance. A relative
// target anchors at the class node's qualified site, so
// both sides compare selection-free.
if target
.prim_path()
.strip_all_variant_selections()
.has_prefix(&class_prefix)
{
continue;
}
if !seen.insert((target.clone(), property.clone())) {
continue;
}
let Some(translated) = map.translate_to_target(&target) else {
continue;
};
candidates.push(InstanceCandidate {
target,
property: property.clone(),
translated,
class_layers: class_layers.clone(),
class_path: class_path.clone(),
});
}
}
}
}
// Phase 2: compose each target prim for the cross-prim inherit check.
// A non-empty candidate set means the result read another prim's instance
// status, so the caller must not memoize it.
let read_cross_prim = !candidates.is_empty();
let mut instance_targets: HashSet<(Path, Path)> = HashSet::new();
for c in candidates {
let target_prim = c.translated.prim_path();
self.ensure_index(graph, &target_prim)?;
if target_prim_inherits_class(self.cached(&target_prim), graph, &c.class_layers, &c.class_path) {
instance_targets.insert((c.target, c.property));
}
}
Ok((instance_targets, read_cross_prim))
}
/// Composes a relationship's target paths together with the paths its
/// list-op deletes, returned as `(targets, deleted)` (C++
/// `PcpBuildFilteredTargetIndex` and its `deletedPaths` out-param). Both are
/// mapped into stage namespace; a non-property path yields two empty lists.
pub fn compute_relationship_target_paths(
&mut self,
graph: &LayerGraph,
path: &Path,
) -> Result<(Vec<Path>, Vec<Path>)> {
self.compute_target_paths(graph, path, FieldKey::TargetPaths)
}
/// Composes an attribute's connection paths together with the paths its
/// list-op deletes (the connection analog of
/// [`Self::compute_relationship_target_paths`]).
pub fn compute_attribute_connection_paths(
&mut self,
graph: &LayerGraph,
path: &Path,
) -> Result<(Vec<Path>, Vec<Path>)> {
self.compute_target_paths(graph, path, FieldKey::ConnectionPaths)
}
/// Composes both the resolved and the deleted entries of a path-list-op
/// property field. TODO(perf): C++ surfaces both from a single target-index
/// build; this composes the field twice.
fn compute_target_paths(
&mut self,
graph: &LayerGraph,
path: &Path,
field: FieldKey,
) -> Result<(Vec<Path>, Vec<Path>)> {
let targets = self.compose_property_paths(graph, path, field, false)?;
let deleted = self.compose_property_paths(graph, path, field, true)?;
Ok((targets, deleted))
}
/// Returns pseudo-root stage metadata, composing session-layer opinions
/// over the root layer (strongest first).
///
/// Unlike [`Self::root_layer_field`] — which is root-layer-only for the
/// spec 12.2.7 fields such as `defaultPrim` — general stage metadata
/// (e.g. `renderSettingsPrimPath`) honors a session-layer override,
/// matching C++ `UsdStage::GetMetadata`. A [`Value::ValueBlock`] in a
/// stronger layer blocks weaker opinions.
pub fn stage_metadata(&self, graph: &LayerGraph, field: &str) -> Result<Option<Value>> {
let root = Path::abs_root();
// Walk session layers then the root layer so the session opinion wins,
// skipping muted session layers (the root is never muted).
let layer_ids = graph
.session_layers()
.iter()
.copied()
.chain(graph.root_id())
.filter(|&id| !graph.is_muted(id))
.collect::<Vec<_>>();
for id in layer_ids {
let layer = graph.layer(id);
match layer.data().try_field(&root, field)? {
Some(value) if matches!(value.as_ref(), Value::ValueBlock) => return Ok(None),
Some(value) => return Ok(Some(value.into_owned())),
None => {}
}
}
Ok(None)
}
/// Returns pseudo-root layer metadata from the root layer only.
///
/// Session-layer and sublayer opinions are intentionally ignored here,
/// matching spec 12.2.7.
fn root_layer_field(&self, graph: &LayerGraph, field: &str) -> Result<Option<Value>> {
let root = Path::abs_root();
let Some(root_layer) = graph.root_layer() else {
return Ok(None);
};
let Some(value) = root_layer.data().try_field(&root, field)? else {
return Ok(None);
};
if matches!(value.as_ref(), Value::ValueBlock) {
return Ok(None);
}
Ok(Some(value.into_owned()))
}
/// Returns the composed list of child names for a prim path (C++
/// `PcpPrimIndex::ComputePrimChildNames`'s `nameOrder` out-param).
pub fn prim_children(&mut self, graph: &LayerGraph, path: &Path) -> Result<Vec<Token>> {
Ok(self.compute_prim_child_names(graph, path)?.0)
}
/// Composes a prim's child names alongside the names prohibited at it (C++
/// `PcpPrimIndex::ComputePrimChildNames` / `_ComposePrimChildNames`, whose
/// `nameOrder` and `prohibitedNames` out-params this returns as a pair).
///
/// The composition graph is walked weakest-to-strongest. At each contributing
/// node, the relocates authored in that node's layer stack are applied to the
/// names contributed so far (`relocates::apply_child_relocates`) — a child renamed
/// within the same parent keeps the source's position, a child relocated to a
/// different parent is removed, and a child relocated in from elsewhere is
/// appended in the normative element order (spec §8.2) — and then the node's own `primChildren` /
/// `primOrder` compose over the running order (mirroring C++
/// `_ComposePrimChildNamesAtNode`). Every relocation source becomes a
/// prohibited name, removed from the final order.
///
/// Within a node, the contributing layers fold weakest-first: each appends
/// its not-yet-seen names in authored order, then its `primOrder` opinion
/// reshuffles the running list, so several sublayers can contribute partial
/// orderings. The recursive build already grafts inherit/specialize/reference
/// targets with their subtrees, so a single structural walk covers class
/// children. On an instance prim, locally-authored children are dropped (spec
/// 11.3.3) so the children come only from the composition arcs.
pub fn compute_prim_child_names(&mut self, graph: &LayerGraph, path: &Path) -> Result<(Vec<Token>, Vec<Token>)> {
let path = self.effective_path(graph, path)?;
self.ensure_index(graph, &path)?;
// An instance prim's children come only from its composition arcs;
// opinions authored at the instance's own namespace — the local root and
// the ancestral references above the instanceable arc — are discarded
// (spec 11.3.3). The instance prim's own index is otherwise left intact.
let drop_local = self.is_instance(graph, &path)?;
let index = self.cached(&path);
// The instance-local partition is keyed by the prim's own namespace depth
// ([`PrimIndex::instance_local_nodes`]); empty when not dropping locals.
let local = if drop_local {
let depth = path.prim_element_count() as u16;
index.instance_local_nodes(depth, depth)
} else {
Vec::new()
};
let has_relocates = graph.has_relocates();
let mut name_order: Vec<Token> = Vec::new();
let mut name_set: HashSet<Token> = HashSet::new();
let mut prohibited: HashSet<Token> = HashSet::new();
// Contributing nodes are walked in reverse strength order (weak-to-
// strong) — the order in which C++ `_ComposePrimChildNames` finishes each
// node, visiting every descendant before its ancestor. A non-contributing
// node (inert or culled) is skipped (C++ `_ComposePrimChildNamesAtNode`'s
// `CanContributeSpecs` guard): an inert relocate placeholder or salted-
// earth source must not inject names or relocates at its site.
let nodes = index
.nodes_with_ids()
.filter(|(id, node)| !(node.is_inert() || node.is_culled() || drop_local && local[id.idx()]))
.map(|(_, node)| node)
.rev();
for node in nodes {
// Apply this node's layer-stack relocates to the names contributed so
// far, then compose the node's own children on top. A relocation
// source is always a namespace child introduced by a composition arc
// (a strictly weaker node), so by the time this node's relocates run
// the source name is already in `name_order`; the relocates therefore
// correctly run before this node's own `primChildren` fold.
//
// The pairs are chained within the node's layer stack
// (`combined_relocates`, C++ `GetRelocatesSourceToTarget`): a same-
// parent chain `A -> B`, `B -> C` resolves `A` straight to `C`, so the
// intermediate `B` (a prohibited source) does not survive as the final
// name. TODO(perf): `combined_relocates` rescans and re-allocates the
// node's layer-stack relocates on every contributing node (here and in
// the indexer's arc-map fold), gated on `has_relocates`. Precompute it
// once per distinct ambient, keyed by `LayerStackId` on the composed
// stack instance, so this becomes a lookup (C++ caches these on
// `PcpLayerStack`).
if has_relocates {
let pairs = graph.combined_relocates(node.layer_stack_id());
apply_child_relocates(&node.path, &pairs, &mut name_order, &mut name_set, &mut prohibited);
}
// The node's contributing layers fold weakest-first; `layer_stack()`
// is strongest-first, so it is reversed here. Only the layer index is
// needed (the offset `layers()` folds in is irrelevant to name
// composition), so the borrowed slice is reversed in place.
for &(layer, _) in graph.layer_stack(node.layer_stack_id()).iter().rev() {
let layer_data = graph.layer(layer);
append_unseen_names(
layer_data,
&node.path,
ChildrenKey::PrimChildren,
&mut name_order,
&mut name_set,
);
if let Ok(Value::TokenVec(order)) = layer_data
.data()
.get_field(&node.path, FieldKey::PrimOrder.as_str())
.map(|v| v.into_owned())
{
sdf::apply_ordering(&mut name_order, &order);
}
}
}
// Names relocated away cannot reappear here (C++ removes the prohibited
// set from the composed order after the walk).
if !prohibited.is_empty() {
name_order.retain(|name| !prohibited.contains(name));
}
let mut prohibited: Vec<Token> = prohibited.into_iter().collect();
// Order the prohibited set the same way as the child names (spec §8.2),
// so the two outputs of this function stay consistent.
prohibited.sort_by(|a, b| sdf::element_cmp(a.as_str(), b.as_str()));
Ok((name_order, prohibited))
}
/// Returns the composed list of property names for a prim path.
///
/// Merges `propertyChildren` weakest-to-strongest. `propertyOrder` is not
/// applied: USD value resolution ignores `reorder properties` (C++
/// `_ComposePrimPropertyNames` passes a null order field in USD mode), so
/// composed property order follows authoring order alone.
pub fn prim_properties(&mut self, graph: &LayerGraph, path: &Path) -> Result<Vec<Token>> {
let path = &self.effective_path(graph, path)?;
self.composed_property_names(graph, path)
}
/// Pushes a [`Error::InconsistentPropertyType`] for each composed property of
/// `prim_path` whose specs mix attribute and relationship kinds (C++
/// `PcpErrorInconsistentPropertyType`). C++ reports the conflict on each
/// property-index composition; the dump's property-name pass (here) and
/// property-stack pass ([`property_stack`](Self::property_stack)) each compose
/// it, so the error surfaces once per pass.
fn report_property_type_conflicts(&mut self, graph: &LayerGraph, prim_path: &Path, names: &[Token]) {
let Some(index) = self.store.index_at(prim_path) else {
return;
};
let mut conflicts = Vec::new();
for name in names {
let Ok(prop_path) = prim_path.append_property(name) else {
continue;
};
conflicts.extend(self.compose_property_specs(graph, index, prim_path, &prop_path).1);
}
self.query_errors.append(&mut conflicts);
}
/// Walks a property's specs strongest-first across the prim's composition
/// graph, returning its `(layer identifier, spec path)` stack and the
/// inconsistent-spec-type errors. The first spec's kind (attribute vs
/// relationship) is the defining type; weaker specs of the other kind are
/// inconsistent (C++ `PcpErrorInconsistentPropertyType`) — dropped from the
/// stack and reported. `prop_path` is the property in `prim_path`'s namespace.
///
/// Reads the memoized prim spec stack as the candidate set: a property spec
/// requires its owning prim spec, so every layer that authors the property
/// also authors the prim spec the stack records. Inert and culled nodes are
/// skipped (matching the structural node walk); permission-denied sites stay.
fn compose_property_specs(
&self,
graph: &LayerGraph,
index: &PrimIndex,
prim_path: &Path,
prop_path: &Path,
) -> (Vec<(String, Path)>, Vec<Error>) {
let mut stack = Vec::new();
let mut conflicts = Vec::new();
let mut defining: Option<(SpecType, String, Path)> = None;
for (site, node) in index.live_spec_sites() {
let Some(p) = prop_path.replace_prefix(prim_path, node.path()) else {
continue;
};
let Some(spec_type) = graph.layer(site.layer).data().spec_type(&p) else {
continue;
};
let layer_id = graph.identifier(site.layer).to_string();
match &defining {
None => defining = Some((spec_type, layer_id.clone(), p.clone())),
Some((def_type, def_layer, def_path)) if *def_type != spec_type => {
conflicts.push(Error::InconsistentPropertyType {
property: prop_path.clone(),
defining_layer: def_layer.clone(),
defining_path: def_path.clone(),
defining_is_attribute: *def_type == SpecType::Attribute,
conflicting_layer: layer_id,
conflicting_path: p.clone(),
conflicting_is_attribute: spec_type == SpecType::Attribute,
composing: prim_path.clone(),
});
continue;
}
Some(_) => {}
}
stack.push((layer_id, p));
}
(stack, conflicts)
}
/// Returns the composed [`PrimIndex`] for a prim, building it if needed (C++
/// `UsdPrim::GetPrimIndex` / `PcpCache::ComputePrimIndex`). The borrow is
/// tied to the cache, so callers reach it through the borrowing
/// [`PrimIndexRef`](crate::usd::PrimIndexRef) view.
pub fn index(&mut self, graph: &LayerGraph, path: &Path) -> Result<&PrimIndex> {
let path = self.effective_path(graph, &path.prim_path())?;
self.ensure_index(graph, &path)?;
Ok(self.cached(&path))
}
/// Returns the prim stack: each `(layer identifier, spec path)` site that
/// contributes a prim spec, strongest first (C++ `UsdPrim::GetPrimStack`).
///
/// Projects the live spec sites; permission-denied sites are kept — they still
/// author a spec, so the structural introspection lists them, unlike value
/// resolution.
pub fn prim_stack(&mut self, graph: &LayerGraph, path: &Path) -> Result<Vec<(String, Path)>> {
let path = self.effective_path(graph, &path.prim_path())?;
self.ensure_index(graph, &path)?;
let index = self.cached(&path);
let stack = index
.live_spec_sites()
.map(|(site, node)| (graph.identifier(site.layer).to_string(), node.path().clone()))
.collect();
Ok(stack)
}
/// Returns the property stack for a property path: each `(layer identifier,
/// spec path)` site that authors a property spec, strongest first. Backs
/// C++ `UsdProperty::GetPropertyStack`. A non-property path yields an empty
/// stack.
pub fn property_stack(&mut self, graph: &LayerGraph, path: &Path) -> Result<Vec<(String, Path)>> {
let path = self.effective_path(graph, path)?;
if !path.is_property_path() {
return Ok(Vec::new());
}
let prim_path = path.prim_path();
self.ensure_index(graph, &prim_path)?;
let Some(index) = self.store.index_at(&prim_path) else {
return Ok(Vec::new());
};
let (stack, mut conflicts) = self.compose_property_specs(graph, index, &prim_path, &path);
// These transient conflicts are cleared on any index invalidation, so
// they never go stale across an edit; repeated `property_stack` queries
// on the same conflicting property without an intervening edit still
// re-append within a session (the `query_errors` TODO).
self.query_errors.append(&mut conflicts);
Ok(stack)
}
/// Returns the variant selections composed onto a prim, as `(set,
/// selection)` pairs sorted by set name. Backs C++
/// `UsdVariantSets::GetAllVariantSelections`. These are the effective
/// selections — authored, fallback, or default — read from the variant
/// selection sites composed into the index, so they match the variant
/// branches that actually contribute opinions.
pub fn variant_selections(&mut self, graph: &LayerGraph, path: &Path) -> Result<Vec<(String, String)>> {
let path = self.effective_path(graph, &path.prim_path())?;
self.ensure_index(graph, &path)?;
Ok(self.cached(&path).variant_selections())
}
/// Returns the `defaultPrim` metadata from the root layer, if set.
///
/// When session layers are present, `defaultPrim` is read from the
/// first non-session layer (the root layer), matching C++ behavior.
pub fn default_prim(&self, graph: &LayerGraph) -> Option<Token> {
let root = Path::abs_root();
let value = graph
.root_layer()?
.data()
.get_field(&root, FieldKey::DefaultPrim.as_str())
.ok()?;
value.into_owned().try_as_token()
}
/// Collects ancestor arcs from all cached ancestors of `path`.
///
/// Returns references into the cached contexts, avoiding allocation
/// of `AncestorArc` (which contains `MapFunction` with a `Vec`).
fn collect_ancestor_arcs(&self, path: &Path) -> Vec<&AncestorArc> {
let mut arcs = Vec::new();
let mut p = Some(path.clone());
while let Some(pp) = p {
if let Some(ctx) = self.store.context_at(&pp) {
arcs.extend(&ctx.ancestor_arcs);
}
p = pp.parent();
}
arcs
}
/// Pre-caches inherit/specialize targets declared in the prim's layer
/// data. Reads inherit paths from each layer, resolves them to composed
/// namespace using ancestor arcs, and ensures those targets are cached.
fn precache_inherit_targets(&mut self, graph: &LayerGraph, path: &Path) {
let Some(parent) = path.parent() else {
return;
};
let Some(parent_index) = self.store.index_at(&parent) else {
return;
};
let ancestor_arcs = self.collect_ancestor_arcs(&parent);
// Scan each parent composition node for inherit/specialize targets: the
// parent's own path in that node's namespace, and the prim's path there
// (the node's path extended by the prim name). A layer that authors the
// prim directly contributes to the parent at the parent path, so it is
// already covered here — no separate all-layers scan of the prim path is
// needed.
let mut nodes_to_scan: Vec<(Path, LayerId)> = Vec::new();
for node in parent_index.nodes() {
for &(layer, _) in graph.layer_stack(node.layer_stack_id()).iter() {
nodes_to_scan.push((node.path.clone(), layer));
if let Some(name) = path.name() {
if let Ok(child_in_node) = node.path.append_path(name) {
nodes_to_scan.push((child_in_node, layer));
}
}
}
}
let mut targets_to_cache = Vec::new();
for (scan_path, scan_layer) in &nodes_to_scan {
for field in [FieldKey::InheritPaths, FieldKey::Specializes] {
let Ok(val) = graph.layer(*scan_layer).data().get_field(scan_path, field.as_str()) else {
continue;
};
let Value::PathListOp(list_op) = val.into_owned() else {
continue;
};
for target in &list_op.flatten() {
// Anchor a relative inherit/specialize target at the path it
// is authored on (the scanned node's namespace), matching the
// indexer's `path.make_absolute`. Anchoring at the
// composed parent would mis-resolve `../` targets by a level.
let raw = scan_path.make_absolute(target);
// Try composed-namespace versions via ancestor arcs.
for a in &ancestor_arcs {
if let Some(composed) = a.map.map_source_to_target(&raw) {
if composed != raw && !targets_to_cache.contains(&composed) {
targets_to_cache.push(composed);
}
}
}
if !targets_to_cache.contains(&raw) {
targets_to_cache.push(raw);
}
}
}
}
for target in targets_to_cache {
self.precache_path(graph, &target);
// Recursively precache the target's own inherit targets.
if self.is_indexed(&target) {
self.precache_inherit_targets(graph, &target);
}
}
}
// ------------------------------------------------------------------
// Core composition
// ------------------------------------------------------------------
/// Ensures the prim index for `path` is built and cached.
///
/// When LIVRPS composition produces an empty index (no layer has a direct
/// spec at the composed path), parent composition nodes are checked for
/// child specs at their respective paths. This handles prims that only
/// exist through ancestor inherit, specialize, or reference arcs.
pub(super) fn ensure_index(&mut self, graph: &LayerGraph, path: &Path) -> Result<()> {
if self.is_indexed(path) {
return Ok(());
}
// Composing a prim whose ancestor is still mid-build cannot seed from that
// ancestor's opinions. This happens only when pre-caching an
// inherit/specialize target that is a namespace descendant of an
// in-progress ancestor (a prim inheriting its own descendant). The
// descendant may be more than one level down (`/A` inheriting `/A/B/C`),
// so every strict ancestor is checked, not just the parent. Defer without
// caching an under-seeded result; a later query composes it correctly once
// the ancestor is cached, and the cycle-closing arc finds no cached target.
if path.strict_ancestors().any(|a| self.in_progress.contains(&a)) {
return Ok(());
}
// A re-entrant call for a path already mid-build is a class-hierarchy
// cycle reached through inherit/specialize pre-caching. Bail out: the
// outer build finishes, and the cycle-closing arc finds no cached target.
if !self.in_progress.insert(path.clone()) {
return Ok(());
}
let result = self.build_index(graph, path);
self.in_progress.remove(path);
result
}
/// Builds and caches the index for `path`, assuming `path` is already
/// recorded in [`in_progress`](Self::in_progress) (see [`ensure_index`](Self::ensure_index)).
fn build_index(&mut self, graph: &LayerGraph, path: &Path) -> Result<()> {
// An already-cached path must not rebuild through here: the builder's
// cache-hit path reports empty expression-variable dependencies (the
// cached entry's registration is authoritative), so re-registering
// would wipe the prim's recorded `${VAR}` reads. `ensure_index`'s
// `is_indexed` check upholds this.
debug_assert!(
!self.is_indexed(path),
"build_index on a cached path would re-register empty expression-variable deps",
);
// Snapshot the demand queue so a reference/payload arc to a not-yet-loaded
// layer — demanded by this build or by a pre-cached ancestor below — is
// detected after the build and keeps the incomplete index out of the cache.
let pending_before = self.pending_loads.len();
// Compose ancestors first so the parent's `CompositionContext` (and
// its `within_instance` flag, spec 11.3.3) is available. Composition
// is a pure function of the layer stack, path, and parent context, so
// building ancestors eagerly only fixes the parent context — it does
// not change any prim's resolved opinions.
if let Some(parent) = path.parent() {
if !parent.is_abs_root() && !self.is_indexed(&parent) {
self.precache_path(graph, &parent);
}
}
// Pre-cache inherit/specialize targets so the indexer can
// find them. This handles the timing issue where a target prim is
// in a sibling subtree that hasn't been traversed yet.
self.precache_inherit_targets(graph, path);
let parent_ctx = path
.parent()
.and_then(|p| self.store.context_at(&p))
.cloned()
.unwrap_or_else(|| self.root_parent_context());
// Computed per path, not inherited from the parent context: two
// siblings can have different load rules, and a rule authored on an
// ancestor doesn't by itself determine this path's own decision (see
// `LoadRules::effective_rule`'s lookahead).
let load_payloads = self.is_loaded(path);
// TODO(rayon): `build_with_cache` is a pure function of `graph`,
// `&parent_ctx`, and the store's entries, so sibling prims compose
// independently and this is the natural per-prim `par_iter` boundary.
// The blocker is the shared store the inherit/specialize targets read
// mid-build — parallelizing the driver needs a concurrent map or a
// topological (targets-first) build order.
let (mut index, mut build_errors, pending_loads, mut expr_var_deps) =
match PrimIndex::build_with_cache(path, graph, &parent_ctx, self.store.entries(), load_payloads) {
Ok(result) => result,
Err(e) => return Err(e.into()),
};
self.pending_loads.extend(pending_loads);
// A reference/payload arc demanded a layer that is not yet loaded — here,
// or in a pre-cached ancestor that then seeded this build incompletely —
// so this index is incomplete: leave `path` uncached for the stage's query
// loop to load and recompose. Returning before `cache_index` keeps a
// partial index — and the transient errors composed without the missing
// layer — out of the cache entirely.
if self.pending_loads.len() > pending_before {
return Ok(());
}
// Retain recoverable composition errors recorded during the build (e.g.
// an unresolvable arc). An invalid opinion at a
// relocation source is reported "while composing" this prim, so stamp its
// path — the indexer may have recorded it deep in a sub-index build whose
// own site path differs.
for error in &mut build_errors {
match error {
Error::OpinionAtRelocationSource { composing, .. } => *composing = path.clone(),
Error::ProhibitedRelocationSource { composing, .. } => *composing = path.clone(),
Error::ArcCycle(info) => info.composing = path.clone(),
_ => {}
}
}
// `build_errors` accumulates every error for this prim and is carried
// into the prim's cache entry at the end, replacing any prior entry, so
// a rebuild never duplicates and a fixed prim drops its stale errors.
// Inside an instance, local opinions on descendants are discarded
// (spec 11.3.3): the subtree is composed purely from the arcs the
// instance brings in. This is enforced at composition time — the indexer
// marks the local root site inert for any prim whose parent context is
// `within_instance`, so the local arcs are never followed — rather than
// pruned afterwards, which would leave the nodes those local arcs spawned.
// Inside an instance, the ancestral references the instance prim is
// nested under contribute opinions at the instance's own namespace that
// must not leak into the shared subtree (spec 11.3.3). The indexer
// already inerted the local root for an instance descendant; this inerts
// those outer references too (the C++ `!HasTransitiveDirectDependency`
// nodes), leaving only the instanceable arc, its descendants, and the
// implied classes. Runs before deriving instance state below so the
// suppressed opinions are already inert.
if let Some(depth) = parent_ctx.instance_depth {
index.mark_instance_local_inert(path.prim_element_count() as u16, depth);
}
// This prim is an instance when its composition declares
// `instanceable = true` and carries an arc; its descendants then
// inherit `within_instance`. A nested instance therefore re-arms the
// flag for its own subtree. Computed from the freshly built index so it
// agrees with a later `Prim::is_instance`, avoiding re-entering
// `ensure_index` for `path`.
let is_instance = index.has_composition_arc()
&& matches!(
index.resolve_field(FieldKey::Instanceable.as_str(), graph, None)?,
Some(Value::Bool(true))
);
// The child-context selection resolution can evaluate a `${VAR}`
// selection no indexing-time task did — one authored here for a set
// declared only on a descendant — so its reads merge into this prim's
// dependency map before it registers.
let (mut child_context, context_deps) = index.context_for_children(graph, &parent_ctx);
expr_var_deps.merge(context_deps);
// A nested instance re-arms the depth to its own (deeper) level, so an
// inner instance's descendants drop opinions above its instanceable arc
// rather than the outer instance's.
child_context.instance_depth = if is_instance {
Some(path.prim_element_count() as u16)
} else {
parent_ctx.instance_depth
};
self.cache_index(graph, path, index, child_context, build_errors, expr_var_deps);
// Report inconsistent property types once per prim composition (C++
// `PcpErrorInconsistentPropertyType`); a later property-stack query
// reports the conflict again, matching C++'s per-pass reporting.
// TODO(perf): this composes property names on every prim build to find a
// rare conflict; gate it on a cheaper signal (e.g. a node carrying both
// attribute and relationship specs) before scanning.
let names = self.composed_property_names(graph, path)?;
self.report_property_type_conflicts(graph, path, &names);
Ok(())
}
/// Ensures a path and all its ancestors are cached (built on the fly if needed).
fn precache_path(&mut self, graph: &LayerGraph, path: &Path) {
let mut to_build = Vec::new();
let mut p = Some(path.clone());
while let Some(pp) = p {
if pp == Path::abs_root() || self.is_indexed(&pp) {
break;
}
to_build.push(pp.clone());
p = pp.parent();
}
for pp in to_build.into_iter().rev() {
let _ = self.ensure_index(graph, &pp);
}
}
/// Composes a prim's property names across its composition index, folding
/// `propertyChildren` weakest-to-strongest (C++ `_ComposePrimPropertyNames`).
///
/// Nodes are visited weakest first (the reverse of strength order), and
/// within each node its contributing layers weakest first; each layer appends
/// its not-yet-seen names in authored order, so a name keeps its weakest
/// position. `propertyOrder` is not applied — USD value resolution ignores
/// `reorder properties` — so composed property order follows authoring order
/// alone. The recursive build already grafts inherit/specialize/reference
/// targets with their subtrees, so this single structural walk covers class
/// properties with no separate target rediscovery.
fn composed_property_names(&mut self, graph: &LayerGraph, path: &Path) -> Result<Vec<Token>> {
self.ensure_index(graph, path)?;
let index = self.cached(path);
let mut result: Vec<Token> = Vec::new();
let mut seen: HashSet<Token> = HashSet::new();
// Fold weakest-to-strongest across both nodes and, within each node, its
// layers: contributing nodes in reverse strength order, and `layer_stack()`
// (strongest first) reversed in place. `seen` dedups names in O(1) while
// `result` preserves the weakest-position order.
for node in index.nodes().rev() {
for &(layer, _) in graph.layer_stack(node.layer_stack_id()).iter().rev() {
let layer_data = graph.layer(layer);
append_unseen_names(
layer_data,
&node.path,
ChildrenKey::PropertyChildren,
&mut result,
&mut seen,
);
}
}
Ok(result)
}
}
/// Appends a layer's not-yet-seen `field` children (`primChildren` /
/// `propertyChildren`) to `order` in authored order, recording each in `seen`.
/// A name already present keeps its weaker position. Shared by the prim- and
/// property-name folds (C++ `PcpComposeSiteChildNames`'s append step).
fn append_unseen_names(
layer: &sdf::Layer,
path: &Path,
field: ChildrenKey,
order: &mut Vec<Token>,
seen: &mut HashSet<Token>,
) {
if let Ok(Value::TokenVec(names)) = layer.data().get_field(path, field.as_str()).map(|v| v.into_owned()) {
for name in names {
if seen.insert(name.clone()) {
order.push(name);
}
}
}
}
/// A class-node target that translates, gathered by
/// [`IndexCache::compute_instance_targets`] for the cross-prim instance check.
struct InstanceCandidate {
/// The authored target, in the authoring (class) node's namespace.
target: Path,
/// The owning property, in the authoring node's namespace.
property: Path,
/// The target translated to the root namespace (C++
/// `PcpTranslatePathFromNodeToRoot`).
translated: Path,
/// The class node's layer-stack layers, for the cross-prim instance check.
class_layers: Vec<LayerId>,
/// The class path, in the node's namespace (the inherit's introduction path).
class_path: Path,
}
/// Whether `index` (a composed target prim) inherits the class at `class_path`
/// from the same `class_layers` layer stack (C++
/// `_TargetInClassAndTargetsInstance`'s node scan): the target names an instance
/// of the class.
fn target_prim_inherits_class(
index: &PrimIndex,
graph: &LayerGraph,
class_layers: &[LayerId],
class_path: &Path,
) -> bool {
index.all_nodes().any(|n| {
n.arc == ArcType::Inherit
&& graph
.layer_stack(n.layer_stack_id())
.iter()
.map(|(l, _)| *l)
.eq(class_layers.iter().copied())
&& n.path.has_prefix(class_path)
})
}
#[cfg(test)]
mod tests {
use super::super::ExpressionContext;
use super::*;
fn manifest_dir() -> String {
std::env::var("CARGO_MANIFEST_DIR").unwrap()
}
/// Builds a stack with the root and the full transitive closure of its
/// sublayers, references, and payloads collected in, so composition can
/// resolve them directly without the stage's on-demand load loop (clip
/// layers are still opened lazily by the cache).
fn collected_stack(path: &str) -> (LayerGraph, IndexCache) {
let registry = sdf::LayerRegistry::default();
let layers = registry.collect_with_arcs(path).expect("collect layers");
let graph = LayerGraph::from_layers(layers, 0, registry);
(
graph,
IndexCache::new(VariantFallbackMap::new(), LoadRules::all(), Vec::new()),
)
}
/// Parses in-memory USDA text into a single `root.usda` layer.
fn parse_layer(text: &str) -> sdf::Layer {
parse_named_layer("root.usda", text)
}
/// Parses in-memory USDA text into a layer with the given identifier, so a
/// test can build a multi-layer stack whose `subLayers` resolve by name.
fn parse_named_layer(identifier: &str, text: &str) -> sdf::Layer {
let data = crate::usda::parser::Parser::new(text).parse().expect("parse usda");
sdf::Layer::new(identifier, Box::new(sdf::Data::from_specs(data)))
}
/// Builds a one-layer graph + cache from in-memory USDA text, for
/// composition cases that need no on-disk asset.
fn in_memory_stack(text: &str) -> (LayerGraph, IndexCache) {
let graph = LayerGraph::from_layers(vec![parse_layer(text)], 0, sdf::LayerRegistry::default());
(
graph,
IndexCache::new(VariantFallbackMap::new(), LoadRules::all(), Vec::new()),
)
}
/// `value_at` with the demand drain the stage's load barrier provides: a
/// first-touch `(target, context)` pair leaves a [`Demand`] for its
/// not-yet-interned stack, so mint and retry until a pass demands nothing
/// new (the fixtures load every layer up front, so a demand only ever needs
/// interning).
fn settled_value_at(
graph: &mut LayerGraph,
cache: &mut IndexCache,
path: &Path,
time: f64,
) -> Result<Option<Value>> {
let interp = |_: &sdf::TimeSampleMap, _: f64| None;
loop {
let value = cache.value_at(graph, path, time, &interp)?;
let mut pending = Vec::new();
cache.swap_pending_loads(&mut pending);
if !graph.intern_demanded(&pending) {
return Ok(value);
}
}
}
/// Run `f` as one atomic transaction on `layer` and return the recorded change
/// list, the test-side spelling of an [`sdf::Layer`] edit. Captures the record
/// the way any observer would — through an `after_commit` sink — since `edit`
/// itself returns only whether anything changed.
fn edit_layer(
layer: &mut sdf::Layer,
f: impl FnOnce(&mut sdf::LayerEdit<'_>) -> Result<(), sdf::AuthoringError>,
) -> Result<sdf::ChangeList, sdf::AuthoringError> {
let captured = std::rc::Rc::new(std::cell::RefCell::new(sdf::ChangeList::new()));
let slot = captured.clone();
let id = layer.add_sink(move |_: &str, changes: &sdf::ChangeList| {
slot.replace(changes.clone());
});
let result = layer.edit(f);
layer.remove_sink(id);
match result {
Ok(_) => Ok(std::rc::Rc::try_unwrap(captured).expect("sink dropped").into_inner()),
Err(sdf::EditError::Author(e)) => Err(e),
Err(sdf::EditError::Rejected(_)) => panic!("no layer sink to veto in tests"),
}
}
/// Builds a one-layer graph + cache whose root is loaded from a real path,
/// so the resolver can anchor clip asset paths relative to it.
fn single_layer_stack(path: &str) -> (LayerGraph, IndexCache) {
let registry = sdf::LayerRegistry::default();
let id = registry.create_identifier(path, None);
let data = registry.open(path).expect("open root").expect("root resolves");
let graph = LayerGraph::from_layers(vec![sdf::Layer::new(id, data)], 0, registry);
(
graph,
IndexCache::new(VariantFallbackMap::new(), LoadRules::all(), Vec::new()),
)
}
/// A prim inheriting its own grand-descendant (`/A` inherits `/A/B/C`) is a
/// cycle whose arc is dropped, but composing `/A` must not cache an
/// under-seeded `/A/B/C`. The inherit-target precache builds `/A/B/C` while
/// `/A` is in progress, and its parent `/A/B` is not the in-progress prim, so
/// the deferral guard must check every ancestor, not just the parent. `/A/B`
/// references `</Lib/Ref>`, so a correctly-seeded `/A/B/C` exposes the
/// reference's `mark` property.
#[test]
fn grandchild_inherit_target_seeds_ancestors() -> Result<()> {
let text = r#"#usda 1.0
def "Lib" {
def "Ref" {
def "C" { custom string mark = "from-ref" }
}
}
def "A" (
inherits = </A/B/C>
)
{
def "B" (
references = </Lib/Ref>
)
{
}
}
"#;
let (graph, mut cache) = in_memory_stack(text);
// Compose /A first so its inherit-target precache runs before /A/B/C is
// queried; the precache must not leave a stale, parentless /A/B/C cached.
cache.ensure_index(&graph, &sdf::path("/A")?)?;
assert!(
cache
.prim_properties(&graph, &sdf::path("/A/B/C")?)?
.iter()
.any(|t| t.as_str() == "mark"),
"/A/B/C must inherit the reference's `mark` via /A/B even when reached through /A's precache"
);
Ok(())
}
/// A child reachable only through a chain of local-class inherits composes
/// its own inherited grandchildren: `SymArmRig` inherits `_Class_ArmRig`
/// (whose `ArmRegion` over inherits `Body/_class_Region`), so
/// `SymArmRig/ArmRegion` must expose `Region`.
#[test]
fn inherited_child_chain_composes() -> Result<()> {
let root = format!(
"{}/vendor/core-spec-supplemental-release_dec2025/composition/tests/assets/\
TrickyLocalClassHierarchyWithRelocates_root/usda/root.usd",
manifest_dir()
);
let (graph, mut cache) = collected_stack(&root);
let arm_region = sdf::path("/C_1/ArmsRig/SymArmRig/ArmRegion")?;
assert!(
cache
.prim_children(&graph, &arm_region)?
.iter()
.any(|t| t.as_str() == "Region"),
"deep local-class inherit chain must surface the inherited grandchild"
);
Ok(())
}
/// Child names fold weakest-to-strongest, reapplying each layer's
/// `primOrder` as it merges. `sub.usda` (weaker) authors `a b c` reordered
/// to `c b a`; `root.usda` (stronger) adds `d` and reorders `a d`. The fold
/// yields `[c, b, a, d]` — a strongest-`primOrder`-wins union would instead
/// give `[a, d, b, c]`.
#[test]
fn child_names_fold_weak_to_strong() -> Result<()> {
let root = format!("{}/fixtures/child_order_fold/root.usda", manifest_dir());
let (graph, mut cache) = collected_stack(&root);
let children = cache.prim_children(&graph, &sdf::path("/P")?)?;
assert_eq!(
children.iter().map(|t| t.as_str()).collect::<Vec<_>>(),
["c", "b", "a", "d"]
);
Ok(())
}
/// A relocated prim's index carries relocate nodes (tagged
/// `RELOCATE_SOURCE`) whose grafted source subtree forms a consistent
/// tree: every stored parent link is mirrored by the parent's child list.
#[test]
fn relocate_nodes_form_subtree() -> Result<()> {
use super::super::prim_graph::NodeFlags;
let root = format!(
"{}/vendor/core-spec-supplemental-release_dec2025/composition/tests/assets/\
BasicRelocateToAnimInterface_root/usda/root.usd",
manifest_dir()
);
let (graph, mut cache) = collected_stack(&root);
let path = sdf::path("/Model/Anim/Path")?;
cache.ensure_index(&graph, &path)?;
let index = cache.cached(&path);
// The relocate source node is composed inert (salted earth, C++
// `rootNodeShouldContributeSpecs == false`): its own site contributes
// nothing — its ancestral children carry the relocated opinions — so it
// is retained in the arena but skipped by `nodes`/`all_nodes`.
assert!(
index
.arena()
.iter()
.any(|n| n.flags().contains(NodeFlags::RELOCATE_SOURCE)),
"relocated prim has a relocate source node"
);
for (id, node) in index.nodes_with_ids() {
if let Some(parent) = node.parent() {
assert!(
index.children(parent).contains(&id),
"relocate node {id:?} parent {parent:?} missing it as a child"
);
}
}
Ok(())
}
/// A relocate source spanning several sublayers keeps every member in the
/// per-site relocate node — the weaker sublayer opinion must not be lost.
/// `/World/Src` (authored in both `root.usda` and `sub.usda`) relocates to
/// `/World/Dst`, whose relocate node must carry both layers.
#[test]
fn relocate_source_spans_sublayers() -> Result<()> {
use super::super::prim_graph::NodeFlags;
let root = format!("{}/fixtures/relocate_multilayer/root.usda", manifest_dir());
let (graph, mut cache) = collected_stack(&root);
let path = sdf::path("/World/Dst")?;
cache.ensure_index(&graph, &path)?;
let index = cache.cached(&path);
// The relocate source node is composed inert (salted earth), so it is
// retained in the arena but skipped by `nodes`/`all_nodes`.
let relocate = index
.arena()
.iter()
.find(|n| n.flags().contains(NodeFlags::RELOCATE_SOURCE))
.expect("relocated prim has a relocate source node");
let layers: Vec<LayerId> = graph
.layer_stack(relocate.layer_stack_id())
.iter()
.map(|&(li, _)| li)
.collect();
let expected: Vec<LayerId> = graph.root_layer_stack().iter().map(|&(id, _)| id).collect();
assert_eq!(
layers, expected,
"relocate node folds both authoring sublayers, strongest first"
);
Ok(())
}
/// A cross-hierarchy relocation source is registered as a dependency of the
/// relocated prim even though its node is inert. `/Source/Inner` relocates to
/// `/Dest/Moved`; the source's ancestors (`/Source`) are not ancestors of the
/// target, so only the source-site registration lets an edit at `/Source/Inner`
/// invalidate `/Dest/Moved`.
#[test]
fn relocate_source_registers_dependency() -> Result<()> {
let root = format!("{}/fixtures/relocate_cross_hierarchy/root.usda", manifest_dir());
let (graph, mut cache) = collected_stack(&root);
let dst = sdf::path("/Dest/Moved")?;
cache.ensure_index(&graph, &dst)?;
let src = sdf::path("/Source/Inner")?;
assert!(
cache
.dependencies()
.lookup_with_ancestors(graph.root_id().unwrap(), &src)
.contains(&dst),
"an edit at relocation source /Source/Inner must invalidate /Dest/Moved"
);
Ok(())
}
/// A recoverable composition error on an ancestor must not erase a
/// descendant's own opinions. `/A` references a missing layer — an error the
/// cache records and continues past — yet `/A/B`'s local opinion still
/// composes, rather than the child caching an empty index.
#[test]
fn ancestor_error_keeps_child_opinions() -> Result<()> {
let text = r#"#usda 1.0
def "A" (
references = @nonexistent.usd@
)
{
def "B"
{
custom string marker = "ok"
}
}
"#;
let data = crate::usda::parser::Parser::new(text).parse().expect("parse usda");
let layer = sdf::Layer::new("root.usda", Box::new(sdf::Data::from_specs(data)));
let graph = LayerGraph::from_layers(vec![layer], 0, sdf::LayerRegistry::default());
let mut cache = IndexCache::new(VariantFallbackMap::new(), LoadRules::all(), Vec::new());
let child = sdf::path("/A/B")?;
cache.ensure_index(&graph, &child)?;
assert!(
!cache.cached(&child).is_empty(),
"child local opinion must survive the ancestor's unresolved reference"
);
assert!(
cache
.take_composition_errors()
.iter()
.any(|e| matches!(e, Error::UnresolvedLayer { .. })),
"the ancestor's unresolved reference is recorded"
);
Ok(())
}
/// A prim's recoverable build error is keyed by its path and replaced on
/// rebuild, so dropping and recomposing the index (as a layer-stack edit
/// does via a scoped drop + re-query) does not duplicate it, and a prim that
/// composes cleanly leaves no stale error behind.
#[test]
fn prim_errors_replace_on_rebuild() -> Result<()> {
let (graph, mut cache) =
in_memory_stack("#usda 1.0\ndef \"A\" (\n references = @nonexistent.usd@\n)\n{\n}\n");
let a = sdf::path("/A")?;
let unresolved = |c: &IndexCache| {
c.composition_errors()
.iter()
.filter(|e| matches!(e, Error::UnresolvedLayer { .. }))
.count()
};
cache.ensure_index(&graph, &a)?;
assert_eq!(unresolved(&cache), 1, "the unresolved reference is recorded once");
// Drop and rebuild — the bookkeeping a SIGNIFICANT layer-stack edit
// performs (a scoped drop then a re-query). The error must not double.
cache.drop_index(&a);
cache.ensure_index(&graph, &a)?;
assert_eq!(
unresolved(&cache),
1,
"rebuilding replaces the prim's error, not appends"
);
// A prim with no error leaves no entry, so its (absent) errors can't go stale.
let (clean_graph, mut clean_cache) = in_memory_stack("#usda 1.0\ndef \"A\" {}\n");
clean_cache.ensure_index(&clean_graph, &a)?;
assert!(
clean_cache.composition_errors().is_empty(),
"a cleanly composing prim records no error"
);
Ok(())
}
/// A reference whose asset path is a variable expression that fails to
/// evaluate (here a non-string result) is recoverable: the broken arc is
/// skipped and recorded as `InvalidExpression`, while the prim's own local
/// opinion still composes — it does not abort the whole prim index.
#[test]
fn invalid_expression_arc_recoverable() -> Result<()> {
let text = r#"#usda 1.0
def "A" (
references = @`42`@
)
{
custom string marker = "ok"
}
"#;
let data = crate::usda::parser::Parser::new(text).parse().expect("parse usda");
let layer = sdf::Layer::new("root.usda", Box::new(sdf::Data::from_specs(data)));
let graph = LayerGraph::from_layers(vec![layer], 0, sdf::LayerRegistry::default());
let mut cache = IndexCache::new(VariantFallbackMap::new(), LoadRules::all(), Vec::new());
let a = sdf::path("/A")?;
cache.ensure_index(&graph, &a)?;
let interp = |_: &sdf::TimeSampleMap, _: f64| None;
assert_eq!(
cache.value_at(&graph, &sdf::path("/A.marker")?, 0.0, &interp)?,
Some(Value::String("ok".to_string())),
"the prim's local opinion survives the broken expression arc"
);
assert!(
cache
.take_composition_errors()
.iter()
.any(|e| matches!(e, Error::InvalidExpression { .. })),
"the invalid asset-path expression is recorded as a recoverable error"
);
Ok(())
}
/// A variant selection whose expression does not evaluate to a string
/// records `InvalidExpression` with the variant context and falls through,
/// so the prim itself still composes.
#[test]
fn variant_expr_error_reported() -> Result<()> {
let text = r#"#usda 1.0
def "A" (
variantSets = "v"
variants = { string v = "`42`" }
)
{
custom string marker = "ok"
variantSet "v" = {
"hi" { custom double y = 1 }
}
}
"#;
let (mut graph, mut cache) = in_memory_stack(text);
assert_eq!(
settled_value_at(&mut graph, &mut cache, &sdf::path("/A.marker")?, 0.0)?,
Some(Value::String("ok".to_string())),
"the prim's local opinion survives the failed selection expression"
);
assert!(
cache.take_composition_errors().iter().any(|e| matches!(
e,
Error::InvalidExpression {
context: ExpressionContext::Variant,
..
}
)),
"the failed selection is recorded with the variant context"
);
Ok(())
}
/// A selection expression authored on the referencing prim evaluates
/// against the referencing stack's variables and selects inside the
/// referenced target (spec 12.2 — the stronger site's opinion wins).
#[test]
fn variant_seed_across_reference() -> Result<()> {
let root_text = r#"#usda 1.0
(
expressionVariables = {
string SEL = "hi"
}
)
def "Model" (
references = @t.usd@</T>
variants = { string v = "`${SEL}`" }
)
{
}
"#;
let target_text = r#"#usda 1.0
def "T" (
variantSets = "v"
)
{
variantSet "v" = {
"hi" { custom double x = 1 }
"lo" { custom double x = 2 }
}
}
"#;
let mut graph = LayerGraph::from_layers(
vec![
parse_named_layer("root.usd", root_text),
parse_named_layer("t.usd", target_text),
],
0,
sdf::LayerRegistry::default(),
);
let mut cache = IndexCache::new(VariantFallbackMap::new(), LoadRules::all(), Vec::new());
assert_eq!(
settled_value_at(&mut graph, &mut cache, &sdf::path("/Model.x")?, 0.0)?,
Some(Value::Double(1.0)),
"the referencing site's evaluated selection picks {{v=hi}} in the target"
);
Ok(())
}
/// A connection authored in a class that targets another instance of the
/// class but is removed by a stronger `delete` must not emit a spurious
/// instance-target diagnostic: `classify_inherit_targets` only reports targets
/// that survive list-op composition, so a deleted target is neither dropped
/// again nor reported.
#[test]
fn class_instance_target_deleted_no_error() -> Result<()> {
let text = r#"#usda 1.0
def "Scope"
{
class "LocalClass"
{
double y
double x
add double x.connect = </Scope/Instance_2.y>
delete double x.connect = </Scope/Instance_2.y>
}
def "Instance_1" (inherits = </Scope/LocalClass>) {}
def "Instance_2" (inherits = </Scope/LocalClass>) {}
}
"#;
let (graph, mut cache) = in_memory_stack(text);
let (targets, _) = cache.compute_attribute_connection_paths(&graph, &sdf::path("/Scope/Instance_1.x")?)?;
assert!(targets.is_empty(), "the deleted connection target composes to nothing");
let errors = cache.take_composition_errors();
assert!(
!errors.iter().any(|e| matches!(
e,
Error::InvalidInstanceTargetPath { .. } | Error::InvalidExternalTargetPath { .. }
)),
"a class target removed by a stronger delete must not be reported: {errors:?}"
);
Ok(())
}
/// An instance-target invalid contribution from a class node drops only that
/// node's contribution: a stronger local opinion authoring the same target
/// validly keeps it, while the class's invalid opinion is still reported.
#[test]
fn class_instance_target_kept_by_stronger_local() -> Result<()> {
let text = r#"#usda 1.0
def "Scope"
{
class "LocalClass"
{
double y
double x
add double x.connect = </Scope/Instance_2.y>
}
def "Instance_1" (inherits = </Scope/LocalClass>)
{
add double x.connect = </Scope/Instance_2.y>
}
def "Instance_2" (inherits = </Scope/LocalClass>) {}
}
"#;
let (graph, mut cache) = in_memory_stack(text);
let (targets, _) = cache.compute_attribute_connection_paths(&graph, &sdf::path("/Scope/Instance_1.x")?)?;
assert_eq!(
targets,
vec![sdf::path("/Scope/Instance_2.y")?],
"the stronger local connection keeps the target even though the class's is invalid"
);
let errors = cache.take_composition_errors();
assert!(
errors
.iter()
.any(|e| matches!(e, Error::InvalidInstanceTargetPath { .. })),
"the class node's instance-target contribution is still reported: {errors:?}"
);
Ok(())
}
/// A reference's asset-path expression authored inside a referenced layer
/// is evaluated against the composed expression variables, with the
/// referencing layer stack overriding the referenced one (C++
/// `PcpExpressionVariables`). The root sets `TARGET = "right.usda"`,
/// overriding mid.usda's local `TARGET = "wrong.usda"`, so `/Model` resolves
/// through mid to right.usda — collection must load right.usda for the arc
/// to compose rather than the locally-named wrong.usda.
#[test]
fn expr_vars_compose_across_reference() -> Result<()> {
let root = format!("{}/fixtures/expr_vars_compose/root.usda", manifest_dir());
let (mut graph, mut cache) = collected_stack(&root);
assert_eq!(
settled_value_at(&mut graph, &mut cache, &sdf::path("/Model.source")?, 0.0)?,
Some(Value::String("right".to_string())),
"the referencing layer's TARGET override resolves the nested reference to right.usda"
);
Ok(())
}
/// The sub-root twin of `expr_vars_compose_across_reference`: `/Model`
/// references a sub-root target `/Sub/Prim`, so composing it spawns a
/// nested ancestral sub-index (`Indexer::compose_and_graft`) for `/Sub`
/// and `/Sub/Prim`. `/Sub`'s own reference expression must still resolve
/// against the outer (root) layer's `TARGET`, not mid.usda's own local
/// value, even though it composes inside that disjoint nested build.
#[test]
fn expr_vars_subroot_reference() -> Result<()> {
let root = format!("{}/fixtures/expr_vars_compose_subroot/root.usda", manifest_dir());
let (mut graph, mut cache) = collected_stack(&root);
assert_eq!(
settled_value_at(&mut graph, &mut cache, &sdf::path("/Model.source")?, 0.0)?,
Some(Value::String("right".to_string())),
"the outer layer's TARGET override resolves Sub's ancestral reference to right.usda \
even though it composes inside the sub-root target's nested sub-build"
);
Ok(())
}
/// Editing a layer stack's `expressionVariables` re-resolves a `${VAR}`
/// reference asset path and recomposes the cached index: with `PICK = "a"`
/// the reference draws a.usda's opinion, and editing it to "b" yields
/// b.usda's — the under-invalidation (stale-read) guard.
#[test]
fn expr_var_edit_recomposes_reference() -> Result<()> {
let root = parse_named_layer(
"root.usda",
"#usda 1.0\n(\n expressionVariables = {\n string PICK = \"a\"\n }\n)\n\
def \"R\" (\n references = @`\"${PICK}.usda\"`@</X>\n) {}\n",
);
let a = parse_named_layer("a.usda", "#usda 1.0\ndef \"X\" { custom double y = 1 }\n");
let b = parse_named_layer("b.usda", "#usda 1.0\ndef \"X\" { custom double y = 2 }\n");
let mut graph = LayerGraph::from_layers(vec![root, a, b], 0, sdf::LayerRegistry::default());
let mut cache = IndexCache::new(VariantFallbackMap::new(), LoadRules::all(), Vec::new());
let root_id = graph.root_id().unwrap();
let y = sdf::path("/R.y")?;
assert_eq!(
settled_value_at(&mut graph, &mut cache, &y, 0.0)?,
Some(Value::Double(1.0)),
"the PICK-valued reference resolves to a.usda"
);
let cl = edit_layer(&mut graph.get_mut(root_id).unwrap().layer, |e| {
e.set_expression_variables(HashMap::from([("PICK".to_string(), Value::String("b".into()))]))
})?;
let mut changes = crate::pcp::Changes::new();
changes.did_change(&cache, &[(root_id, &cl)]);
changes.apply(&mut cache, &mut graph);
assert_eq!(
settled_value_at(&mut graph, &mut cache, &y, 0.0)?,
Some(Value::Double(2.0)),
"editing PICK re-resolves the reference to b.usda and recomposes the cached index"
);
Ok(())
}
/// An expression-valued asset with no variables in scope (no composed index
/// or no authoring site for the field) stays unevaluated — like a malformed
/// expression — rather than aborting.
#[test]
fn expr_asset_without_vars() {
let (graph, _) = in_memory_stack("#usda 1.0\n");
let resolved = IndexCache::resolve_asset_path(&graph, sdf::AssetPath::new("`${A}`"), None, None);
assert_eq!(resolved.as_str(), "`${A}`", "the authored expression is kept");
assert!(resolved.evaluated_path().is_none(), "no evaluated path is derived");
}
/// An asset attribute's `${VAR}` inside a referenced target resolves against
/// the variable authored on the referencing root. The target has no
/// expression sublayers, so only the contextual instance the arc minted
/// carries the variable to value-resolution time.
#[test]
fn expr_asset_inherited_context() -> Result<()> {
let root = parse_named_layer(
"root.usda",
"#usda 1.0\n(\n expressionVariables = {\n string A = \"tex.png\"\n }\n)\ndef \"M\" (\n references = @base.usda@</B>\n) {}\n",
);
let base = parse_named_layer(
"base.usda",
"#usda 1.0\ndef \"B\" {\n custom asset tex = @`${A}`@\n}\n",
);
let mut graph = LayerGraph::from_layers(vec![root, base], 0, sdf::LayerRegistry::default());
let mut cache = IndexCache::new(VariantFallbackMap::new(), LoadRules::all(), Vec::new());
let value = settled_value_at(&mut graph, &mut cache, &sdf::path("/M.tex")?, 0.0)?.expect("tex resolves");
let asset = value.try_as_asset_path().expect("attribute is asset-typed");
assert_eq!(
asset.evaluated_path(),
Some("tex.png"),
"the referencing root's A evaluates the target's asset expression"
);
Ok(())
}
/// An `expressionVariables` edit on a referenced layer drops only the indices
/// that read it: the referencing prim's index is evicted, while a sibling
/// composed solely from the root keeps its cached index — the
/// over-invalidation (dropped-sibling) guard.
#[test]
fn expr_var_edit_scoped_drop() -> Result<()> {
let root = parse_named_layer(
"root.usda",
"#usda 1.0\ndef \"Local\" {}\ndef \"Ref\" (\n references = @base.usda@</Base>\n) {}\n",
);
let base = parse_named_layer("base.usda", "#usda 1.0\ndef \"Base\" {}\n");
let mut graph = LayerGraph::from_layers(vec![root, base], 0, sdf::LayerRegistry::default());
let mut cache = IndexCache::new(VariantFallbackMap::new(), LoadRules::all(), Vec::new());
let base_id = graph.id_of("base.usda").unwrap();
let local = sdf::path("/Local")?;
let refp = sdf::path("/Ref")?;
cache.ensure_index(&graph, &local)?;
cache.ensure_index(&graph, &refp)?;
assert!(cache.store.index_at(&local).is_some());
assert!(cache.store.index_at(&refp).is_some());
let cl = edit_layer(&mut graph.get_mut(base_id).unwrap().layer, |e| {
e.set_expression_variables(HashMap::from([("V".to_string(), Value::String("x".into()))]))
})?;
let mut changes = crate::pcp::Changes::new();
changes.did_change(&cache, &[(base_id, &cl)]);
changes.apply(&mut cache, &mut graph);
assert!(
cache.store.index_at(&local).is_some(),
"the root-only sibling does not read base.usda, so its index stays warm"
);
assert!(
cache.store.index_at(&refp).is_none(),
"the referencing prim reads base.usda, so the expr-var edit drops its index"
);
Ok(())
}
/// A `targetPaths` edit clears only the edited relationship's memo; a sibling
/// relationship on the same prim keeps its cached resolved-target list — the
/// suffix-precise target-memo clear.
#[test]
fn target_edit_clears_one_memo() -> Result<()> {
let (mut graph, mut cache) = in_memory_stack(
"#usda 1.0\ndef \"P\" {\n rel relA = [</X>]\n rel relB = [</Y>]\n}\ndef \"X\" {}\ndef \"Y\" {}\n",
);
let root_id = graph.root_id().unwrap();
let p_prim = sdf::path("/P")?;
let key = |suffix: &str| TargetMemoKey {
kind: PropertyTargetKind::Relationship,
property_suffix: suffix.to_owned(),
};
// The first query of each relationship populates its memo on /P's entry.
cache.relationship_targets(&graph, &sdf::path("/P.relA")?)?;
cache.relationship_targets(&graph, &sdf::path("/P.relB")?)?;
assert!(cache.store.target_memo(&p_prim, &key(".relA")).is_some());
assert!(cache.store.target_memo(&p_prim, &key(".relB")).is_some());
let cl = edit_layer(&mut graph.get_mut(root_id).unwrap().layer, |e| {
e.relationship_mut("/P.relA")
.expect("relationship spec")
.set_target_paths([sdf::path("/Z").unwrap()]);
Ok(())
})?;
let mut changes = crate::pcp::Changes::new();
changes.did_change(&cache, &[(root_id, &cl)]);
changes.apply(&mut cache, &mut graph);
assert!(
cache.store.target_memo(&p_prim, &key(".relA")).is_none(),
"the edited relationship's memo is cleared"
);
assert!(
cache.store.target_memo(&p_prim, &key(".relB")).is_some(),
"the sibling relationship's memo survives the suffix-precise clear"
);
Ok(())
}
/// A template clip set (`templateAssetPath` + start/end/stride) is
/// expanded to explicit clips and resolves end to end through
/// `value_at` (spec 12.3.4.1.3): `clip.1.usda` drives t=1, `clip.2.usda`
/// drives t=2.
#[test]
fn resolves_template_clip_values() -> Result<()> {
let root = format!("{}/fixtures/clip_template/root.usda", manifest_dir());
let (graph, mut cache) = single_layer_stack(&root);
// Exact-match sampler: each clip authors a single sample at its frame.
let interp =
|samples: &sdf::TimeSampleMap, t: f64| samples.iter().find(|(time, _)| *time == t).map(|(_, v)| v.clone());
let size =
|cache: &mut IndexCache, t: f64| cache.value_at(&graph, &sdf::path("/Model.size").unwrap(), t, &interp);
assert_eq!(size(&mut cache, 1.0)?, Some(sdf::Value::Double(10.0)));
assert_eq!(size(&mut cache, 2.0)?, Some(sdf::Value::Double(20.0)));
Ok(())
}
/// A template clip set authored in a sublayer with a layer offset has its
/// derived schedule retimed into stage time (spec 12.3.4): the offset of 10
/// shifts `clip.1`'s frame to stage t=11 and `clip.2`'s to t=12.
#[test]
fn template_clip_schedule_retimed_by_offset() -> Result<()> {
let root = format!("{}/fixtures/clip_template_offset/root.usda", manifest_dir());
let (graph, mut cache) = collected_stack(&root);
let size =
|cache: &mut IndexCache, t: f64| cache.value_at(&graph, &sdf::path("/Model.size").unwrap(), t, &exact);
assert_eq!(size(&mut cache, 11.0)?, Some(Value::Double(10.0)));
assert_eq!(size(&mut cache, 12.0)?, Some(Value::Double(20.0)));
Ok(())
}
/// When a stronger layer authors explicit `assetPaths` and a weaker
/// sublayer authors `templateAssetPath` for the same set, the explicit
/// paths win (spec 12.3.4.1.3) and must anchor on the layer that authored
/// them: `@./clip.usda@` resolves next to the root, not the sublayer.
#[test]
fn explicit_asset_paths_anchor_over_template() -> Result<()> {
let root = format!("{}/fixtures/clip_asset_anchor/root.usda", manifest_dir());
let (graph, mut cache) = collected_stack(&root);
let size =
|cache: &mut IndexCache, t: f64| cache.value_at(&graph, &sdf::path("/Model.size").unwrap(), t, &exact);
assert_eq!(size(&mut cache, 0.0)?, Some(Value::Double(42.0)));
Ok(())
}
/// Exact-match sampler: a clip resolves only at a frame it authors.
fn exact(samples: &sdf::TimeSampleMap, t: f64) -> Option<Value> {
samples.iter().find(|(time, _)| *time == t).map(|(_, v)| v.clone())
}
/// Linear sampler over `float` samples, held outside the sample range.
fn lerp(samples: &sdf::TimeSampleMap, t: f64) -> Option<Value> {
let as_f = |v: &Value| match v {
Value::Float(f) => *f as f64,
Value::Double(d) => *d,
_ => 0.0,
};
let first = samples.first()?;
if t <= first.0 {
return Some(first.1.clone());
}
let last = samples.last()?;
if t >= last.0 {
return Some(last.1.clone());
}
let w = samples.windows(2).find(|w| t >= w[0].0 && t <= w[1].0)?;
let f = (t - w[0].0) / (w[1].0 - w[0].0);
Some(Value::Double(as_f(&w[0].1) + (as_f(&w[1].1) - as_f(&w[0].1)) * f))
}
/// A gap in the active clip falls to the manifest's authored default
/// (spec 12.3.4.6): `t=0` is sampled from the clip, `t=10` (no sample)
/// resolves to the manifest default `99.0`.
#[test]
fn missing_clip_value_uses_manifest_default() -> Result<()> {
let root = format!("{}/fixtures/clip_missing_default/root.usda", manifest_dir());
let (graph, mut cache) = single_layer_stack(&root);
let size =
|cache: &mut IndexCache, t: f64| cache.value_at(&graph, &sdf::path("/Model.size").unwrap(), t, &exact);
assert_eq!(size(&mut cache, 0.0)?, Some(Value::Double(5.0)));
assert_eq!(size(&mut cache, 10.0)?, Some(Value::Float(99.0)));
Ok(())
}
/// A manifest-declared attribute with no default and a gap is
/// authoritatively absent (spec 12.3.4.6): the clip owns the attribute, so
/// the gap blocks fall-through to the referenced time samples (`777.0`) and
/// resolves to `None` rather than the weaker value.
#[test]
fn missing_clip_value_without_default_blocks() -> Result<()> {
let root = format!("{}/fixtures/clip_missing_block/root.usda", manifest_dir());
let (graph, mut cache) = collected_stack(&root);
let size =
|cache: &mut IndexCache, t: f64| cache.value_at(&graph, &sdf::path("/Model.size").unwrap(), t, &exact);
assert_eq!(size(&mut cache, 0.0)?, Some(Value::Double(5.0)));
assert_eq!(size(&mut cache, 10.0)?, None);
Ok(())
}
/// `resolve_value_source` gates clips precisely: on a clip-bearing prim, an
/// attribute the manifest declares (`size`) resolves as
/// [`AttributeValueSource::Clips`], while a sibling the manifest does not
/// declare (`extra`) falls through to its referenced `timeSamples` rather
/// than being routed conservatively through the per-call clip path.
#[test]
fn value_source_skips_undeclared_clip_attr() -> Result<()> {
let root = format!("{}/fixtures/clip_undeclared_arc/root.usda", manifest_dir());
let (graph, mut cache) = collected_stack(&root);
assert!(matches!(
cache.resolve_value_source(&graph, &sdf::path("/Model.size")?)?,
AttributeValueSource::Clips
));
// `extra` is not in the manifest, so the clip set does not own it; the
// source is the reference's time samples, queryable on the fast path.
let AttributeValueSource::TimeSamples { samples, .. } =
cache.resolve_value_source(&graph, &sdf::path("/Model.extra")?)?
else {
panic!("undeclared clip attribute must resolve as arc time samples");
};
assert_eq!(samples.as_slice(), &[(3.0, Value::Double(42.0))]);
Ok(())
}
/// A manifest-less clip holds its value across its active interval, so it
/// owns the attribute even at times where it authors no sample inside that
/// interval. `resolve_value_source` must agree with `value_at` here: clip0
/// (active over stage `[0, 10)`) authors only at clip-time 50, yet holds
/// `50.0` at stage 5, so the source is `Clips` (deferring to `value_at`) and
/// must not collapse to the reference's weaker `999.0` time sample — the
/// divergence a discrete sample-time gate would cache.
#[test]
fn value_source_clips_held_manifestless() -> Result<()> {
let root = format!("{}/fixtures/clip_manifestless_held/root.usda", manifest_dir());
let (graph, mut cache) = collected_stack(&root);
assert_eq!(
cache.value_at(&graph, &sdf::path("/Model.size")?, 5.0, &lerp)?,
Some(Value::Double(50.0))
);
assert!(matches!(
cache.resolve_value_source(&graph, &sdf::path("/Model.size")?)?,
AttributeValueSource::Clips
));
Ok(())
}
/// `clip_sample_times` reports every active-window boundary of a
/// participating set and `None` when no set sources the attribute. The
/// manifest-less held set contributes only clip1's boundary at 10 (clip0's
/// sole sample maps to stage 50, outside its `[0, 10)` window). A
/// manifest that omits an attribute does not source it: `extra` returns
/// `None`, falling through to the arc.
#[test]
fn clip_sample_times_boundaries() -> Result<()> {
let held = format!("{}/fixtures/clip_manifestless_held/root.usda", manifest_dir());
let (graph, mut cache) = collected_stack(&held);
assert_eq!(
cache.clip_sample_times(&graph, &sdf::path("/Model")?, ".size")?,
Some(vec![10.0])
);
let arc = format!("{}/fixtures/clip_undeclared_arc/root.usda", manifest_dir());
let (graph, mut cache) = collected_stack(&arc);
assert!(cache
.clip_sample_times(&graph, &sdf::path("/Model")?, ".extra")?
.is_none());
Ok(())
}
/// With `interpolateMissingClipValues`, a gap is filled by interpolating
/// across the surrounding contributing clips (spec 12.3.4.7): the empty
/// middle clip at `t=15` interpolates `0.0` (t=0 clip) and `100.0`
/// (t=20 clip) to `75.0`.
#[test]
fn interpolate_missing_clip_values_across_clips() -> Result<()> {
let root = format!("{}/fixtures/clip_missing_interp/root.usda", manifest_dir());
let (graph, mut cache) = single_layer_stack(&root);
let size =
|cache: &mut IndexCache, t: f64| cache.value_at(&graph, &sdf::path("/Model.size").unwrap(), t, &lerp);
assert_eq!(size(&mut cache, 0.0)?, Some(Value::Double(0.0)));
assert_eq!(size(&mut cache, 15.0)?, Some(Value::Double(75.0)));
assert_eq!(size(&mut cache, 20.0)?, Some(Value::Double(100.0)));
Ok(())
}
/// Instances sharing a prototype compose their subtree once: every
/// instance's descendants redirect into the shared prototype namespace, so
/// the descendant is indexed under `/__Prototype_N` and never under an
/// instance's own path (spec 11.3.3).
#[test]
fn instances_share_prototype() -> Result<()> {
let root = format!("{}/fixtures/instancing_shared.usda", manifest_dir());
let (graph, mut cache) = single_layer_stack(&root);
let interp = |_: &sdf::TimeSampleMap, _: f64| None;
// Query /A first so it mints /__Prototype_0 for its key.
let size = |cache: &mut IndexCache, p: &str| cache.value_at(&graph, &sdf::path(p).unwrap(), 0.0, &interp);
assert_eq!(size(&mut cache, "/A/Child.size")?, Some(sdf::Value::Double(5.0)));
assert_eq!(size(&mut cache, "/B/Child.size")?, Some(sdf::Value::Double(5.0)));
assert_eq!(size(&mut cache, "/C/Child.size")?, Some(sdf::Value::Double(9.0)));
// /A and /B share /__Prototype_0; /C uses /__Prototype_1. The shared
// subtree composes once in each prototype namespace, and no instance's
// own descendant path is ever indexed.
assert!(cache.is_indexed(&sdf::path("/__Prototype_0/Child")?));
assert!(cache.is_indexed(&sdf::path("/__Prototype_1/Child")?));
assert!(!cache.is_indexed(&sdf::path("/A/Child")?));
assert!(!cache.is_indexed(&sdf::path("/B/Child")?));
assert!(!cache.is_indexed(&sdf::path("/C/Child")?));
Ok(())
}
/// Reading a deep instance-proxy value composes the shared prototype subtree
/// once: the instance-ness check on an intermediate proxy prim redirects to
/// the shared `/__Prototype_N` index instead of composing a throwaway literal
/// index per instance, so no intermediate proxy path is ever indexed (spec
/// 11.3.3).
#[test]
fn proxy_descendants_share_prototype() -> Result<()> {
let root = format!("{}/fixtures/instancing_deep.usda", manifest_dir());
let (graph, mut cache) = single_layer_stack(&root);
let interp = |_: &sdf::TimeSampleMap, _: f64| None;
let v = |cache: &mut IndexCache, p: &str| cache.value_at(&graph, &sdf::path(p).unwrap(), 0.0, &interp);
// Reading the deep value walks the proxy ancestors (/A/Mid, /B/Mid),
// testing each for instance-ness.
assert_eq!(v(&mut cache, "/A/Mid/Leaf.v")?, Some(sdf::Value::Double(1.0)));
assert_eq!(v(&mut cache, "/B/Mid/Leaf.v")?, Some(sdf::Value::Double(1.0)));
// The shared subtree composes once, under the prototype namespace.
assert!(cache.is_indexed(&sdf::path("/__Prototype_0/Mid")?));
assert!(cache.is_indexed(&sdf::path("/__Prototype_0/Mid/Leaf")?));
// No intermediate proxy prim is composed literally at an instance path.
for p in ["/A/Mid", "/B/Mid", "/A/Mid/Leaf", "/B/Mid/Leaf"] {
assert!(!cache.is_indexed(&sdf::path(p)?), "{p} must not be indexed literally");
}
Ok(())
}
/// A nested instance inside a prototype namespace mints its own prototype and
/// its descendants redirect onto it: both an outer proxy (`/A/Nested/Leaf`)
/// and the prototype-namespace path (`/__Prototype_0/Nested/Leaf`) resolve
/// through the nested prototype, so the nested descendant never composes in
/// place under the outer prototype (spec 11.3.3).
#[test]
fn nested_prototype_proxy_redirects() -> Result<()> {
let root = format!("{}/fixtures/instancing_nested_in_prototype.usda", manifest_dir());
let (graph, mut cache) = single_layer_stack(&root);
let interp = |_: &sdf::TimeSampleMap, _: f64| None;
let v = |cache: &mut IndexCache, p: &str| cache.value_at(&graph, &sdf::path(p).unwrap(), 0.0, &interp);
// /A mints /__Prototype_0 (for /Outer); the nested instance mints
// /__Prototype_1 (for /Inner). Both the outer proxy and the
// prototype-namespace path resolve the nested leaf.
assert_eq!(v(&mut cache, "/A/Nested/Leaf.v")?, Some(sdf::Value::Double(3.0)));
assert_eq!(
v(&mut cache, "/__Prototype_0/Nested/Leaf.v")?,
Some(sdf::Value::Double(3.0))
);
// Both redirect to the nested prototype; neither the prototype-namespace
// nested descendant nor the outer proxy is composed in place.
assert!(cache.is_indexed(&sdf::path("/__Prototype_1/Leaf")?));
assert!(!cache.is_indexed(&sdf::path("/__Prototype_0/Nested/Leaf")?));
assert!(!cache.is_indexed(&sdf::path("/A/Nested/Leaf")?));
// The nested instance reached via the instance namespace (/A/Nested) and
// via the prototype namespace (/__Prototype_0/Nested) is the same shared
// composition, so both resolve to one nested prototype — exactly two
// prototypes total, not three.
assert_eq!(
cache.prototype_of(&graph, &sdf::path("/A/Nested")?)?,
cache.prototype_of(&graph, &sdf::path("/__Prototype_0/Nested")?)?,
);
assert_eq!(cache.prototypes().len(), 2);
Ok(())
}
/// A reference nested inside the prototype (below the instanceable arc) is
/// shared (spec 11.3.3): its opinions reach the instance through the direct
/// instanceable arc, so they survive in the instance's child names and
/// descendants. The structural trunk partition keeps it shared on two counts:
/// the arc is authored on the prim it targets rather than above the instance,
/// and its parent (the prototype root) is not on the instance trunk.
#[test]
fn nested_reference_in_prototype_shared() -> Result<()> {
let root = format!("{}/fixtures/instancing_nested_reference.usda", manifest_dir());
let (graph, mut cache) = single_layer_stack(&root);
let inst = sdf::path("/World/Inst")?;
// The instance is at namespace depth 2 and is a real instance.
assert!(cache.is_instance(&graph, &inst)?, "/World/Inst resolves as an instance");
// Child names come from the shared prototype: ProtoChild from /Proto and
// OtherChild from the nested /Other reference (the leaked case the flat
// depth proxy dropped).
let children = cache.prim_children(&graph, &inst)?;
assert!(
children.iter().any(|t| t.as_str() == "ProtoChild"),
"prototype child must appear: {children:?}"
);
assert!(
children.iter().any(|t| t.as_str() == "OtherChild"),
"nested-reference child must appear: {children:?}"
);
// The nested reference's opinions resolve on the shared descendant.
let interp = |_: &sdf::TimeSampleMap, _: f64| None;
assert_eq!(
cache.value_at(&graph, &sdf::path("/World/Inst/OtherChild.size")?, 0.0, &interp)?,
Some(Value::Double(7.0)),
"nested-reference descendant value survives in the shared subtree"
);
assert_eq!(
cache.value_at(&graph, &sdf::path("/World/Inst.otherAttr")?, 0.0, &interp)?,
Some(Value::Double(5.0)),
"nested-reference attribute survives on the instance root"
);
Ok(())
}
/// An instanceable prim reached through a reference on a non-root prim
/// materializes the same prototype as one reached through a reference on a
/// root prim (spec 11.3.3): the depth of the prim carrying the outer
/// reference does not change what composes. The instanceable arc is authored
/// in the referenced namespace, so its namespace depth is shallower than the
/// nested instance's stage depth and must be told apart from the outer
/// reference by where its arc was introduced relative to the instance.
#[test]
fn ancestral_reference_prototype() -> Result<()> {
let root = format!("{}/fixtures/instancing_ancestral_reference.usda", manifest_dir());
let (graph, mut cache) = single_layer_stack(&root);
let interp = |_: &sdf::TimeSampleMap, _: f64| None;
// The instance one level below the root and the instance at the root are
// the same shared composition, so they share a single prototype.
let shallow = cache.prototype_of(&graph, &sdf::path("/Shallow/A")?)?;
let deep = cache.prototype_of(&graph, &sdf::path("/Deep/G/A")?)?;
assert_eq!(shallow, deep, "nesting the referencing prim must not change the key");
let proto = deep.expect("nested instance resolves a prototype");
assert_eq!(cache.prototypes(), vec![proto.clone()]);
// The prototype materializes: the instanceable arc stayed shared, so the
// referenced subtree is there rather than an empty root.
assert_eq!(cache.prim_children(&graph, &proto)?, vec![Token::from("ProtoChild")]);
assert_eq!(
cache.value_at(&graph, &sdf::path("/__Prototype_0.protoAttr")?, 0.0, &interp)?,
Some(Value::Double(3.0)),
);
// And the nested instance's own namespace serves that shared content.
assert_eq!(
cache.prim_children(&graph, &sdf::path("/Deep/G/A")?)?,
vec![Token::from("ProtoChild")]
);
assert_eq!(
cache.value_at(&graph, &sdf::path("/Deep/G/A/ProtoChild.size")?, 0.0, &interp)?,
Some(Value::Double(7.0)),
);
Ok(())
}
/// A prototype root whose shared content carries `instanceable = true` — the
/// opinion an asset authors on the prim its referencing layer targets — is
/// still not an instance (spec 11.3.3). The opinion describes the prims that
/// share the prototype, so the prototype keeps it as content but mints no
/// prototype of its own and composes its plain content in place.
#[test]
fn prototype_root_instanceable() -> Result<()> {
let root = format!(
"{}/fixtures/instancing_prototype_root_instanceable.usda",
manifest_dir()
);
let (graph, mut cache) = single_layer_stack(&root);
let interp = |_: &sdf::TimeSampleMap, _: f64| None;
let proto = cache
.prototype_of(&graph, &sdf::path("/World/Place")?)?
.expect("the referencing prim is an instance");
// The opinion resolves true on the prototype root, yet the root is not an
// instance and so mints nothing further.
assert_eq!(
cache
.cached(&proto)
.resolve_field(FieldKey::Instanceable.as_str(), &graph, None)?,
Some(Value::Bool(true)),
"the instanceable opinion is shared content of the prototype"
);
assert!(
!cache.is_instance(&graph, &proto)?,
"a prototype root is never an instance"
);
assert_eq!(cache.prototype_of(&graph, &proto)?, None);
assert_eq!(cache.prototypes(), vec![proto.clone()]);
// Its content composes in place rather than redirecting back through it.
assert_eq!(cache.prim_children(&graph, &proto)?, vec![Token::from("BodyChild")]);
assert_eq!(
cache.value_at(&graph, &sdf::path("/__Prototype_0.bodyAttr")?, 0.0, &interp)?,
Some(Value::Double(4.0)),
);
assert_eq!(
cache.value_at(&graph, &sdf::path("/World/Place.bodyAttr")?, 0.0, &interp)?,
Some(Value::Double(4.0)),
);
Ok(())
}
/// `instances_of` is sorted by path, so the result is independent of the
/// order instances were registered (spec 11.3.3).
#[test]
fn instances_of_sorted() -> Result<()> {
let root = format!("{}/fixtures/instancing_shared.usda", manifest_dir());
let (graph, mut cache) = single_layer_stack(&root);
// Register /B before /A so registration order is [/B, /A].
let proto = cache.prototype_of(&graph, &sdf::path("/B")?)?.unwrap();
assert_eq!(cache.prototype_of(&graph, &sdf::path("/A")?)?, Some(proto.clone()));
// The returned instances are still sorted by path.
assert_eq!(cache.instances_of(&proto), vec![sdf::path("/A")?, sdf::path("/B")?]);
Ok(())
}
/// A significant change (here, flipping `instanceable`) clears the
/// prototype registry so stale instance-to-prototype mappings do not
/// persist (spec 11.3.3).
#[test]
fn instance_change_invalidates_prototypes() -> Result<()> {
let root = format!("{}/fixtures/instancing_shared.usda", manifest_dir());
let (mut graph, mut cache) = single_layer_stack(&root);
let root_id = graph.root_id().unwrap();
assert!(cache.prototype_of(&graph, &sdf::path("/A")?)?.is_some());
assert!(!cache.prototypes().is_empty());
let mut cl = sdf::ChangeList::new();
cl.entry_mut(&sdf::path("/A")?)
.info_changed
.insert(sdf::FieldKey::Instanceable.as_str().into());
let mut changes = crate::pcp::Changes::new();
changes.did_change(&cache, &[(root_id, &cl)]);
changes.apply(&mut cache, &mut graph);
assert!(cache.prototypes().is_empty());
Ok(())
}
/// A plain inert `over` authored after a prim was queried as empty must
/// become visible: the spec-tier rescan refreshes the cached site's
/// `has_specs` in place (or drops a nodeless stale index), so the next
/// query sees the spec without a significant subtree rebuild.
#[test]
fn inert_add_recomposes() -> Result<()> {
let (mut graph, mut cache) = in_memory_stack("#usda 1.0\ndef \"A\" {}\n");
let root_id = graph.root_id().unwrap();
// Query a prim no layer authors: cached as an empty index.
assert!(!cache.has_spec(&graph, &sdf::path("/Foo")?)?);
// Author an inert `over "Foo"` into the root layer.
let node = graph.get_mut(root_id).unwrap();
edit_layer(&mut node.layer, |e| {
sdf::PrimSpec::new(e.data_mut(), "/Foo", sdf::Specifier::Over, "")?;
Ok(())
})?;
// Drive the inert add through the change pipeline.
let mut cl = sdf::ChangeList::new();
cl.entry_mut(&sdf::path("/Foo")?).flags = sdf::ChangeFlags::ADD_INERT_PRIM;
let mut changes = crate::pcp::Changes::new();
changes.did_change(&cache, &[(root_id, &cl)]);
changes.apply(&mut cache, &mut graph);
// The spec-tier rescan made the new opinion visible.
assert!(cache.has_spec(&graph, &sdf::path("/Foo")?)?);
Ok(())
}
/// An `over` authored together with a composition arc recomposes despite
/// the inert specifier: the change record surfaces `references` in
/// `info_changed` (only the auto-stamped `specifier` folds into the add), so
/// the classifier treats the inert add as significant.
#[test]
fn inert_add_with_arc_recomposes() -> Result<()> {
let (mut graph, mut cache) = in_memory_stack("#usda 1.0\ndef \"Class\" { int x = 5 }\n");
let root_id = graph.root_id().unwrap();
let inst = sdf::path("/Inst")?;
// Query /Inst before it exists: cached as empty, composing no arc.
assert!(!cache.has_composition_arc(&graph, &inst)?);
// Author `over "Inst" ( references = </Class> )` through the recording proxy.
let cl = edit_layer(&mut graph.get_mut(root_id).unwrap().layer, |l| {
let data = l.data_mut();
data.create_spec(inst.clone(), sdf::SpecType::Prim);
data.set_field(
&inst,
sdf::FieldKey::Specifier.as_str(),
Value::Specifier(sdf::Specifier::Over),
);
let refs = sdf::ReferenceListOp::explicit([sdf::Reference {
prim_path: sdf::path("/Class").unwrap(),
..Default::default()
}]);
data.set_field(&inst, sdf::FieldKey::References.as_str(), Value::ReferenceListOp(refs));
Ok(())
})
.unwrap();
let mut changes = crate::pcp::Changes::new();
changes.did_change(&cache, &[(root_id, &cl)]);
changes.apply(&mut cache, &mut graph);
// The reference is composed, not skipped by an in-place spec refresh.
assert!(cache.has_composition_arc(&graph, &inst)?);
Ok(())
}
/// Erasing an `over` that carried a composition arc recomposes: the change
/// record carries the removed `references` field, so the classifier
/// treats the inert removal as significant and the arc is torn down.
#[test]
fn inert_remove_of_arc_recomposes() -> Result<()> {
let (mut graph, mut cache) =
in_memory_stack("#usda 1.0\ndef \"Class\" { int x = 5 }\nover \"Inst\" ( references = </Class> ) {}\n");
let root_id = graph.root_id().unwrap();
let inst = sdf::path("/Inst")?;
// The reference composes initially.
assert!(cache.has_composition_arc(&graph, &inst)?);
// Erase the /Inst spec through the recording proxy and drive the removal.
let cl = edit_layer(&mut graph.get_mut(root_id).unwrap().layer, |l| {
l.data_mut().erase_spec(&inst);
Ok(())
})
.unwrap();
let mut changes = crate::pcp::Changes::new();
changes.did_change(&cache, &[(root_id, &cl)]);
changes.apply(&mut cache, &mut graph);
// The arc is gone, not left dangling by an in-place spec refresh.
assert!(!cache.has_composition_arc(&graph, &inst)?);
Ok(())
}
/// An inert `over` add into a stronger sublayer is a spec-tier change that
/// refreshes the memoized spec stack in place: the new site joins the prim
/// stack ahead of the weaker one, and the refreshed stack matches a
/// from-scratch composition of the edited layers.
#[test]
fn spec_tier_refresh_updates_prim_stack() -> Result<()> {
let root = parse_named_layer("root.usd", "#usda 1.0\n(\n subLayers = [@weak.usd@]\n)\n");
let weak = parse_named_layer("weak.usd", "#usda 1.0\ndef \"A\" { custom int x = 1 }\n");
let mut graph = LayerGraph::from_layers(vec![root, weak], 0, sdf::LayerRegistry::default());
let root_id = graph.id_of("root.usd").unwrap();
let mut cache = IndexCache::new(VariantFallbackMap::new(), LoadRules::all(), Vec::new());
let a = sdf::path("/A")?;
// Before the edit only the weak sublayer authors /A.
assert_eq!(cache.prim_stack(&graph, &a)?, vec![("weak.usd".into(), a.clone())]);
// Author an inert `over "A"` into the strong root layer.
let cl = edit_layer(&mut graph.get_mut(root_id).unwrap().layer, |l| {
sdf::PrimSpecMut::over(l.data_mut(), "/A")?;
Ok(())
})
.unwrap();
let mut changes = crate::pcp::Changes::new();
changes.did_change(&cache, &[(root_id, &cl)]);
assert!(
changes.cache.did_change_specs.contains(&(root_id, a.clone())),
"an inert over add routes through the spec tier"
);
changes.apply(&mut cache, &mut graph);
// The refreshed spec stack lists the strong site first and equals a fresh
// composition of the same layers.
let refreshed = cache.prim_stack(&graph, &a)?;
assert_eq!(
refreshed,
vec![("root.usd".into(), a.clone()), ("weak.usd".into(), a.clone())],
"the spec-tier refresh adds the new strong site to the prim stack"
);
let mut fresh = IndexCache::new(VariantFallbackMap::new(), LoadRules::all(), Vec::new());
assert_eq!(
refreshed,
fresh.prim_stack(&graph, &a)?,
"in-place refresh matches a fresh build"
);
Ok(())
}
/// A single change round whose inert spec adds reach the same index through
/// several sites stays correct. `/A` composes across three sublayers; adding an
/// `over "A"` into two of them in one round produces two `(layer, /A)` sites
/// that both reach index `/A`, and the batched rescan must compose the prim
/// stack a fresh build would. (The batch also finalizes each index's stack once
/// per round, but the idempotent finalize makes that performance property
/// invisible to the result; this guards the correctness it must preserve.)
#[test]
fn spec_refresh_multi_site() -> Result<()> {
let root = parse_named_layer("root.usd", "#usda 1.0\n(\n subLayers = [@mid.usd@, @weak.usd@]\n)\n");
let mid = parse_named_layer("mid.usd", "#usda 1.0\n");
let weak = parse_named_layer("weak.usd", "#usda 1.0\ndef \"A\" { custom int x = 1 }\n");
let mut graph = LayerGraph::from_layers(vec![root, mid, weak], 0, sdf::LayerRegistry::default());
let root_id = graph.id_of("root.usd").unwrap();
let mid_id = graph.id_of("mid.usd").unwrap();
let mut cache = IndexCache::new(VariantFallbackMap::new(), LoadRules::all(), Vec::new());
let a = sdf::path("/A")?;
// Only the weakest sublayer authors /A before the edit.
assert_eq!(cache.prim_stack(&graph, &a)?, vec![("weak.usd".into(), a.clone())]);
// In one change round author an inert `over "A"` into both the root and
// the middle sublayer — two spec-tier sites that both reach index /A.
let cl_root = edit_layer(&mut graph.get_mut(root_id).unwrap().layer, |l| {
sdf::PrimSpecMut::over(l.data_mut(), "/A")?;
Ok(())
})
.unwrap();
let cl_mid = edit_layer(&mut graph.get_mut(mid_id).unwrap().layer, |l| {
sdf::PrimSpecMut::over(l.data_mut(), "/A")?;
Ok(())
})
.unwrap();
let mut changes = crate::pcp::Changes::new();
changes.did_change(&cache, &[(root_id, &cl_root), (mid_id, &cl_mid)]);
assert!(changes.cache.did_change_specs.contains(&(root_id, a.clone())));
assert!(changes.cache.did_change_specs.contains(&(mid_id, a.clone())));
changes.apply(&mut cache, &mut graph);
// Both new sites joined the stack in strength order, matching a fresh
// composition of the edited layers.
let refreshed = cache.prim_stack(&graph, &a)?;
assert_eq!(
refreshed,
vec![
("root.usd".into(), a.clone()),
("mid.usd".into(), a.clone()),
("weak.usd".into(), a.clone()),
],
"the batched spec-tier refresh adds both new strong sites"
);
let mut fresh = IndexCache::new(VariantFallbackMap::new(), LoadRules::all(), Vec::new());
assert_eq!(
refreshed,
fresh.prim_stack(&graph, &a)?,
"in-place refresh matches a fresh build"
);
Ok(())
}
/// Authoring a spec at a previously-empty arc target recomposes a dependent
/// that had culled the arc: the spec-tier rescan drops the dependent so its
/// rebuild un-culls the reference, which an in-place `has_specs` flip cannot.
#[test]
fn inert_add_unculls_dependent() -> Result<()> {
// /A references a prim the base layer does not define, so the reference
// is culled until the target is authored.
let root = parse_named_layer(
"root.usd",
"#usda 1.0\ndef \"A\" ( references = @base.usd@</Empty> ) {}\n",
);
let base = parse_named_layer("base.usd", "#usda 1.0\ndef \"Other\" {}\n");
let mut graph = LayerGraph::from_layers(vec![root, base], 0, sdf::LayerRegistry::default());
let base_id = graph.id_of("base.usd").unwrap();
let mut cache = IndexCache::new(VariantFallbackMap::new(), LoadRules::all(), Vec::new());
let a = sdf::path("/A")?;
// The empty target makes /A's reference culled — no composition arc.
assert!(!cache.has_composition_arc(&graph, &a)?);
// Author `over "Empty"` into the base layer so the target now exists.
let cl = edit_layer(&mut graph.get_mut(base_id).unwrap().layer, |l| {
let data = l.data_mut();
data.create_spec(sdf::path("/Empty").unwrap(), sdf::SpecType::Prim);
data.set_field(
&sdf::path("/Empty").unwrap(),
sdf::FieldKey::Specifier.as_str(),
Value::Specifier(sdf::Specifier::Over),
);
Ok(())
})
.unwrap();
let mut changes = crate::pcp::Changes::new();
changes.did_change(&cache, &[(base_id, &cl)]);
// The inert add routes through the spec tier (not a significant fanout),
// so the rescan's un-cull path is what recomposes /A.
assert!(changes
.cache
.did_change_specs
.contains(&(base_id, sdf::path("/Empty")?)));
changes.apply(&mut cache, &mut graph);
// The reference un-culled: /A now composes the arc.
assert!(cache.has_composition_arc(&graph, &a)?);
Ok(())
}
/// The same un-cull path works for an empty *inherit* target: authoring the
/// class via an inert `over` recomposes the dependent, since the spec-tier
/// rescan now sees the inherit as culled and rebuilds rather than flipping
/// `has_specs` in place.
#[test]
fn inert_add_unculls_inherit() -> Result<()> {
// /A inherits a class the layer does not define, so the inherit is culled
// until the class is authored.
let root = parse_named_layer("root.usd", "#usda 1.0\ndef \"A\" ( inherits = </_class_Foo> ) {}\n");
let mut graph = LayerGraph::from_layers(vec![root], 0, sdf::LayerRegistry::default());
let root_id = graph.id_of("root.usd").unwrap();
let mut cache = IndexCache::new(VariantFallbackMap::new(), LoadRules::all(), Vec::new());
let a = sdf::path("/A")?;
// The empty class makes /A's inherit culled — no composition arc.
assert!(!cache.has_composition_arc(&graph, &a)?);
// Author `over "_class_Foo"` so the class now exists.
let cl = edit_layer(&mut graph.get_mut(root_id).unwrap().layer, |l| {
sdf::PrimSpecMut::over(l.data_mut(), "/_class_Foo")?;
Ok(())
})
.unwrap();
let mut changes = crate::pcp::Changes::new();
changes.did_change(&cache, &[(root_id, &cl)]);
assert!(changes
.cache
.did_change_specs
.contains(&(root_id, sdf::path("/_class_Foo")?)));
changes.apply(&mut cache, &mut graph);
// The inherit un-culled: /A now composes the arc.
assert!(cache.has_composition_arc(&graph, &a)?);
Ok(())
}
/// An empty *specialize* target un-culls the same way: the culled
/// copy-to-root node carries the dependency, so authoring the class
/// recomposes the dependent.
#[test]
fn inert_add_unculls_specialize() -> Result<()> {
let root = parse_named_layer("root.usd", "#usda 1.0\ndef \"A\" ( specializes = </_class_Foo> ) {}\n");
let mut graph = LayerGraph::from_layers(vec![root], 0, sdf::LayerRegistry::default());
let root_id = graph.id_of("root.usd").unwrap();
let mut cache = IndexCache::new(VariantFallbackMap::new(), LoadRules::all(), Vec::new());
let a = sdf::path("/A")?;
assert!(!cache.has_composition_arc(&graph, &a)?);
let cl = edit_layer(&mut graph.get_mut(root_id).unwrap().layer, |l| {
sdf::PrimSpecMut::over(l.data_mut(), "/_class_Foo")?;
Ok(())
})
.unwrap();
let mut changes = crate::pcp::Changes::new();
changes.did_change(&cache, &[(root_id, &cl)]);
assert!(changes
.cache
.did_change_specs
.contains(&(root_id, sdf::path("/_class_Foo")?)));
changes.apply(&mut cache, &mut graph);
assert!(cache.has_composition_arc(&graph, &a)?);
Ok(())
}
/// A descendant under an empty ancestral variant selection carries the
/// variant as a culled node and reports no live composition arc. The parent's
/// local variant arc is culled when its `{set=sel}` site authors nothing, and
/// the ancestral seed clones that culled node down to the descendant — so the
/// cull reaches descendants without a separate path. `has_composition_arc`
/// stays gated on `has_specs`, so the spec-less variant never counts as a
/// composition arc.
#[test]
fn empty_ancestral_variant_culled() -> Result<()> {
// /A selects a variant its set never authors; /A/Child is authored
// directly, so it composes under the empty ancestral selection.
let (graph, mut cache) = in_memory_stack(
"#usda 1.0\ndef \"A\" (\n variantSets = \"v\"\n variants = { string v = \"missing\" }\n) {\n def \"Child\" { custom double x = 1 }\n variantSet \"v\" = {\n \"present\" {}\n }\n}\n",
);
let child = sdf::path("/A/Child")?;
// The child composes from its own opinion, not the empty variant.
assert!(!cache.has_composition_arc(&graph, &child)?);
let index = cache.store.index_at(&child).expect("child index");
assert!(
index.all_nodes().any(|n| n.arc == ArcType::Variant && n.is_culled()),
"the empty ancestral variant target is culled"
);
assert!(
index.nodes().all(|n| n.arc != ArcType::Variant),
"the culled variant contributes nothing to resolution"
);
Ok(())
}
/// Removing the final spec at an inherit target re-culls it. The contributing
/// node loses its last spec, so the spec-tier rescan rebuilds and the now-empty
/// target composes as a culled node — the same representation as an
/// always-empty target, which keeps a later re-add on the un-cull rebuild path
/// rather than an in-place flip that would skip grafting.
#[test]
fn inert_remove_reculls_inherit() -> Result<()> {
// /A inherits a class that exists only as an inert `over`, so the inherit
// node contributes a spec.
let (mut graph, mut cache) =
in_memory_stack("#usda 1.0\ndef \"A\" ( inherits = </_class_Foo> ) {}\nover \"_class_Foo\" {}\n");
let root_id = graph.root_id().unwrap();
let a = sdf::path("/A")?;
// The class exists, so /A composes the inherit.
assert!(cache.has_composition_arc(&graph, &a)?);
// Erase the class's only spec — a purely inert removal.
let cl = edit_layer(&mut graph.get_mut(root_id).unwrap().layer, |l| {
l.data_mut().erase_spec(&sdf::path("/_class_Foo").unwrap());
Ok(())
})
.unwrap();
let mut changes = crate::pcp::Changes::new();
changes.did_change(&cache, &[(root_id, &cl)]);
assert!(changes
.cache
.did_change_specs
.contains(&(root_id, sdf::path("/_class_Foo")?)));
changes.apply(&mut cache, &mut graph);
// The emptied inherit composes as a culled node, just like an always-empty
// target — the rescan rebuilt rather than flipping `has_specs` in place.
assert!(!cache.has_composition_arc(&graph, &a)?);
let index = cache.store.index_at(&a).expect("index rebuilt on query");
assert!(
index.all_nodes().any(|n| n.arc == ArcType::Inherit && n.is_culled()),
"the emptied inherit target re-culled"
);
Ok(())
}
/// A reference to a *nested* missing target also recomposes when the target
/// is authored. A sub-root target is grafted as a non-culled spec-less node
/// (not the root case's culled node), so the spec-tier rescan refreshes its
/// `has_specs` in place — no separate empty-target cull is needed.
#[test]
fn inert_add_recomposes_subroot_target() -> Result<()> {
let root = parse_named_layer(
"root.usd",
"#usda 1.0\ndef \"A\" ( references = @base.usd@</Parent/Empty> ) {}\n",
);
let base = parse_named_layer("base.usd", "#usda 1.0\ndef \"Other\" {}\n");
let mut graph = LayerGraph::from_layers(vec![root, base], 0, sdf::LayerRegistry::default());
let base_id = graph.id_of("base.usd").unwrap();
let mut cache = IndexCache::new(VariantFallbackMap::new(), LoadRules::all(), Vec::new());
let a = sdf::path("/A")?;
// The missing nested target makes /A's reference contribute nothing.
assert!(!cache.has_composition_arc(&graph, &a)?);
// Author the nested target through the recording proxy.
let cl = edit_layer(&mut graph.get_mut(base_id).unwrap().layer, |l| {
l.data_mut()
.create_spec(sdf::path("/Parent/Empty").unwrap(), sdf::SpecType::Prim);
Ok(())
})
.unwrap();
let mut changes = crate::pcp::Changes::new();
changes.did_change(&cache, &[(base_id, &cl)]);
changes.apply(&mut cache, &mut graph);
// /A now composes the reference.
assert!(cache.has_composition_arc(&graph, &a)?);
Ok(())
}
/// Removing an inert `over` carrying `active = false` reactivates the prim:
/// the change record carries the removed `active` field, so the classifier
/// treats the removal as significant, the subtree recomposes from the weaker
/// `def`, and `active` resolves to its default — the subtree is not left
/// inactive after the opinion is gone.
#[test]
fn inert_remove_of_active_reactivates() -> Result<()> {
// A strong layer deactivates /World with an inert over; the weak layer
// it sublayers defines /World and its child.
let strong = parse_named_layer(
"strong.usda",
"#usda 1.0\n(\n subLayers = [@weak.usda@]\n)\nover \"World\" ( active = false ) {}\n",
);
let weak = parse_named_layer("weak.usda", "#usda 1.0\ndef \"World\" {\n def \"Child\" {}\n}\n");
let mut graph = LayerGraph::from_layers(vec![strong, weak], 0, sdf::LayerRegistry::default());
let strong_id = graph.root_id().unwrap();
let mut cache = IndexCache::new(VariantFallbackMap::new(), LoadRules::all(), Vec::new());
let world = sdf::path("/World")?;
let has_child = |cache: &mut IndexCache, graph: &LayerGraph| -> Result<bool> {
Ok(cache
.prim_children(graph, &world)?
.iter()
.any(|c| c.as_str() == "Child"))
};
// The over is in effect: `active` resolves false, the child still composes.
assert_eq!(
cache.resolve_field(&graph, &world, sdf::FieldKey::Active.as_str())?,
Some(Value::Bool(false))
);
assert!(has_child(&mut cache, &graph)?);
// Erase the over spec on the strong layer and drive the change the
// layer derives from it.
let cl = edit_layer(&mut graph.get_mut(strong_id).unwrap().layer, |l| {
l.data_mut().erase_spec(&world);
Ok(())
})
.unwrap();
let mut changes = crate::pcp::Changes::new();
changes.did_change(&cache, &[(strong_id, &cl)]);
changes.apply(&mut cache, &mut graph);
// The active=false opinion is gone — the prim reactivates by default —
// and the def-composed subtree survives.
assert_eq!(
cache.resolve_field(&graph, &world, sdf::FieldKey::Active.as_str())?,
None
);
assert!(cache.has_spec(&graph, &world)?);
assert!(has_child(&mut cache, &graph)?);
Ok(())
}
/// Authors a `layerRelocates` edit on the root layer and drives it through
/// the change pipeline, returning the graph's diagnostics afterward.
fn relocate_edit(graph: &mut LayerGraph, cache: &mut IndexCache, text: &str) -> Vec<Error> {
let root_id = graph.root_id().unwrap();
graph.get_mut(root_id).expect("root layer exists").layer = parse_layer(text);
let mut cl = sdf::ChangeList::new();
cl.entry_mut(&Path::abs_root())
.info_changed
.insert(sdf::FieldKey::LayerRelocates.as_str().into());
let mut changes = crate::pcp::Changes::new();
changes.did_change(cache, &[(root_id, &cl)]);
changes.apply(cache, graph);
graph.errors()
}
/// A `layerRelocates` edit that authors an invalid relocate after stage
/// creation must surface an `InvalidRelocate` diagnostic from the graph,
/// which the recompute path refreshes in place.
#[test]
fn invalid_relocate_edit_surfaces_error() -> Result<()> {
let (mut graph, mut cache) = in_memory_stack("#usda 1.0\ndef \"A\" {}\n");
// No relocates authored yet, so the graph holds no diagnostics.
assert!(graph.errors().is_empty());
// Author an invalid relocate (the target is an ancestor of the source).
let errors = relocate_edit(
&mut graph,
&mut cache,
"#usda 1.0\n(\n relocates = { </A/B/C>: </A> }\n)\ndef \"A\" {}\n",
);
assert!(
errors.iter().any(|e| matches!(e, Error::InvalidRelocate { .. })),
"an invalid relocate authored after construction must be retained"
);
Ok(())
}
/// Re-authoring a valid relocate over an invalid one clears the diagnostic,
/// and recomputing the same state twice does not duplicate it — the graph's
/// relocate-error bucket is replaced wholesale on every rebuild.
#[test]
fn relocate_error_clears_and_dedups() -> Result<()> {
let (mut graph, mut cache) = in_memory_stack("#usda 1.0\ndef \"A\" {}\n");
// Author an invalid relocate, then the same edit twice: still exactly one.
let invalid = "#usda 1.0\n(\n relocates = { </A/B/C>: </A> }\n)\ndef \"A\" {}\n";
let _ = relocate_edit(&mut graph, &mut cache, invalid);
let errors = relocate_edit(&mut graph, &mut cache, invalid);
assert_eq!(
errors
.iter()
.filter(|e| matches!(e, Error::InvalidRelocate { .. }))
.count(),
1,
"recomputing the same invalid relocate must not duplicate the diagnostic"
);
// Re-author a valid relocate; the stale invalid diagnostic disappears.
let valid = "#usda 1.0\n(\n relocates = { </A/B>: </A/C> }\n)\ndef \"A\" {}\n";
let errors = relocate_edit(&mut graph, &mut cache, valid);
assert!(
!errors.iter().any(|e| matches!(e, Error::InvalidRelocate { .. })),
"fixing the relocate must clear the diagnostic"
);
Ok(())
}
}