plasma-prp 0.1.0

Read, write, inspect, and manipulate Plasma engine PRP files used by Myst Online: Uru Live
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
//! .prp (Plasma Resource Page) binary format parser and writer
//!
//! Reads and writes the binary format used by Myst Online: Uru Live to store
//! age data: geometry, textures, materials, scene nodes.

use anyhow::{Context, Result, bail};
use std::io::{Read, Write, Seek, SeekFrom, Cursor};
use std::path::Path;

// ============================================================================
// Stream helpers — Plasma uses little-endian for all numeric types
// ============================================================================

pub trait PlasmaRead: Read {
    fn read_u8(&mut self) -> Result<u8> {
        let mut buf = [0u8; 1];
        self.read_exact(&mut buf)?;
        Ok(buf[0])
    }

    fn read_u16(&mut self) -> Result<u16> {
        let mut buf = [0u8; 2];
        self.read_exact(&mut buf)?;
        Ok(u16::from_le_bytes(buf))
    }

    fn read_u32(&mut self) -> Result<u32> {
        let mut buf = [0u8; 4];
        self.read_exact(&mut buf)?;
        Ok(u32::from_le_bytes(buf))
    }

    fn read_i16(&mut self) -> Result<i16> {
        let mut buf = [0u8; 2];
        self.read_exact(&mut buf)?;
        Ok(i16::from_le_bytes(buf))
    }

    fn read_i32(&mut self) -> Result<i32> {
        let mut buf = [0u8; 4];
        self.read_exact(&mut buf)?;
        Ok(i32::from_le_bytes(buf))
    }

    fn read_f32(&mut self) -> Result<f32> {
        let mut buf = [0u8; 4];
        self.read_exact(&mut buf)?;
        Ok(f32::from_le_bytes(buf))
    }

    fn read_f64(&mut self) -> Result<f64> {
        let mut buf = [0u8; 8];
        self.read_exact(&mut buf)?;
        Ok(f64::from_le_bytes(buf))
    }

    fn read_safe_string(&mut self) -> Result<String> {
        let raw_len = self.read_u16()?;
        let len = (raw_len & 0x0FFF) as usize;
        if len == 0 {
            return Ok(String::new());
        }
        let mut buf = vec![0u8; len];
        self.read_exact(&mut buf)?;

        // XOR-invert if high bit marker was set (0xF000 flag)
        if raw_len & 0xF000 == 0xF000 {
            for byte in &mut buf {
                *byte = !*byte;
            }
        }

        // Handle null terminator
        if buf.last() == Some(&0) {
            buf.pop();
        }

        Ok(String::from_utf8_lossy(&buf).into_owned())
    }

    fn read_matrix44(&mut self) -> Result<[f32; 16]> {
        let mut m = [0f32; 16];
        for val in &mut m {
            *val = self.read_f32()?;
        }
        Ok(m)
    }

    fn skip(&mut self, n: usize) -> Result<()> {
        let mut buf = vec![0u8; n];
        self.read_exact(&mut buf)?;
        Ok(())
    }
}

impl<T: Read> PlasmaRead for T {}

// ============================================================================
// Stream write helpers — Plasma uses little-endian for all numeric types
// ============================================================================

pub trait PlasmaWrite: Write {
    fn write_u8(&mut self, v: u8) -> Result<()> {
        self.write_all(&[v])?;
        Ok(())
    }

    fn write_u16(&mut self, v: u16) -> Result<()> {
        self.write_all(&v.to_le_bytes())?;
        Ok(())
    }

    fn write_u32(&mut self, v: u32) -> Result<()> {
        self.write_all(&v.to_le_bytes())?;
        Ok(())
    }

    fn write_i16(&mut self, v: i16) -> Result<()> {
        self.write_all(&v.to_le_bytes())?;
        Ok(())
    }

    fn write_i32(&mut self, v: i32) -> Result<()> {
        self.write_all(&v.to_le_bytes())?;
        Ok(())
    }

    fn write_f32(&mut self, v: f32) -> Result<()> {
        self.write_all(&v.to_le_bytes())?;
        Ok(())
    }

    fn write_f64(&mut self, v: f64) -> Result<()> {
        self.write_all(&v.to_le_bytes())?;
        Ok(())
    }

    fn write_safe_string(&mut self, s: &str) -> Result<()> {
        let bytes = s.as_bytes();
        let len = bytes.len();
        let raw_len = (len as u16) | 0xF000; // set high nibble flag
        self.write_all(&raw_len.to_le_bytes())?;

        // Write XOR-inverted bytes (no null terminator — matches C++ WriteSafeString)
        let inverted: Vec<u8> = bytes.iter().map(|b| !b).collect();
        self.write_all(&inverted)?;
        Ok(())
    }

    fn write_matrix44(&mut self, m: &[f32; 16]) -> Result<()> {
        for val in m {
            self.write_all(&val.to_le_bytes())?;
        }
        Ok(())
    }
}

impl<T: Write> PlasmaWrite for T {}

// ============================================================================
// Page header
// ============================================================================

#[derive(Debug, Clone)]
pub struct PageHeader {
    pub version: u32,
    pub sequence_number: u32,
    pub flags: u16,
    pub age_name: String,
    pub page_name: String,
    pub major_version: u16,
    pub checksum: u32,
    pub data_start: u32,
    pub index_start: u32,
    /// Class version table: (class_type, version) pairs.
    /// Preserved for byte-identical round-tripping.
    pub class_versions: Vec<(u16, u16)>,
}

impl PageHeader {
    fn read(reader: &mut impl Read) -> Result<Self> {
        let version = reader.read_u32()?;
        if version != 6 {
            bail!("Unsupported .prp version: {} (expected 6)", version);
        }

        let sequence_number = reader.read_u32()?;
        let flags = reader.read_u16()?;
        let age_name = reader.read_safe_string()?;
        let page_name = reader.read_safe_string()?;
        let major_version = reader.read_u16()?;
        let checksum = reader.read_u32()?;
        let data_start = reader.read_u32()?;
        let index_start = reader.read_u32()?;

        // Read class version table (only present in some versions)
        let mut class_versions = Vec::new();
        if data_start > 0 {
            let num_class_versions = reader.read_u16()?;
            for _ in 0..num_class_versions {
                let class_type = reader.read_u16()?;
                let version = reader.read_u16()?;
                class_versions.push((class_type, version));
            }
        }

        Ok(Self {
            version,
            sequence_number,
            flags,
            age_name,
            page_name,
            major_version,
            checksum,
            data_start,
            index_start,
            class_versions,
        })
    }

    fn write(&self, writer: &mut impl Write) -> Result<()> {
        writer.write_u32(self.version)?;
        writer.write_u32(self.sequence_number)?;
        writer.write_u16(self.flags)?;
        writer.write_safe_string(&self.age_name)?;
        writer.write_safe_string(&self.page_name)?;
        writer.write_u16(self.major_version)?;
        writer.write_u32(self.checksum)?;
        writer.write_u32(self.data_start)?;
        writer.write_u32(self.index_start)?;

        // Class version table
        if self.data_start > 0 {
            writer.write_u16(self.class_versions.len() as u16)?;
            for &(class_type, version) in &self.class_versions {
                writer.write_u16(class_type)?;
                writer.write_u16(version)?;
            }
        }

        Ok(())
    }
}

// ============================================================================
// Object key (plUoid + file position)
// ============================================================================

#[derive(Debug, Clone)]
pub struct ObjectKey {
    pub class_type: u16,
    pub object_name: String,
    pub object_id: u32,
    pub start_pos: u32,
    pub data_len: u32,
    pub location_sequence: u32,
    pub location_flags: u16,
    /// Packed load mask byte; 0xFF = always load.
    /// C++ ref: plLoadMask (CoreLib/plLoadMask.h)
    pub load_mask: u8,
    /// Clone ID (0 if not cloned).
    /// C++ ref: plUoid.h — fCloneID
    pub clone_id: u16,
    /// Clone player ID (0 if not cloned).
    /// C++ ref: plUoid.h — fClonePlayerID
    pub clone_player_id: u32,
}

impl ObjectKey {
    /// Convert to a full Uoid for use as collision-free HashMap key.
    pub fn to_uoid(&self) -> crate::core::uoid::Uoid {
        crate::core::uoid::Uoid {
            location: crate::core::location::Location {
                sequence_number: self.location_sequence,
                flags: self.location_flags,
            },
            class_type: self.class_type,
            object_name: self.object_name.clone(),
            object_id: self.object_id,
            load_mask: crate::core::load_mask::LoadMask::from_byte(self.load_mask),
            clone_id: self.clone_id,
            clone_player_id: self.clone_player_id,
        }
    }

    fn read(reader: &mut impl Read) -> Result<Self> {
        let contents = reader.read_u8()?;

        // plLocation
        let location_sequence = reader.read_u32()?;
        let location_flags = reader.read_u16()?;

        // LoadMask (optional, 1 byte packed)
        // C++ ref: plUoid.cpp:159 — kHasLoadMask = 0x2
        let load_mask = if contents & 0x02 != 0 {
            reader.read_u8()?
        } else {
            0xFF // SetAlways — C++ ref: plLoadMask.h
        };

        let class_type = reader.read_u16()?;
        let object_id = reader.read_u32()?;
        let object_name = reader.read_safe_string()?;

        // Clone IDs (optional)
        // C++ ref: plUoid.cpp:169-173 — kHasCloneIDs = 0x1
        let (clone_id, clone_player_id) = if contents & 0x01 != 0 {
            let clone_id = reader.read_u16()?;
            let _reserved = reader.read_u16()?;
            let clone_player_id = reader.read_u32()?;
            (clone_id, clone_player_id)
        } else {
            (0, 0)
        };

        // File position
        let start_pos = reader.read_u32()?;
        let data_len = reader.read_u32()?;

        Ok(Self {
            class_type,
            object_name,
            object_id,
            start_pos,
            data_len,
            location_sequence,
            location_flags,
            load_mask,
            clone_id,
            clone_player_id,
        })
    }

    /// Write an ObjectKey in the PRP key index format.
    pub fn write(&self, writer: &mut impl Write) -> Result<()> {
        // Reconstruct contents byte
        let has_load_mask = self.load_mask != 0xFF;
        let has_clone = self.clone_id != 0 || self.clone_player_id != 0;
        let mut contents: u8 = 0;
        if has_clone { contents |= 0x01; }
        if has_load_mask { contents |= 0x02; }
        writer.write_u8(contents)?;

        // plLocation
        writer.write_u32(self.location_sequence)?;
        writer.write_u16(self.location_flags)?;

        // LoadMask
        if has_load_mask {
            writer.write_u8(self.load_mask)?;
        }

        writer.write_u16(self.class_type)?;
        writer.write_u32(self.object_id)?;
        writer.write_safe_string(&self.object_name)?;

        // Clone IDs
        if has_clone {
            writer.write_u16(self.clone_id)?;
            writer.write_u16(0u16)?; // reserved
            writer.write_u32(self.clone_player_id)?;
        }

        // File position
        writer.write_u32(self.start_pos)?;
        writer.write_u32(self.data_len)?;

        Ok(())
    }
}

// ============================================================================
// Plasma class types (from plFactory — only the ones we care about)
// ============================================================================

#[allow(dead_code)]
pub mod class_types {
    // Class indices from plCreatableIndex.h (0-based, excluding LIST_START)
    pub const PL_SCENE_NODE: u16 = 0x0000;
    pub const PL_SCENE_OBJECT: u16 = 0x0001;
    pub const PL_MIPMAP: u16 = 0x0004;
    pub const PL_CUBIC_ENVIRONMAP: u16 = 0x0005;
    pub const PL_LAYER: u16 = 0x0006;
    pub const HS_GMATERIAL: u16 = 0x0007;
    pub const PL_DRAWABLE_SPANS: u16 = 0x004C;
    pub const PL_CLUSTER_GROUP: u16 = 0x012B;
    pub const PL_DYNAMIC_TEXT_MAP: u16 = 0x00AD;
}

// ============================================================================
// Page reader — reads header, index, and provides object access
// ============================================================================

/// Key index group — preserves per-class metadata for round-tripping.
#[derive(Debug, Clone)]
pub struct KeyIndexGroup {
    pub class_type: u16,
    pub deprecated_flags: u8,
}

#[derive(Debug)]
pub struct PrpPage {
    pub header: PageHeader,
    pub keys: Vec<ObjectKey>,
    /// Per-class-type metadata from the key index, in file order.
    /// Preserved for byte-identical round-tripping.
    pub key_groups: Vec<KeyIndexGroup>,
    data: Vec<u8>,
}

impl PrpPage {
    fn parse_keys(cursor: &mut Cursor<&[u8]>, index_start: u64) -> Result<(Vec<ObjectKey>, Vec<KeyIndexGroup>)> {
        cursor.seek(SeekFrom::Start(index_start))?;
        let mut keys = Vec::new();
        let mut key_groups = Vec::new();

        let num_class_types = cursor.read_u32()?;
        for _ in 0..num_class_types {
            let class_type = cursor.read_u16()?;
            let key_list_len = cursor.read_u32()?;
            let pos_before = cursor.position();
            let pos_end = pos_before + key_list_len as u64;

            let deprecated_flags = cursor.read_u8()?;
            let num_keys = cursor.read_u32()?;

            key_groups.push(KeyIndexGroup { class_type, deprecated_flags });

            for _ in 0..num_keys {
                if cursor.position() >= pos_end { break; }
                match ObjectKey::read(cursor) {
                    Ok(key) => keys.push(key),
                    Err(_) => break,
                }
            }
            cursor.seek(SeekFrom::Start(pos_end))?;
        }

        Ok((keys, key_groups))
    }

    pub fn from_file(path: &Path) -> Result<Self> {
        let data = std::fs::read(path)
            .with_context(|| format!("Failed to read {:?}", path))?;
        let mut cursor = Cursor::new(data.as_slice());

        let header = PageHeader::read(&mut cursor)
            .with_context(|| format!("Failed to parse header of {:?}", path))?;

        let (keys, key_groups) = Self::parse_keys(&mut cursor, header.index_start as u64)?;

        Ok(Self { header, keys, key_groups, data })
    }

    /// Parse a PRP page from raw bytes (for WASM HTTP loading).
    pub fn from_bytes(data: Vec<u8>) -> Result<Self> {
        let mut cursor = Cursor::new(data.as_slice());
        let header = PageHeader::read(&mut cursor)
            .with_context(|| "Failed to parse PRP header from bytes")?;

        let (keys, key_groups) = Self::parse_keys(&mut cursor, header.index_start as u64)?;

        Ok(Self { header, keys, key_groups, data })
    }

    /// Get raw object data for a key
    pub fn object_data(&self, key: &ObjectKey) -> Option<&[u8]> {
        let start = key.start_pos as usize;
        let end = start + key.data_len as usize;
        if end <= self.data.len() {
            Some(&self.data[start..end])
        } else {
            None
        }
    }

    /// Get the full raw data blob (header + objects + index).
    pub fn raw_data(&self) -> &[u8] {
        &self.data
    }

    /// Get all keys of a specific class type
    pub fn keys_of_type(&self, class_type: u16) -> Vec<&ObjectKey> {
        self.keys.iter().filter(|k| k.class_type == class_type).collect()
    }

    /// Count objects by class type
    pub fn count_by_type(&self, class_type: u16) -> usize {
        self.keys.iter().filter(|k| k.class_type == class_type).count()
    }

    /// Serialize the PRP page back to bytes (byte-identical to original file).
    ///
    /// Reconstructs: header + raw object data section + key index.
    pub fn to_bytes(&self) -> Result<Vec<u8>> {
        let mut buf: Vec<u8> = Vec::with_capacity(self.data.len());

        // 1. Write header
        self.header.write(&mut buf)?;

        // 2. Write data section (raw object bytes, preserved exactly)
        let data_start = self.header.data_start as usize;
        let index_start = self.header.index_start as usize;
        if data_start <= self.data.len() && index_start <= self.data.len() {
            // Pad if header is shorter than data_start
            while buf.len() < data_start {
                buf.push(0);
            }
            buf.extend_from_slice(&self.data[data_start..index_start]);
        }

        // 3. Write key index
        self.write_key_index(&mut buf)?;

        Ok(buf)
    }

    /// Write the key index section.
    fn write_key_index(&self, writer: &mut impl Write) -> Result<()> {
        // Group keys by class type, preserving the order from key_groups
        let num_class_types = self.key_groups.len() as u32;
        writer.write_u32(num_class_types)?;

        for group in &self.key_groups {
            let class_keys: Vec<&ObjectKey> = self.keys.iter()
                .filter(|k| k.class_type == group.class_type)
                .collect();

            // Compute the byte length of the key list payload
            // (deprecated_flags(1) + num_keys(4) + serialized keys)
            let mut key_payload = Vec::new();
            key_payload.write_u8(group.deprecated_flags)?;
            key_payload.write_u32(class_keys.len() as u32)?;
            for key in &class_keys {
                key.write(&mut key_payload)?;
            }

            writer.write_u16(group.class_type)?;
            writer.write_u32(key_payload.len() as u32)?;
            writer.write_all(&key_payload)?;
        }

        Ok(())
    }

    /// Save the PRP page to a file (byte-identical round-trip).
    pub fn save(&self, path: &Path) -> Result<()> {
        let bytes = self.to_bytes()?;
        std::fs::write(path, &bytes)
            .with_context(|| format!("Failed to write {:?}", path))?;
        Ok(())
    }
}

// ============================================================================
// Key reference reader (returns name if non-nil)
// ============================================================================

pub fn read_key_name(reader: &mut (impl Read + Seek)) -> Result<Option<String>> {
    let non_nil = reader.read_u8()?;
    if non_nil == 0 {
        return Ok(None);
    }
    let contents = reader.read_u8()?;
    reader.skip(6)?; // plLocation: sequence(4) + flags(2)
    // C++ plUoid: kHasCloneIDs=0x01, kHasLoadMask=0x02
    if contents & 0x02 != 0 {
        reader.skip(1)?; // LoadMask (1 byte)
    }
    let _class_type = reader.read_u16()?;
    let _object_id = reader.read_u32()?;
    let name = reader.read_safe_string()?;
    if contents & 0x01 != 0 {
        reader.skip(8)?; // cloneID(2) + reserved(2) + clonePlayerID(4)
    }
    Ok(Some(name))
}

/// Public wrapper for skip_synched_object.
pub fn skip_synched_object_pub(reader: &mut (impl Read + Seek)) -> Result<()> {
    skip_synched_object(reader)
}

fn skip_synched_object(reader: &mut (impl Read + Seek)) -> Result<()> {
    let synch_flags = reader.read_u32()?;
    if synch_flags & 0x10 != 0 { // kExcludePersistentState
        let n = reader.read_u16()?;
        for _ in 0..n { reader.read_safe_string()?; }
    }
    if synch_flags & 0x20 != 0 { // kHasVolatileState
        let n = reader.read_u16()?;
        for _ in 0..n { reader.read_safe_string()?; }
    }
    Ok(())
}

// ============================================================================
// hsGMaterial — parse to extract layer key names
// ============================================================================

/// Parse hsGMaterial to get the names of its layer key refs
pub fn parse_material_layers(data: &[u8]) -> Result<Vec<String>> {
    let mut cursor = Cursor::new(data);

    // Creatable class index
    let class_idx = cursor.read_i16()?;
    if class_idx < 0 { bail!("Null creatable"); }

    // hsKeyedObject::Read (self-key)
    read_key_name(&mut cursor)?;

    // plSynchedObject::Read
    skip_synched_object(&mut cursor)?;

    // hsGMaterial::Read
    let _load_flags = cursor.read_u32()?;
    let _comp_flags = cursor.read_u32()?;
    let num_layers = cursor.read_u32()?;
    let _num_piggybacks = cursor.read_u32()?;

    let mut layer_names = Vec::new();
    for _ in 0..num_layers {
        if let Some(name) = read_key_name(&mut cursor)? {
            layer_names.push(name);
        }
    }

    Ok(layer_names)
}

// ============================================================================
// plLayer — parse to extract texture key name
// ============================================================================

/// Parse plLayer to get the texture key name
pub fn parse_layer_texture(data: &[u8]) -> Result<Option<String>> {
    let mut cursor = Cursor::new(data);

    // Creatable class index
    let class_idx = cursor.read_i16()?;
    if class_idx < 0 { bail!("Null creatable"); }

    // plLayerInterface::Read
    //   plSynchedObject::Read
    //     hsKeyedObject::Read (self-key)
    read_key_name(&mut cursor)?;
    skip_synched_object(&mut cursor)?;
    //   underLay key
    read_key_name(&mut cursor)?;

    // plLayer::Read
    // hsGMatState: 5 uint32s
    cursor.skip(20)?;
    // Transform matrix (hsMatrix44)
    let has_matrix = cursor.read_u8()?;
    if has_matrix != 0 {
        cursor.skip(64)?; // 16 floats
    }
    // PreshadeColor (4 floats)
    cursor.skip(16)?;
    // RuntimeColor (4 floats)
    cursor.skip(16)?;
    // AmbientColor (4 floats)
    cursor.skip(16)?;
    // SpecularColor (4 floats)
    cursor.skip(16)?;
    // UVWSrc (uint32)
    cursor.skip(4)?;
    // Opacity (float)
    cursor.skip(4)?;
    // LODBias (float)
    cursor.skip(4)?;
    // SpecularPower (float)
    cursor.skip(4)?;

    // Texture key — this is what we want!
    let texture_name = read_key_name(&mut cursor)?;

    Ok(texture_name)
}

/// Parsed layer state for compositing decisions.
#[derive(Debug, Clone)]
pub struct LayerState {
    pub name: String,
    pub texture_name: Option<String>,
    pub blend_flags: u32,
    pub shade_flags: u32,
    pub misc_flags: u32,
    pub z_flags: u32,
    pub uv_channel: u8,
    /// Full UVWSrc including mode bits (kUVWNormal=0x10000, kUVWPosition=0x20000, kUVWReflect=0x30000)
    pub uvw_src_full: u32,
    pub opacity: f32,
    /// UV transform matrix from plLayer (hsMatrix44, row-major fMap[row][col]).
    /// Applied as: uv_out = (transform * vec4(uv, 0, 1)).xy
    /// Identity when None (no transform or identity flag set).
    pub uv_transform: Option<[[f32; 4]; 4]>,
    /// Material colors from plLayer::Read (plLayer.cpp:124-127)
    /// Order: preshadeColor, runtimeColor, ambientColor, specularColor
    pub preshade_color: [f32; 4],
    pub runtime_color: [f32; 4],
    pub ambient_color: [f32; 4],
    pub specular_color: [f32; 4],
}

/// Parse a plLayer's blend/misc/z flags and UV channel (using correct key parsers).
pub fn parse_layer_state(data: &[u8]) -> Result<LayerState> {
    use crate::core::uoid::read_key_uoid;
    use crate::core::synched_object::SynchedObjectData;

    let mut cursor = Cursor::new(data);
    let class_idx = cursor.read_i16()?;
    if class_idx < 0 { bail!("Null creatable"); }

    let self_key = read_key_uoid(&mut cursor)?;
    let name = self_key.map(|u| u.object_name).unwrap_or_default();
    let _synched = SynchedObjectData::read(&mut cursor)?;
    let _underlay = read_key_uoid(&mut cursor)?;

    // hsGMatState: 5 u32s
    let blend_flags = cursor.read_u32()?;
    let _clamp_flags = cursor.read_u32()?;
    let shade_flags = cursor.read_u32()?;
    let z_flags = cursor.read_u32()?;
    let misc_flags = cursor.read_u32()?;

    // UV Transform matrix (hsMatrix44: row-major fMap[row][col])
    // C++ ref: hsMatrix44.cpp:870-882 — ReadBool + optionally 16 LE floats
    let has_matrix = cursor.read_u8()?;
    let uv_transform = if has_matrix != 0 {
        let mut m = [[0.0f32; 4]; 4];
        for row in &mut m {
            for val in row.iter_mut() {
                *val = cursor.read_f32()?;
            }
        }
        Some(m)
    } else {
        None
    };
    // 4 colors: preshade, runtime, ambient, specular (hsColorRGBA = 4 floats each)
    // plLayer.cpp:124-127
    let mut preshade_color = [0.0f32; 4];
    let mut runtime_color = [0.0f32; 4];
    let mut ambient_color = [0.0f32; 4];
    let mut specular_color = [0.0f32; 4];
    for c in &mut preshade_color { *c = cursor.read_f32()?; }
    for c in &mut runtime_color { *c = cursor.read_f32()?; }
    for c in &mut ambient_color { *c = cursor.read_f32()?; }
    for c in &mut specular_color { *c = cursor.read_f32()?; }
    // UVWSrc, Opacity
    let uvwsrc = cursor.read_u32()?;
    let opacity = cursor.read_f32()?;
    cursor.skip(8)?; // LODBias + SpecPower

    // Texture key
    let tex = read_key_uoid(&mut cursor)?;
    let texture_name = tex.map(|u| u.object_name);

    Ok(LayerState {
        name,
        texture_name,
        blend_flags,
        shade_flags,
        misc_flags,
        z_flags,
        uv_channel: (uvwsrc & 0xFFFF) as u8,
        uvw_src_full: uvwsrc,
        opacity,
        uv_transform,
        preshade_color,
        runtime_color,
        ambient_color,
        specular_color,
    })
}

/// Parse hsGMaterial to get its compFlags.
pub fn parse_material_comp_flags(data: &[u8]) -> Result<u32> {
    use crate::core::uoid::read_key_uoid;
    use crate::core::synched_object::SynchedObjectData;

    let mut cursor = Cursor::new(data);
    let class_idx = cursor.read_i16()?;
    if class_idx < 0 { bail!("Null creatable"); }

    let _self_key = read_key_uoid(&mut cursor)?;
    let _synched = SynchedObjectData::read(&mut cursor)?;

    let _load_flags = cursor.read_u32()?;
    let comp_flags = cursor.read_u32()?;
    Ok(comp_flags)
}

/// Parse a plLayer to get the UV channel index.
/// Returns the UVWSrc channel (lower 16 bits).
pub fn parse_layer_uv_channel(data: &[u8]) -> Result<u8> {
    use crate::core::uoid::read_key_uoid;
    use crate::core::synched_object::SynchedObjectData;

    let mut cursor = Cursor::new(data);
    let class_idx = cursor.read_i16()?;
    if class_idx < 0 { bail!("Null creatable"); }

    // plLayerInterface::Read
    let _self_key = read_key_uoid(&mut cursor)?;
    let _synched = SynchedObjectData::read(&mut cursor)?;
    let _underlay = read_key_uoid(&mut cursor)?;

    // plLayer::Read — state (5 u32) + matrix + 4 colors + uvwsrc
    cursor.skip(20)?; // state
    let has_matrix = cursor.read_u8()?;
    if has_matrix != 0 { cursor.skip(64)?; }
    cursor.skip(64)?; // 4 colors
    let uvwsrc = cursor.read_u32()?;

    Ok((uvwsrc & 0xFFFF) as u8)
}

/// UV scroll rate extracted from a plLayerAnimation's transform controller.
/// Represents a constant-rate UV translation per second.
#[derive(Debug, Clone, Copy)]
pub struct UvScrollRate {
    pub u: f32,
    pub v: f32,
}

/// Key type constants matching Plasma's hsKeyFrame enum (hsKeys.h)
#[allow(dead_code)]
mod key_types {
    pub const POINT3: u8 = 1;
    pub const BEZ_POINT3: u8 = 2;
    pub const SCALAR: u8 = 3;
    pub const BEZ_SCALAR: u8 = 4;
    pub const SCALE: u8 = 5;
    pub const BEZ_SCALE: u8 = 6;
    pub const QUAT: u8 = 7;
    pub const COMPRESSED_QUAT32: u8 = 8;
    pub const COMPRESSED_QUAT64: u8 = 9;
    pub const MAX_KEY: u8 = 10;
    pub const MATRIX33: u8 = 11;
    pub const MATRIX44: u8 = 12;
}

/// Byte size of a single key for a given key type (frame u16 + value data).
fn key_size(key_type: u8) -> Option<usize> {
    match key_type {
        key_types::POINT3 => Some(2 + 12),          // frame + 3 floats
        key_types::BEZ_POINT3 => Some(2 + 36),      // frame + 3 tangent pairs + 3 floats
        key_types::SCALAR => Some(2 + 4),            // frame + 1 float
        key_types::BEZ_SCALAR => Some(2 + 12),       // frame + inTan + outTan + value
        key_types::SCALE => Some(2 + 28),            // frame + hsScaleValue (3 floats + quat)
        key_types::BEZ_SCALE => Some(2 + 52),        // frame + 2 tangents + hsScaleValue
        key_types::QUAT => Some(2 + 16),             // frame + 4 floats
        key_types::COMPRESSED_QUAT32 => Some(2 + 4), // frame + u32
        key_types::COMPRESSED_QUAT64 => Some(2 + 8), // frame + 2 u32
        key_types::MATRIX33 => Some(2 + 36),          // frame + 9 floats
        key_types::MATRIX44 => Some(2 + 64),           // frame + 16 floats
        _ => None,
    }
}

/// Controller class IDs as they appear in compiled PRP files.
/// NOTE: These differ from the open-source plCreatableIndex.h because the game
/// data was compiled with the original CyanWorlds class numbering, not the
/// reorganized open-source enum.
/// Verified empirically from Cleft_District_Cleft.prp binary analysis.
const LEAF_CONTROLLER: u16 = 0x0230;    // plLeafController
const COMPOUND_CONTROLLER: u16 = 0x0231; // plCompoundController

/// Skip a plCreatable reference (class_idx + data).
/// Returns Ok(true) if a creatable was read, Ok(false) if null (0x8000).
fn skip_creatable(cursor: &mut Cursor<&[u8]>) -> Result<bool> {
    let class_idx = cursor.read_u16()?;
    if class_idx == 0x8000 { return Ok(false); } // null creatable

    match class_idx {
        LEAF_CONTROLLER => {
            skip_leaf_controller(cursor)?;
        }
        COMPOUND_CONTROLLER => {
            // 3 sub-controllers (X, Y, Z) — used for plCompoundController,
            // plCompoundRotController, plCompoundPosController, plTMController
            for _ in 0..3 {
                skip_creatable(cursor)?;
            }
        }
        _ => {
            // Unknown controller type — can't determine size to skip.
            // Return error so callers can handle gracefully.
            bail!("Unknown controller class 0x{:04X}", class_idx);
        }
    }
    Ok(true)
}

/// Skip a plLeafController's data (type + numKeys + key data).
fn skip_leaf_controller(cursor: &mut Cursor<&[u8]>) -> Result<()> {
    let key_type = cursor.read_u8()?;
    let num_keys = cursor.read_u32()?;
    if let Some(ks) = key_size(key_type) {
        cursor.skip(ks * num_keys as usize)?;
    } else if key_type == key_types::MAX_KEY {
        // k3dsMaxKeyFrame — complex, skip by reading hsAffineParts per key
        // frame(2) + T(12) + Q(16) + U(16) + K(12) + f(4) = 62 bytes per key
        cursor.skip(62 * num_keys as usize)?;
    } else {
        bail!("Unknown key type {} with {} keys", key_type, num_keys);
    }
    Ok(())
}

/// Read a plLeafController's matrix44 keyframes and extract UV scroll rate.
/// Returns Some(UvScrollRate) if the controller has ≥2 matrix44 keys that
/// represent a linear UV translation.
fn read_transform_leaf_controller(cursor: &mut Cursor<&[u8]>) -> Result<Option<UvScrollRate>> {
    let key_type = cursor.read_u8()?;
    let num_keys = cursor.read_u32()?;

    if key_type != key_types::MATRIX44 || num_keys < 2 {
        // Not a matrix44 controller or too few keys — skip
        if let Some(ks) = key_size(key_type) {
            cursor.skip(ks * num_keys as usize)?;
        } else if key_type == key_types::MAX_KEY {
            cursor.skip(62 * num_keys as usize)?;
        } else {
            bail!("Unknown key type {} with {} keys", key_type, num_keys);
        }
        return Ok(None);
    }

    // Read first and last matrix44 keyframes to compute scroll rate.
    // Format per key: [u16 frame] [16 × f32 matrix] = 66 bytes
    let frame0 = cursor.read_u16()?;
    let mat0 = cursor.read_matrix44()?;

    // Skip to last key
    if num_keys > 2 {
        let skip_bytes = 66 * (num_keys as usize - 2);
        let pos = cursor.position() as usize;
        let data_len = cursor.get_ref().len();
        if pos + skip_bytes + 66 > data_len {
            // Not enough data for all keys — object may be truncated
            return Ok(None);
        }
        cursor.skip(skip_bytes)?;
    }

    let frame_last = cursor.read_u16()?;
    let mat_last = cursor.read_matrix44()?;

    let dt_frames = frame_last as f32 - frame0 as f32;
    if dt_frames <= 0.0 { return Ok(None); }

    // Plasma animation runs at 30 fps (MAX_FRAMES_PER_SEC)
    let dt_secs = dt_frames / 30.0;

    // UV translation is in the matrix translation component.
    // hsMatrix44 row-major: translation at m[3] (U offset) and m[7] (V offset).
    let du = mat_last[3] - mat0[3];
    let dv = mat_last[7] - mat0[7];

    let rate_u = du / dt_secs;
    let rate_v = dv / dt_secs;

    // Filter out nonsensical values (non-translation matrices, or no scroll)
    if (rate_u.abs() < 1e-6 && rate_v.abs() < 1e-6) || rate_u.abs() > 100.0 || rate_v.abs() > 100.0 {
        return Ok(None);
    }

    Ok(Some(UvScrollRate {
        u: rate_u,
        v: rate_v,
    }))
}

/// Parse a plLayerAnimation to extract the UV scroll rate from its
/// transform controller (the 6th controller in the read order).
///
/// C++ ref: plLayerAnimation.cpp:79-88 — reads 6 controllers:
///   fPreshadeColorCtl, fRuntimeColorCtl, fAmbientColorCtl,
///   fSpecularColorCtl, fOpacityCtl, fTransformCtl
/// Parsed plLayerAnimation runtime data.
/// Contains animated property controllers for opacity, color, transform.
#[derive(Debug, Clone)]
pub struct LayerAnimData {
    pub self_key: Option<crate::core::uoid::Uoid>,
    pub underlay_key: Option<crate::core::uoid::Uoid>,
    /// Opacity keyframes: (time_secs, value_0_to_100) pairs.
    pub opacity_keys: Vec<(f32, f32)>,
    /// Whether this has an opacity controller at all.
    pub has_opacity: bool,
    /// Preshade color keyframes: (time_secs, [r, g, b]).
    /// C++ ref: plController.cpp:221-228 — color uses Point3 keys, maps r=X g=Y b=Z.
    pub preshade_color_keys: Vec<(f32, [f32; 3])>,
    /// Runtime color keyframes: (time_secs, [r, g, b]).
    pub runtime_color_keys: Vec<(f32, [f32; 3])>,
    /// Ambient color keyframes: (time_secs, [r, g, b]).
    pub ambient_color_keys: Vec<(f32, [f32; 3])>,
    /// Specular color keyframes: (time_secs, [r, g, b]).
    pub specular_color_keys: Vec<(f32, [f32; 3])>,
    /// Total animation length in seconds (max of all controller lengths).
    /// C++ ref: plLayerAnimationBase::IMakeUniformLength (plLayerAnimation.cpp:276-293)
    pub length: f32,
    /// SDL variable name (only for plLayerSDLAnimation, 0x00F0).
    /// When set, animation time = sdl_value * length.
    pub sdl_var_name: Option<String>,
}

/// Read color keyframes (Point3 keys) from a leaf controller.
/// C++ ref: plController.cpp:221-228 — color uses Point3 keys, maps r=X g=Y b=Z.
fn read_color_keys(cursor: &mut Cursor<&[u8]>) -> Result<Vec<(f32, [f32; 3])>> {
    let mut keys = Vec::new();
    let class_id = cursor.read_u16()?;
    if class_id == 0x8000 { return Ok(keys); }

    if class_id == LEAF_CONTROLLER {
        let key_type = cursor.read_u8()?;
        let num_keys = cursor.read_u32()?;
        if key_type == key_types::POINT3 {
            for _ in 0..num_keys {
                let frame = cursor.read_u16()? as f32 / 30.0;
                let x = cursor.read_f32()?;
                let y = cursor.read_f32()?;
                let z = cursor.read_f32()?;
                keys.push((frame, [x, y, z]));
            }
        } else if key_type == key_types::BEZ_POINT3 {
            for _ in 0..num_keys {
                let frame = cursor.read_u16()? as f32 / 30.0;
                cursor.skip(24)?; // inTan(3f) + outTan(3f) = 24 bytes
                let x = cursor.read_f32()?;
                let y = cursor.read_f32()?;
                let z = cursor.read_f32()?;
                keys.push((frame, [x, y, z]));
            }
        } else {
            if let Some(ks) = key_size(key_type) {
                cursor.skip(ks * num_keys as usize)?;
            }
        }
    } else if class_id == COMPOUND_CONTROLLER {
        for _ in 0..3 { skip_creatable(cursor)?; }
    }
    Ok(keys)
}

/// Read scalar (opacity) keyframes from a leaf controller.
fn read_opacity_keys(cursor: &mut Cursor<&[u8]>) -> Result<(bool, Vec<(f32, f32)>)> {
    let mut keys = Vec::new();
    let class_id = cursor.read_u16()?;
    if class_id == 0x8000 { return Ok((false, keys)); }

    if class_id == LEAF_CONTROLLER {
        let key_type = cursor.read_u8()?;
        let num_keys = cursor.read_u32()?;
        if key_type == key_types::SCALAR {
            for _ in 0..num_keys {
                let frame = cursor.read_u16()? as f32 / 30.0;
                let value = cursor.read_f32()?;
                keys.push((frame, value));
            }
        } else if key_type == key_types::BEZ_SCALAR {
            for _ in 0..num_keys {
                let frame = cursor.read_u16()? as f32 / 30.0;
                let _in_tan = cursor.read_f32()?;
                let _out_tan = cursor.read_f32()?;
                let value = cursor.read_f32()?;
                keys.push((frame, value));
            }
        } else {
            if let Some(ks) = key_size(key_type) {
                cursor.skip(ks * num_keys as usize)?;
            }
        }
    } else if class_id == COMPOUND_CONTROLLER {
        for _ in 0..3 { skip_creatable(cursor)?; }
    }
    Ok((true, keys))
}

/// Parse a plLayerAnimation to extract all controller keyframes.
/// C++ ref: plLayerAnimationBase::Read (plLayerAnimation.cpp:79-120)
pub fn parse_layer_animation_full(data: &[u8]) -> Result<LayerAnimData> {
    use crate::core::uoid::read_key_uoid;
    use crate::core::synched_object::SynchedObjectData;

    let mut cursor = Cursor::new(data);
    let class_idx = cursor.read_i16()?;
    if class_idx < 0 { bail!("Null creatable"); }

    let self_key = read_key_uoid(&mut cursor)?;
    let _synched = SynchedObjectData::read(&mut cursor)?;
    let underlay_key = read_key_uoid(&mut cursor)?;

    // Read 4 color controllers: preshade, runtime, ambient, specular
    let preshade_color_keys = read_color_keys(&mut cursor)?;
    let runtime_color_keys = read_color_keys(&mut cursor)?;
    let ambient_color_keys = read_color_keys(&mut cursor)?;
    let specular_color_keys = read_color_keys(&mut cursor)?;

    // Read 5th controller: opacity
    let (has_opacity, opacity_keys) = read_opacity_keys(&mut cursor)?;

    // Skip 6th controller: transform
    skip_creatable(&mut cursor)?;

    // Compute uniform length
    let mut length: f32 = 0.0;
    if let Some(last) = preshade_color_keys.last() { length = length.max(last.0); }
    if let Some(last) = runtime_color_keys.last() { length = length.max(last.0); }
    if let Some(last) = ambient_color_keys.last() { length = length.max(last.0); }
    if let Some(last) = specular_color_keys.last() { length = length.max(last.0); }
    if let Some(last) = opacity_keys.last() { length = length.max(last.0); }

    Ok(LayerAnimData {
        self_key,
        underlay_key,
        opacity_keys,
        has_opacity,
        preshade_color_keys,
        runtime_color_keys,
        ambient_color_keys,
        specular_color_keys,
        length,
        sdl_var_name: None,
    })
}

pub fn parse_layer_animation_scroll(data: &[u8]) -> Result<Option<UvScrollRate>> {
    use crate::core::uoid::read_key_uoid;
    use crate::core::synched_object::SynchedObjectData;

    let mut cursor = Cursor::new(data);
    let class_idx = cursor.read_i16()?;
    if class_idx < 0 { bail!("Null creatable"); }

    // plLayerInterface::Read: self-key + synched + underlay key
    let _self_key = read_key_uoid(&mut cursor)?;
    let _synched = SynchedObjectData::read(&mut cursor)?;
    let _underlay = read_key_uoid(&mut cursor)?;

    // Skip first 5 controllers (preshade, runtime, ambient, specular, opacity)
    for _ in 0..5 {
        skip_creatable(&mut cursor)?;
    }

    // Read 6th controller: transform
    let xform_class = cursor.read_u16()?;
    if xform_class == 0x8000 { return Ok(None); } // no transform controller

    match xform_class {
        LEAF_CONTROLLER => {
            read_transform_leaf_controller(&mut cursor)
        }
        COMPOUND_CONTROLLER => {
            // CompoundController has 3 sub-controllers (X, Y, Z).
            // UV scrolling in a compound controller is unusual — skip.
            Ok(None)
        }
        _ => {
            // Unknown controller type
            Ok(None)
        }
    }
}

/// Parse a plLayerSDLAnimation (0x00F0) — same base + SDL var name.
/// C++ ref: plLayerSDLAnimation::Read (plLayerAnimation.cpp:725-730)
pub fn parse_layer_sdl_animation_full(data: &[u8]) -> Result<LayerAnimData> {
    let mut la = parse_layer_animation_full(data)?;
    use crate::core::uoid::read_key_uoid;
    use crate::core::synched_object::SynchedObjectData;

    let mut cursor = Cursor::new(data);
    let _class_idx = cursor.read_i16()?;
    let _self_key = read_key_uoid(&mut cursor)?;
    let _synched = SynchedObjectData::read(&mut cursor)?;
    let _underlay = read_key_uoid(&mut cursor)?;
    for _ in 0..6 { skip_creatable(&mut cursor)?; }
    match cursor.read_safe_string() {
        Ok(name) if !name.is_empty() => { la.sdl_var_name = Some(name); }
        _ => {}
    }
    Ok(la)
}

/// Parse a plLayerAnimation (or plLayerSDLAnimation, plLayerLinkAnimation) to
/// extract the underlay key name. The underlay is the plLayer beneath this
/// animation that holds the actual texture reference.
///
/// Format: [i16 classIdx] [plLayerInterface::Read: self_key + synched + underlay_key]
///         [6 controller creatables] [plAnimTimeConvert...]
///
/// We only need the underlay key name.
pub fn parse_layer_animation_underlay(data: &[u8]) -> Result<Option<crate::core::uoid::Uoid>> {
    use crate::core::uoid::read_key_uoid;
    use crate::core::synched_object::SynchedObjectData;

    let mut cursor = Cursor::new(data);
    let class_idx = cursor.read_i16()?;
    if class_idx < 0 { bail!("Null creatable"); }

    // plLayerInterface::Read: self-key + synched + underlay key
    // Use the correct (fixed) parsers from core::uoid
    let _self_key = read_key_uoid(&mut cursor)?;
    let _synched = SynchedObjectData::read(&mut cursor)?;
    let underlay = read_key_uoid(&mut cursor)?;
    Ok(underlay)
}

#[cfg(test)]
mod scroll_tests {
    use super::*;
    use std::path::Path;

    #[test]
    fn test_parse_cleft_layer_animation_scroll() {
        let path = Path::new("../../Plasma/staging/client/dat/Cleft_District_Cleft.prp");
        if !path.exists() {
            eprintln!("Skipping test: {:?} not found", path);
            return;
        }
        let page = PrpPage::from_file(path).unwrap();
        let mut parsed = 0;
        let mut ok = 0;
        let mut errs = 0;
        let mut with_scroll = 0;

        for key in page.keys_of_type(0x0043) { // plLayerAnimation
            if let Some(data) = page.object_data(key) {
                parsed += 1;
                match parse_layer_animation_scroll(data) {
                    Ok(Some(scroll)) => {
                        with_scroll += 1;
                        ok += 1;
                        eprintln!("  scroll '{}': u={:.4} v={:.4}", key.object_name, scroll.u, scroll.v);
                    }
                    Ok(None) => { ok += 1; }
                    Err(e) => {
                        errs += 1;
                        if errs <= 3 {
                            let hex: Vec<String> = data.iter().take(100).map(|b| format!("{:02x}", b)).collect();
                            eprintln!("  ERR '{}': {} (data: {}...)", key.object_name, e, hex.join(" "));
                        }
                    }
                }
            }
        }
        eprintln!("plLayerAnimation: {} total, {} ok, {} with scroll, {} errors",
            parsed, ok, with_scroll, errs);

        // Also test Teledahn which has water
        let path2 = Path::new("../../Plasma/staging/client/dat/Teledahn_District_Teledahn.prp");
        if !path2.exists() {
            eprintln!("Skipping Teledahn test");
            return;
        }
        let page2 = PrpPage::from_file(path2).unwrap();
        let mut t_parsed = 0;
        let mut t_ok = 0;
        let mut t_scroll = 0;
        let mut t_err = 0;
        for key in page2.keys_of_type(0x0043) {
            if let Some(data) = page2.object_data(key) {
                t_parsed += 1;
                match parse_layer_animation_scroll(data) {
                    Ok(Some(scroll)) => {
                        t_scroll += 1;
                        t_ok += 1;
                        eprintln!("  Teledahn scroll '{}': u={:.4} v={:.4}", key.object_name, scroll.u, scroll.v);
                    }
                    Ok(None) => { t_ok += 1; }
                    Err(_) => { t_err += 1; }
                }
            }
        }
        eprintln!("Teledahn plLayerAnimation: {} total, {} ok, {} with scroll, {} errors",
            t_parsed, t_ok, t_scroll, t_err);
    }

    #[test]
    fn test_parse_layer_animation_color_keys() {
        let path = Path::new("../../Plasma/staging/client/dat/Cleft_District_Cleft.prp");
        if !path.exists() { eprintln!("Skipping: {:?} not found", path); return; }
        let page = PrpPage::from_file(path).unwrap();
        let mut parsed = 0;
        let mut with_color = 0;
        let mut errors = 0;
        for key in page.keys_of_type(0x0043) {
            if let Some(data) = page.object_data(key) {
                parsed += 1;
                match parse_layer_animation_full(data) {
                    Ok(la) => {
                        let c = la.preshade_color_keys.len() + la.runtime_color_keys.len()
                            + la.ambient_color_keys.len() + la.specular_color_keys.len();
                        if c > 0 { with_color += 1; }
                    }
                    Err(_) => { errors += 1; }
                }
            }
        }
        eprintln!("Color test: {} total, {} with color, {} errors", parsed, with_color, errors);
        assert!(errors <= 2);
    }

    #[test]
    fn test_parse_layer_sdl_animation() {
        let path = Path::new("../../Plasma/staging/client/dat/Cleft_District_Cleft.prp");
        if !path.exists() { eprintln!("Skipping: {:?} not found", path); return; }
        let page = PrpPage::from_file(path).unwrap();
        let mut parsed = 0;
        let mut errors = 0;
        for key in page.keys_of_type(0x00F0) {
            if let Some(data) = page.object_data(key) {
                parsed += 1;
                match parse_layer_sdl_animation_full(data) {
                    Ok(la) => {
                        eprintln!("  SDL '{}': var={:?} len={:.2}s", key.object_name, la.sdl_var_name, la.length);
                    }
                    Err(_) => { errors += 1; }
                }
            }
        }
        eprintln!("SDL anim: {} total, {} errors", parsed, errors);
        if parsed > 0 { assert_eq!(errors, 0); }
    }
}

// ============================================================================
// plMipmap / plBitmap data extraction
// Translated from plMipmap::Read() in plMipmap.cpp, plBitmap::Read() in plBitmap.cpp
// ============================================================================

/// plBitmap compression types.
/// Translated from plBitmap enum in plBitmap.h
pub mod bitmap_compression {
    pub const UNCOMPRESSED: u8 = 0x0;
    pub const DIRECTX_COMPRESSION: u8 = 0x1;
    pub const JPEG_COMPRESSION: u8 = 0x2;
    pub const PNG_COMPRESSION: u8 = 0x3;
}

/// plBitmap::DirectXInfo::CompressionType.
/// Translated from plBitmap::DirectXInfo enum in plBitmap.h
pub mod dxt_type {
    pub const ERROR: u8 = 0x0;
    pub const DXT1: u8 = 0x1;
    // DXT2 = 0x2, DXT3 = 0x3, DXT4 = 0x4 — unused in Plasma
    pub const DXT5: u8 = 0x5;
}

/// plBitmap::UncompressedInfo::Type.
/// Translated from plBitmap::UncompressedInfo enum in plBitmap.h
pub mod uncompressed_type {
    pub const RGB8888: u8 = 0x00;
    pub const RGB4444: u8 = 0x01;
    pub const RGB1555: u8 = 0x02;
    pub const INTEN8: u8 = 0x03;
    pub const A_INTEN88: u8 = 0x04;
}

#[derive(Debug, Clone)]
pub struct MipmapData {
    pub name: String,
    pub width: u32,
    pub height: u32,
    /// plBitmap::fCompressionType — 0=uncompressed, 1=DirectX, 2=JPEG, 3=PNG
    pub compression: u8,
    /// For DirectX: DXT type (1=DXT1, 5=DXT5). For uncompressed: pixel type.
    pub pixel_format: u8,
    /// plBitmap::DirectXInfo::fBlockSize — 8 for DXT1, 16 for DXT5
    pub block_size: u8,
    /// plBitmap::fPixelSize — bits per pixel (8, 16, 32)
    pub pixel_size: u8,
    pub num_levels: u8,
    /// Raw pixel data for all mip levels, contiguous.
    /// Level 0 at offset 0, level 1 at offset level_sizes[0], etc.
    pub pixel_data: Vec<u8>,
    /// Size of each mip level in bytes.
    /// Translated from plMipmap::IBuildLevelSizes() in plMipmap.cpp
    pub level_sizes: Vec<u32>,
    /// plMipmap::fRowBytes — bytes per row at level 0
    pub row_bytes: u32,
}

impl MipmapData {
    /// Software-decode DXT1/DXT5 compressed texture to RGBA8 bytes.
    /// Returns None for uncompressed or unsupported formats.
    pub fn decode_to_rgba(&self) -> Option<Vec<u8>> {
        if self.compression != 1 { // Not DirectX compressed
            // Uncompressed 32-bit: Plasma stores as BGRA (hsColor32 { b, g, r, a }),
            // swizzle to RGBA for wgpu Rgba8Unorm format
            if self.pixel_size == 32 && !self.pixel_data.is_empty() {
                let pixel_count = (self.width * self.height) as usize;
                let expected = pixel_count * 4;
                if self.pixel_data.len() < expected { return None; }
                let mut rgba = vec![0u8; expected];
                for i in 0..pixel_count {
                    let s = i * 4;
                    rgba[s]     = self.pixel_data[s + 2]; // R ← byte 2
                    rgba[s + 1] = self.pixel_data[s + 1]; // G ← byte 1
                    rgba[s + 2] = self.pixel_data[s];     // B ← byte 0
                    rgba[s + 3] = self.pixel_data[s + 3]; // A ← byte 3
                }
                return Some(rgba);
            }
            return None;
        }
        let w = self.width as usize;
        let h = self.height as usize;
        if w == 0 || h == 0 { return None; }
        let blocks_wide = (w + 3) / 4;
        let blocks_high = (h + 3) / 4;
        let is_dxt5 = self.pixel_format == 5;
        let block_size: usize = if is_dxt5 { 16 } else { 8 };
        let needed = blocks_wide * blocks_high * block_size;
        if self.pixel_data.len() < needed { return None; }

        let mut rgba = vec![0u8; w * h * 4];
        let expand5 = |v: u8| -> u8 { (v << 3) | (v >> 2) };
        let expand6 = |v: u8| -> u8 { (v << 2) | (v >> 4) };

        for by in 0..blocks_high {
            for bx in 0..blocks_wide {
                let block_off = (by * blocks_wide + bx) * block_size;
                let color_off = if is_dxt5 { block_off + 8 } else { block_off };
                let cb = &self.pixel_data[color_off..color_off + 8];
                let c0 = u16::from_le_bytes([cb[0], cb[1]]);
                let c1 = u16::from_le_bytes([cb[2], cb[3]]);
                let (r0, g0, b0) = ((c0 >> 11) as u8 & 0x1F, (c0 >> 5) as u8 & 0x3F, c0 as u8 & 0x1F);
                let (r1, g1, b1) = ((c1 >> 11) as u8 & 0x1F, (c1 >> 5) as u8 & 0x3F, c1 as u8 & 0x1F);

                let colors: [[u8; 4]; 4] = if c0 > c1 {
                    let a = [expand5(r0), expand6(g0), expand5(b0), 255];
                    let b = [expand5(r1), expand6(g1), expand5(b1), 255];
                    let c2 = [((2*a[0] as u16+b[0] as u16)/3) as u8, ((2*a[1] as u16+b[1] as u16)/3) as u8, ((2*a[2] as u16+b[2] as u16)/3) as u8, 255];
                    let c3 = [((a[0] as u16+2*b[0] as u16)/3) as u8, ((a[1] as u16+2*b[1] as u16)/3) as u8, ((a[2] as u16+2*b[2] as u16)/3) as u8, 255];
                    [a, b, c2, c3]
                } else {
                    let a = [expand5(r0), expand6(g0), expand5(b0), 255];
                    let b = [expand5(r1), expand6(g1), expand5(b1), 255];
                    let c2 = [((a[0] as u16+b[0] as u16)/2) as u8, ((a[1] as u16+b[1] as u16)/2) as u8, ((a[2] as u16+b[2] as u16)/2) as u8, 255];
                    [a, b, c2, [0, 0, 0, 0]]
                };
                let indices = u32::from_le_bytes([cb[4], cb[5], cb[6], cb[7]]);

                let alpha_block: [u8; 16] = if is_dxt5 {
                    let ab = &self.pixel_data[block_off..block_off + 8];
                    let (a0, a1) = (ab[0], ab[1]);
                    let mut alphas = [0u8; 8];
                    alphas[0] = a0; alphas[1] = a1;
                    if a0 > a1 {
                        for i in 1..7u16 { alphas[(i+1) as usize] = (((7-i)*a0 as u16 + i*a1 as u16)/7) as u8; }
                    } else {
                        for i in 1..5u16 { alphas[(i+1) as usize] = (((5-i)*a0 as u16 + i*a1 as u16)/5) as u8; }
                        alphas[6] = 0; alphas[7] = 255;
                    }
                    let idx_bits = (ab[2] as u64)|((ab[3] as u64)<<8)|((ab[4] as u64)<<16)|((ab[5] as u64)<<24)|((ab[6] as u64)<<32)|((ab[7] as u64)<<40);
                    let mut result = [255u8; 16];
                    for i in 0..16 { result[i] = alphas[((idx_bits >> (i as u64 * 3)) & 7) as usize]; }
                    result
                } else { [255; 16] };

                for py in 0..4 {
                    for px in 0..4 {
                        let (x, y) = (bx * 4 + px, by * 4 + py);
                        if x >= w || y >= h { continue; }
                        let pi = py * 4 + px;
                        let ci = ((indices >> (pi * 2)) & 3) as usize;
                        let out = y * w * 4 + x * 4;
                        rgba[out] = colors[ci][0]; rgba[out+1] = colors[ci][1];
                        rgba[out+2] = colors[ci][2]; rgba[out+3] = alpha_block[pi];
                    }
                }
            }
        }
        Some(rgba)
    }

    /// Parse a plMipmap from raw object data.
    /// Translated from plMipmap::Read() in plMipmap.cpp
    /// Inheritance: plMipmap : plBitmap : hsKeyedObject (NO plSynchedObject!)
    pub fn from_object_data(data: &[u8], name: &str) -> Result<Self> {
        let mut cursor = Cursor::new(data);

        // Creatable class index (hsKeyedObject prologue)
        let class_idx = cursor.read_i16()?;
        if class_idx < 0 {
            bail!("Null creatable");
        }

        // hsKeyedObject::Read — key reference
        read_key_name(&mut cursor)?;

        // === plBitmap::Read(stream) ===
        // Translated from plBitmap::Read() in plBitmap.cpp
        let version = cursor.read_u8()?;  // sBitmapVersion, must be 2
        if version != 2 {
            bail!("Unsupported bitmap version: {} (expected 2)", version);
        }
        let pixel_size = cursor.read_u8()?;    // fPixelSize (bits per pixel)
        let _space = cursor.read_u8()?;         // fSpace
        let _flags = cursor.read_u16()?;        // fFlags
        let compression_type = cursor.read_u8()?; // fCompressionType

        // Compression-specific info — union in C++
        // Translated from plBitmap::Read() branch on fCompressionType
        let (pixel_format, block_size) = match compression_type {
            bitmap_compression::UNCOMPRESSED |
            bitmap_compression::JPEG_COMPRESSION |
            bitmap_compression::PNG_COMPRESSION => {
                // fUncompressedInfo.fType (1 byte)
                let fmt = cursor.read_u8()?;
                (fmt, 0u8)
            }
            bitmap_compression::DIRECTX_COMPRESSION => {
                // fDirectXInfo: fBlockSize (1 byte) + fCompressionType (1 byte)
                let bs = cursor.read_u8()?;
                let ct = cursor.read_u8()?;
                (ct, bs)
            }
            _ => {
                bail!("Unknown compression type: {}", compression_type);
            }
        };

        // Modification timestamps
        let _low_modified_time = cursor.read_u32()?;
        let _high_modified_time = cursor.read_u32()?;

        // === plMipmap::Read(stream) ===
        // Translated from plMipmap::Read() in plMipmap.cpp
        let width = cursor.read_u32()?;
        let height = cursor.read_u32()?;
        let row_bytes = cursor.read_u32()?;
        let total_size = cursor.read_u32()?;
        let num_levels = cursor.read_u8()?;

        if width == 0 || height == 0 {
            return Ok(Self {
                name: name.to_string(), width, height,
                compression: compression_type, pixel_format, block_size,
                pixel_size, num_levels, pixel_data: Vec::new(),
                level_sizes: Vec::new(), row_bytes,
            });
        }

        // IBuildLevelSizes() — compute per-level sizes
        // Translated from plMipmap::IBuildLevelSizes() in plMipmap.cpp
        let level_sizes = build_level_sizes(
            width, height, row_bytes, num_levels,
            compression_type, block_size,
        );

        // Read pixel data based on compression type
        // Translated from plMipmap::Read() dispatch in plMipmap.cpp
        let mut pixel_data = Vec::new();
        if total_size > 0 {
            let remaining = data.len().saturating_sub(cursor.position() as usize);
            let read_size = (total_size as usize).min(remaining);

            match compression_type {
                bitmap_compression::DIRECTX_COMPRESSION => {
                    // DirectX: raw read of fTotalSize bytes
                    // Translated from plMipmap::Read() — stream->Read(fTotalSize, fImage)
                    pixel_data = vec![0u8; read_size];
                    cursor.read_exact(&mut pixel_data)?;
                }
                bitmap_compression::UNCOMPRESSED => {
                    // IReadRawImage — reads level-by-level with endian swap
                    // Translated from plMipmap::IReadRawImage() in plMipmap.cpp
                    // On LE systems (x86/ARM), the u32/u16 reads are no-ops.
                    // We read raw bytes since our target is always LE.
                    pixel_data = vec![0u8; read_size];
                    cursor.read_exact(&mut pixel_data)?;
                }
                bitmap_compression::JPEG_COMPRESSION => {
                    // IReadJPEGImage — JPEG decompression not yet implemented.
                    // Read raw bytes for now; GPU upload will skip these.
                    pixel_data = vec![0u8; read_size];
                    cursor.read_exact(&mut pixel_data)?;
                    log::debug!("JPEG texture '{}' ({}x{}) — decompression not implemented",
                        name, width, height);
                }
                bitmap_compression::PNG_COMPRESSION => {
                    // IReadPNGImage — PNG decompression not yet implemented.
                    pixel_data = vec![0u8; read_size];
                    cursor.read_exact(&mut pixel_data)?;
                    log::debug!("PNG texture '{}' ({}x{}) — decompression not implemented",
                        name, width, height);
                }
                _ => {
                    bail!("Unknown compression type: {}", compression_type);
                }
            }
        }

        Ok(Self {
            name: name.to_string(),
            width,
            height,
            compression: compression_type,
            pixel_format,
            block_size,
            pixel_size,
            num_levels,
            pixel_data,
            level_sizes,
            row_bytes,
        })
    }

    /// Parse a plCubicEnvironmap and extract the first face as a regular mipmap.
    /// C++ ref: plCubicEnvironmap::Read (plCubicEnvironmap.cpp:99-110)
    /// Format: hsKeyedObject + plBitmap (outer) + 6 × plMipmap (face)
    /// Each face's plMipmap::Read includes its own plBitmap::Read + mipmap data.
    /// Read all 6 faces from a plCubicEnvironmap.
    /// C++ ref: plCubicEnvironmap.cpp:99-110 — reads 6 plMipmap faces in order:
    /// kLeftFace=0, kRightFace=1, kFrontFace=2, kBackFace=3, kTopFace=4, kBottomFace=5
    pub fn from_cubic_envmap_data(data: &[u8], name: &str) -> Result<Vec<Self>> {
        let mut cursor = Cursor::new(data);

        // hsKeyedObject prologue
        let class_idx = cursor.read_i16()?;
        if class_idx < 0 { bail!("Null creatable"); }
        read_key_name(&mut cursor)?;

        // Outer plBitmap::Read — skip (face bitmaps have their own headers)
        Self::skip_bitmap_header(&mut cursor)?;

        // Read all 6 faces
        let mut faces = Vec::with_capacity(6);
        for i in 0..6 {
            let face_name = format!("{}_face{}", name, i);
            let face = Self::read_mipmap_from_cursor(&mut cursor, &face_name)?;
            faces.push(face);
        }
        Ok(faces)
    }

    /// Skip a plBitmap header in the stream.
    fn skip_bitmap_header(cursor: &mut Cursor<&[u8]>) -> Result<()> {
        let _version = cursor.read_u8()?;
        let _pixel_size = cursor.read_u8()?;
        let _space = cursor.read_u8()?;
        let _flags = cursor.read_u16()?;
        let compression_type = cursor.read_u8()?;
        match compression_type {
            bitmap_compression::UNCOMPRESSED |
            bitmap_compression::JPEG_COMPRESSION |
            bitmap_compression::PNG_COMPRESSION => { cursor.skip(1)?; }
            bitmap_compression::DIRECTX_COMPRESSION => { cursor.skip(2)?; }
            _ => { bail!("Unknown compression type: {}", compression_type); }
        }
        cursor.skip(8)?; // timestamps
        Ok(())
    }

    /// Read a plMipmap (plBitmap header + mipmap data) from the current cursor position.
    fn read_mipmap_from_cursor(cursor: &mut Cursor<&[u8]>, name: &str) -> Result<Self> {
        // plBitmap::Read
        let version = cursor.read_u8()?;
        if version != 2 { bail!("Unsupported bitmap version: {}", version); }
        let pixel_size = cursor.read_u8()?;
        let _space = cursor.read_u8()?;
        let _flags = cursor.read_u16()?;
        let compression_type = cursor.read_u8()?;
        let (pixel_format, block_size) = match compression_type {
            bitmap_compression::UNCOMPRESSED |
            bitmap_compression::JPEG_COMPRESSION |
            bitmap_compression::PNG_COMPRESSION => { (cursor.read_u8()?, 0u8) }
            bitmap_compression::DIRECTX_COMPRESSION => {
                let bs = cursor.read_u8()?;
                let ct = cursor.read_u8()?;
                (ct, bs)
            }
            _ => { bail!("Unknown compression type: {}", compression_type); }
        };
        cursor.skip(8)?; // timestamps

        // plMipmap data
        let width = cursor.read_u32()?;
        let height = cursor.read_u32()?;
        let row_bytes = cursor.read_u32()?;
        let total_size = cursor.read_u32()?;
        let num_levels = cursor.read_u8()?;

        if width == 0 || height == 0 || total_size == 0 {
            return Ok(Self {
                name: name.to_string(), width, height,
                compression: compression_type, pixel_format, block_size,
                pixel_size, num_levels, pixel_data: Vec::new(),
                level_sizes: Vec::new(), row_bytes,
            });
        }

        let level_sizes = build_level_sizes(width, height, row_bytes, num_levels, compression_type, block_size);
        let remaining = cursor.get_ref().len().saturating_sub(cursor.position() as usize);
        let read_size = (total_size as usize).min(remaining);
        let mut pixel_data = vec![0u8; read_size];
        cursor.read_exact(&mut pixel_data)?;

        Ok(Self {
            name: name.to_string(), width, height,
            compression: compression_type, pixel_format, block_size,
            pixel_size, num_levels, pixel_data, level_sizes, row_bytes,
        })
    }
}

/// Compute per-level byte sizes for all mip levels.
/// Translated from plMipmap::IBuildLevelSizes() in plMipmap.cpp
fn build_level_sizes(
    width: u32, height: u32, row_bytes: u32, num_levels: u8,
    compression_type: u8, block_size: u8,
) -> Vec<u32> {
    let mut sizes = Vec::with_capacity(num_levels as usize);
    let mut w = width;
    let mut h = height;
    let mut rb = row_bytes;

    for _ in 0..num_levels {
        let level_size = if compression_type == bitmap_compression::DIRECTX_COMPRESSION {
            // Translated from plMipmap::IBuildLevelSizes() DXT path
            if (w | h) & 0x03 != 0 {
                // Sub-4x4 block: use height × rowBytes
                h * rb
            } else {
                // Full blocks: (height × width × blockSize) >> 4
                (h * w * block_size as u32) >> 4
            }
        } else {
            // Uncompressed / JPEG / PNG: height × rowBytes
            h * rb
        };

        sizes.push(level_size);

        // Scale down for next level
        // Translated from plMipmap::IBuildLevelSizes() mip reduction
        if w > 1 { w >>= 1; rb >>= 1; }
        if h > 1 { h >>= 1; }
    }

    sizes
}

// ============================================================================
// plPythonFileMod — parse script filename, receivers, and parameters
// ============================================================================

/// Parsed parameter from a plPythonFileMod.
/// C++ ref: plPythonParameter.h:59-475
#[derive(Debug, Clone)]
pub enum PythonParamValue {
    Int(i32),
    Float(f32),
    Bool(bool),
    String(String),
    Key(Option<crate::core::uoid::Uoid>),
    None,
}

/// A single script parameter (id + typed value).
#[derive(Debug, Clone)]
pub struct PythonParam {
    pub id: i32,
    pub value_type: i32,
    pub value: PythonParamValue,
}

/// Parsed plPythonFileMod data from a PRP object.
#[derive(Debug, Clone)]
pub struct PythonFileModData {
    /// Script filename (e.g. "Cleft.py")
    pub script_file: String,
    /// Receiver keys — scene objects that notify this script
    pub receivers: Vec<crate::core::uoid::Uoid>,
    /// Script parameters set in 3ds Max
    pub parameters: Vec<PythonParam>,
    /// The Uoid of the plPythonFileMod object itself (for receiver matching)
    pub self_key: Option<crate::core::uoid::Uoid>,
}

/// Parse a plPythonFileMod from raw PRP object data.
///
/// Serialization chain:
///   class_idx(i16) → hsKeyedObject(self-key) → plSynchedObject → plMultiModifier(hsBitVector) →
///   SafeString(filename) → u32(receiver count) → keys → u32(param count) → params
///
/// C++ ref: plPythonFileMod.cpp:1686-1704, plPythonParameter.h:362-421
pub fn parse_python_file_mod(data: &[u8]) -> Result<PythonFileModData> {
    use crate::core::uoid::read_key_uoid;

    let mut cursor = Cursor::new(data);

    // Creatable class index (i16)
    let _class_idx = cursor.read_i16()?;

    // hsKeyedObject::Read — self-key
    let self_key = read_key_uoid(&mut cursor)?;

    // plSynchedObject::Read
    skip_synched_object(&mut cursor)?;

    // plMultiModifier::Read — hsBitVector
    // C++ ref: hsBitVector.cpp:90-101 — u32 count, then count × u32 words
    let num_bit_vectors = cursor.read_u32()?;
    for _ in 0..num_bit_vectors {
        let _word = cursor.read_u32()?;
    }

    // plPythonFileMod data
    let script_file = cursor.read_safe_string()?;

    // Receiver keys
    let num_receivers = cursor.read_u32()?;
    let mut receivers = Vec::with_capacity(num_receivers as usize);
    for _ in 0..num_receivers {
        if let Some(uoid) = read_key_uoid(&mut cursor)? {
            receivers.push(uoid);
        }
    }

    // Parameters
    let num_params = cursor.read_u32()?;
    let mut parameters = Vec::with_capacity(num_params as usize);
    for _ in 0..num_params {
        let id = cursor.read_i32()?;
        let value_type = cursor.read_i32()?;

        // C++ plPythonParameter::valueType enum starts at kInt=1
        let value = match value_type {
            1 => { // kInt
                let v = cursor.read_i32()?;
                PythonParamValue::Int(v)
            }
            2 => { // kFloat
                let v = cursor.read_f32()?;
                PythonParamValue::Float(v)
            }
            3 => { // kbool — C++ ReadBOOL() reads 4 bytes (hsStream.h:90)
                let v = cursor.read_u32()?;
                PythonParamValue::Bool(v != 0)
            }
            4 | 13 => { // kString, kAnimationName
                let count = cursor.read_u32()? as usize;
                if count > 0 {
                    let mut buf = vec![0u8; count - 1];
                    cursor.read_exact(&mut buf)?;
                    let _null = cursor.read_u8()?; // consume null terminator
                    PythonParamValue::String(String::from_utf8_lossy(&buf).into_owned())
                } else {
                    PythonParamValue::String(String::new())
                }
            }
            5..=12 | 14..=23 => { // All key types
                let uoid = read_key_uoid(&mut cursor)?;
                PythonParamValue::Key(uoid)
            }
            24 => { // kNone
                PythonParamValue::None
            }
            _ => {
                log::warn!("Unknown plPythonParameter type {}", value_type);
                PythonParamValue::None
            }
        };

        parameters.push(PythonParam { id, value_type, value });
    }

    Ok(PythonFileModData {
        script_file,
        receivers,
        parameters,
        self_key,
    })
}

// ============================================================================
// plInterfaceInfoModifier — identifies clickable objects
// ============================================================================

/// Parsed plInterfaceInfoModifier: marks an object as clickable and lists its logic modifiers.
/// C++ ref: plInterfaceInfoModifier.cpp:60-67
#[derive(Debug, Clone)]
pub struct InterfaceInfoModData {
    pub self_key: Option<crate::core::uoid::Uoid>,
    /// Keys to plLogicModifier instances on this clickable object.
    pub logic_keys: Vec<crate::core::uoid::Uoid>,
}

/// Parse plInterfaceInfoModifier from PRP object data.
/// Format: plSingleModifier::Read (self-key + synched + hsBitVector) → u32 key_count → keys
pub fn parse_interface_info_modifier(data: &[u8]) -> Result<InterfaceInfoModData> {
    use crate::core::uoid::read_key_uoid;
    let mut cursor = Cursor::new(data);

    let _class_idx = cursor.read_i16()?;
    let self_key = read_key_uoid(&mut cursor)?;
    skip_synched_object(&mut cursor)?;
    // hsBitVector fFlags
    let n_words = cursor.read_u32()?;
    for _ in 0..n_words { let _ = cursor.read_u32()?; }

    let key_count = cursor.read_u32()?;
    let mut logic_keys = Vec::with_capacity(key_count as usize);
    for _ in 0..key_count {
        if let Some(uoid) = read_key_uoid(&mut cursor)? {
            logic_keys.push(uoid);
        }
    }

    Ok(InterfaceInfoModData { self_key, logic_keys })
}

// ============================================================================
// plOneShotMod — one-shot avatar animation modifier
// ============================================================================

/// Parsed plOneShotMod: holds animation name and seek parameters for one-shot behaviors.
/// C++ ref: plOneShotMod.h:54-82, plOneShotMod.cpp:154-165
#[derive(Debug, Clone)]
pub struct OneShotModData {
    pub self_key: Option<crate::core::uoid::Uoid>,
    /// The name of the animation to play (e.g., "ClickTurnLeft").
    pub anim_name: String,
    /// How long to seek to the one-shot position (seconds).
    pub seek_duration: f32,
    /// Whether the user can control animation progress.
    pub drivable: bool,
    /// Whether the user can reverse the animation.
    pub reversable: bool,
    /// Use smart seek to walk to the seek point.
    pub smart_seek: bool,
    /// Skip seeking entirely (teleport to position).
    pub no_seek: bool,
}

/// Parse plOneShotMod from PRP object data.
/// Format: plMultiModifier::Read (self-key + synched + hsBitVector) → SafeString animName
///         → f32 seekDuration → bool×4 (drivable, reversable, smartSeek, noSeek)
/// C++ ref: plOneShotMod.cpp:154-165
pub fn parse_one_shot_mod(data: &[u8]) -> Result<OneShotModData> {
    use crate::core::uoid::read_key_uoid;
    let mut cursor = Cursor::new(data);

    // Creatable class index (i16)
    let _class_idx = cursor.read_i16()?;

    // hsKeyedObject::Read — self-key
    let self_key = read_key_uoid(&mut cursor)?;

    // plSynchedObject::Read
    skip_synched_object(&mut cursor)?;

    // plMultiModifier::Read — hsBitVector fFlags
    let num_bit_vectors = cursor.read_u32()?;
    for _ in 0..num_bit_vectors {
        let _word = cursor.read_u32()?;
    }

    // plOneShotMod data
    let anim_name = cursor.read_safe_string()?;
    let seek_duration = cursor.read_f32()?;
    let drivable = cursor.read_u8()? != 0;     // ReadBool = 1 byte
    let reversable = cursor.read_u8()? != 0;
    let smart_seek = cursor.read_u8()? != 0;
    let no_seek = cursor.read_u8()? != 0;

    Ok(OneShotModData {
        self_key,
        anim_name,
        seek_duration,
        drivable,
        reversable,
        smart_seek,
        no_seek,
    })
}

// ============================================================================
// plLogicModifier — evaluates conditions and sends plNotifyMsg
// ============================================================================

/// Parsed plLogicModifier — enough data for click dispatch.
/// C++ ref: plLogicModifier.cpp:259-271, plLogicModBase.cpp:280-297
#[derive(Debug, Clone)]
pub struct LogicModData {
    pub self_key: Option<crate::core::uoid::Uoid>,
    /// Notify receiver keys (from the embedded plNotifyMsg).
    pub notify_receivers: Vec<crate::core::uoid::Uoid>,
    /// fID from the embedded plNotifyMsg — passed as `id` to script OnNotify.
    /// C++ ref: plNotifyMsg.cpp:812 — fID read as i32 after fType and fState.
    pub notify_id: i32,
    /// Cursor type from fMyCursor. C++ ref: plCursorChangeMsg cursor types.
    pub cursor_type: i32,
    /// Condition keys from plLogicModifier::fConditionList.
    /// C++ ref: plLogicModifier.cpp:Read — ReadKeyNotifyMe for each condition.
    pub condition_keys: Vec<crate::core::uoid::Uoid>,
    /// plLogicModBase flags (hsBitVector).
    /// C++ ref: plLogicModBase.h — kOneShot=0x4, kMultiTrigger=0x8, etc.
    pub flags: u32,
    /// Whether this logic modifier is disabled.
    /// C++ ref: plLogicModBase::fDisabled
    pub disabled: bool,
}

/// Parse plLogicModifier from PRP object data.
///
/// We parse just enough to extract notify receivers and cursor type,
/// skipping the full command list and condition list deserialization.
/// Format: plSingleModifier + plLogicModBase(commands + notify + flags + disabled)
///         + u32 condition_count + condition_keys + i32 cursor_type
pub fn parse_logic_modifier(data: &[u8]) -> Result<LogicModData> {
    use crate::core::uoid::read_key_uoid;
    let mut cursor = Cursor::new(data);

    let _class_idx = cursor.read_i16()?;
    let self_key = read_key_uoid(&mut cursor)?;
    skip_synched_object(&mut cursor)?;
    // hsBitVector fFlags (plSingleModifier)
    let n_words = cursor.read_u32()?;
    for _ in 0..n_words { let _ = cursor.read_u32()?; }

    // plLogicModBase::Read
    // u32 command_count, then skip creatables (complex — we skip by scanning)
    let cmd_count = cursor.read_u32()?;
    for _ in 0..cmd_count {
        // Each command is a ReadCreatable: i16 class_idx, then object data.
        // We can't easily skip these without knowing each type's size,
        // so for now only support cmd_count == 0 (common for click activators).
        if cmd_count > 0 {
            // Can't skip commands — return partial data
            return Ok(LogicModData {
                self_key,
                notify_receivers: Vec::new(),
                notify_id: 0,
                cursor_type: 0,
                condition_keys: Vec::new(),
                flags: 0,
                disabled: false,
            });
        }
    }

    // fNotify: ReadCreatable → plNotifyMsg
    // Read class index for the plNotifyMsg creatable
    let notify_class = cursor.read_i16()?;
    let mut notify_receivers = Vec::new();
    let mut notify_id = 0i32;
    if notify_class >= 0 {
        // plNotifyMsg inherits plMessage which has sender + receivers
        // plMessage::IMsgRead: sender_key, then u32 num_receivers, then receiver keys,
        //   then f64 timestamp, then BCastFlags (u32)
        let _sender = read_key_uoid(&mut cursor)?;
        let num_receivers = cursor.read_u32()?;
        for _ in 0..num_receivers {
            if let Some(uoid) = read_key_uoid(&mut cursor)? {
                notify_receivers.push(uoid);
            }
        }
        let _timestamp = cursor.read_f32()?; let _ = cursor.read_f32()?; // f64 as 2×f32
        let _bcast_flags = cursor.read_u32()?;

        // plNotifyMsg own data: fType(i32), fState(f32), fID(i32)
        // C++ ref: plNotifyMsg.cpp:809-815
        let _notify_type = cursor.read_i32()?;
        let _notify_state = cursor.read_f32()?;
        notify_id = cursor.read_i32()?;

        // event_count(u32) + events — skip
        let num_events = cursor.read_u32()?;
        for _ in 0..num_events {
            let event_type = cursor.read_i32()?;
            match event_type {
                1 => cursor.skip(1 + 1)?,     // kCollision: 2 bools
                7 => cursor.skip(1 + 1)?,     // kActivate: 2 bools
                8 => cursor.skip(4)?,         // kCallback: i32
                9 => cursor.skip(4)?,         // kResponderState: i32
                _ => {} // other types may have keys — stop parsing
            }
        }
    }

    // hsBitVector fFlags (plLogicModBase)
    let n_words2 = cursor.read_u32()?;
    let flags = if n_words2 > 0 { cursor.read_u32()? } else { 0 };
    for _ in 1..n_words2 { let _ = cursor.read_u32()?; }

    // bool fDisabled
    let disabled = cursor.read_u8()? != 0;

    // plLogicModifier own data:
    // u32 condition_count, condition keys (ReadKeyNotifyMe = regular key read)
    let cond_count = cursor.read_u32()?;
    let mut condition_keys = Vec::with_capacity(cond_count as usize);
    for _ in 0..cond_count {
        if let Some(key) = read_key_uoid(&mut cursor)? {
            condition_keys.push(key);
        }
    }

    // i32 fMyCursor
    let cursor_type = cursor.read_i32()?;

    Ok(LogicModData {
        self_key,
        notify_receivers,
        notify_id,
        cursor_type,
        condition_keys,
        flags,
        disabled,
    })
}

// ============================================================================
// plResponderModifier — state machine that executes command sequences
// ============================================================================

/// A one-shot callback entry from plOneShotCallbacks.
/// C++ ref: plOneShotCallbacks.h:65-73
#[derive(Debug, Clone)]
pub struct OneShotCallback {
    /// Animation marker name (e.g., "Touch" — resolved to time at runtime).
    pub marker: String,
    /// Key of the object to notify when this marker is reached.
    pub receiver: Option<crate::core::uoid::Uoid>,
    /// User data passed back with the callback.
    pub user: i16,
}

/// A parsed command from a responder state.
#[derive(Debug, Clone)]
pub struct ResponderCmd {
    /// Class index of the command message (e.g., 0x0206 = plAnimCmdMsg).
    pub class_id: u16,
    /// Callback wait dependency (-1 = none).
    pub wait_on: i8,
    /// For plAnimCmdMsg: animation name.
    pub anim_name: Option<String>,
    /// For plAnimCmdMsg: command flags (hsBitVector word 0).
    pub anim_flags: u32,
    /// For plNotifyMsg: receiver keys.
    pub notify_receivers: Vec<crate::core::uoid::Uoid>,
    /// Receiver keys from the base plMessage (target objects for the command).
    pub msg_receivers: Vec<crate::core::uoid::Uoid>,
    /// For plSoundMsg: sound index.
    pub sound_index: i32,
    /// For plSoundMsg: command flags (hsBitVector word 0).
    pub sound_flags: u32,
    /// For plOneShotMsg: animation callbacks (marker → receiver).
    /// C++ ref: plOneShotCallbacks.h — sent when animation reaches named markers.
    pub oneshot_callbacks: Vec<OneShotCallback>,
    /// For plTimerCallbackMsg: timer ID (callback wait ID).
    /// C++ ref: plTimerCallbackMsg.h — fID returned when timer fires.
    pub timer_id: i32,
    /// For plTimerCallbackMsg: delay in seconds.
    /// C++ ref: plTimerCallbackMsg.h — fTime passed to plgTimerCallbackMgr::NewTimer.
    pub timer_delay: f32,
    /// For plEnableMsg: enable/disable command flags.
    /// C++ ref: plEnableMsg.h — hsBitVector fCmd (bit 0 = disable, bit 1 = enable).
    pub enable_cmd: u32,
}

/// A parsed responder state.
#[derive(Debug, Clone)]
pub struct ResponderState {
    pub num_callbacks: u8,
    pub switch_to_state: u8,
    pub commands: Vec<ResponderCmd>,
}

/// Parsed plResponderModifier.
/// C++ ref: plResponderModifier.cpp:627-665
#[derive(Debug, Clone)]
pub struct ResponderModData {
    pub self_key: Option<crate::core::uoid::Uoid>,
    pub states: Vec<ResponderState>,
    pub cur_state: u8,
    pub enabled: bool,
    pub flags: u8,
    /// Runtime: current command index during execution (-1 = not running).
    /// C++ ref: plResponderModifier::fCurCommand
    pub cur_command: i32,
    /// Runtime: bitfield of completed callback events.
    /// C++ ref: plResponderModifier::fCompletedEvents
    pub completed_events: u64,
    /// Runtime: the key that triggered this responder (for NotifyMsg receiver substitution).
    /// C++ ref: plResponderModifier::fTriggerer — set from msg->GetSender() in Trigger()
    pub triggerer: Option<crate::core::uoid::Uoid>,
}

/// Read plMessage::IMsgRead base fields, returning (sender, receivers).
/// C++ ref: plMessage.cpp:109-121
fn read_msg_base(cursor: &mut Cursor<&[u8]>) -> Result<(Option<crate::core::uoid::Uoid>, Vec<crate::core::uoid::Uoid>)> {
    use crate::core::uoid::read_key_uoid;
    let sender = read_key_uoid(cursor)?;
    let num_receivers = cursor.read_u32()?;
    let mut receivers = Vec::with_capacity(num_receivers as usize);
    for _ in 0..num_receivers {
        if let Some(u) = read_key_uoid(cursor)? {
            receivers.push(u);
        }
    }
    // f64 timestamp + u32 BCastFlags
    cursor.skip(12)?;
    Ok((sender, receivers))
}

/// Read plMessageWithCallbacks (extends plMessage with callback list).
/// Returns (sender, receivers, num_callbacks_skipped).
/// C++ ref: plMessageWithCallbacks.cpp:66-79
fn read_msg_with_callbacks(cursor: &mut Cursor<&[u8]>) -> Result<(Option<crate::core::uoid::Uoid>, Vec<crate::core::uoid::Uoid>)> {
    let (sender, receivers) = read_msg_base(cursor)?;
    let num_callbacks = cursor.read_u32()?;
    // Each callback is a ReadCreatable (plEventCallbackMsg)
    for _ in 0..num_callbacks {
        let cb_class = cursor.read_i16()?;
        if cb_class >= 0 {
            // plEventCallbackMsg: IMsgRead + f32 + 4×i16
            let _ = read_msg_base(cursor)?;
            cursor.skip(12)?; // f32 eventTime + i16×4 (event, index, repeats, user)
        }
    }
    Ok((sender, receivers))
}

/// Parse a single responder command (creatable message).
/// Returns None if the command type is unknown and can't be skipped.
fn parse_responder_cmd(cursor: &mut Cursor<&[u8]>) -> Result<Option<ResponderCmd>> {
    let class_id = cursor.read_u16()?;

    let mut cmd = ResponderCmd {
        class_id,
        wait_on: -1,
        anim_name: None,
        anim_flags: 0,
        notify_receivers: Vec::new(),
        msg_receivers: Vec::new(),
        sound_index: -1,
        sound_flags: 0,
        oneshot_callbacks: Vec::new(),
        timer_id: -1,
        timer_delay: 0.0,
        enable_cmd: 0,
    };

    match class_id {
        0x0206 => { // plAnimCmdMsg
            let (_, receivers) = read_msg_with_callbacks(cursor)?;
            cmd.msg_receivers = receivers;
            // hsBitVector fCmd
            let n = cursor.read_u32()?;
            cmd.anim_flags = if n > 0 { cursor.read_u32()? } else { 0 };
            for _ in 1..n { let _ = cursor.read_u32()?; }
            // f32 × 7: begin, end, loopEnd, loopBegin, speed, speedChangeRate, time
            cursor.skip(28)?;
            // SafeString animName, loopName
            cmd.anim_name = Some(cursor.read_safe_string()?);
            let _loop_name = cursor.read_safe_string()?;
        }
        0x025A => { // plSoundMsg
            let (_, receivers) = read_msg_with_callbacks(cursor)?;
            cmd.msg_receivers = receivers;
            // hsBitVector fCmd
            let n = cursor.read_u32()?;
            cmd.sound_flags = if n > 0 { cursor.read_u32()? } else { 0 };
            for _ in 1..n { let _ = cursor.read_u32()?; }
            // f64 begin, f64 end, bool loop, bool playing, f32 speed, f64 time
            cursor.skip(8 + 8 + 1 + 1 + 4 + 8)?;
            // i32 index, i32 repeats, u32 nameStr, f32 volume, u8 fadeType
            cmd.sound_index = cursor.read_i32()?;
            cursor.skip(4 + 4 + 4 + 1)?;
        }
        0x02ED => { // plNotifyMsg
            let (_, receivers) = read_msg_base(cursor)?;
            cmd.msg_receivers = receivers.clone();
            cmd.notify_receivers = receivers;
            // fType(i32), fState(f32), fID(i32)
            cursor.skip(12)?;
            // u32 numEvents, then events
            let num_events = cursor.read_u32()?;
            for _ in 0..num_events {
                let event_type = cursor.read_i32()?;
                // Skip event-specific data based on type
                match event_type {
                    1 => cursor.skip(1 + 1)?, // kCollision: 2 bools (keys read as nil)
                    2 => cursor.skip(1 + 12)?, // kPicked: bool + hitPoint(3×f32) (keys read as nil)
                    3 => cursor.skip(4 + 1)?, // kControlKey: i32 + bool
                    7 => cursor.skip(1 + 1)?, // kActivate: 2 bools
                    8 => cursor.skip(4)?,     // kCallback: i32
                    9 => cursor.skip(4)?,     // kResponderState: i32
                    _ => {
                        // Complex event types with keys — bail
                        return Ok(Some(cmd));
                    }
                }
            }
        }
        0x0254 => { // plEnableMsg
            let (_, receivers) = read_msg_base(cursor)?;
            cmd.msg_receivers = receivers;
            // hsBitVector fCmd (bit 0 = disable, bit 1 = enable)
            let n1 = cursor.read_u32()?;
            cmd.enable_cmd = if n1 > 0 { cursor.read_u32()? } else { 0 };
            for _ in 1..n1 { let _ = cursor.read_u32()?; }
            // hsBitVector fTypes
            let n2 = cursor.read_u32()?;
            for _ in 0..n2 { let _ = cursor.read_u32()?; }
        }
        0x024F => { // plTimerCallbackMsg
            let (_, receivers) = read_msg_base(cursor)?;
            cmd.msg_receivers = receivers;
            cmd.timer_id = cursor.read_i32()?;
            cmd.timer_delay = cursor.read_f32()?;
        }
        0x020A => { // plCameraMsg
            let (_, receivers) = read_msg_base(cursor)?;
            cmd.msg_receivers = receivers;
            // hsBitVector fCmd
            let n = cursor.read_u32()?;
            for _ in 0..n { let _ = cursor.read_u32()?; }
            // f64 transTime, bool activated
            cursor.skip(8 + 1)?;
            // Key newCam, Key triggerer
            let _ = crate::core::uoid::read_key_uoid(cursor)?;
            let _ = crate::core::uoid::read_key_uoid(cursor)?;
            // plCameraConfig: 8×f32 + 3×f32(offset) + bool
            cursor.skip(44 + 1)?;
        }
        0x0302 => { // plResponderEnableMsg
            let (_, receivers) = read_msg_base(cursor)?;
            cmd.msg_receivers = receivers;
            cursor.skip(1)?; // bool fEnable
        }
        0x0306 => { // plResponderMsg
            let (_, receivers) = read_msg_base(cursor)?;
            cmd.msg_receivers = receivers;
            // No additional fields serialized
        }
        0x0332 => { // plAGCmdMsg
            let (_, receivers) = read_msg_base(cursor)?;
            cmd.msg_receivers = receivers;
            // hsBitVector fCmd
            let n = cursor.read_u32()?;
            for _ in 0..n { let _ = cursor.read_u32()?; }
            // f32×4: blend, blendRate, amp, ampRate
            cursor.skip(16)?;
            // SafeString animName
            cmd.anim_name = Some(cursor.read_safe_string()?);
        }
        0x0335 => { // plExcludeRegionMsg
            let (_, receivers) = read_msg_base(cursor)?;
            cmd.msg_receivers = receivers;
            // u8 fCmd, u32 fSynchFlags
            cursor.skip(1 + 4)?;
        }
        0x0307 => { // plOneShotMsg (extends plResponderMsg)
            let (_, receivers) = read_msg_base(cursor)?;
            cmd.msg_receivers = receivers;
            // plOneShotCallbacks::Read — u32 count, then (SafeString + plKey + i16) triples
            // C++ ref: plOneShotCallbacks.cpp:72-84
            let n = cursor.read_u32()?;
            for _ in 0..n {
                let marker = cursor.read_safe_string()?;
                let receiver = crate::core::uoid::read_key_uoid(cursor)?;
                let user = cursor.read_i16()?;
                cmd.oneshot_callbacks.push(OneShotCallback { marker, receiver, user });
            }
        }
        0x03BF => { // plSubWorldMsg
            let (_, receivers) = read_msg_base(cursor)?;
            cmd.msg_receivers = receivers;
            let _ = crate::core::uoid::read_key_uoid(cursor)?; // fWorldKey
        }
        0x0453 => { // plSimSuppressMsg
            let (_, receivers) = read_msg_base(cursor)?;
            cmd.msg_receivers = receivers;
            cursor.skip(1)?; // bool fSuppress
        }
        0x0393 => { // plArmatureEffectStateMsg
            // C++ ref: plArmatureEffectMsg.cpp — IMsgRead + u8 surface + bool addSurface
            let (_, receivers) = read_msg_base(cursor)?;
            cmd.msg_receivers = receivers;
            cursor.skip(1 + 1)?; // u8 fSurface + bool fAddSurface
        }
        _ => {
            // Unknown command type — can't skip, return what we have
            log::debug!("Unknown responder command class 0x{:04X}", class_id);
            return Ok(None);
        }
    }

    Ok(Some(cmd))
}

/// Parse plResponderModifier from PRP object data.
/// C++ ref: plResponderModifier.cpp:627-665
pub fn parse_responder_modifier(data: &[u8]) -> Result<ResponderModData> {
    use crate::core::uoid::read_key_uoid;
    let mut cursor = Cursor::new(data);

    // plSingleModifier::Read
    let _class_idx = cursor.read_i16()?;
    let self_key = read_key_uoid(&mut cursor)?;
    skip_synched_object(&mut cursor)?;
    let n_flags = cursor.read_u32()?;
    for _ in 0..n_flags { let _ = cursor.read_u32()?; }

    let num_states = cursor.read_u8()?;
    let mut states = Vec::with_capacity(num_states as usize);
    let mut parse_ok = true;

    for _si in 0..num_states {
        if !parse_ok { break; }

        let num_callbacks = cursor.read_u8()?;
        let switch_to_state = cursor.read_u8()?;
        let num_cmds = cursor.read_u8()?;

        let mut commands = Vec::with_capacity(num_cmds as usize);
        for _ in 0..num_cmds {
            if !parse_ok { break; }
            match parse_responder_cmd(&mut cursor) {
                Ok(Some(mut cmd)) => {
                    let wait_on = cursor.read_u8()? as i8;
                    cmd.wait_on = wait_on;
                    commands.push(cmd);
                }
                Ok(None) => {
                    // Unknown command — can't continue parsing
                    parse_ok = false;
                    break;
                }
                Err(e) => {
                    log::debug!("Responder cmd parse error: {}", e);
                    parse_ok = false;
                    break;
                }
            }
        }

        if parse_ok {
            // Read wait-to-cmd map
            let map_size = cursor.read_u8()?;
            for _ in 0..map_size {
                let _wait = cursor.read_u8()?;
                let _cmd = cursor.read_u8()?;
            }
        }

        states.push(ResponderState {
            num_callbacks,
            switch_to_state,
            commands,
        });
    }

    // Read footer fields only if all states parsed successfully
    let (cur_state, enabled, flags) = if parse_ok {
        let cs = cursor.read_u8()?;
        let en = cursor.read_u8()? != 0; // ReadBool = 1 byte (hsStream.h:91)
        let fl = cursor.read_u8()?;
        (cs, en, fl)
    } else {
        (0, true, 0x01) // defaults: state 0, enabled, kDetectTrigger
    };

    Ok(ResponderModData {
        self_key,
        states,
        cur_state,
        enabled,
        flags,
        cur_command: -1,
        completed_events: 0,
        triggerer: None,
    })
}

// ============================================================================
// plObjectInVolumeDetector — trigger volume (class 0x007B)
// C++ ref: plCollisionDetector.cpp:215-219, plDetectorModifier.cpp:50-60
// ============================================================================

/// Parsed plObjectInVolumeDetector data.
#[derive(Debug, Clone)]
pub struct VolumeDetectorData {
    pub name: String,
    /// Collision type flags (kTypeEnter=0x01, kTypeExit=0x02, etc.)
    pub collision_type: u8,
    /// Keys of modifiers to notify (plLogicModifier, plResponderModifier, etc.)
    pub receivers: Vec<crate::core::uoid::Uoid>,
    /// Optional proxy key — alternative hitee for activation messages.
    pub proxy_key: Option<crate::core::uoid::Uoid>,
}

/// Parse plObjectInVolumeDetector from PRP object data.
///
/// Inheritance: plObjectInVolumeDetector → plCollisionDetector → plDetectorModifier
///              → plSingleModifier → plModifier → plSynchedObject → hsKeyedObject
///
/// C++ ref: plCollisionDetector.cpp:215-219, plDetectorModifier.cpp:50-60
pub fn parse_volume_detector(data: &[u8]) -> Result<VolumeDetectorData> {
    use crate::core::uoid::read_key_uoid;
    let mut cursor = Cursor::new(data);

    // Creatable class index
    let _class_idx = cursor.read_i16()?;

    // hsKeyedObject::Read — self-key
    let self_key = read_key_uoid(&mut cursor)?;
    let name = self_key.as_ref().map(|k| k.object_name.clone()).unwrap_or_default();

    // plSynchedObject::Read
    skip_synched_object(&mut cursor)?;

    // plSingleModifier::Read — hsBitVector fFlags
    let num_bit_vectors = cursor.read_u32()?;
    for _ in 0..num_bit_vectors {
        let _word = cursor.read_u32()?;
    }

    // plDetectorModifier::Read
    // C++ ref: plDetectorModifier.cpp:50-60
    let receiver_count = cursor.read_u32()?;
    let mut receivers = Vec::with_capacity(receiver_count as usize);
    for _ in 0..receiver_count {
        if let Some(uoid) = read_key_uoid(&mut cursor)? {
            receivers.push(uoid);
        }
    }
    // Remote modifier key
    let _remote_mod = read_key_uoid(&mut cursor)?;
    // Proxy key
    let proxy_key = read_key_uoid(&mut cursor)?;

    // plCollisionDetector::Read — u8 fType
    let collision_type = cursor.read_u8()?;

    Ok(VolumeDetectorData {
        name,
        collision_type,
        receivers,
        proxy_key,
    })
}

// ============================================================================
// plPostEffectMod — GUI camera for dialog screen projection (class 0x007A)
// C++ ref: plPostEffectMod.cpp:281-301
// ============================================================================

/// Read hsMatrix44 from stream: 1-byte bool + optionally 16 × f32.
/// C++ ref: hsMatrix44::Read (hsMatrix44.cpp) — ReadBool then 16 floats if not identity.
fn read_hs_matrix44(reader: &mut (impl std::io::Read + Seek)) -> Result<[f32; 16]> {
    let has_data = reader.read_u8()? != 0;
    if has_data {
        let mut m = [0f32; 16];
        for val in &mut m {
            *val = reader.read_f32()?;
        }
        Ok(m)
    } else {
        // Identity matrix
        Ok([
            1.0, 0.0, 0.0, 0.0,
            0.0, 1.0, 0.0, 0.0,
            0.0, 0.0, 1.0, 0.0,
            0.0, 0.0, 0.0, 1.0,
        ])
    }
}

/// Parsed plPostEffectMod data — contains the camera transform for GUI projection.
#[derive(Debug, Clone)]
pub struct PostEffectModData {
    pub name: String,
    pub hither: f32,
    pub yon: f32,
    pub fov_x: f32,
    pub fov_y: f32,
    /// World-to-camera matrix (hsMatrix44, row-major 4x4).
    pub w2c: [f32; 16],
    /// Camera-to-world matrix (hsMatrix44, row-major 4x4).
    pub c2w: [f32; 16],
}

/// Parse plPostEffectMod from PRP object data.
/// C++ ref: plPostEffectMod.cpp:281-301
/// Inheritance: plPostEffectMod → plSingleModifier → plModifier → plSynchedObject
pub fn parse_post_effect_mod(data: &[u8]) -> Result<PostEffectModData> {
    use crate::core::uoid::read_key_uoid;
    let mut cursor = Cursor::new(data);

    let _class_idx = cursor.read_i16()?;
    let self_key = read_key_uoid(&mut cursor)?;
    let name = self_key.as_ref().map(|k| k.object_name.clone()).unwrap_or_default();
    skip_synched_object(&mut cursor)?;

    // plSingleModifier: hsBitVector flags
    let num_bv = cursor.read_u32()?;
    for _ in 0..num_bv { let _w = cursor.read_u32()?; }

    // plPostEffectMod: hsBitVector state
    let num_sv = cursor.read_u32()?;
    let mut state_bits = 0u32;
    for i in 0..num_sv {
        let w = cursor.read_u32()?;
        if i == 0 { state_bits = w; }
    }
    log::debug!("  PostEffectMod flags_bv={} state_bv={} state_bits=0x{:X} pos={}",
        num_bv, num_sv, state_bits, cursor.position());

    // Camera params
    let hither = cursor.read_f32()?;
    let yon = cursor.read_f32()?;
    let fov_x = cursor.read_f32()?;
    let fov_y = cursor.read_f32()?;
    log::debug!("  hither={} yon={} fov_x={} fov_y={}", hither, yon, fov_x, fov_y);

    // Node key
    let _node_key = read_key_uoid(&mut cursor)?;

    // W2C and C2W matrices (hsMatrix44::Read = 1-byte bool + optionally 16 × f32)
    let w2c = read_hs_matrix44(&mut cursor)?;
    let c2w = read_hs_matrix44(&mut cursor)?;

    log::debug!("  W2C row0=({:.3},{:.3},{:.3},{:.3})", w2c[0], w2c[1], w2c[2], w2c[3]);
    log::debug!("  W2C row1=({:.3},{:.3},{:.3},{:.3})", w2c[4], w2c[5], w2c[6], w2c[7]);
    log::debug!("  W2C row2=({:.3},{:.3},{:.3},{:.3})", w2c[8], w2c[9], w2c[10], w2c[11]);
    log::debug!("  W2C row3=({:.3},{:.3},{:.3},{:.3})", w2c[12], w2c[13], w2c[14], w2c[15]);

    Ok(PostEffectModData {
        name, hither, yon, fov_x, fov_y, w2c, c2w,
    })
}

// ============================================================================
// pfGUI controls — button, textbox, editbox, checkbox
// C++ ref: pfGameGUIMgr/pfGUIControlMod.cpp, pfGUIButtonMod.cpp, etc.
// ============================================================================

/// Parsed GUI control data.
#[derive(Debug, Clone)]
pub struct GuiControlData {
    pub name: String,
    pub control_type: String,
    pub tag_id: u32,
    pub visible: bool,
    pub text: Option<String>,
}

/// Skip pfGUICtrlProcWriteableObject inline.
/// C++ ref: pfGUIControlHandlers.cpp:70-100 — u32 type, then type-specific IRead.
fn skip_gui_proc(reader: &mut (impl std::io::Read + Seek)) -> Result<()> {
    let proc_type = reader.read_u32()?; // u32 LE type
    match proc_type {
        3 => {} // kNull — return nullptr, no more data
        0 => {  // kConsoleCmd — u32 strlen + string bytes
            let len = reader.read_u32()? as usize;
            if len > 0 { reader.skip(len)?; }
        }
        1 => {} // kPythonScript — no extra data
        2 => {} // kCloseDlg — no extra data
        _ => {} // unknown — hope for the best
    }
    Ok(())
}

/// Parse pfGUIControlMod base class data from stream.
/// Returns (tag_id, visible). Leaves cursor after base class data.
/// C++ ref: pfGUIControlMod.cpp:780-823
fn parse_gui_control_base(cursor: &mut Cursor<&[u8]>) -> Result<(u32, bool)> {
    use crate::core::uoid::read_key_uoid;

    // plSingleModifier: hsBitVector flags
    let num_bv = cursor.read_u32()?;
    let mut flags = 0u32;
    for i in 0..num_bv {
        let w = cursor.read_u32()?;
        if i == 0 { flags = w; }
    }

    // pfGUIControlMod fields
    let tag_id = cursor.read_u32()?;
    let visible = cursor.read_u8()? != 0;

    // pfGUICtrlProcWriteableObject handler
    skip_gui_proc(cursor)?;

    // Dynamic text map (optional)
    let has_dyn_text = cursor.read_u8()? != 0;
    if has_dyn_text {
        let _layer_key = read_key_uoid(cursor)?;
        let _dyn_text_key = read_key_uoid(cursor)?;
    }

    // Color scheme (optional)
    // C++ ref: pfGUIColorScheme::Read — 4 colors + bool + string + 2 bytes
    let has_color = cursor.read_u8()? != 0;
    if has_color {
        cursor.skip(4 * 4 * 4)?; // 4 × hsColorRGBA (16 floats)
        cursor.read_u32()?;      // fTransparent (ReadBOOL = 4 bytes)
        cursor.read_safe_string()?; // fFontFace
        cursor.read_u8()?;       // fFontSize
        cursor.read_u8()?;       // fFontFlags
    }

    // Sound indices
    let sound_count = cursor.read_u8()? as usize;
    cursor.skip(sound_count * 4)?; // u32 indices

    // Proxy key (if kHasProxy = bit 21 in flags)
    if flags & (1 << 21) != 0 {
        let _proxy_key = read_key_uoid(cursor)?;
    }

    // Skin key
    let _skin_key = read_key_uoid(cursor)?;

    Ok((tag_id, visible))
}

/// Parse a pfGUIButtonMod from PRP data — extracts name and tag ID.
/// Resilient: returns partial data on parse failure.
/// C++ ref: pfGUIButtonMod.cpp:199-219
pub fn parse_gui_button(data: &[u8]) -> Result<GuiControlData> {
    use crate::core::uoid::read_key_uoid;
    let mut cursor = Cursor::new(data);

    let _class_idx = cursor.read_i16()?;
    let self_key = read_key_uoid(&mut cursor)?;
    let name = self_key.as_ref().map(|k| k.object_name.clone()).unwrap_or_default();
    skip_synched_object(&mut cursor)?;

    // Try to parse control base; return partial data if it fails
    match parse_gui_control_base(&mut cursor) {
        Ok((tag_id, visible)) => Ok(GuiControlData {
            name,
            control_type: "Button".to_string(),
            tag_id,
            visible,
            text: None,
        }),
        Err(_) => Ok(GuiControlData {
            name,
            control_type: "Button".to_string(),
            tag_id: 0,
            visible: true,
            text: None,
        }),
    }
}

/// Parse a pfGUITextBoxMod from PRP data — extracts name, tag ID, and text.
/// Resilient: returns partial data on parse failure.
/// C++ ref: pfGUITextBoxMod.cpp:141-162
pub fn parse_gui_textbox(data: &[u8]) -> Result<GuiControlData> {
    use crate::core::uoid::read_key_uoid;
    let mut cursor = Cursor::new(data);

    let _class_idx = cursor.read_i16()?;
    let self_key = read_key_uoid(&mut cursor)?;
    let name = self_key.as_ref().map(|k| k.object_name.clone()).unwrap_or_default();
    skip_synched_object(&mut cursor)?;

    let (tag_id, visible) = match parse_gui_control_base(&mut cursor) {
        Ok(v) => v,
        Err(_) => return Ok(GuiControlData {
            name, control_type: "TextBox".to_string(), tag_id: 0, visible: true, text: None,
        }),
    };

    // pfGUITextBoxMod-specific: text content
    let text = if let Ok(text_len) = cursor.read_u32() {
        let text_len = text_len as usize;
        if text_len > 0 && text_len < 65536 {
            let mut text_bytes = vec![0u8; text_len];
            if cursor.read_exact(&mut text_bytes).is_ok() {
                let s = String::from_utf8_lossy(&text_bytes).trim_end_matches('\0').to_string();
                if s.is_empty() { None } else { Some(s) }
            } else { None }
        } else { None }
    } else { None };

    Ok(GuiControlData {
        name,
        control_type: "TextBox".to_string(),
        tag_id,
        visible,
        text,
    })
}

// ============================================================================
// plParticleSystem — particle effect (class 0x0008)
// C++ ref: plParticleSystem.cpp:608-648
// ============================================================================

/// Minimal parsed particle system data.
#[derive(Debug, Clone)]
pub struct ParticleSystemData {
    pub name: String,
    /// Material key name (texture for particles).
    pub material_name: Option<String>,
    /// Texture atlas dimensions.
    pub x_tiles: u32,
    pub y_tiles: u32,
    /// Maximum particle count.
    pub max_particles: u32,
    /// Acceleration vector (gravity/wind).
    pub accel: [f32; 3],
    /// Pre-simulation time (seconds). First frame runs sim for this duration.
    pub pre_sim: f32,
    /// Drag factor. Per-frame: vel *= max(0, 1 + drag * dt). Negative = decelerate.
    pub drag: f32,
    /// Wind multiplier for environmental wind effects.
    pub wind_mult: f32,
    /// Emitter source positions (from plSimpleParticleGenerator).
    pub emitter_sources: Vec<[f32; 3]>,
    /// Particle size (width, height) from generator.
    pub particle_size: [f32; 2],
    /// Number of emitters parsed.
    pub num_emitters: u32,
    /// Generator particle lifetime range (min, max) in seconds.
    pub particle_life_range: [f32; 2],
    /// Particles per second emission rate.
    pub particles_per_second: f32,
    /// Velocity range (min, max) for spawned particles.
    pub velocity_range: [f32; 2],
    /// Cone angle range (radians) for spawn direction jitter.
    pub angle_range: f32,
    /// Scale range (min, max) for particle size variation.
    pub scale_range: [f32; 2],
    /// Emitter miscFlags — orientation mode + normal mode.
    /// C++ ref: plParticleEmitter.h:106-129
    ///   kNormalViewFacing=0x100, kOrientationUp=0x10000000,
    ///   kOrientationVelocityBased=0x20000000, kOrientationVelocityStretch=0x40000000
    pub emitter_misc_flags: u32,
    /// Emitter color (RGBA). Applied to all particles from this emitter.
    pub emitter_color: [f32; 4],
}

/// Skip a Creatable controller inline (plLeafController or nil).
/// C++ ref: plResManager::ReadCreatable → u16 classIdx, then object.Read()
/// plLeafController::Read: u8 type + u32 numKeys + keyframe data
fn skip_creatable_controller(reader: &mut (impl std::io::Read + Seek)) -> Result<()> {
    let class_idx = reader.read_u16()?;
    if class_idx & 0x8000 != 0 {
        return Ok(()); // nil
    }

    // plLeafController (0x01A9) or plCompoundController (0x01AA)
    if class_idx == 0x01A9 {
        // plLeafController::Read: u8 type + u32 numKeys + numKeys × key_size
        let key_type = reader.read_u8()?;
        let num_keys = reader.read_u32()?;
        let key_size: usize = match key_type {
            0 => 0,  // kUnknownKeyFrame
            1 => 14, // kPoint3KeyFrame: u16 + 3×f32
            2 => 38, // kBezPoint3KeyFrame: u16 + 9×f32
            3 => 6,  // kScalarKeyFrame: u16 + f32
            4 => 14, // kBezScalarKeyFrame: u16 + 3×f32
            5 => 30, // kScaleKeyFrame: u16 + 7×f32 (quat+point3)
            6 => 54, // kBezScaleKeyFrame: u16 + 13×f32
            7 => 18, // kQuatKeyFrame: u16 + 4×f32
            8 => 6,  // kCompressedQuatKeyFrame32: u16 + u32
            9 => 10, // kCompressedQuatKeyFrame64: u16 + u64
            10 => 42, // k3dsMaxKeyFrame
            11 => 38, // kMatrix33KeyFrame: u16 + 9×f32
            12 => 66, // kMatrix44KeyFrame: u16 + 16×f32
            _ => bail!("Unknown keyframe type {}", key_type),
        };
        reader.seek(SeekFrom::Current((num_keys as usize * key_size) as i64))?;
    } else if class_idx == 0x01AA {
        // plCompoundController: 3 sub-controllers (X, Y, Z)
        for _ in 0..3 {
            skip_creatable_controller(reader)?;
        }
    } else {
        bail!("Unsupported controller class 0x{:04X}", class_idx);
    }
    Ok(())
}

/// Try to parse plParticleSystem from PRP object data.
/// Only extracts material key and basic params — skips controllers.
///
/// C++ ref: plParticleSystem.cpp:608-648
/// Inheritance: plParticleSystem → plModifier → plSynchedObject → hsKeyedObject
pub fn parse_particle_system(data: &[u8]) -> Result<ParticleSystemData> {
    use crate::core::uoid::read_key_uoid;
    let mut cursor = Cursor::new(data);

    // Creatable class index
    let _class_idx = cursor.read_i16()?;

    // hsKeyedObject::Read — self-key
    let self_key = read_key_uoid(&mut cursor)?;
    let name = self_key.as_ref().map(|k| k.object_name.clone()).unwrap_or_default();

    // plSynchedObject::Read
    skip_synched_object(&mut cursor)?;

    // plModifier has no Read/Write — goes straight to plParticleSystem data.
    // (plSingleModifier adds hsBitVector, but plModifier does not)

    // Material key (first field in plParticleSystem::Read)
    let mat_key = read_key_uoid(&mut cursor)?;
    let material_name = mat_key.map(|k| k.object_name);

    // 5 Controllers as Creatables — each is u16 classIdx, then object data.
    // 0x8000 = nil. For non-nil: skip plLeafController data.
    // C++ ref: plResManager::ReadCreatable → u16 classIdx, then object.Read()
    for _i in 0..5 {
        skip_creatable_controller(&mut cursor)?;
    }

    // All controllers nil — read the params
    let x_tiles = cursor.read_u32()?;
    let y_tiles = cursor.read_u32()?;
    let max_particles = cursor.read_u32()?;
    let _max_emitters = cursor.read_u32()?;
    let pre_sim = cursor.read_f32()?;
    let accel_x = cursor.read_f32()?;
    let accel_y = cursor.read_f32()?;
    let accel_z = cursor.read_f32()?;
    let drag = cursor.read_f32()?;
    let wind_mult = cursor.read_f32()?;

    // Read emitters: u32 numValidEmitters, then each as ReadCreatable
    let num_emitters = cursor.read_u32()?;
    let mut emitter_sources = Vec::new();
    let mut particle_size = [1.0_f32, 1.0];
    let mut particle_life_range = [1.0_f32, 1.0];
    let mut particles_per_second = 0.0_f32;
    let mut velocity_range = [0.0_f32, 0.0];
    let mut angle_range = 0.0_f32;
    let mut scale_range = [1.0_f32, 1.0];
    let mut emitter_misc_flags = 0u32;
    let mut emitter_color = [1.0_f32, 1.0, 1.0, 1.0];

    for _ei in 0..num_emitters {
        // ReadCreatable: u16 classIdx
        let emitter_class = cursor.read_u16()?;
        if emitter_class & 0x8000 != 0 { continue; }

        // plParticleEmitter::Read — first reads a generator via ReadCreatable
        let gen_class = cursor.read_u16()?;
        if gen_class & 0x8000 == 0 {
            log::debug!("  Emitter generator class: 0x{:04X}", gen_class);
            if gen_class == 0x02D8 {
                // plSimpleParticleGenerator::Read (0x02D8)
                let _gen_life = cursor.read_f32()?;
                let part_life_min = cursor.read_f32()?;
                let part_life_max = cursor.read_f32()?;
                particle_life_range = [part_life_min, part_life_max];
                let pps = cursor.read_f32()?;
                particles_per_second = pps;
                let num_sources = cursor.read_u32()?;
                for _ in 0..num_sources {
                    let px = cursor.read_f32()?;
                    let py = cursor.read_f32()?;
                    let pz = cursor.read_f32()?;
                    emitter_sources.push([px, py, pz]);
                    let _pitch = cursor.read_f32()?;
                    let _yaw = cursor.read_f32()?;
                }
                let ang = cursor.read_f32()?;
                angle_range = ang;
                let vel_min = cursor.read_f32()?;
                let vel_max = cursor.read_f32()?;
                velocity_range = [vel_min, vel_max];
                let x_size = cursor.read_f32()?;
                let y_size = cursor.read_f32()?;
                particle_size = [x_size, y_size];
                let sc_min = cursor.read_f32()?;
                let sc_max = cursor.read_f32()?;
                scale_range = [sc_min, sc_max];
                cursor.skip(4 * 2)?; // massRange, radsPerSec
            } else if gen_class == 0x0336 {
                // plOneTimeParticleGenerator: positions + directions
                let count = cursor.read_u32()?;
                let x_size = cursor.read_f32()?;
                let y_size = cursor.read_f32()?;
                particle_size = [x_size, y_size];
                let sc_min = cursor.read_f32()?;
                let sc_max = cursor.read_f32()?;
                scale_range = [sc_min, sc_max];
                cursor.skip(4)?; // radsPerSecRange
                for _ in 0..count {
                    let px = cursor.read_f32()?;
                    let py = cursor.read_f32()?;
                    let pz = cursor.read_f32()?;
                    emitter_sources.push([px, py, pz]);
                }
                cursor.skip((count as usize) * 12)?; // skip direction vectors
            } else {
                // Unknown generator type — can't skip reliably
                break;
            }
        }
        // Rest of plParticleEmitter::Read: u32 spanIndex + u32 maxParticles + u32 miscFlags + hsColorRGBA
        // C++ ref: plParticleEmitter.h:106-129 — miscFlags contains orientation + normal modes
        let _span_idx = cursor.read_u32()?;
        let _max_parts = cursor.read_u32()?;
        let misc_flags = cursor.read_u32()?;
        emitter_misc_flags = misc_flags;
        let cr = cursor.read_f32()?;
        let cg = cursor.read_f32()?;
        let cb = cursor.read_f32()?;
        let ca = cursor.read_f32()?;
        emitter_color = [cr, cg, cb, ca];
    }

    Ok(ParticleSystemData {
        name,
        material_name,
        x_tiles, y_tiles,
        max_particles,
        accel: [accel_x, accel_y, accel_z],
        pre_sim,
        drag,
        wind_mult,
        emitter_sources,
        particle_size,
        num_emitters,
        particle_life_range,
        particles_per_second,
        velocity_range,
        angle_range,
        scale_range,
        emitter_misc_flags,
        emitter_color,
    })
}

// ============================================================================
// plWaveSet7 — water surface (class 0x00FB)
// C++ ref: plWaveSet7.cpp:332-380, plFixedWaterState7.cpp:113-160
// ============================================================================

/// Parsed water surface data.
/// C++ ref: plFixedWaterState7 (plFixedWaterState7.h:52-129)
#[derive(Debug, Clone)]
pub struct WaveSetData {
    pub name: String,
    pub water_height: f32,
    pub water_tint: [f32; 4],  // RGBA
    pub opacity: f32,
    pub max_length: f32,
    /// GeoState: wave geometry parameters (plFixedWaterState7::GeoState)
    pub geo_max_len: f32,
    pub geo_min_len: f32,
    pub geo_amp_over_len: f32,
    pub geo_chop: f32,
    pub geo_angle_dev: f32,
    /// Wind direction (normalized 2D, stored as 3 floats in PRP)
    pub wind_dir: [f32; 3],
}

/// Parse plWaveSet7 from PRP object data.
///
/// C++ ref: plWaveSet7.cpp:332-380
/// Inheritance: plWaveSet7 → plMultiModifier → plModifier → plSynchedObject
pub fn parse_wave_set(data: &[u8]) -> Result<WaveSetData> {
    use crate::core::uoid::read_key_uoid;
    let mut cursor = Cursor::new(data);

    let _class_idx = cursor.read_i16()?;
    let self_key = read_key_uoid(&mut cursor)?;
    let name = self_key.as_ref().map(|k| k.object_name.clone()).unwrap_or_default();

    // plSynchedObject::Read
    skip_synched_object(&mut cursor)?;

    // plMultiModifier::Read — hsBitVector fFlags
    let num_bv = cursor.read_u32()?;
    let mut flags = 0u32;
    for i in 0..num_bv {
        let w = cursor.read_u32()?;
        if i == 0 { flags = w; }
    }

    // plWaveSet7::Read — fMaxLen
    let max_length = cursor.read_f32()?;

    // plFixedWaterState7::Read — 60 float values total
    // C++ ref: plFixedWaterState7.cpp:113-160, plFixedWaterState7.h:52-129
    //
    // GeoState: 5 floats (maxLen, minLen, ampOverLen, chop, angleDev)
    let geo_max_len = cursor.read_f32()?;
    let geo_min_len = cursor.read_f32()?;
    let geo_amp_over_len = cursor.read_f32()?;
    let geo_chop = cursor.read_f32()?;
    let geo_angle_dev = cursor.read_f32()?;

    // TexState: 5 floats (maxLen, minLen, ampOverLen, chop, angleDev)
    cursor.skip(5 * 4)?;

    // RippleScale: 1 float
    cursor.skip(4)?;

    // WindDir: 3 floats (hsVector3)
    let wind_x = cursor.read_f32()?;
    let wind_y = cursor.read_f32()?;
    let wind_z = cursor.read_f32()?;

    // SpecVec: 3 floats (hsVector3)
    cursor.skip(3 * 4)?;

    // WaterHeight: 1 float
    let water_height = cursor.read_f32()?;

    // WaterOffset: 3 floats (hsVector3, NOT 1 float!)
    cursor.skip(3 * 4)?;

    // MaxAtten: 3 floats (hsVector3)
    cursor.skip(3 * 4)?;

    // MinAtten: 3 floats (hsVector3)
    cursor.skip(3 * 4)?;

    // DepthFalloff: 3 floats (hsVector3)
    cursor.skip(3 * 4)?;

    // Wispiness: 1 float
    cursor.skip(4)?;

    // ShoreTint: 4 floats (hsColorRGBA)
    cursor.skip(4 * 4)?;

    // MaxColor: 4 floats (hsColorRGBA)
    cursor.skip(4 * 4)?;

    // MinColor: 4 floats (hsColorRGBA)
    cursor.skip(4 * 4)?;

    // EdgeOpac: 1 float
    let opacity = cursor.read_f32()?;

    // EdgeRadius: 1 float
    cursor.skip(4)?;

    // Period, FingerLength: 2 floats
    cursor.skip(2 * 4)?;

    // WaterTint: 4 floats (hsColorRGBA)
    let r = cursor.read_f32()?;
    let g = cursor.read_f32()?;
    let b = cursor.read_f32()?;
    let a = cursor.read_f32()?;

    Ok(WaveSetData {
        name,
        water_height,
        water_tint: [r, g, b, a],
        opacity,
        max_length,
        geo_max_len,
        geo_min_len,
        geo_amp_over_len,
        geo_chop,
        geo_angle_dev,
        wind_dir: [wind_x, wind_y, wind_z],
    })
}

// ============================================================================
// plWin32Sound — sound object (classes 0x0096, 0x0084, 0x00FD)
// C++ ref: plSound.cpp:1223-1273, plWin32Sound.cpp:456-460
// ============================================================================

/// Parsed sound data — minimal fields for logging.
#[derive(Debug, Clone)]
pub struct SoundData {
    pub name: String,
    pub volume: f32,
    pub looping: bool,
    pub is_3d: bool,
    pub auto_start: bool,
    pub sound_type: u8, // 0=SFX, 1=Ambience, 2=Music, 3=GUI, 4=NPCVoices
    /// Name of the sound buffer (WAV/OGG file reference).
    pub buffer_name: Option<String>,
    /// World position for 3D sounds (from scene object transform).
    pub position: [f32; 3],
    /// Min falloff distance (full volume within this range).
    pub min_falloff: f32,
    /// Max falloff distance (silent beyond this range).
    pub max_falloff: f32,
    /// Soft volume region key name (for volume-based attenuation).
    /// C++ ref: plSound::fSoftRegion → plSoftVolume, read at plSound.cpp:1263
    pub soft_region: Option<String>,
}

/// Parse plWin32StaticSound or plWin32StreamingSound from PRP object data.
///
/// C++ ref: plSound.cpp:1223-1273 (IRead), plWin32Sound.cpp:456-460
/// Inheritance: plWin32StaticSound → plWin32Sound → plSound → plSynchedObject
pub fn parse_win32_sound(data: &[u8]) -> Result<SoundData> {
    use crate::core::uoid::read_key_uoid;
    let mut cursor = Cursor::new(data);

    // Creatable class index
    let _class_idx = cursor.read_i16()?;

    // hsKeyedObject::Read — self-key
    let self_key = read_key_uoid(&mut cursor)?;
    let name = self_key.as_ref().map(|k| k.object_name.clone()).unwrap_or_default();

    // plSynchedObject::Read
    skip_synched_object(&mut cursor)?;

    // plSound::IRead — C++ ref: plSound.cpp:1223-1273
    let _playing = cursor.read_u8()?;           // bool fPlaying
    let _time = cursor.read_f32()?;             // f64 fTime (only 4 bytes in some versions)
    // Actually it's 8 bytes (double)
    cursor.skip(4)?;                            // remaining 4 bytes of f64
    let max_falloff = cursor.read_i32()? as f32;
    let min_falloff = cursor.read_i32()? as f32;
    let _curr_volume = cursor.read_f32()?;
    let desired_vol = cursor.read_f32()?;
    let _outer_vol = cursor.read_i32()?;
    let _inner_cone = cursor.read_i32()?;
    let _outer_cone = cursor.read_i32()?;
    let _faded_volume = cursor.read_f32()?;
    let properties = cursor.read_u32()?;
    let sound_type = cursor.read_u8()?;
    let _priority = cursor.read_u8()?;

    // Fade in params: f32 length, f32 volStart, f32 volEnd, u8 type, f32 currTime, u32 stopWhenDone, u32 fadeSoftVol
    cursor.skip(4 + 4 + 4 + 1 + 4 + 4 + 4)?;
    // Fade out params: same
    cursor.skip(4 + 4 + 4 + 1 + 4 + 4 + 4)?;

    // Keys: softRegion, dataBufferKey
    let soft_region_key = read_key_uoid(&mut cursor)?;
    let soft_region = soft_region_key.map(|k| k.object_name);
    let buffer_key = read_key_uoid(&mut cursor)?;
    let buffer_name = buffer_key.map(|k| k.object_name);

    let looping = properties & 0x00000004 != 0;  // kPropLooping
    let is_3d = properties & 0x00000001 != 0;     // kPropIs3DSound
    let auto_start = properties & 0x00000008 != 0; // kPropAutoStart

    Ok(SoundData {
        name,
        volume: desired_vol,
        looping,
        is_3d,
        auto_start,
        sound_type,
        buffer_name,
        position: [0.0, 0.0, 0.0], // Position set from scene object transform
        min_falloff,
        max_falloff,
        soft_region,
    })
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::path::Path;

    #[test]
    fn test_parse_one_shot_mods() {
        let prp_path = Path::new("../../Plasma/staging/client/dat/Cleft_District_Cleft.prp");
        if !prp_path.exists() { return; }

        let page = PrpPage::from_file(prp_path).unwrap();
        let keys: Vec<_> = page.keys_of_type(crate::core::class_index::ClassIndex::PL_ONE_SHOT_MOD)
            .iter().cloned().cloned().collect();

        assert!(keys.len() >= 10, "Cleft should have 14+ OneShotMod objects, got {}", keys.len());

        let mut ok = 0;
        for key in &keys {
            if let Some(data) = page.object_data(key) {
                let osm = parse_one_shot_mod(data)
                    .unwrap_or_else(|e| panic!("Failed to parse OneShotMod '{}': {}", key.object_name, e));
                assert!(!osm.anim_name.is_empty(), "OneShotMod '{}' has empty anim_name", key.object_name);
                assert!(osm.seek_duration >= 0.0, "OneShotMod '{}' has negative seek_duration", key.object_name);
                ok += 1;
            }
        }
        assert_eq!(ok, keys.len(), "All OneShotMod objects should parse successfully");
    }

    #[test]
    fn test_responder_oneshot_callbacks_parse() {
        // Verify responders with plOneShotMsg parse correctly after the callback fix
        let prp_path = Path::new("../../Plasma/staging/client/dat/Cleft_District_Cleft.prp");
        if !prp_path.exists() { return; }

        let page = PrpPage::from_file(prp_path).unwrap();
        let mut ok = 0;
        let mut err = 0;
        for key in page.keys_of_type(crate::core::class_index::ClassIndex::PL_RESPONDER_MODIFIER) {
            if let Some(data) = page.object_data(key) {
                match parse_responder_modifier(data) {
                    Ok(resp) => {
                        // Count it as "ok" if at least one state has commands
                        let n_cmds: usize = resp.states.iter().map(|s| s.commands.len()).sum();
                        if n_cmds > 0 || resp.enabled {
                            ok += 1;
                        }
                    }
                    Err(_) => err += 1,
                }
            }
        }
        // The runtime counts Ok results, not command completeness
        // 261 keys with 88+ Result::Ok is expected given unknown command types
        assert!(ok >= 80, "At least 80 responders should parse Ok, got {} (err={})", ok, err);
    }

    #[test]
    fn test_px_physical_parse() {
        let prp_path = Path::new("../../Plasma/staging/client/dat/Cleft_District_Cleft.prp");
        if !prp_path.exists() { return; }

        let page = PrpPage::from_file(prp_path).unwrap();
        let keys: Vec<_> = page.keys_of_type(crate::core::class_index::ClassIndex::PL_PXPHYSICAL)
            .iter().cloned().cloned().collect();

        assert!(keys.len() >= 50, "Cleft should have 100+ PXPhysical objects, got {}", keys.len());

        let mut ok = 0;
        let mut fail = 0;
        let mut trimesh_count = 0;
        let mut hull_count = 0;
        let mut total_verts = 0;
        for key in &keys {
            if let Some(data) = page.object_data(key) {
                match parse_px_physical(data) {
                    Ok(phys) => {
                        match &phys.shape {
                            PhysShapeData::TriMesh { vertices, indices } => {
                                trimesh_count += 1;
                                total_verts += vertices.len();
                                assert!(indices.len() % 3 == 0, "trimesh {} indices not multiple of 3", phys.name);
                            }
                            PhysShapeData::Hull { vertices } => {
                                hull_count += 1;
                                total_verts += vertices.len();
                            }
                            _ => {}
                        }
                        ok += 1;
                    }
                    Err(e) => {
                        eprintln!("FAIL: {}{}", key.object_name, e);
                        fail += 1;
                    }
                }
            }
        }
        eprintln!("PXPhysical: {} ok, {} fail, {} trimesh, {} hull, {} total verts",
            ok, fail, trimesh_count, hull_count, total_verts);
        // Most physicals should parse — allow a few failures for edge cases
        assert!(ok >= 100, "At least 100 PXPhysical should parse, got {} (fail={})", ok, fail);
    }

}

// ============================================================================
// plPXPhysical — physics collision object (class 0x003F)
// C++ ref: plGenericPhysical.cpp:340-387, plPXCooking.cpp
// ============================================================================

/// Bounds/shape type for a physical object.
/// C++ ref: plSimDefs.h — Bounds enum
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PhysBoundsType {
    Box = 1,
    Sphere = 2,
    Hull = 3,
    Proxy = 4,
    Explicit = 5,
}

/// Collision group for a physical object.
/// C++ ref: plSimDefs.h — Group enum
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PhysGroup {
    Static = 0,
    AvatarBlocker = 1,
    DynamicBlocker = 2,
    Avatar = 3,
    Dynamic = 4,
    Detector = 5,
    LOSOnly = 6,
    ExcludeRegion = 7,
    Max = 255,
}

/// Shape data parsed from a plPXPhysical.
#[derive(Debug, Clone)]
pub enum PhysShapeData {
    Sphere { radius: f32, offset: [f32; 3] },
    Box { dimensions: [f32; 3], offset: [f32; 3] },
    Hull { vertices: Vec<[f32; 3]> },
    TriMesh { vertices: Vec<[f32; 3]>, indices: Vec<u32> },
}

/// Parsed plPXPhysical data — collision geometry for one physical object.
#[derive(Debug, Clone)]
pub struct PxPhysicalData {
    pub name: String,
    pub mass: f32,
    pub friction: f32,
    pub restitution: f32,
    pub bounds: PhysBoundsType,
    pub group: PhysGroup,
    pub reports_on: u32,
    pub los_dbs: u16,
    pub position: [f32; 3],
    pub rotation: [f32; 4], // quaternion (x, y, z, w)
    pub shape: PhysShapeData,
}

fn read_phys_group(val: u8) -> PhysGroup {
    match val {
        0 => PhysGroup::Static,
        1 => PhysGroup::AvatarBlocker,
        2 => PhysGroup::DynamicBlocker,
        3 => PhysGroup::Avatar,
        4 => PhysGroup::Dynamic,
        5 => PhysGroup::Detector,
        6 => PhysGroup::LOSOnly,
        7 => PhysGroup::ExcludeRegion,
        _ => PhysGroup::Max,
    }
}

fn read_phys_bounds(val: u8) -> Result<PhysBoundsType> {
    match val {
        1 => Ok(PhysBoundsType::Box),
        2 => Ok(PhysBoundsType::Sphere),
        3 => Ok(PhysBoundsType::Hull),
        4 => Ok(PhysBoundsType::Proxy),
        5 => Ok(PhysBoundsType::Explicit),
        _ => bail!("Unknown bounds type: {}", val),
    }
}

/// Read hsPoint3 (3 × f32 LE) into [f32; 3].
fn read_point3(reader: &mut impl std::io::Read) -> Result<[f32; 3]> {
    let mut buf = [0u8; 12];
    reader.read_exact(&mut buf)?;
    Ok([
        f32::from_le_bytes([buf[0], buf[1], buf[2], buf[3]]),
        f32::from_le_bytes([buf[4], buf[5], buf[6], buf[7]]),
        f32::from_le_bytes([buf[8], buf[9], buf[10], buf[11]]),
    ])
}

/// Read hsQuat (4 × f32 LE: x, y, z, w) into [f32; 4].
/// C++ ref: hsQuat.cpp:246-252 — reads fX, fY, fZ, fW
fn read_quat(reader: &mut impl std::io::Read) -> Result<[f32; 4]> {
    let mut buf = [0u8; 16];
    reader.read_exact(&mut buf)?;
    let mut q = [
        f32::from_le_bytes([buf[0], buf[1], buf[2], buf[3]]),
        f32::from_le_bytes([buf[4], buf[5], buf[6], buf[7]]),
        f32::from_le_bytes([buf[8], buf[9], buf[10], buf[11]]),
        f32::from_le_bytes([buf[12], buf[13], buf[14], buf[15]]),
    ];
    // C++ ref: plPXPhysical.cpp:220-221 — fix zero quat from bad exports
    if q[0] == 0.0 && q[1] == 0.0 && q[2] == 0.0 && q[3] == 0.0 {
        q[3] = 1.0;
    }
    Ok(q)
}

/// Skip hsBitVector: u32 count + count × u32 words.
/// C++ ref: hsBitVector.cpp:90-101
fn skip_bit_vector(reader: &mut (impl std::io::Read + Seek)) -> Result<()> {
    let mut buf = [0u8; 4];
    reader.read_exact(&mut buf)?;
    let count = u32::from_le_bytes(buf) as usize;
    if count > 0 {
        let mut skip_buf = vec![0u8; count * 4];
        reader.read_exact(&mut skip_buf)?;
    }
    Ok(())
}

/// Read hsBitVector: u32 count + count × u32 words. Returns the raw u32 words.
/// C++ ref: hsBitVector.cpp:90-101
fn read_bit_vector_words(reader: &mut impl std::io::Read) -> Result<Vec<u32>> {
    let mut buf = [0u8; 4];
    reader.read_exact(&mut buf)?;
    let count = u32::from_le_bytes(buf) as usize;
    let mut words = Vec::with_capacity(count);
    for _ in 0..count {
        reader.read_exact(&mut buf)?;
        words.push(u32::from_le_bytes(buf));
    }
    Ok(words)
}

/// Read convex hull or trimesh data from an uncooked stream (HSP\x01 magic).
/// C++ ref: plPXCooking.cpp:90-97 (convex), 222-231 (trimesh)
fn read_uncooked_hull(reader: &mut (impl std::io::Read + Seek)) -> Result<PhysShapeData> {
    let mut buf4 = [0u8; 4];
    reader.read_exact(&mut buf4)?;
    let nverts = u32::from_le_bytes(buf4) as usize;
    let mut vertices = Vec::with_capacity(nverts);
    for _ in 0..nverts {
        vertices.push(read_point3(reader)?);
    }
    Ok(PhysShapeData::Hull { vertices })
}

fn read_uncooked_trimesh(reader: &mut (impl std::io::Read + Seek)) -> Result<PhysShapeData> {
    let mut buf4 = [0u8; 4];
    reader.read_exact(&mut buf4)?;
    let nverts = u32::from_le_bytes(buf4) as usize;
    let mut vertices = Vec::with_capacity(nverts);
    for _ in 0..nverts {
        vertices.push(read_point3(reader)?);
    }
    reader.read_exact(&mut buf4)?;
    let nfaces = u32::from_le_bytes(buf4) as usize;
    let mut indices = Vec::with_capacity(nfaces * 3);
    for _ in 0..(nfaces * 3) {
        reader.read_exact(&mut buf4)?;
        indices.push(u32::from_le_bytes(buf4));
    }
    Ok(PhysShapeData::TriMesh { vertices, indices })
}

/// Skip a max-dependent list: read u32 max, then `size` elements whose width depends on max.
/// C++ ref: plPXCooking.cpp:67-76
fn skip_max_dependent_list(reader: &mut (impl std::io::Read + Seek), size: usize) -> Result<()> {
    let mut buf4 = [0u8; 4];
    reader.read_exact(&mut buf4)?;
    let max_val = u32::from_le_bytes(buf4);
    let bytes_per_elem = if max_val > 0xFFFF { 4 } else if max_val > 0xFF { 2 } else { 1 };
    reader.seek(SeekFrom::Current((size * bytes_per_elem) as i64))?;
    Ok(())
}

/// Read the suffix section common to both cooked convex and trimesh.
/// C++ ref: plPXCooking.cpp:78-86
fn read_cooked_suffix(reader: &mut (impl std::io::Read + Seek)) -> Result<()> {
    let mut buf4 = [0u8; 4];
    // HBM block — skip variable-length
    reader.read_exact(&mut buf4)?;
    let hbm_size = u32::from_le_bytes(buf4) as i64;
    reader.seek(SeekFrom::Current(hbm_size))?;
    // 11 floats
    reader.seek(SeekFrom::Current(11 * 4))?;
    // One more float; if > -1, skip 12 more floats
    let mut fbuf = [0u8; 4];
    reader.read_exact(&mut fbuf)?;
    let val = f32::from_le_bytes(fbuf);
    if val > -1.0 {
        reader.seek(SeekFrom::Current(12 * 4))?;
    }
    Ok(())
}

/// Read cooked convex hull (NXS\x01 / CVXM format).
/// C++ ref: plPXCooking.cpp:90-218
fn read_cooked_hull(reader: &mut (impl std::io::Read + Seek)) -> Result<PhysShapeData> {
    let mut tag = [0u8; 4];
    let mut buf4 = [0u8; 4];

    // CVXM header
    reader.read_exact(&mut tag)?;
    if &tag != b"CVXM" { bail!("Expected CVXM, got {:?}", tag); }
    reader.read_exact(&mut buf4)?; // version — must be 2
    reader.read_exact(&mut buf4)?; // unknown

    // ICE + CLHL
    reader.read_exact(&mut tag)?; // ICE\x01
    reader.read_exact(&mut tag)?; // CLHL
    reader.read_exact(&mut buf4)?; // version 0

    // ICE + CVHL
    reader.read_exact(&mut tag)?; // ICE\x01
    reader.read_exact(&mut tag)?; // CVHL
    reader.read_exact(&mut buf4)?; // version 5

    reader.read_exact(&mut buf4)?;
    let num_verts = u32::from_le_bytes(buf4) as usize;
    reader.read_exact(&mut buf4)?;
    let num_tris = u32::from_le_bytes(buf4) as usize;
    reader.read_exact(&mut buf4)?;
    let unk2 = u32::from_le_bytes(buf4) as usize;
    reader.read_exact(&mut buf4)?;
    let _unk3 = u32::from_le_bytes(buf4) as usize;
    reader.read_exact(&mut buf4)?;
    let unk4 = u32::from_le_bytes(buf4) as usize;
    reader.read_exact(&mut buf4)?;
    let _unk5 = u32::from_le_bytes(buf4) as usize;

    // Read vertices
    let mut vertices = Vec::with_capacity(num_verts);
    for _ in 0..num_verts {
        vertices.push(read_point3(reader)?);
    }

    // Skip triangle indices (variable-size based on maxVertIndex)
    reader.read_exact(&mut buf4)?;
    let max_vert_index = u32::from_le_bytes(buf4);
    let idx_size = if max_vert_index > 0xFFFF { 4 } else if max_vert_index > 0xFF { 2 } else { 1 };
    reader.seek(SeekFrom::Current((num_tris * 3 * idx_size) as i64))?;

    // Skip remaining data
    reader.seek(SeekFrom::Current(2))?; // u16
    reader.seek(SeekFrom::Current((num_verts * 2) as i64))?;
    reader.seek(SeekFrom::Current(12))?; // 3 floats
    reader.seek(SeekFrom::Current((_unk3 * 36) as i64))?;
    reader.seek(SeekFrom::Current(unk4 as i64))?;

    skip_max_dependent_list(reader, unk4)?;

    reader.seek(SeekFrom::Current(8))?; // 2 × u32
    reader.seek(SeekFrom::Current((unk2 * 2) as i64))?;
    reader.seek(SeekFrom::Current((unk2 * 2) as i64))?;

    skip_max_dependent_list(reader, unk2)?;
    skip_max_dependent_list(reader, unk2)?;
    skip_max_dependent_list(reader, unk2)?;
    reader.seek(SeekFrom::Current((unk2 * 2) as i64))?;

    // ICE + VALE
    reader.read_exact(&mut tag)?; // ICE\x01
    reader.read_exact(&mut tag)?; // VALE
    reader.read_exact(&mut buf4)?; // version 2

    reader.read_exact(&mut buf4)?;
    let vale_unk1 = u32::from_le_bytes(buf4) as usize;
    reader.read_exact(&mut buf4)?;
    let vale_unk2 = u32::from_le_bytes(buf4) as usize;

    skip_max_dependent_list(reader, vale_unk1)?;
    reader.seek(SeekFrom::Current(vale_unk2 as i64))?;

    read_cooked_suffix(reader)?;

    // Optional SUPM section for large hulls (> 0x20 verts)
    if num_verts > 0x20 {
        // ICE + SUPM
        reader.read_exact(&mut tag)?;
        reader.read_exact(&mut tag)?;
        reader.read_exact(&mut buf4)?;
        // ICE + GAUS
        reader.read_exact(&mut tag)?;
        reader.read_exact(&mut tag)?;
        reader.read_exact(&mut buf4)?;

        reader.read_exact(&mut buf4)?; // u32
        reader.read_exact(&mut buf4)?;
        let gaus_unk2 = u32::from_le_bytes(buf4) as usize;
        reader.seek(SeekFrom::Current((gaus_unk2 * 2) as i64))?;
    }

    Ok(PhysShapeData::Hull { vertices })
}

/// Read cooked triangle mesh (NXS\x01 / MESH format).
/// C++ ref: plPXCooking.cpp:222-289
fn read_cooked_trimesh(reader: &mut (impl std::io::Read + Seek)) -> Result<PhysShapeData> {
    let mut tag = [0u8; 4];
    let mut buf4 = [0u8; 4];

    // MESH header
    reader.read_exact(&mut tag)?;
    if &tag != b"MESH" { bail!("Expected MESH, got {:?}", tag); }
    reader.read_exact(&mut buf4)?; // version 0

    reader.read_exact(&mut buf4)?;
    let flags = u32::from_le_bytes(buf4);
    reader.seek(SeekFrom::Current(4))?; // float
    reader.seek(SeekFrom::Current(4))?; // u32
    reader.seek(SeekFrom::Current(4))?; // float

    reader.read_exact(&mut buf4)?;
    let num_verts = u32::from_le_bytes(buf4) as usize;
    reader.read_exact(&mut buf4)?;
    let num_tris = u32::from_le_bytes(buf4) as usize;

    // Read vertices
    let mut vertices = Vec::with_capacity(num_verts);
    for _ in 0..num_verts {
        vertices.push(read_point3(reader)?);
    }

    // Read indices — size depends on flags
    let mut indices = Vec::with_capacity(num_tris * 3);
    for _ in 0..(num_tris * 3) {
        let idx = if flags & 0x08 != 0 {
            let mut b = [0u8; 1];
            reader.read_exact(&mut b)?;
            b[0] as u32
        } else if flags & 0x10 != 0 {
            let mut b = [0u8; 2];
            reader.read_exact(&mut b)?;
            u16::from_le_bytes(b) as u32
        } else {
            reader.read_exact(&mut buf4)?;
            u32::from_le_bytes(buf4)
        };
        indices.push(idx);
    }

    // Skip optional material indices
    if flags & 0x01 != 0 {
        reader.seek(SeekFrom::Current((num_tris * 2) as i64))?;
    }
    if flags & 0x02 != 0 {
        reader.read_exact(&mut buf4)?;
        let max_val = u32::from_le_bytes(buf4);
        let elem_size = if max_val > 0xFFFF { 4 } else if max_val > 0xFF { 2 } else { 1 };
        reader.seek(SeekFrom::Current((num_tris * elem_size) as i64))?;
    }

    // Skip convex/flat parts
    reader.read_exact(&mut buf4)?;
    let num_convex_parts = u32::from_le_bytes(buf4) as usize;
    reader.read_exact(&mut buf4)?;
    let num_flat_parts = u32::from_le_bytes(buf4) as usize;

    if num_convex_parts > 0 {
        reader.seek(SeekFrom::Current((num_tris * 2) as i64))?;
    }
    if num_flat_parts > 0 {
        let elem_size = if num_flat_parts > 0xFF { 2 } else { 1 };
        reader.seek(SeekFrom::Current((num_tris * elem_size) as i64))?;
    }

    read_cooked_suffix(reader)?;

    // Optional extra block
    reader.read_exact(&mut buf4)?;
    let extra = u32::from_le_bytes(buf4);
    if extra != 0 {
        reader.seek(SeekFrom::Current(num_tris as i64))?;
    }

    Ok(PhysShapeData::TriMesh { vertices, indices })
}

/// Read shape data (convex hull or trimesh) by detecting HSP/NXS magic.
fn read_mesh_shape(reader: &mut (impl std::io::Read + Seek), is_hull: bool) -> Result<PhysShapeData> {
    let mut magic = [0u8; 4];
    reader.read_exact(&mut magic)?;

    if &magic == b"HSP\x01" {
        // Uncooked format
        if is_hull {
            read_uncooked_hull(reader)
        } else {
            read_uncooked_trimesh(reader)
        }
    } else if &magic == b"NXS\x01" {
        // Cooked PhysX format
        if is_hull {
            read_cooked_hull(reader)
        } else {
            read_cooked_trimesh(reader)
        }
    } else {
        bail!("Unknown mesh magic: {:02x}{:02x}{:02x}{:02x}", magic[0], magic[1], magic[2], magic[3]);
    }
}

/// Parse plPXPhysical from PRP object data.
///
/// C++ ref: plGenericPhysical.cpp:340-387
/// Inheritance: plPXPhysical → plPhysical → plSynchedObject → hsKeyedObject
pub fn parse_px_physical(data: &[u8]) -> Result<PxPhysicalData> {
    use crate::core::uoid::read_key_uoid;
    let mut cursor = Cursor::new(data);

    // Creatable class index (i16)
    let _class_idx = cursor.read_i16()?;

    // hsKeyedObject::Read — self-key
    let self_key = read_key_uoid(&mut cursor)?;
    let name = self_key.as_ref().map(|k| k.object_name.clone()).unwrap_or_default();

    // plSynchedObject::Read
    skip_synched_object(&mut cursor)?;

    // plPXPhysical-specific data (plGenericPhysical.cpp:345-380)
    let mass = cursor.read_f32()?;
    let friction = cursor.read_f32()?;
    let restitution = cursor.read_f32()?;
    let bounds_raw = cursor.read_u8()?;
    let group_raw = cursor.read_u8()?;
    let reports_on = cursor.read_u32()?;
    let los_dbs = cursor.read_u16()?;

    // C++ ref: plGenericPhysical.cpp:353-355 — swim region hack
    let mut group = read_phys_group(group_raw);
    if los_dbs == 0x0080 { // kLOSDBSwimRegion
        group = PhysGroup::Max;
    }

    let bounds = read_phys_bounds(bounds_raw)?;

    // 4 keys: objectKey, sceneNode, worldKey, soundGroup
    let _object_key = read_key_uoid(&mut cursor)?;
    let _scene_node = read_key_uoid(&mut cursor)?;
    let _world_key = read_key_uoid(&mut cursor)?;
    let _sound_group = read_key_uoid(&mut cursor)?;

    // Transform: hsPoint3 position + hsQuat rotation
    let position = read_point3(&mut cursor)?;
    let rotation = read_quat(&mut cursor)?;

    // hsBitVector fProps — skip
    skip_bit_vector(&mut cursor)?;

    // Shape data based on bounds type
    // C++ ref: plGenericPhysical.cpp:370-380
    let shape = match bounds {
        PhysBoundsType::Sphere => {
            let radius = cursor.read_f32()?;
            let offset = read_point3(&mut cursor)?;
            PhysShapeData::Sphere { radius, offset }
        }
        PhysBoundsType::Box => {
            let dimensions = read_point3(&mut cursor)?;
            let offset = read_point3(&mut cursor)?;
            PhysShapeData::Box { dimensions, offset }
        }
        PhysBoundsType::Hull => {
            read_mesh_shape(&mut cursor, true)?
        }
        PhysBoundsType::Proxy | PhysBoundsType::Explicit => {
            read_mesh_shape(&mut cursor, false)?
        }
    };

    Ok(PxPhysicalData {
        name,
        mass,
        friction,
        restitution,
        bounds,
        group,
        reports_on,
        los_dbs,
        position,
        rotation,
        shape,
    })
}

// ============================================================================
// plVisRegion (0x0116) — visibility region
// ============================================================================

/// A visibility region — groups objects by visibility.
/// C++ ref: plVisRegion.h — properties kDisable=0, kIsNot=1, kReplaceNormal=2, kDisableNormal=3
#[derive(Debug, Clone)]
pub struct VisRegionData {
    pub self_key: Option<crate::core::uoid::Uoid>,
    /// Key to the soft volume region (plRegionBase / plSoftVolume).
    pub region_key: Option<crate::core::uoid::Uoid>,
    /// If true, this region disables normal rendering when active.
    pub disable_normal: bool,
    /// If true, this is a "not" region — excludes objects from rendering.
    pub is_not: bool,
    /// If true, replaces normal visibility (default: true).
    pub replace_normal: bool,
    /// If true, region is disabled and always returns false.
    pub disabled: bool,
}

impl Default for VisRegionData {
    fn default() -> Self {
        Self {
            self_key: None,
            region_key: None,
            disable_normal: false,
            is_not: false,
            replace_normal: true,
            disabled: false,
        }
    }
}

/// Parse plVisRegion from PRP object data.
/// C++ ref: plVisRegion.cpp:128-137
///
/// Wire format:
///   plObjInterface::Read:
///     plSynchedObject::Read:
///       hsKeyedObject::Read (self-key)
///       synch_flags(u32) + optional exclude/volatile strings
///     owner key
///     fProps (hsBitVector)
///   region key (plSoftVolume / plRegionBase)
///   visMgr key (plVisMgr)
pub fn parse_vis_region(data: &[u8]) -> Result<VisRegionData> {
    use crate::core::uoid::read_key_uoid;
    let mut cursor = Cursor::new(data);

    // Creatable class index
    let class_idx = cursor.read_i16()?;
    if class_idx < 0 { bail!("Null creatable in plVisRegion"); }

    // hsKeyedObject::Read — self-key
    let self_key = read_key_uoid(&mut cursor)?;

    // plSynchedObject::Read
    skip_synched_object(&mut cursor)?;

    // plObjInterface::Read — owner key
    let _owner_key = read_key_uoid(&mut cursor)?;

    // plObjInterface::Read — fProps (hsBitVector)
    let prop_words = read_bit_vector_words(&mut cursor)?;

    // Extract property bits
    // C++ plVisRegion.h: kDisable=0, kIsNot=1, kReplaceNormal=2, kDisableNormal=3
    let get_bit = |bit: usize| -> bool {
        let word_idx = bit / 32;
        let bit_idx = bit % 32;
        word_idx < prop_words.len() && (prop_words[word_idx] & (1 << bit_idx)) != 0
    };

    let disabled = get_bit(0);       // kDisable
    let is_not = get_bit(1);         // kIsNot
    let replace_normal = get_bit(2); // kReplaceNormal
    let disable_normal = get_bit(3); // kDisableNormal

    // region key (kRefRegion → plSoftVolume)
    let region_key = read_key_uoid(&mut cursor)?;

    // visMgr key (kRefVisMgr → plVisMgr) — we read but don't need it (global singleton)
    let _vis_mgr_key = read_key_uoid(&mut cursor)?;

    Ok(VisRegionData {
        self_key,
        region_key,
        disable_normal,
        is_not,
        replace_normal,
        disabled,
    })
}

// ============================================================================
// plVolumeIsect types — inline creatables inside plSoftVolumeSimple
// ============================================================================

/// Parsed volume intersection geometry.
/// Used by plSoftVolumeSimple for containment testing.
#[derive(Debug, Clone)]
pub enum VolumeIsectData {
    /// plConvexIsect (0x02FA): convex hull of half-planes.
    /// C++ ref: plVolumeIsect.cpp:737-751
    Convex {
        planes: Vec<ConvexPlane>,
    },
    /// plSphereIsect (0x02F6): sphere containment.
    /// C++ ref: plVolumeIsect.cpp:147-154
    Sphere {
        center: [f32; 3],
        world_center: [f32; 3],
        radius: f32,
        mins: [f32; 3],
        maxs: [f32; 3],
    },
    /// plCylinderIsect (0x02F8): cylinder containment.
    /// C++ ref: plVolumeIsect.cpp:497-508
    Cylinder {
        top: [f32; 3],
        bot: [f32; 3],
        radius: f32,
        world_bot: [f32; 3],
        world_norm: [f32; 3],
        length: f32,
        min: f32,
        max: f32,
    },
    /// plParallelIsect (0x02F9): pairs of parallel planes.
    /// C++ ref: plVolumeIsect.cpp:607-621
    Parallel {
        planes: Vec<ParallelPlane>,
    },
    /// plConeIsect (0x02F7): cone containment.
    /// C++ ref: plVolumeIsect.cpp:325-345
    Cone {
        capped: bool,
        rad_angle: f32,
        length: f32,
        world_tip: [f32; 3],
        world_norm: [f32; 3],
        norms: Vec<[f32; 3]>,
        dists: Vec<f32>,
    },
}

#[derive(Debug, Clone)]
pub struct ConvexPlane {
    pub norm: [f32; 3],
    pub pos: [f32; 3],
    pub dist: f32,
    pub world_norm: [f32; 3],
    pub world_dist: f32,
}

#[derive(Debug, Clone)]
pub struct ParallelPlane {
    pub norm: [f32; 3],
    pub min: f32,
    pub max: f32,
    pub pos_one: [f32; 3],
    pub pos_two: [f32; 3],
}

/// Read an inline plVolumeIsect creatable (class_index + data).
/// C++ ref: plResManager::ReadCreatable — u16 class, then object::Read()
fn read_volume_isect(reader: &mut (impl std::io::Read + Seek)) -> Result<Option<VolumeIsectData>> {
    use crate::core::class_index::ClassIndex;

    let class_idx = reader.read_u16()?;
    if class_idx == 0x8000 {
        return Ok(None); // nil creatable
    }

    match class_idx {
        ClassIndex::PL_CONVEX_ISECT => {
            // C++ plConvexIsect::Read — u16 n, then n planes
            let n = reader.read_u16()? as usize;
            let mut planes = Vec::with_capacity(n);
            for _ in 0..n {
                let norm = read_point3(reader)?;
                let pos = read_point3(reader)?;
                let dist = reader.read_f32()?;
                let world_norm = read_point3(reader)?;
                let world_dist = reader.read_f32()?;
                planes.push(ConvexPlane { norm, pos, dist, world_norm, world_dist });
            }
            Ok(Some(VolumeIsectData::Convex { planes }))
        }
        ClassIndex::PL_SPHERE_ISECT => {
            // C++ plSphereIsect::Read
            let center = read_point3(reader)?;
            let world_center = read_point3(reader)?;
            let radius = reader.read_f32()?;
            let mins = read_point3(reader)?;
            let maxs = read_point3(reader)?;
            Ok(Some(VolumeIsectData::Sphere { center, world_center, radius, mins, maxs }))
        }
        ClassIndex::PL_CYLINDER_ISECT => {
            // C++ plCylinderIsect::Read
            let top = read_point3(reader)?;
            let bot = read_point3(reader)?;
            let radius = reader.read_f32()?;
            let world_bot = read_point3(reader)?;
            let world_norm = read_point3(reader)?;
            let length = reader.read_f32()?;
            let min = reader.read_f32()?;
            let max = reader.read_f32()?;
            Ok(Some(VolumeIsectData::Cylinder { top, bot, radius, world_bot, world_norm, length, min, max }))
        }
        ClassIndex::PL_PARALLEL_ISECT => {
            // C++ plParallelIsect::Read — u16 n, then n plane pairs
            let n = reader.read_u16()? as usize;
            let mut planes = Vec::with_capacity(n);
            for _ in 0..n {
                let norm = read_point3(reader)?;
                let min = reader.read_f32()?;
                let max = reader.read_f32()?;
                let pos_one = read_point3(reader)?;
                let pos_two = read_point3(reader)?;
                planes.push(ParallelPlane { norm, min, max, pos_one, pos_two });
            }
            Ok(Some(VolumeIsectData::Parallel { planes }))
        }
        ClassIndex::PL_CONE_ISECT => {
            // C++ plConeIsect::Read
            let capped = reader.read_u32()? != 0; // ReadBOOL = ReadLE32
            let rad_angle = reader.read_f32()?;
            let length = reader.read_f32()?;
            let world_tip = read_point3(reader)?;
            let world_norm = read_point3(reader)?;
            // Skip world-to-NDC and light-to-NDC matrices (hsMatrix44 with bool prefix each)
            let has_w2ndc = reader.read_u8()?;
            if has_w2ndc != 0 { reader.skip(64)?; }
            let has_l2ndc = reader.read_u8()?;
            if has_l2ndc != 0 { reader.skip(64)?; }
            let n = if capped { 5 } else { 4 };
            let mut norms = Vec::with_capacity(n);
            let mut dists = Vec::with_capacity(n);
            for _ in 0..n {
                norms.push(read_point3(reader)?);
                dists.push(reader.read_f32()?);
            }
            Ok(Some(VolumeIsectData::Cone { capped, rad_angle, length, world_tip, world_norm, norms, dists }))
        }
        _ => {
            bail!("Unknown plVolumeIsect subtype: 0x{:04X}", class_idx);
        }
    }
}

// ============================================================================
// plSoftVolume subtypes (0x0088-0x008C) — spatial containment volumes
// ============================================================================

/// Soft volume — position-based strength evaluation.
/// C++ ref: plSoftVolume hierarchy.
#[derive(Debug, Clone)]
pub enum SoftVolume {
    Simple {
        key: Option<crate::core::uoid::Uoid>,
        inside_strength: f32,
        outside_strength: f32,
        soft_dist: f32,
        bounds_min: [f32; 3],
        bounds_max: [f32; 3],
        disabled: bool,
    },
    Union {
        key: Option<crate::core::uoid::Uoid>,
        inside_strength: f32,
        outside_strength: f32,
        sub_keys: Vec<crate::core::uoid::Uoid>,
    },
    Intersect {
        key: Option<crate::core::uoid::Uoid>,
        inside_strength: f32,
        outside_strength: f32,
        sub_keys: Vec<crate::core::uoid::Uoid>,
    },
    Invert {
        key: Option<crate::core::uoid::Uoid>,
        inside_strength: f32,
        outside_strength: f32,
        sub_key: Option<crate::core::uoid::Uoid>,
    },
}

impl SoftVolume {
    pub fn key(&self) -> &Option<crate::core::uoid::Uoid> {
        match self {
            SoftVolume::Simple { key, .. } => key,
            SoftVolume::Union { key, .. } => key,
            SoftVolume::Intersect { key, .. } => key,
            SoftVolume::Invert { key, .. } => key,
        }
    }
}

/// Read the plObjInterface prologue (self-key + synch + owner key + props bitvector).
/// Returns (self_key, disabled).
/// C++: plObjInterface::Read → plSynchedObject::Read + owner key + fProps
fn read_obj_interface_header(cursor: &mut Cursor<&[u8]>) -> Result<(Option<crate::core::uoid::Uoid>, bool)> {
    use crate::core::uoid::read_key_uoid;

    // Creatable class index
    let class_idx = cursor.read_i16()?;
    if class_idx < 0 { bail!("Null creatable in soft volume"); }

    // hsKeyedObject::Read — self-key
    let self_key = read_key_uoid(cursor)?;

    // plSynchedObject::Read
    skip_synched_object(cursor)?;

    // plObjInterface — owner key
    let _owner_key = read_key_uoid(cursor)?;

    // plObjInterface — fProps (hsBitVector)
    let prop_words = read_bit_vector_words(cursor)?;
    let disabled = !prop_words.is_empty() && (prop_words[0] & 1) != 0; // bit 0 = kDisable

    Ok((self_key, disabled))
}

/// Read plSoftVolume base fields after plObjInterface header.
/// Returns (listen_state, inside_strength, outside_strength).
/// C++ ref: plSoftVolume.cpp:51-61
fn read_soft_volume_base(cursor: &mut Cursor<&[u8]>) -> Result<(u32, f32, f32)> {
    let listen_state = cursor.read_u32()?;
    let inside_strength = cursor.read_f32()?;
    let outside_strength = cursor.read_f32()?;
    Ok((listen_state, inside_strength, outside_strength))
}

/// Parse plSoftVolumeSimple (0x0088) from PRP object data.
/// C++ ref: plSoftVolumeTypes.cpp:92-98
pub fn parse_soft_volume_simple(data: &[u8]) -> Result<(SoftVolume, Option<VolumeIsectData>)> {
    let mut cursor = Cursor::new(data);

    let (self_key, disabled) = read_obj_interface_header(&mut cursor)?;
    let (_listen_state, inside_strength, outside_strength) = read_soft_volume_base(&mut cursor)?;

    // plSoftVolumeSimple::Read
    let soft_dist = cursor.read_f32()?;

    // Inline creatable: plVolumeIsect subtype
    let volume = read_volume_isect(&mut cursor)?;

    // Compute AABB from isect for the existing SoftVolume::Simple struct
    let (bounds_min, bounds_max) = match &volume {
        Some(VolumeIsectData::Convex { planes }) => compute_convex_bounds(planes),
        Some(VolumeIsectData::Sphere { world_center, radius, .. }) => {
            let r = *radius;
            (
                [world_center[0] - r, world_center[1] - r, world_center[2] - r],
                [world_center[0] + r, world_center[1] + r, world_center[2] + r],
            )
        }
        Some(VolumeIsectData::Cylinder { world_bot, world_norm, length, radius, .. }) => {
            let r = *radius;
            let top = [
                world_bot[0] + world_norm[0] * length,
                world_bot[1] + world_norm[1] * length,
                world_bot[2] + world_norm[2] * length,
            ];
            (
                [
                    world_bot[0].min(top[0]) - r,
                    world_bot[1].min(top[1]) - r,
                    world_bot[2].min(top[2]) - r,
                ],
                [
                    world_bot[0].max(top[0]) + r,
                    world_bot[1].max(top[1]) + r,
                    world_bot[2].max(top[2]) + r,
                ],
            )
        }
        _ => ([f32::MIN, f32::MIN, f32::MIN], [f32::MAX, f32::MAX, f32::MAX]),
    };

    let sv = SoftVolume::Simple {
        key: self_key,
        inside_strength,
        outside_strength,
        soft_dist,
        bounds_min,
        bounds_max,
        disabled,
    };

    Ok((sv, volume))
}

/// Compute AABB from convex planes (intersection of half-spaces).
/// Uses plane positions as approximate bounds since exact convex hull is expensive.
fn compute_convex_bounds(planes: &[ConvexPlane]) -> ([f32; 3], [f32; 3]) {
    if planes.is_empty() {
        return ([0.0; 3], [0.0; 3]);
    }
    let mut min = [f32::MAX; 3];
    let mut max = [f32::MIN; 3];
    for p in planes {
        for i in 0..3 {
            min[i] = min[i].min(p.pos[i]);
            max[i] = max[i].max(p.pos[i]);
        }
    }
    (min, max)
}

/// Parse plSoftVolumeComplex base (Union/Intersect/Invert all share this).
/// C++ ref: plSoftVolumeTypes.cpp:127-133
fn parse_soft_volume_complex_base(data: &[u8]) -> Result<(
    Option<crate::core::uoid::Uoid>,
    f32, f32,
    Vec<crate::core::uoid::Uoid>,
)> {
    use crate::core::uoid::read_key_uoid;
    let mut cursor = Cursor::new(data);

    let (self_key, _disabled) = read_obj_interface_header(&mut cursor)?;
    let (_listen_state, inside_strength, outside_strength) = read_soft_volume_base(&mut cursor)?;

    // Sub-volume keys
    let n = cursor.read_u32()? as usize;
    let mut sub_keys = Vec::with_capacity(n);
    for _ in 0..n {
        if let Some(uoid) = read_key_uoid(&mut cursor)? {
            sub_keys.push(uoid);
        }
    }

    Ok((self_key, inside_strength, outside_strength, sub_keys))
}

/// Parse plSoftVolumeUnion (0x008A).
/// C++ ref: plSoftVolumeTypes.cpp — reads plSoftVolumeComplex::Read only.
pub fn parse_soft_volume_union(data: &[u8]) -> Result<SoftVolume> {
    let (self_key, inside_strength, outside_strength, sub_keys) =
        parse_soft_volume_complex_base(data)?;
    Ok(SoftVolume::Union { key: self_key, inside_strength, outside_strength, sub_keys })
}

/// Parse plSoftVolumeIntersect (0x008B).
/// C++ ref: plSoftVolumeTypes.cpp — reads plSoftVolumeComplex::Read only.
pub fn parse_soft_volume_intersect(data: &[u8]) -> Result<SoftVolume> {
    let (self_key, inside_strength, outside_strength, sub_keys) =
        parse_soft_volume_complex_base(data)?;
    Ok(SoftVolume::Intersect { key: self_key, inside_strength, outside_strength, sub_keys })
}

/// Parse plSoftVolumeInvert (0x008C).
/// C++ ref: plSoftVolumeTypes.cpp — reads plSoftVolumeComplex::Read only.
/// Constraint: sub_volumes.len() <= 1
pub fn parse_soft_volume_invert(data: &[u8]) -> Result<SoftVolume> {
    let (self_key, inside_strength, outside_strength, sub_keys) =
        parse_soft_volume_complex_base(data)?;
    let sub_key = sub_keys.into_iter().next();
    Ok(SoftVolume::Invert { key: self_key, inside_strength, outside_strength, sub_key })
}

/// Read hsBitVector and return as Vec<u32> words. Public for span vis parsing.
pub fn read_bit_vector(data: &[u8], offset: &mut usize) -> Vec<u32> {
    if *offset + 4 > data.len() { return Vec::new(); }
    let count = u32::from_le_bytes([data[*offset], data[*offset+1], data[*offset+2], data[*offset+3]]) as usize;
    *offset += 4;
    let mut words = Vec::with_capacity(count);
    for _ in 0..count {
        if *offset + 4 > data.len() { break; }
        words.push(u32::from_le_bytes([data[*offset], data[*offset+1], data[*offset+2], data[*offset+3]]));
        *offset += 4;
    }
    words
}

// ============================================================================
// plDynaDecalMgr (0x00E6) and subclasses — dynamic decals
// ============================================================================

/// Type of dynamic decal manager parsed from PRP.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DecalManagerType {
    Foot,
    Ripple,
    Puddle,
    Bullet,
    Wake,
    Torpedo,
    RippleVS,
    TorpedoVS,
}

/// Parsed plDynaDecalMgr data from PRP.
#[derive(Debug, Clone)]
pub struct DecalManagerData {
    pub name: String,
    pub manager_type: DecalManagerType,
    pub mat_pre_shade: Option<String>,
    pub mat_rt_shade: Option<String>,
    pub target_names: Vec<String>,
    pub max_num_verts: u32,
    pub max_num_idx: u32,
    pub wait_on_enable: u32,
    pub intensity: f32,
    pub wet_length: f32,
    pub ramp_end: f32,
    pub decay_start: f32,
    pub life_span: f32,
    pub grid_size_u: f32,
    pub grid_size_v: f32,
    pub scale: [f32; 3],
    pub party_time: f32,
    pub notify_names: Vec<String>,
    pub init_uvw: Option<[f32; 3]>,
    pub final_uvw: Option<[f32; 3]>,
    pub wake_default_dir: Option<[f32; 3]>,
    pub wake_anim_wgt: Option<f32>,
    pub wake_vel_wgt: Option<f32>,
}

/// Parse plDynaDecalMgr base. C++ ref: plDynaDecalMgr.cpp:193-249
fn parse_dyna_decal_mgr_base(cursor: &mut Cursor<&[u8]>) -> Result<DecalManagerData> {
    use crate::core::uoid::read_key_uoid;
    let self_key = read_key_uoid(cursor)?;
    let name = self_key.as_ref().map(|k| k.object_name.clone()).unwrap_or_default();
    skip_synched_object(cursor)?;
    let mat_pre = read_key_name(cursor)?;
    let mat_rt = read_key_name(cursor)?;
    let num_targets = cursor.read_u32()?;
    let mut target_names = Vec::new();
    for _ in 0..num_targets { if let Some(n) = read_key_name(cursor)? { target_names.push(n); } }
    let num_party = cursor.read_u32()?;
    for _ in 0..num_party { let _ = read_key_name(cursor)?; }
    let max_num_verts = cursor.read_u32()?;
    let max_num_idx = cursor.read_u32()?;
    let wait_on_enable = cursor.read_u32()?;
    let intensity = cursor.read_f32()?;
    let wet_length = cursor.read_f32()?;
    let ramp_end = cursor.read_f32()?;
    let decay_start = cursor.read_f32()?;
    let life_span = cursor.read_f32()?;
    let grid_size_u = cursor.read_f32()?;
    let grid_size_v = cursor.read_f32()?;
    let sx = cursor.read_f32()?; let sy = cursor.read_f32()?; let sz = cursor.read_f32()?;
    let party_time = cursor.read_f32()?;
    let num_notifies = cursor.read_u32()?;
    let mut notify_names = Vec::new();
    for _ in 0..num_notifies { if let Some(n) = read_key_name(cursor)? { notify_names.push(n); } }
    Ok(DecalManagerData {
        name, manager_type: DecalManagerType::Foot,
        mat_pre_shade: mat_pre, mat_rt_shade: mat_rt, target_names,
        max_num_verts, max_num_idx, wait_on_enable,
        intensity, wet_length, ramp_end, decay_start, life_span,
        grid_size_u, grid_size_v, scale: [sx, sy, sz], party_time, notify_names,
        init_uvw: None, final_uvw: None,
        wake_default_dir: None, wake_anim_wgt: None, wake_vel_wgt: None,
    })
}

fn read_ripple_uvw(c: &mut Cursor<&[u8]>, m: &mut DecalManagerData) -> Result<()> {
    let ix = c.read_f32()?; let iy = c.read_f32()?; let iz = c.read_f32()?;
    m.init_uvw = Some([ix, iy, iz]);
    let fx = c.read_f32()?; let fy = c.read_f32()?; let fz = c.read_f32()?;
    m.final_uvw = Some([fx, fy, fz]);
    Ok(())
}

/// Parse plDynaFootMgr (0x00E8).
pub fn parse_dyna_foot_mgr(data: &[u8]) -> Result<DecalManagerData> {
    let mut c = Cursor::new(data); let _ = c.read_i16()?;
    let mut m = parse_dyna_decal_mgr_base(&mut c)?; m.manager_type = DecalManagerType::Foot; Ok(m)
}
/// Parse plDynaRippleMgr (0x00E9).
pub fn parse_dyna_ripple_mgr(data: &[u8]) -> Result<DecalManagerData> {
    let mut c = Cursor::new(data); let _ = c.read_i16()?;
    let mut m = parse_dyna_decal_mgr_base(&mut c)?; m.manager_type = DecalManagerType::Ripple;
    read_ripple_uvw(&mut c, &mut m)?; Ok(m)
}
/// Parse plDynaBulletMgr (0x00EA).
pub fn parse_dyna_bullet_mgr(data: &[u8]) -> Result<DecalManagerData> {
    let mut c = Cursor::new(data); let _ = c.read_i16()?;
    let mut m = parse_dyna_decal_mgr_base(&mut c)?; m.manager_type = DecalManagerType::Bullet; Ok(m)
}
/// Parse plDynaPuddleMgr (0x00ED).
pub fn parse_dyna_puddle_mgr(data: &[u8]) -> Result<DecalManagerData> {
    let mut c = Cursor::new(data); let _ = c.read_i16()?;
    let mut m = parse_dyna_decal_mgr_base(&mut c)?; m.manager_type = DecalManagerType::Puddle;
    read_ripple_uvw(&mut c, &mut m)?; Ok(m)
}
/// Parse plDynaWakeMgr (0x00F9).
pub fn parse_dyna_wake_mgr(data: &[u8]) -> Result<DecalManagerData> {
    let mut c = Cursor::new(data); let _ = c.read_i16()?;
    let mut m = parse_dyna_decal_mgr_base(&mut c)?; m.manager_type = DecalManagerType::Wake;
    read_ripple_uvw(&mut c, &mut m)?;
    let dx = c.read_f32()?; let dy = c.read_f32()?; let dz = c.read_f32()?;
    m.wake_default_dir = Some([dx, dy, dz]);
    let ac = c.read_u16()?; if ac != 0x8000 { return Ok(m); }
    m.wake_anim_wgt = Some(c.read_f32()?); m.wake_vel_wgt = Some(c.read_f32()?); Ok(m)
}
/// Parse plDynaTorpedoMgr (0x0129).
pub fn parse_dyna_torpedo_mgr(data: &[u8]) -> Result<DecalManagerData> {
    let mut c = Cursor::new(data); let _ = c.read_i16()?;
    let mut m = parse_dyna_decal_mgr_base(&mut c)?; m.manager_type = DecalManagerType::Torpedo;
    read_ripple_uvw(&mut c, &mut m)?; Ok(m)
}
/// Parse plDynaRippleVSMgr (0x010A).
pub fn parse_dyna_ripple_vs_mgr(data: &[u8]) -> Result<DecalManagerData> {
    let mut c = Cursor::new(data); let _ = c.read_i16()?;
    let mut m = parse_dyna_decal_mgr_base(&mut c)?; m.manager_type = DecalManagerType::RippleVS;
    read_ripple_uvw(&mut c, &mut m)?; let _ = read_key_name(&mut c)?; Ok(m)
}
/// Parse plDynaTorpedoVSMgr (0x012A).
pub fn parse_dyna_torpedo_vs_mgr(data: &[u8]) -> Result<DecalManagerData> {
    let mut c = Cursor::new(data); let _ = c.read_i16()?;
    let mut m = parse_dyna_decal_mgr_base(&mut c)?; m.manager_type = DecalManagerType::TorpedoVS;
    read_ripple_uvw(&mut c, &mut m)?; let _ = read_key_name(&mut c)?; Ok(m)
}

// ============================================================================
// plEAXListenerMod (0x00E5) — EAX reverb zone modifier
// ============================================================================

/// EAX reverb properties parsed from PRP.
/// C++ ref: EAXREVERBPROPERTIES (plEAXStructures.h:52-78)
/// C++ ref: plEAXListenerMod::Read (plEAXListenerMod.cpp:167-202)
#[derive(Debug, Clone)]
pub struct EaxListenerModData {
    pub self_key: Option<crate::core::uoid::Uoid>,
    /// Soft volume key — spatial zone that controls this reverb.
    /// C++ ref: plEAXListenerMod::fSoftRegion (kRefSoftRegion = 0)
    pub soft_region_key: Option<String>,
    /// EAX environment preset index.
    pub environment: u32,
    /// Environment size in meters.
    pub environment_size: f32,
    /// Environment diffusion (0.0-1.0).
    pub environment_diffusion: f32,
    /// Room effect level in millibels (-10000 to 0).
    pub room: i32,
    /// Room HF effect level in millibels (-10000 to 0).
    pub room_hf: i32,
    /// Room LF effect level in millibels (-10000 to 0).
    pub room_lf: i32,
    /// Reverberation decay time in seconds (0.1 to 20.0).
    pub decay_time: f32,
    /// High-frequency to mid-frequency decay time ratio (0.1 to 2.0).
    pub decay_hf_ratio: f32,
    /// Low-frequency to mid-frequency decay time ratio.
    pub decay_lf_ratio: f32,
    /// Early reflections level in millibels (-10000 to 1000).
    pub reflections: i32,
    /// Initial reflection delay in seconds (0.0 to 0.3).
    pub reflections_delay: f32,
    /// Late reverberation level in millibels (-10000 to 2000).
    pub reverb: i32,
    /// Late reverberation delay in seconds (0.0 to 0.1).
    pub reverb_delay: f32,
    /// Echo time in seconds.
    pub echo_time: f32,
    /// Echo depth (0.0-1.0).
    pub echo_depth: f32,
    /// Modulation time in seconds.
    pub modulation_time: f32,
    /// Modulation depth (0.0-1.0).
    pub modulation_depth: f32,
    /// Air absorption HF in millibels/meter.
    pub air_absorption_hf: f32,
    /// HF reference frequency in Hz.
    pub hf_reference: f32,
    /// LF reference frequency in Hz.
    pub lf_reference: f32,
    /// Room rolloff factor.
    pub room_rolloff_factor: f32,
    /// EAX environment flags.
    pub flags: u32,
}

/// Parse plEAXListenerMod (0x00E5) from PRP object data.
/// Format: plSingleModifier::Read (self-key + synched + hsBitVector)
///         -> key ref (soft volume) -> 21 EAX reverb parameters
/// C++ ref: plEAXListenerMod.cpp:167-202
pub fn parse_eax_listener_mod(data: &[u8]) -> Result<EaxListenerModData> {
    use crate::core::uoid::read_key_uoid;
    let mut cursor = Cursor::new(data);

    // Creatable class index (i16)
    let _class_idx = cursor.read_i16()?;

    // hsKeyedObject::Read — self-key
    let self_key = read_key_uoid(&mut cursor)?;

    // plSynchedObject::Read
    skip_synched_object(&mut cursor)?;

    // plSingleModifier::Read — hsBitVector fFlags
    let num_bit_vectors = cursor.read_u32()?;
    for _ in 0..num_bit_vectors {
        let _word = cursor.read_u32()?;
    }

    // Soft volume key reference
    // C++ ref: mgr->ReadKeyNotifyMe(s, ..., kRefSoftRegion)
    let soft_region_uoid = read_key_uoid(&mut cursor)?;
    let soft_region_key = soft_region_uoid.map(|u| u.object_name.clone());

    // EAX reverb properties — exact field order from plEAXListenerMod::Read
    // C++ ref: plEAXListenerMod.cpp:175-198
    let environment = cursor.read_u32()?;
    let environment_size = cursor.read_f32()?;
    let environment_diffusion = cursor.read_f32()?;
    let room = cursor.read_i32()?;
    let room_hf = cursor.read_i32()?;
    let room_lf = cursor.read_i32()?;
    let decay_time = cursor.read_f32()?;
    let decay_hf_ratio = cursor.read_f32()?;
    let decay_lf_ratio = cursor.read_f32()?;
    let reflections = cursor.read_i32()?;
    let reflections_delay = cursor.read_f32()?;
    // Note: vReflectionsPan (EAXVECTOR) is NOT serialized — C++ skips it
    let reverb = cursor.read_i32()?;
    let reverb_delay = cursor.read_f32()?;
    // Note: vReverbPan (EAXVECTOR) is NOT serialized — C++ skips it
    let echo_time = cursor.read_f32()?;
    let echo_depth = cursor.read_f32()?;
    let modulation_time = cursor.read_f32()?;
    let modulation_depth = cursor.read_f32()?;
    let air_absorption_hf = cursor.read_f32()?;
    let hf_reference = cursor.read_f32()?;
    let lf_reference = cursor.read_f32()?;
    let room_rolloff_factor = cursor.read_f32()?;
    let flags = cursor.read_u32()?;

    Ok(EaxListenerModData {
        self_key,
        soft_region_key,
        environment,
        environment_size,
        environment_diffusion,
        room,
        room_hf,
        room_lf,
        decay_time,
        decay_hf_ratio,
        decay_lf_ratio,
        reflections,
        reflections_delay,
        reverb,
        reverb_delay,
        echo_time,
        echo_depth,
        modulation_time,
        modulation_depth,
        air_absorption_hf,
        hf_reference,
        lf_reference,
        room_rolloff_factor,
        flags,
    })
}

// ============================================================================
// Round-trip tests — read PRP, write back, compare bytes
// ============================================================================

#[cfg(test)]
mod round_trip_tests {
    use super::*;
    use std::path::Path;

    /// Round-trip a single PRP file: read → write → compare bytes.
    fn round_trip_file(path: &Path) -> Result<()> {
        let original = std::fs::read(path)?;
        let page = PrpPage::from_file(path)?;
        let written = page.to_bytes()?;

        if original != written {
            // Find first difference
            let min_len = original.len().min(written.len());
            for i in 0..min_len {
                if original[i] != written[i] {
                    bail!(
                        "{}: first byte diff at offset 0x{:X} (orig={:#04X}, written={:#04X}), \
                         original={} bytes, written={} bytes",
                        path.display(), i, original[i], written[i],
                        original.len(), written.len()
                    );
                }
            }
            if original.len() != written.len() {
                bail!(
                    "{}: length mismatch: original={} bytes, written={} bytes",
                    path.display(), original.len(), written.len()
                );
            }
        }
        Ok(())
    }

    #[test]
    fn test_round_trip_cleft() {
        let path = Path::new("../../Plasma/staging/client/dat/Cleft_District_Cleft.prp");
        if !path.exists() {
            eprintln!("Skipping: {:?} not found", path);
            return;
        }
        round_trip_file(path).unwrap();
        eprintln!("Round-trip OK: Cleft_District_Cleft.prp");
    }

    #[test]
    fn test_round_trip_all_ages() {
        let dat_dir = Path::new("../../Plasma/staging/client/dat");
        if !dat_dir.exists() {
            eprintln!("Skipping: {:?} not found", dat_dir);
            return;
        }

        let mut total = 0;
        let mut passed = 0;
        let mut failed = 0;
        let mut failures: Vec<String> = Vec::new();

        let mut entries: Vec<_> = std::fs::read_dir(dat_dir).unwrap()
            .filter_map(|e| e.ok())
            .filter(|e| e.path().extension().is_some_and(|ext| ext == "prp"))
            .collect();
        entries.sort_by_key(|e| e.file_name());

        for entry in &entries {
            total += 1;
            match round_trip_file(&entry.path()) {
                Ok(()) => passed += 1,
                Err(e) => {
                    failed += 1;
                    let msg = format!("{}", e);
                    if failures.len() < 10 {
                        failures.push(msg.clone());
                    }
                    eprintln!("FAIL: {}", msg);
                }
            }
        }

        eprintln!("\nRound-trip results: {}/{} passed, {} failed", passed, total, failed);

        if failed > 0 {
            panic!("{} PRP files failed round-trip. First failures:\n{}",
                failed, failures.join("\n"));
        }
    }
}