This file is indexed.

/usr/src/castle-game-engine-5.0.0/x3d/x3dnodes_node.inc is in castle-game-engine-src 5.0.0-3.

This file is owned by root:root, with mode 0o644.

The actual contents of the file can be viewed below.

   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
{
  Copyright 2002-2014 Michalis Kamburelis.

  This file is part of "Castle Game Engine".

  "Castle Game Engine" is free software; see the file COPYING.txt,
  included in this distribution, for details about the copyright.

  "Castle Game Engine" is distributed in the hope that it will be useful,
  but WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

  ----------------------------------------------------------------------------
}

{ TX3DNode class. Huge class, the basic building block of VRML nodes. }

{$ifdef read_interface}

  { Private stuff for TX3DNode.DeepCopy and friends implementation. }
  TX3DNodeDeepCopyState = class
  private
    { These two lists must always have exactly the same length. }
    Original, New: TX3DNodeList;
  public
    constructor Create;
    destructor Destroy; override;
    { Return a copy or OriginalNode.

      To keep sharing of nodes (DEF/USE mechanism) within the newly
      created copy, we need a list of already duplicated children.
      This method uses and updates such list. When called for the
      first time with OriginalNode, it actually creates a duplicate
      (by OriginalNode.DeepCopy). Next time, it will just return
      this copy. }
    function DeepCopy(OriginalNode: TX3DNode): TX3DNode;
  end;

  { X3D node interface.
    All other interfaces for X3D nodes descend from this. }
  IX3DNode = interface
  ['{5BD33327-430F-47EC-9241-AD899F072BF8}']
  end;

  { X3D node. Every VRML/X3D node class descends from this. }
  TX3DNode = class(TX3DFileItem, IX3DNode)
  private
    fNodeName: string;
    FBaseUrl: string;
    FVRML1Children, FVRML1Parents: TX3DNodeList;
    FKeepExisting: Cardinal;
    FParentFields: TX3DFieldList;
    FPrototypes: TX3DPrototypeBaseList;
    FRoutes: TX3DRouteList;
    FImportsList, FExportsList: TX3DFileItemList;
    FFields: TX3DFieldList;
    FEvents: TX3DEventList;
    FPrototypeInstance: boolean;
    FPrototypeInstanceSourceNode: TX3DPrototypeNode;
    FPrototypeInstanceHelpers: TX3DNode;
    FDefaultContainerField: string;
    FHasInterfaceDeclarations: TX3DAccessTypes;
    FInterfaceDeclarations: TX3DInterfaceDeclarationList;
    FCDataField: TMFString;
    FDestructionNotifications: TNodeDestructionNotificationList;
    FScene: TX3DEventsEngine;
    FShapeTrees: TObject;

    { Internally used by PROTO instantiating mechanism,
      in TX3DPrototypeNode.InstantiateIsClauses
      and TX3DPrototypeNode.Instantiate.

      This is always @false outside of TX3DPrototypeNode.Instantiate
      implementation (as TX3DPrototypeNode.Instantiate sets it to @true
      and changes back to @false for appropriate nodes). }
    NeedsInstantiateIsClause: boolean;

    function GetVRML1Child(i: integer): TX3DNode;
    function GetVRML1Parent(i: integer): TX3DNode;
    procedure SetVRML1Child(I: Integer; Value: TX3DNode);
    function GetParentFieldsItem(Index: Integer): TX3DField;
    function GetParentFieldsNodeItem(Index: Integer): TX3DNode;
    procedure RemoveParentField(Field: TX3DField);
    procedure AddParentField(Field: TX3DField);
    procedure TryFindNode_Found(Node: TX3DNode);
    procedure SetHasInterfaceDeclarations(const Value: TX3DAccessTypes);
    { Internal save to stream utility.
      When CurrentContainerField is not empty, it means we know our containing field
      (and should adjust containerField= for XML encoding output). }
    procedure NodeSaveToStream(Writer: TX3DWriter; const CurrentContainerField: string = '');
  protected

    { Does actual DeepCopy work. You can override this to copy some
      more properties for descendants. }
    function DeepCopyCore(CopyState: TX3DNodeDeepCopyState): TX3DNode; virtual;

    { This should be a mere call to constructor of your own class.

      In TX3DNode, this simply calls default virtual constructor,
      which is Ok for all normal nodes. But we have some special nodes,
      like TX3DPrototypeNode or TX3DUnknownNode, that simply cannot
      be created by default constructor. They need to override this. }
    function DeepCopyCreate(CopyState: TX3DNodeDeepCopyState): TX3DNode; virtual;
  protected
    { Are VRML 1.0 children allowed.
      This condition is checked in VRML1ChildAdd, so it's strictly
      impossible to add a node that is not allowed.

      Note that in some special cases VRML1ChildrenAllowed and
      VRML1ChildrenParsingAllowed values may be changed during object lifetime.
      Currently, this may concern TX3DUnknownNode.

      Default @false. }
    VRML1ChildrenAllowed: boolean;

    { VRML 1.0 children allowed to be added during parsing.
      This is used only by *Inline nodes for now, that do not allow
      reading children during parsing but may get new children
      in memory. So their VRML1ChildrenParsingAllowed must be empty,
      but VRML1ChildrenAllowed must allow all.

      When VRML1ChildrenAllowed is @false then VRML1ChildrenParsingAllowed should
      also be @false.

      Default @false. }
    VRML1ChildrenParsingAllowed: boolean;

    { Should SaveToStream save our VRML1Children.
      In this class default implementation returns @true,
      this is what you will want in 99% of cases.
      It's useful to set this to false if you use
      VRML1Children internally, e.g. *Inline nodes. }
    class function VRML1ChildrenSaveToStream: boolean; virtual;

    { Enumerate all active child nodes of given node.

      "Active nodes" are the ones affecting current VRML graph look
      or collisions, e.g. from Switch
      node only one child will be enumerated.
      See @link(Traverse) for more precise definition.

      "Direct" means that this enumerates only direct
      descendants, i.e. this is not recursive.
      See methods like Traverse or EnumerateNodes if you
      want recursive behavior.

      This can enumerate both @link(VRML1Children) nodes
      nodes within TSFNode and TMFNode fields.

      Default implementation in this class returns all Children
      nodes of VRML 1.0. If you need to remove some children
      for VRML 1.0 (e.g. for Switch or LOD nodes)
      or add some children for VRML 2.0 you
      have to override this. You're not required to call
      inherited when overriding this. }
    procedure DirectEnumerateActive(
      Func: TEnumerateChildrenFunction); virtual;

    { Enumerate all active child nodes of given node,
      and may additionally modify StateStack. It's used by Traverse.

      Default implementation in this class simply calls
      DirectEnumerateActive, ignoring StateStack, and this is suitable
      for 99% of nodes. However, for some special nodes (only Collision
      node for now), they have to modify state during traversing into
      various children, and then they can override this. }
    procedure DirectEnumerateActiveForTraverse(
      Func: TEnumerateChildrenFunction;
      StateStack: TX3DGraphTraverseStateStack); virtual;

    { Simply enumerate all direct descendant nodes.
      That is, all children in VRML 1.0 style and
      all nodes in SFNode and MFNode fields.
      This includes prototype stuff, if this node is expanded
      from prototype: PrototypeInstanceSourceNode and PrototypeInstanceHelpers. }
    procedure DirectEnumerateAll(
      Func: TEnumerateChildrenFunction);

    { This enumerates direct descendant nodes of this node.
      This is equivalent to DirectEnumerateActive or
      DirectEnumerateAll, depending on value of OnlyActive param. }
    procedure DirectEnumerate(
      Func: TEnumerateChildrenFunction;
      OnlyActive: boolean);

    { Override these methods to determine what happens when
      given node is traversed during Traverse call.
      The main use of this is to operate on TX3DGraphTraverseStateStack.

      Remember to always call inherited when overriding.
      In BeforeTraverse and MiddleTraverse you should call inherited
      at the beginning, in AfterTraverse inherited should be called at the end.

      Besides changing StateStack.Top fields, you can do push/pop
      on the stack. Remember that if you do StateStack.Push in BeforeTraverse,
      and then you @italic(must call StateStack.Pop in AfterTraverse).

      @groupBegin }
    procedure BeforeTraverse(StateStack: TX3DGraphTraverseStateStack); virtual;
    procedure MiddleTraverse(StateStack: TX3DGraphTraverseStateStack); virtual;
    procedure AfterTraverse(StateStack: TX3DGraphTraverseStateStack); virtual;
    { @groupEnd }

    { Parse VRML node body element. Usually, this is a field.
      May also be VRML 1.0 style child node.
      May also be VRML 2.0 Script node interface declaration, etc.
      --- see VRML 2.0 grammar spec.

      This should be overriden to parse special features within particular
      nodes. While generally VRML is very clean and there's no need to
      override this, there's one use for this currently:

      @orderedList(
        @item(Since we handle a couple of VRML flavors (at least
          Inventor, VRML 1.0 and VRML 97), sometimes the same node has
          different fields to express the same things in various VRML flavors.
          So it may be useful to parse a field and copy it's value into
          other fields.

          Example: TShapeHintsNode_1 in Inventor parses "hints" field,
          and copies it's value to other fields as appropriate.
          "hints" field is not exposed in TShapeHintsNode_1 interface,
          so everything is clean in the interface, and under the hood
          TShapeHintsNode_1 can "magically" handle "hints" field for Inventor.)
      )

      When overriding, always check inherited result first, and exit if
      inherited handled successfully.
      Otherwise either read your stuff and return @true
      (Lexer should advance to the position of next "nodeBodyElement").
      Or return @false without changing Lexer position. }
    function ParseNodeBodyElement(Lexer: TX3DLexer; Reader: TX3DReaderNames;
      const APositionInParent: Integer): boolean; virtual;

    { Called at the end of parsing (in both classic and XML encoding). }
    procedure ParseAfter(Reader: TX3DReaderNames); virtual;

    procedure CreateNode; virtual;

    { The field where CDATA section from XML is added.
      Used when loading X3D in XML encoding: XML elements may contain
      CDATA sections, that are added to "url" field.
      See X3D XML encoding specification about
      "Encapsulating Script node code"
      [http://www.web3d.org/x3d/specifications/ISO-IEC-19776-1.2-X3DEncodings-XML/Part01/concepts.html#EncapsulatingScriptNodeCode].
      We also allow this for shader nodes (sensible (follows the intention
      of the spec) and compatible with InstantReality).

      When not assigned, then CDATA section for this node is not allowed.

      This should be set in descendants constructor. }
    property CDataField: TMFString read FCDataField write FCDataField;
  public
    { Node fields.

      For normal nodes, all Fields are created and added
      to Fields list in constructor. Fields default values are set,
      and of course current field values are set to these defaults.
      Later, we only modify these fields current values (e.g. when parsing).

      However, there are special node classes that set their Fields differently.
      TX3DPrototypeNode has their fields set according to it's VRML 2.0 prototype.
      TX3DUnknownNode may have it's fields set by VRML 1.0 "fields" feature
      (so it's Fields are initialized by parsing it).

      Nodes with HasInterfaceDeclarations have some Fields and Events
      added when reading node.

      All fields on this list are owned by this object. }
    property Fields: TX3DFieldList read FFields;

    { Explicit events (that is, not exposed by some field) of this node.
      For exposed events, see each field's property ExposedEvents. }
    property Events: TX3DEventList read FEvents;

    { Search by name for given field or event (exposed by some field or not).

      @nil if not found. }
    function FieldOrEvent(const Name: string): TX3DFieldOrEvent;

    { Search by name for given event (exposed by some field or not).

      @nil if not found. }
    function AnyEvent(const Name: string): TX3DEvent;

    { VRML 1.0 children nodes. These are nodes directly specified inside
      a VRML 1.0 node, they don't belong to any node field. (In VRML 1.0,
      there was no SFNode / MFNode fields.)

      In VRML 2.0, this is always empty.

      VRML 1.0 nodes may have any number of children.
      The children nodes refer back to it's parent nodes in VRML1Parents list.
      When travelling over VRML/X3D graph, remember that cycles
      are possible, because of DEF/USE.
      Obviously, they possible when travelling along the VRML1Parents list.
      We currently assume that there are no cycles when we treat the graph
      as directed, but it may change one day (some VRML/X3D models
      create real cycles).

      Adding/removing stuff from the VRML1Children list keeps track
      of how many times a node is used. If the child node has no parents,
      it will be freed.
      Actually, nodes can be children of both nodes (VRML 1.0 style,
      then VRML1Children and VRML1Parents is used) or fields (TMFNode or TSFNode,
      in VRML 2.0 style; then ParentFields is used). So the node is freed
      only when it's not referenced by any node and not referenced by any
      field. Generally, it's the parent that takes care of reference-counting
      and freeing the children, not the other way around.

      Note that given node instance may be a children of a single node
      multiple times, through DEF/USE mechanism. The order of children
      is important and preserved. (On the other hand, the order of
      VRML1Parents is not important, as that list is mostly for reference-counting.)

      You can replace one children with another like
      @code(VRML1Children[I] := NewChildren;).
      This works like a shortcut for
      @code(VRML1ChildRemove(I); VRML1ChildAdd(I, NewChildren);).
      But 1. it's more efficient; 2. it's safer --- if Children[I]
      is already equal to NewChildren, it does nothing.

      @groupBegin }
    property VRML1Children [i: integer]: TX3DNode read GetVRML1Child write SetVRML1Child;
    function VRML1ChildrenCount: integer;
    { @groupEnd }

    { Add a VRML 1.0 child node at given position.
      Index (position) must be in [0..VRML1ChildrenCount].
      Items at and above Index position are moved to the right,
      to insert new child at Index position. }
    procedure VRML1ChildAdd(Index: Integer; child: TX3DNode); overload;

    { Add a VRML 1.0 child node at the end of VRML1Children list. }
    procedure VRML1ChildAdd(child: TX3DNode); overload;

    procedure VRML1ChildRemove(i: integer);
    procedure VRML1ChildrenClear;

    { Remove a VRML 1.0 children at index I and return it (do not free it).
      Compare this with VRML1Remove, that removes children I and
      frees it if it's no longer used by anything.

      This removes children I, appropriately adjusting
      all parent / children links, but even if a node is unused after removing,
      it is not freed. It's always returned. }
    function VRML1ChildExtract(I: Integer): TX3DNode;

    { VRML 1.0 parent nodes. VRML1Parents is a reverse of
      VRML1Children --- it lists all the nodes where we are on VRML1Children
      list.

      @groupBegin }
    property VRML1Parents [i: integer] :TX3DNode read GetVRML1Parent;
    function VRML1ParentsCount: integer;
    { @groupEnd }

    { This lists all SFNode and MFNode fields where this node is referenced.
      This is somewhat analogous for VRML1Parents, but for VRML 2.0.

      ParentFieldsNode is just for your comfort, it returns always
      appropriate field's ParentNode property value
      (i.e. @code((ParentField[Index] as TSFNode).ParentNode)
      or @code((ParentField[Index] as TMFNode).ParentNode)).

      @groupBegin }
    property ParentFields[Index: Integer]: TX3DField read GetParentFieldsItem;
    property ParentFieldsNode[Index: Integer]: TX3DNode
      read GetParentFieldsNodeItem;
    function ParentFieldsCount: Integer;
    { @groupEnd }

    { Free this object (if it's not @nil) @italic(also removing
      it from @bold(all) parent nodes and fields).

      By design, normal destructor (Destroy called by Free)
      doesn't care about removing references to this object from
      it's parents. That's because it's the parents that usually
      initialize freeing of their children, and they free child
      when it's reference count is 0. So this freeing method
      is special in this regard.

      Use this if you really want to remove all node occurrences from the middle
      of VRML hierarchy. }
    procedure FreeRemovingFromAllParents;

    { Free this node if it is not referenced by any parent fields or nodes.
      Takes into account that node may have VRML 1.0 parent nodes
      and VRML 2.0 / X3D parent fields (SFNode or MFNode).
      This is a safe way of removing
      a node that may, but doesn't have to, be part of some VRML/X3D graph.
      The idea is that if a node is a part of some graph,
      we don't need to do anything (since you should have
      a reference to the entine graph somewhere anyway), otherwise node is
      considered unused and freed.

      Analogous to standard TObject.Free, this also works when called on
      a @nil value (does nothing in this case).

      For safety, it's advised to set reference to @nil after calling FreeIfUnused.
      You can use FreeIfUnusedAndNil utility for this (that employs a trick
      to @nil the visible reference even before freeing, which is even safer).
      This is analogous to standard FreeAndNil. }
    procedure FreeIfUnused;

    { Increase KeepExisting property value to disable automatic freeing
      of the node when unused.
      This may be useful in cases when you remove the node from VRML graph
      hierarchy, but you want to keep a valid reference to it anyway
      (for example, maybe you'll free it later by hand or add it somewhere
      else).

      Simple methods KeepExistingBegin and KeepExistingEnd simply increase /
      decrease KeepExisting value by 1. This is the most usual usage.

      @groupBegin }
    property KeepExisting: Cardinal read FKeepExisting write FKeepExisting;
    procedure KeepExistingBegin;
    procedure KeepExistingEnd;
    { @groupEnd }

    { Name of this node. When saving/loading, this comes from VRML/X3D
      "DEF" construct. Empty value means that the name is not defined.

      Do not change it during loading / saving or searching. }
    property NodeName: string read fNodeName write FNodeName;

    { Base URL for all URLs inside our fields.
      Used everywhere as a base for relative URLs, to handle fields that refer
      to external files like textures, other 3D models (ImageTexture,
      Inline nodes, many others).

      It must be an absolute URL. Currently, it doesn't have to contain
      a protocol, and is then interpreted as a path on local filesystem
      (just like it had file:// prefix). Still, it must be an absolute path.

      This is set in constructor, and eventually adjusted by
      various parsing routines.
      This way we could, if only we would like to, resolve nodes
      like Inline or ImageTexture immediately after parsing them. }
    property BaseUrl: string read FBaseUrl write FBaseUrl;

    { Old deprecated name for BaseUrl. @deprecated }
    property WWWBasePath: string read FBaseUrl write FBaseUrl; deprecated;

    { Returns an absolute path, assuming that RelativePath is relative
      path from BaseUrl or that RelativePath is already absolute. }
    function PathFromBaseUrl(const RelativePath: string): string;

    { Parse node. This should set values of your fields, VRML 1.0 Children
      list, BaseUrl.

      In special cases like TX3DUnknownNode this may
      actually initialize whole Fields list (by VRML 1.0 "fields" extensibility
      feature). }
    procedure Parse(Lexer: TX3DLexer; Reader: TX3DReaderNames); virtual;

    { Parse node body, i.e. mainly node's fields. }
    procedure ParseXML(Element: TDOMElement; Reader: TX3DReaderNames);

    { Constructor. Initializes various properties:

      @unorderedList(
        @item(NodeName, BaseUrl are initialized
          directly from given parameters.)
        @item(The @link(Fields), @link(Events) lists are filled
          in every descendant, to have all the fields/events defined
          by the specification.)
        @item(DefaultContainerField, and other node-specific
          stuff, is filled in descendants. This is actually implemented
          in CreateNode, that is called at the end of this constructor.)
      )
    }
    constructor Create(const ANodeName: string = '';
      const ABaseUrl: string = ''); virtual;

    destructor Destroy; override;

    { Node type name in VRML/X3D. Never empty.
      Constant for the class lifetime (even for special
      TX3DUnknownNode and TX3DPrototypeNode, where this is calculated
      at runtime).

      Note that VRML/X3D is generally case-sensitive, so this property is too.

      In TX3DNode, this returns ClassNodeTypeName, which is suitable
      for most nodes. See ClassNodeTypeName. }
    function NodeTypeName: string; virtual;

    { Node type name in VRML/X3D, for this class.
      Normal VRML/X3D node classes should override this to return something
      non-empty, and then NodeTypeName automatically will return the same value.

      Empty for classes that don't have a hardcoded VRML/X3D node name,
      like a special TX3DUnknownNode. Such special classes should override
      then NodeTypeName to return actual non-empty name there.

      You usually should call NodeTypeName. The only use of this method
      is that it works on classes (it's "class function"), without needing
      at actual instance. }
    class function ClassNodeTypeName: string; virtual;

    { Traverse all the nodes of VRML graph that are active.

      An "active" part of the VRML graph are the nodes that actually
      change what the VRML file represents, in terms of geometry,
      collision detection etc. For example, the Switch node has only
      one child usually active. Nodes that merely influence
      the active graph by some events and routes do not have to be
      active (these nodes may change what the VRML file actually represents,
      but only by changing other nodes).

      For all nodes of NodeClass TraversingFunc
      will be called.

      Traverse not only enumerates these
      nodes, it also collects all state (transformation, etc ---
      see TX3DGraphTraverseState) that affects how given node should
      be presented.

      Also, TraversingInfo is passed to each TraversingFunc call.
      This allows you to investigate, during TraversingFunc call, the parents
      hierarchy (you can't use VRML1Parents / ParentFields of the current node,
      since a node may have many parents). Traverse calls are
      naturally recursive, and so the stack of TraversingInfo
      structures is naturally build and destroyed by recursive calls.
      For the root node (the one where you called Traverse without
      specifying initial TraversingInfo), ParentInfo is simply @nil.

      The scheme of how Traverse works:

@preformatted(
  BeforeTraverse;

  TraverseIntoChildren := true;
  if Self is NodeClass then TraversingFunc (Self, State, TraverseIntoChildren);

  MiddleTraverse;

  if TraverseIntoChildren is still true then
    for all children returned by DirectEnumerateActive
      call their Traverse(State);

  AfterTraverse;

  Add Self to State.LastNodes (for VRML 1.0 state nodes, see
    TraverseStateLastNodesClasses);
)

      Note: setting TraverseIntoChildren to false means that some
      part of the tree is explicitly omitted from traversing.
      Use this only if you know what you're doing, as for some
      nodes they actually affect their parents too (for example,
      chilren within VRML 1.0 Group affect other nodes too;
      global lights within VRML >= 2.0 affect all nodes; and so on...).
      Usually, you will use this only for separator-like nodes
      (for VRML >= 2.0, all Group, Transform, Switch etc. act like separators),
      and only when you will somehow traverse into these nodes anyway.

      We guarantee that AfterTraverse will be called if BeforeTraverse
      was called and finished (that is, AfterTraverse is called in the
      @code(finally..end)).

      During traversing, you can only modify the children (direct or not)
      nodes of the current node. }
    procedure Traverse(
      NodeClass: TX3DNodeClass;
      TraversingFunc: TTraversingFunc);

    { Like @link(Traverse), but it takes explicit starting state stack
      and starting ParentInfo. Not generally useful, use only for special
      purposes. }
    procedure TraverseInternal(StateStack: TX3DGraphTraverseStateStack;
      NodeClass: TX3DNodeClass;
      TraversingFunc: TTraversingFunc;
      ParentInfo: PTraversingInfo);

    { Like @link(Traverse), but only enters children.
      This does the job of Traverse normally omitted if your @link(Traverse)
      callback returns TraverseIntoChildren = @false.
      Using this method, you can traverse into children explicitly
      from your callback. }
    procedure TraverseIntoChildren(StateStack: TX3DGraphTraverseStateStack;
      NodeClass: TX3DNodeClass;
      TraversingFunc: TTraversingFunc;
      ParentInfo: PTraversingInfo);

    { Enumerate all our children of some class. Recursively.
      Enumerates also this instance (Self), if it satisfies the
      NodeClass and SeekNodeName conditions.

      This enumerates both VRML 1.0 children (@link(VRML1Children)) as well as
      VRML >= 2.0 (including X3D) children (nodes in TSFNode and TMFNode fields).

      If OnlyActive then it will enumerate only active parts
      of the graph ("active" as defined by @link(Traverse)),
      so it will work as a simpler version of Traverse
      (simpler, because it doesn't track any state).

      If not OnlyActive then it will simply enumerate all nodes.
      This will include then also prototype helpers, if this node
      was expanded from prototype: see PrototypeInstanceSourceNode
      and PrototypeInstanceHelpers.

      If you give SeekNodeName parameter, we'll only look for nodes
      with NodeName = SeekNodeName. When SeekNodeName = '' it,
      consistently, looks for unnamed nodes (where NodeName = '').

      Enumerates children only after enumerating Self.
      So you can modify children before enumerating them in the Proc callback.
      You can only modify your children in the Proc callback.

      @groupBegin }
    procedure EnumerateNodes(
      proc: TX3DNodeProc; OnlyActive: boolean); overload;
    procedure EnumerateNodes(nodeClass: TX3DNodeClass;
      proc: TX3DNodeProc; OnlyActive: boolean); overload;
    procedure EnumerateNodes(nodeClass: TX3DNodeClass;
      const SeekNodeName: string;
      proc: TX3DNodeProc; OnlyActive: boolean); overload;
    { @groupEnd }

    { TryFindNodeByName and TryFindNode seek for a node with
      given class (and node name, in case of TryFindNodeByName).
      If OnlyActive then they seek among only active nodes
      ("active" as defined by @link(Traverse)), otherwise all nodes.

      These functions are quite like EnumerateNodes, except
      they stop at the first occurrence and return it.

      TryFindNodeByName and TryFindNode return @nil if such node
      is not found. FindNodeByName and FindNode raise exception EX3DNotFound
      in this case.
      @raises(EX3DNotFound FindNodeByName and FindNode raise
        this exception when node is not found.)
      @groupBegin }
    function TryFindNodeByName(FindClass: TX3DNodeClass;
      const FindName: string;
      OnlyActive: boolean): TX3DNode;
    function FindNodeByName(FindClass: TX3DNodeClass;
      const FindName: string;
      OnlyActive: boolean): TX3DNode;
    function TryFindNode(FindClass: TX3DNodeClass;
      OnlyActive: boolean): TX3DNode;
    function FindNode(FindClass: TX3DNodeClass;
      OnlyActive: boolean): TX3DNode;
    { @groupEnd }

    { Find the first node with given class (NodeClass),
      return it's state or just transformation.
      Similar to @link(Traverse), but stops as soon as the given node is found.

      Returns @false when not found ("out" parametrs
      Node, State and Transform are undefined then).
      @groupBegin }
    function TryFindNodeState(
      NodeClass: TX3DNodeClass;
      out Node: TX3DNode;
      out State: TX3DGraphTraverseState): boolean;
    function TryFindNodeTransform(
      NodeClass: TX3DNodeClass;
      out Node: TX3DNode;
      out Transform: TMatrix4Single;
      out TransformScale: Single): boolean;
    { @groupEnd }

    { Seeks Self and parent nodes (from VRML1Parents and ParentFields,
      recursively) for given node name.

      In other words, this is similar to TryNodeByName or NodeByName,
      but it goes "upward" in graph hierarchy. Note that this
      never restricts itself only to "active" graph part
      ("active" as defined by @link(Traverse))
      because you really can't detect what is the "active"
      part of the graph when going upward.

      @raises(EX3DNotFound
        FindParentByName raises this exception when node is not found.)

      @groupBegin }
    function TryFindParentByName(const FindName: string): TX3DNode;
    function FindParentByName(const FindName: string): TX3DNode;
    { @groupEnd }

    { Looks for a given Node in parents (and self), recursively.
      Similar to TryFindParentByName. Returns @true only if found. }
    function HasParent(Node: TX3DNode): boolean;

    { Search immediate parents of this node for a node with given FindName.
      Returns @nil if not found. }
    function TryFindDirectParentByName(const FindName: string): TX3DNode;

    { Looks for a given node in our children (direct and not, including self).
      If OnlyActive, then only active parts are searched
      ("active" as defined by @link(Traverse)). }
    function IsNodePresent(Node: TX3DNode; OnlyActive: boolean): boolean;

    { Count the occurrences of given node class in our children.
      For example, you can pass NodeClass = TAbstractLightNode to count
      the light sources in the scene.

      If CountOnlyActiveNodes, then only active parts are searched
      ("active" as defined by @link(Traverse)).

      This traverses both VRML 1.0 children nodes and VRML 2.0 nodes
      inside SFNode and MFNode fields. }
    function NodesCount(NodeClass: TX3DNodeClass;
      CountOnlyActiveNodes: boolean): integer;

    { Save node to a stream. Saves everything, including node name,
      node type, and node contents. }
    procedure SaveToStream(Writer: TX3DWriter); override;

    { Do the nodes of (exactly) this class should be included
      in VRML 1.0 state (see TX3DGraphTraverseState.LastNodes). }
    class function VRML1StateNode(out StateNode: TVRML1StateNode): boolean;

    { Some nodes are present only in specific VRML/X3D version.
      This functions decides it.

      For example some nodes can only work in VRML < 2.0,
      some others only in VRML >= 2.0. There are even some pairs
      of nodes: for example TConeNode_1 works with VRML < 2.0,
      TConeNode works with VRML >= 2.0.

      NodesManager will use this.

      Default implementation of this function returns always @true.
      Generally, I don't try to set this too aggresively ---
      in other words, for all cases when it's sensible, I allow
      nodes to be used in every VRML/X3D version, even when official
      specification doesn't. This means that when reading VRML 1.0
      files actually a large part of VRML 2.0 is allowed too,
      and also while reading VRML 2.0 many constructs from VRML 1.0
      (officially no longer present in VRML 2.0) are allowed too.
      I'm trying to support what I call a "sum of VRML 1.0 and 2.0".

      In practice I only use this function when various VRML/X3D versions
      specify the same node name but

      @unorderedList(
        @item(With different fields.

          For example Cone and Cylinder have slightly different fields,
          due to the fact that VRML 2.0 resigned from using TSFBitMask fields.)

        @item(With different behavior.

          For example definitions of Sphere for VRML 1.0
          and 2.0 are practically equal. However, the behavior from where
          to take texture and material info is different --- in VRML 1.0
          we take last Texture2, Material etc. nodes, while in VRML 2.0
          we look in parent Shape's "appearance" field. So once again
          two different Sphere classes are needed.)
      ) }
    class function ForVRMLVersion(const Version: TX3DVersion): boolean;
      virtual;

    { Enumerates all children nodes (recursively),
      allowing you to decide for each node to replace or remove it.

      So this is something like EnumerateNodes,
      except that it allows you to remove the nodes. It always
      enumerates all nodes, not only active (e.g. it enumerates all
      Switch node children, not only the chosen one).

      Note that (unlike regular EnumerateNodes) @bold(this doesn't
      report Self to Func !). Which is natural, since this may remove
      nodes by normal VRML1ChildRemove calls, so it needs to know ParentNode
      of the removed node.

      For each node Func will be called, with ParentNode and Node set.
      If you change the Node to something else, then the old node will
      be removed and new Node inserted in the same place.
      If new Node is @nil, then only the old node will be removed.

      Nodes are traversed in depth-first search. Node is first reported
      to Func, and then (if it's not replaced) we descend into this Node.

      @returns The number of removed (and possibly replaced) nodes. }
    function EnumerateReplaceChildren(
      Func: TEnumerateReplaceNodesFunction): Cardinal;

    { Removes all children (and their children, recursively) with
      node names matchig Wildcard. You can use * and ? special chars
      in the Wildcard.
      @returns The number of removed nodes. }
    function RemoveChildrenWithMatchingName(
      const Wildcard: string; IgnoreCase: Boolean): Cardinal;

    property Prototypes: TX3DPrototypeBaseList read FPrototypes;
    property Routes: TX3DRouteList read FRoutes;
    property ImportsList: TX3DFileItemList read FImportsList;
    property ExportsList: TX3DFileItemList read FExportsList;

    { Create a deep copy of this node and all it's children.

      New copy is completely independent from original,
      having all children nodes (in both VRML 1.0 sense (Children)
      and VRML >= 2.0 (inside SFNode and MFNode fields)) also
      duplicated. New copy has protypes, routes, interface declarations
      and generally everything established like in the original, using copied
      nodes.

      Doesn't copy things which are dependent on container hierarchy.
      (So copying them would be more dangerous than useful.)
      This means: DestructionNotifications, Scene, VRML1Parents,
      ParentFields. VRML1Parents and ParentFields will be set for children
      anyway (to appropriate copies).

      Caller owns this newly created copy --- as returned by this method,
      it's not linked anywhere. }
    function DeepCopy: TX3DNode;

    { Internal notes:

      TODO: memory leaks are known to be possible in some difficult cases
      with PrototypeInstanceHelpers. See e.g.
      ../../../demo_models/vrml_2/warnings/errors/proto_leak.wrl and
      ../../../demo_models/vrml_2/warnings/errors/proto_leak_2.wrl
      for simple testcases. Reason: PrototypeInstanceHelpers may contain,
      by DEF statements, links to Self.
      This causes circular dependency (Self is child of some node on
      PrototypeInstanceHelpers, but PrototypeInstanceHelpers will
      be freed only if Self is freed) causing some memory to be left
      always allocated.

      PrototypeInstanceHelpers are actually always TX3DRootNode,
      may be declared as such in the future if needed.
    }

    { PrototypeInstance = @true indicates that this node was created
      from a non-external prototype instantiation.

      Then PrototypeInstanceSourceNode is non-nil and indicates
      parsed prototype node (and PrototypeInstanceSourceNode.Prototype
      gives you even a link to the actual prototype specification).

      PrototypeInstanceSourceNode is used for events: any ROUTEs
      specified @italic(outside) of prototype and
      leading to/from instantiated prototype should actually lead
      to PrototypeInstanceSourceNode events (not to events of Self).
      Reason: prototype events may be different than actual expanded
      node events, and ROUTEs want to lead to prototype events.
      This is implemented when expanding prototype
      (@link(TX3DPrototypeNode.Instantiate))
      and when linking ROUTE (TX3DRoute.SetSource, TX3DRoute.SetDestination).

      PrototypeInstanceHelpers may be @nil if empty, or may contain
      a list of other nodes duplicated along with the main prototype node.
      From VRML spec:

      @preformatted(
        Any other nodes and accompanying scene graphs
        are not part of the transformation hierarchy, but may be referenced
        by ROUTE statements or Script nodes in the prototype definition.)

      Note that for TX3DPrototypeNode (within PrototypeInstanceSourceNode)
      these have a little different meaning: they describe the
      @italic(nested prototype), if any, that was used to create this node.
      This may happen if the node was expanded from one prototype within
      another. (Usually, you shouldn't be concerned about this;
      see TX3DPrototypeNode.Instantiate implementation comments for
      gory details about this.)

      @groupBegin }
    property PrototypeInstance: boolean read FPrototypeInstance;
    property PrototypeInstanceSourceNode: TX3DPrototypeNode
      read FPrototypeInstanceSourceNode;
    property PrototypeInstanceHelpers: TX3DNode read FPrototypeInstanceHelpers;
    { @groupEnd }

    { Should we use this node when URN is required by EXTERNPROTO ?

      Implementors note: in this class, this returns @false.
      You can use constants like URNVRML97Nodes and URNKambiNodes to help
      implementing this. }
    class function URNMatching(const URN: string): boolean; virtual;

    { Default value of "containerField" attribute for this node in X3D XML
      encoding. }
    property DefaultContainerField: string
      read FDefaultContainerField write FDefaultContainerField;

    { For some special VRML / X3D nodes (like Script, ComposedShader)
      that allow the definition of additional fields/events within.

      In X3D specification this is marked like

@preformatted(
  # And any number of:
  fieldType [in]     fieldName
  fieldType [in,out] fieldName    initialValue
  fieldType [out]    fieldName
  fieldType []       fieldName    initialValue
)

      If HasInterfaceDeclarations is not [], then InterfaceDeclarations
      will be non-nil and parser (classic VRML parser in this unit,
      X3D XML reader too) will read this from VRML files.
      Moreover, for each interface declaration, also appropriate field/event
      will be added to the list of @link(Fields) or @link(Events),
      so fields/events created by interface declarations will function
      just like other standard fields everywhere.

      @groupBegin }
    property HasInterfaceDeclarations: TX3DAccessTypes
      read FHasInterfaceDeclarations
      write SetHasInterfaceDeclarations default [];

    property InterfaceDeclarations: TX3DInterfaceDeclarationList
      read FInterfaceDeclarations;
    { @groupEnd }

    { Functions registered here will be called when this TX3DNode descendant
      will be destroyed. }
    property DestructionNotifications: TNodeDestructionNotificationList
      read FDestructionNotifications;

    { Scene that will be notified about changes to this node.
      This is necessary to allow the scene to properly process VRML/X3D
      events, and also to react properly to any other changes to the nodes
      (like when you change some field directly by ObjectPascal code,
      e.g. by TX3DField.Send).

      May be @nil if none.

      A given TX3DNode may be renderable only by a single renderer.
      This means it can be placed only within one TCastleScene
      or one TCastlePrecalculatedAnimation (nothing else gives you a renderer).

      A given TX3DNode may be placed inside many TCastleSceneCore instances
      (including TCastleScene). But if more than one scene is used,
      then all the scenes must be static (TCastleSceneCore.ProcessEvents = false
      and TCastleSceneCore.Static = true). Static scenes are ones
      that never change, that is never have any TCastleSceneCore.ChangedField called.
      This means that events processing is disabled, and also
      other dynamic scene changes from code are disallowed.

      These two rules are both at action when you think about
      a node inside many TCastleScene instances. In this case,
      all such scene instances must be created with the same
      renderer (hence the need for TCastleScene.CreateCustomRenderer)
      and all must be static. This is actually exactly how
      TCastlePrecalculatedAnimation works: it internally creates a single renderer
      and a series of TCastleScene instances. }
    property Scene: TX3DEventsEngine read FScene write FScene;

    { Managed and used by TCastleSceneCore to keep TShapeTreesList
      for every ITransformNode. }
    property ShapeTrees: TObject read FShapeTrees write FShapeTrees;

    { This will be always called by VRML parsers after adding new item
      to our InterfaceDeclarations.

      In this class, this simply adds
      IDecl.FieldOrEvent to our normal fields/events by IDecl.AddFieldOrEvent.
      You may override this in subclasses to react in some special way
      to new fields/events, for example Script node may register here
      to receive notification when input event is received. }
    procedure PostAddInterfaceDeclaration(IDecl: TX3DInterfaceDeclaration); virtual;

    { Add to node InterfaceDeclarations given field.
      Sets the field's exposed to given Exposed parameter, for comfort.
      This should only be used with nodes having
      HasInterfaceDeclarations = @true, like Script or ComposedShader. }
    procedure AddCustomField(Field: TX3DField; const Exposed: boolean = false);

    { What happens when transformation of the node changes.
      This is internally used by TCastleSceneCore when Transform (or similar)
      node affecting this node changes. It's an important optimization,
      to avoid large if clause with many "is" and "Supports" checks
      that would be quite slow.
      @exclude }
    function TransformationChange: TNodeTransformationChange; virtual;

    { Nice and concise node description for user.
      Shows node type and name. }
    function NiceName: string;
  end;

  TX3DNodeList = class(specialize TFPGObjectList<TX3DNode>)
    { Find node by name, @nil if not found.

      For empty node name, always returns @nil. This follows the definition
      of NodeName: empty means that node has no name, so it should not be found
      by searches by name, ever.

      @seealso(IndexOfName Returns the node index. This is sometimes more
        flexible (you can always quickly get actual node knowing the index,
        by Items[Index], but not the other way around). It is also sometimes
        less comfortable (often you're not interested in node index).) }
    function FindName(const Name: string): TX3DNode;

    { Find index of a node with given name, -1 if not found. }
    function IndexOfName(const Name: string): Integer;

    procedure AddIfNotExists(const Node: TX3DNode);

    function Equals(SecondValue: TObject): boolean; {$ifdef TOBJECT_HAS_EQUALS} override; {$endif}
  end;

{$endif read_interface}

{$ifdef read_implementation}

{ TX3DNodeDeepCopyState ----------------------------------------------------- }

constructor TX3DNodeDeepCopyState.Create;
begin
  inherited;
  Original := TX3DNodeList.Create(false);
  New := TX3DNodeList.Create(false);
end;

destructor TX3DNodeDeepCopyState.Destroy;
begin
  FreeAndNil(Original);
  FreeAndNil(New);
  inherited;
end;

function TX3DNodeDeepCopyState.DeepCopy(OriginalNode: TX3DNode): TX3DNode;
var
  I: Integer;
begin
  Assert(New.Count = Original.Count);

  I := Original.IndexOf(OriginalNode);
  if I = -1 then
  begin
    { DeepCopyCore will expand (Original, New) lists by (OriginalNode, Result).
      This is needed, see DeepCopyCore comments. }
    Result := OriginalNode.DeepCopyCore(Self);
  end else
    Result := New[I];
end;

{ TX3DNode ------------------------------------------------------------------ }

constructor TX3DNode.Create(const ANodeName, ABaseUrl: string);
begin
  inherited Create;
  VRML1ChildrenAllowed := false;
  VRML1ChildrenParsingAllowed := false;

  FNodeName := ANodeName;
  FBaseUrl := ABaseUrl;

  FVRML1Children := TX3DNodeList.Create(false);
  FVRML1Parents := TX3DNodeList.Create(false);
  FParentFields := TX3DFieldList.Create(false);
  FFields := TX3DFieldList.Create(false);

  FEvents := TX3DEventList.Create(false);

  FPrototypes := TX3DPrototypeBaseList.Create(true);
  FRoutes := TX3DRouteList.Create(true);
  FImportsList := TX3DFileItemList.Create(true);
  FExportsList := TX3DFileItemList.Create(true);

  FHasInterfaceDeclarations := [];
  FInterfaceDeclarations := nil;

  FDestructionNotifications := TNodeDestructionNotificationList.Create;

  CreateNode;
end;

destructor TX3DNode.Destroy;
var
  I: Integer;
begin
  { This whole unit, including AnyNodeDestructionNotifications,
    may be already finalized when calling this. }
  if AnyNodeDestructionNotifications <> nil then
    AnyNodeDestructionNotifications.ExecuteAll(Self);

  if DestructionNotifications <> nil then
  begin
    DestructionNotifications.ExecuteAll(Self);
    FreeAndNil(FDestructionNotifications);
  end;

  if FVRML1Children <> nil then VRML1ChildrenClear;

  if PrototypeInstance then
  begin
    FreeAndNil(FPrototypeInstanceSourceNode);
    FreeAndNil(FPrototypeInstanceHelpers);
    FPrototypeInstance := false;
  end;

  FreeAndNil(FPrototypes);
  FreeAndNil(FRoutes);
  FreeAndNil(FImportsList);
  FreeAndNil(FExportsList);

  { First free Fields and Events, before freeing InterfaceDeclarations.
    Reason: Fields and Events may contains references to InterfaceDeclarations
    items (since parsing added them there by PostAddInterfaceDeclaration(IDecl)).
    So these references have to be valid, and omitted by checking
    ParentInterfaceDeclaration <> nil. }

  if FEvents <> nil then
  begin
    for I := 0 to FEvents.Count - 1 do
      if FEvents[I].ParentInterfaceDeclaration = nil then
        FPGObjectList_FreeAndNilItem(FEvents, I);
    FreeAndNil(FEvents);
  end;

  if FFields <> nil then
  begin
    for I := 0 to FFields.Count - 1 do
      if FFields[I].ParentInterfaceDeclaration = nil then
        FPGObjectList_FreeAndNilItem(FFields, I);
    FreeAndNil(FFields);
  end;

  FreeAndNil(FInterfaceDeclarations);

  FreeAndNil(FVRML1Children);
  FreeAndNil(FVRML1Parents);
  FreeAndNil(FParentFields);

  inherited;
end;

procedure TX3DNode.FreeIfUnused;
begin
  if (Self <> nil) and
     (FVRML1Parents.Count = 0) and
     (FParentFields.Count = 0) and
     (KeepExisting = 0) then
  begin
    { For FPC <= 2.2.2:
      This is written as "Self.Destroy" to actually do the desctruction,
      freeing memory etc. If I would just call it "Destroy", it would
      perform what destructor does but leaving object instance unfreed.

      In FPC 2.2.4, 2.4.0, 2.4.2, 2.4.4, 2.6.0, calling Destroy always
      does the actual destruction, there seems to be no difference
      between "Self.Destroy" and "Destroy" below. }
    Self.Destroy;
  end;
end;

procedure TX3DNode.KeepExistingBegin;
begin
  Inc(FKeepExisting);
end;

procedure TX3DNode.KeepExistingEnd;
begin
  Dec(FKeepExisting);
end;

procedure TX3DNode.VRML1ChildAdd(Index: Integer; child: TX3DNode);
begin
 Check(VRML1ChildrenAllowed,
   'Node '+NodeTypeName+' is not allowed to have child node of type '+
   Child.NodeTypeName);
 child.FVRML1Parents.Add(Self);
 FVRML1Children.Insert(Index, child);
end;

procedure TX3DNode.VRML1ChildAdd(child: TX3DNode);
begin
  VRML1ChildAdd(FVRML1Children.Count, child);
end;

procedure TX3DNode.VRML1ChildRemove(i: integer);
var
  OldChild: TX3DNode;
begin
  OldChild := FVRML1Children[i];
  FVRML1Children.Delete(i);
  OldChild.FVRML1Parents.Remove(Self);
  OldChild.FreeIfUnused;
end;

function TX3DNode.VRML1ChildExtract(I: Integer): TX3DNode;
begin
  Result := FVRML1Children[i];
  FVRML1Children.Delete(i);
  Result.FVRML1Parents.Remove(Self);

  { VRML1ChildRemove now does
      OldChild.FreeIfUnused;
    but ExtractChild doesn't do it. }
end;

procedure TX3DNode.SetVRML1Child(I: Integer; Value: TX3DNode);
var
  OldChild: TX3DNode;
begin
  { Inefficient implementation: VRML1ChildRemove(I); VRML1ChildAdd(I, Value); }

  if Value <> FVRML1Children[I] then
  begin
    Check(VRML1ChildrenAllowed,
      'Node '+NodeTypeName+' is not allowed to have child node of type '+
      Value.NodeTypeName);

    OldChild := FVRML1Children[i];
    FVRML1Children[I] := Value;

    OldChild.FVRML1Parents.Remove(Self);
    OldChild.FreeIfUnused;

    Value.FVRML1Parents.Add(Self);
  end;
end;

procedure TX3DNode.VRML1ChildrenClear;
begin
 while FVRML1Children.Count > 0 do VRML1ChildRemove(0);
end;

function TX3DNode.GetVRML1Child(i: integer): TX3DNode;
begin
  result := FVRML1Children[i];
end;

function TX3DNode.GetVRML1Parent(i: integer): TX3DNode;
begin
  result := FVRML1Parents[i];
end;

function TX3DNode.VRML1ChildrenCount: integer;
begin
  result := FVRML1Children.Count
end;

function TX3DNode.VRML1ParentsCount: integer;
begin
  result := FVRML1Parents.Count
end;

procedure TX3DNode.FreeRemovingFromAllParents;
var
  i, j: integer;
  SF: TSFNode;
  MF: TMFNode;
begin
  if Self = nil then exit;

  for i := 0 to FVRML1Parents.Count - 1 do
  begin
    j := FVRML1Parents[i].FVRML1Children.IndexOf(Self);
    FVRML1Parents[i].FVRML1Children.Delete(j);
    { nie musimy sie tu martwic usuwaniem naszego Parenta z listy
      FVRML1Parents ktora
     wlasnie przegladamy bo przeciez i tak zaraz zrobimy sobie Destroy; }
  end;

  for I := 0 to FParentFields.Count - 1 do
  begin
    if FParentFields[I] is TSFNode then
    begin
      SF := TSFNode(FParentFields[I]);
      { We remove accessing private SF.FValue,
        not SF.Value property setter,
        to avoid checking our reference count (and possibly calling
        our destructor) by this setter. }
      SF.FValue := nil;
    end else
    if FParentFields[I] is TMFNode then
    begin
      MF := TMFNode(FParentFields[I]);
      { Again we remove using internal methods, that shouldn't be used
        by normal usage from outside: we call directly FItems methods
        (instead of calling MFNode.RemoveItem method that would call our
        RemoveParentField that possibly calls our destructor). }
      J := MF.FItems.IndexOf(Self);
      Assert(J <> -1, 'Node must be present on Items list of parent MFNode');
      MF.FItems.Delete(J);
    end else
      raise EInternalError.Create('TX3DNode.ParentFields not SF or MF Node class');
  end;

  Self.Destroy;
end;

function TX3DNode.GetParentFieldsItem(Index: Integer): TX3DField;
begin
  Result := FParentFields[Index];
end;

function TX3DNode.GetParentFieldsNodeItem(Index: Integer): TX3DNode;
var
  F: TX3DField;
begin
  F := ParentFields[Index];
  if F is TSFNode then
    Result := TSFNode(F).ParentNode else
    Result := (F as TMFNode).ParentNode;
end;

function TX3DNode.ParentFieldsCount: Integer;
begin
  Result := FParentFields.Count;
end;

procedure TX3DNode.DirectEnumerateActive(Func: TEnumerateChildrenFunction);
var
  I: Integer;
begin
  for I := 0 to VRML1ChildrenCount - 1 do
    Func(Self, VRML1Children[I]);
end;

procedure TX3DNode.DirectEnumerateActiveForTraverse(
  Func: TEnumerateChildrenFunction;
  StateStack: TX3DGraphTraverseStateStack);
begin
  DirectEnumerateActive(Func);
end;

procedure TX3DNode.DirectEnumerateAll(
  Func: TEnumerateChildrenFunction);
var
  I, J: Integer;
  F: TX3DField;
  SF: TSFNode;
  MF: TMFNode;
begin
  for I := 0 to VRML1ChildrenCount - 1 do
    Func(Self, VRML1Children[I]);

  for I := 0 to Fields.Count - 1 do
  begin
    F := Fields[I];
    if F is TSFNode then
    begin
      SF := TSFNode(F);
      if SF.Value <> nil then
        Func(Self, SF.Value);
    end else
    if F is TMFNode then
    begin
      MF := TMFNode(F);
      for J := 0 to MF.Items.Count - 1 do
        Func(Self, MF.Items[J]);
    end;
  end;

  if PrototypeInstance then
  begin
    Assert(PrototypeInstanceSourceNode <> nil);
    Func(Self, PrototypeInstanceSourceNode);

    if PrototypeInstanceHelpers <> nil then
      Func(Self, PrototypeInstanceHelpers);
  end;
end;

procedure TX3DNode.DirectEnumerate(
  Func: TEnumerateChildrenFunction;
  OnlyActive: boolean);
begin
  if OnlyActive then
    DirectEnumerateActive(Func) else
    DirectEnumerateAll(Func);
end;

procedure TX3DNode.BeforeTraverse(StateStack: TX3DGraphTraverseStateStack);
begin
  if PrototypeInstance then
    Inc(StateStack.Top.InsidePrototype);
end;

procedure TX3DNode.MiddleTraverse(StateStack: TX3DGraphTraverseStateStack);
begin
end;

procedure TX3DNode.AfterTraverse(StateStack: TX3DGraphTraverseStateStack);
begin
  if PrototypeInstance then
    Dec(StateStack.Top.InsidePrototype);
end;

type
  TTraverseEnumerator = class
    StateStack: TX3DGraphTraverseStateStack;
    NodeClass: TX3DNodeClass;
    TraversingFunc: TTraversingFunc;
    ParentInfo: PTraversingInfo;
    procedure DoTraverseIntoChildren(Child: TX3DNode);
    procedure EnumerateChildrenFunction(Node, Child: TX3DNode);
  end;

  procedure TTraverseEnumerator.DoTraverseIntoChildren(Child: TX3DNode);
  var
    ParentInfoForChildren: TTraversingInfo;
  begin
    ParentInfoForChildren.Node := Child;
    ParentInfoForChildren.ParentInfo := ParentInfo;
    ParentInfo := @ParentInfoForChildren;
    try
      Child.DirectEnumerateActiveForTraverse(@EnumerateChildrenFunction, StateStack);
    finally
      ParentInfo := ParentInfoForChildren.ParentInfo;
    end;
  end;

  procedure TTraverseEnumerator.EnumerateChildrenFunction(
    Node, Child: TX3DNode);
  var
    StateNode: TVRML1StateNode;
    IsTraverseIntoChildren: boolean;
  begin
    Child.BeforeTraverse(StateStack);
    try
      IsTraverseIntoChildren := true;
      if Child is NodeClass then
        TraversingFunc(Child, StateStack, ParentInfo, IsTraverseIntoChildren);

      Child.MiddleTraverse(StateStack);

      if IsTraverseIntoChildren then
        DoTraverseIntoChildren(Child);
    finally Child.AfterTraverse(StateStack) end;

    if Child.VRML1StateNode(StateNode) then
      StateStack.Top.SetLastNodes(StateNode, Child, false);
  end;

procedure TX3DNode.TraverseInternal(StateStack: TX3DGraphTraverseStateStack;
  NodeClass: TX3DNodeClass;
  TraversingFunc: TTraversingFunc;
  ParentInfo: PTraversingInfo);
var
  Enumerator: TTraverseEnumerator;
begin
  Enumerator := TTraverseEnumerator.Create;
  try
    Enumerator.StateStack := StateStack;
    Enumerator.NodeClass := NodeClass;
    Enumerator.TraversingFunc := TraversingFunc;
    Enumerator.ParentInfo := ParentInfo;
    Enumerator.EnumerateChildrenFunction(nil, Self);

    { Check that, if all went without exception, Enumerator.ParentInfo
      returned to original state. }
    Assert(Enumerator.ParentInfo = ParentInfo);
  finally FreeAndNil(Enumerator) end;
end;

procedure TX3DNode.TraverseIntoChildren(StateStack: TX3DGraphTraverseStateStack;
  NodeClass: TX3DNodeClass;
  TraversingFunc: TTraversingFunc;
  ParentInfo: PTraversingInfo);
var
  Enumerator: TTraverseEnumerator;
begin
  Enumerator := TTraverseEnumerator.Create;
  try
    Enumerator.StateStack := StateStack;
    Enumerator.NodeClass := NodeClass;
    Enumerator.TraversingFunc := TraversingFunc;
    Enumerator.ParentInfo := ParentInfo;
    Enumerator.DoTraverseIntoChildren(Self);

    { Check that, if all went without exception, Enumerator.ParentInfo
      returned to original state. }
    Assert(Enumerator.ParentInfo = ParentInfo);
  finally FreeAndNil(Enumerator) end;
end;

var
  TraverseSingleStack: TX3DGraphTraverseStateStack;

procedure TX3DNode.Traverse(NodeClass: TX3DNodeClass;
  TraversingFunc: TTraversingFunc);
begin
  TraverseSingleStack.PushClear;
  try
    TraverseInternal(TraverseSingleStack, NodeClass, TraversingFunc, nil);
  finally TraverseSingleStack.Pop end;
end;

function TX3DNode.NodeTypeName: string;
begin
 result := ClassNodeTypeName;
end;

class function TX3DNode.ClassNodeTypeName: string;
begin
 result := '';
end;

function TX3DNode.PathFromBaseUrl(const RelativePath: string): string;
begin
  { This is a workaround for Blender errorneous VRML 1.0 export.
    Blender exports relative paths by prefixing them by "//"
    (that's a general convention used internally by Blender, AFAIK).
    Here I simply remove this "//". }
  if IsPrefix('//', RelativePath) then
    Result := CombineURI(BaseUrl, SEnding(RelativePath, 3)) else
    Result := CombineURI(BaseUrl, RelativePath);
end;

procedure TX3DNode.Parse(Lexer: TX3DLexer; Reader: TX3DReaderNames);
var
  Handled: boolean;
  Position: Integer;
  ChildNode: TX3DNode;
begin
  VRML1ChildrenClear;

  Position := 0;

  Lexer.CheckTokenIs(vtOpenCurlyBracket);
  Lexer.NextToken;
  while Lexer.Token <> vtCloseCurlyBracket do
  begin
    Handled := ParseNodeBodyElement(Lexer, Reader, Position);

    { VRML 1.0 children nodes are handled as a last resort here
      (that's also why they can't be inside our ParseNodeBodyElement).
      That's because ParseNode just raises exception in case of unknown
      node, so I have to catch first everything else (like "hints" field
      of TShapeHintsNode_1). }
    if not Handled then
    begin
      if VRML1ChildrenParsingAllowed then
      begin
        ChildNode := ParseNode(Lexer, Reader, false);
        ChildNode.PositionInParent := Position;
        VRML1ChildAdd(ChildNode);
      end else
      begin
        raise EX3DParserError.Create(Lexer,
          Format('Invalid VRML node content (probably unknown or not allowed' +
            ' field, prototype or VRML 1.0-style children) inside "%s": got %s',
            [NodeTypeName, Lexer.DescribeToken]));
      end;
    end;

    Inc(Position);
  end;
  Lexer.NextToken;

  FBaseUrl := Reader.BaseUrl;

  ParseAfter(Reader);
end;

function TX3DNode.ParseNodeBodyElement(Lexer: TX3DLexer; Reader: TX3DReaderNames;
  const APositionInParent: Integer): boolean;

  procedure ParseExtensibilityFields;

    procedure ReadOneField;
    var
      FieldTypeName: string;
      //FieldName: string;
      FieldType: TX3DFieldClass;
    begin
      Lexer.CheckTokenIs(vtName, 'Field type name');
      FieldTypeName := Lexer.TokenName;
      FieldType := X3DFieldsManager.FieldTypeNameToClass(FieldTypeName);
      if FieldType = nil then
        raise EX3DParserError.Create(
          Lexer, Format(SExpectedFieldType, [Lexer.DescribeToken]));

      Lexer.NextToken;

      Lexer.CheckTokenIs(vtName, 'Field name');
      //FieldName := Lexer.TokenName;

      Lexer.NextToken;

      { TODO: we should actually do something with obtained here
        FieldName, FieldType }
    end;

  begin
    { We parse VRML 1.0 "fields" extensibility feature in a way similar to
      MF fields syntax, this was the intention (although not clarified precisely)
      of VRML 1.0 spec. }
    if Lexer.Token = vtOpenSqBracket then
    begin
      Lexer.NextToken;

      while Lexer.Token <> vtCloseSqBracket do
      begin
        ReadOneField;

        if Lexer.Token = vtCloseSqBracket then break;

        { In VRML >= 2.0 the comma is simply a whitespace and will be ignored
          by the lexer. }
        if Lexer.Version.Major < 2 then
        begin
          Lexer.CheckTokenIs(vtComma);
          Lexer.NextToken;
        end;
      end;

      { consume final "]" }
      Lexer.NextToken;
    end else
    begin
      { one single field - not enclosed in [] brackets }
      ReadOneField;
    end;
  end;

  procedure ParseExtensibilityIsA;
  var
    IsAField: TMFString;
  begin
    IsAField := TMFString.Create(Self, '', []);
    try
      IsAField.Parse(Lexer, Reader, false);

      { TODO: we should actually do something with obtained here
        isA value }
    finally FreeAndNil(IsAField) end;
  end;

var
  I: integer;
  Route: TX3DRoute;
  Proto: TX3DPrototypeBase;
  Event: TX3DEvent;
  IDecl: TX3DInterfaceDeclaration;
  Import: TX3DImport;
  ExportItem: TX3DExport; { "export" is a keyword in Pascal }
begin
  Result := false;

  { If I would know that all fields used are standard, I could
    check first for if Lexer.TokenName[0] in ['a'..'z'], since all
    standard field names start lowercase. But of course I can't,
    all VRML versions allow to define your own nodes and fields. }
  if Lexer.Token = vtName then
  begin
    I := Fields.IndexOf(Lexer.TokenName);
    if I >= 0 then
    begin
      Result := true;

      { Advance to the next token. Usually, it should be just "Lexer.NextToken;"
        But I have to add here some dirty hack to allow SFString fields
        to contain strings not enclosed in double quotes in VRML 1.0.
        So I call here NextTokenForceVTString before SFString field.

        For VRML >= 2.0, this nonsense feature was fortunately removed,
        and that's good because in VRML >= 2.0 you must be able to use
        keyword "IS" here, so calling NextTokenForceVTString would be bad. }
      if (Fields[I] is TSFString) and (Lexer.Version.Major <= 1) then
        Lexer.NextTokenForceVTString else
        Lexer.NextToken;

      Fields[I].Parse(Lexer, Reader, true);
      Fields[I].PositionInParent := APositionInParent;
    end else
    begin
      Event := AnyEvent(Lexer.TokenName);
      if Event <> nil then
      begin
        Result := true;
        Lexer.NextToken;
        Event.Parse(Lexer);
        Event.PositionInParent := APositionInParent;
      end else
      if Lexer.TokenName = 'fields' then
      begin
        Result := true;
        Lexer.NextToken;
        ParseExtensibilityFields;
      end else
      if Lexer.TokenName = 'isA' then
      begin
        Result := true;
        Lexer.NextToken;
        ParseExtensibilityIsA;
      end;
    end;
  end else
  if Lexer.TokenIsKeyword(InterfaceDeclarationKeywords(HasInterfaceDeclarations)) then
  begin
    Result := true;

    { since we're here, HasInterfaceDeclarations is <> [] }
    Assert(InterfaceDeclarations <> nil);

    IDecl := TX3DInterfaceDeclaration.Create(Self);
    InterfaceDeclarations.Add(IDecl);
    IDecl.Parse(Lexer, Reader, true, true);
    IDecl.PositionInParent := APositionInParent;
    PostAddInterfaceDeclaration(IDecl);
  end else
  if Lexer.TokenIsKeyword(vkPROTO) then
  begin
    Result := true;

    Proto := TX3DPrototype.Create;
    Prototypes.Add(Proto);
    Proto.Parse(Lexer, Reader);
    Proto.PositionInParent := APositionInParent;
  end else
  if Lexer.TokenIsKeyword(vkEXTERNPROTO) then
  begin
    Result := true;

    Proto := TX3DExternalPrototype.Create;
    Prototypes.Add(Proto);
    Proto.Parse(Lexer, Reader);
    Proto.PositionInParent := APositionInParent;
  end else
  if Lexer.TokenIsKeyword(vkROUTE) then
  begin
    Result := true;

    Route := TX3DRoute.Create;
    Routes.Add(Route);
    Route.Parse(Lexer, Reader);
    Route.PositionInParent := APositionInParent;
  end else
  if Lexer.TokenIsKeyword(vkIMPORT) then
  begin
    Result := true;

    Import := TX3DImport.Create;
    ImportsList.Add(Import);
    Import.Parse(Lexer, Reader);
    Import.PositionInParent := APositionInParent;
  end else
  if Lexer.TokenIsKeyword(vkEXPORT) then
  begin
    Result := true;

    ExportItem := TX3DExport.Create;
    ExportsList.Add(ExportItem);
    ExportItem.Parse(Lexer, Reader);
    ExportItem.PositionInParent := APositionInParent;
  end;
end;

procedure TX3DNode.ParseXML(Element: TDOMElement; Reader: TX3DReaderNames);
var
  Position: Integer;

  procedure ParseXMLAttributes;
  var
    Attr: TDOMAttr;
    AttrNode: TDOMNode;
    AttrIndex, Index: Integer;
  begin
    { enumerate over all attributes }
    for AttrIndex := 0 to Element.Attributes.Length - 1 do
    begin
      AttrNode := Element.Attributes[AttrIndex];
      Assert(AttrNode.NodeType = ATTRIBUTE_NODE);
      Attr := AttrNode as TDOMAttr;

      { containerField and DEF attributes are handled in ParseNode,
        we can safely ignore them now. }
      if (Attr.Name = SAttrContainerField) or
         (Attr.Name = SAttrDEF) then
        Continue;

      Index := Fields.IndexOf(Attr.Name);
      if Index >= 0 then
      begin
        Fields[Index].ParseXMLAttribute(Attr.Value, Reader);
        { Note that saving PositionInParent from XML attributes order
          isn't really useful, as FPC DOM unit already sorted
          Element.Attributes (TDOMNamedNodeMap) by name. }
        Fields[Index].PositionInParent := Position;
        Inc(Position);
      end else
        OnWarning(wtMajor, 'VRML/X3D', 'Unknown X3D field name (unhandled X3D XML attribute) "' + Attr.Name + '" in node "' + NodeTypeName + '"');
    end;
  end;

  procedure ParseXMLChildrenNodes;
  var
    FieldIndex: Integer;
    Child: TX3DNode;
    ContainerField: string;
    SF: TSFNode;
    MF: TMFNode;
    Route: TX3DRoute;
    I: TXMLElementIterator;
    Proto: TX3DPrototype;
    ExternProto: TX3DExternalPrototype;
    IDecl: TX3DInterfaceDeclaration;
    Import: TX3DImport;
    ExportItem: TX3DExport;
  begin
    I := TXMLElementIterator.Create(Element);
    try
      while I.GetNext do
      begin
        if I.Current.TagName = 'ROUTE' then
        begin
          Route := TX3DRoute.Create;
          Route.PositionInParent := Position;
          Routes.Add(Route);
          Route.ParseXML(I.Current, Reader);
        end else
        if I.Current.TagName = 'IS' then
        begin
          ParseISStatement(Self, I.Current, Position);
        end else
        if I.Current.TagName = 'IMPORT' then
        begin
          Import := TX3DImport.Create;
          Import.PositionInParent := Position;
          ImportsList.Add(Import);
          Import.ParseXML(I.Current, Reader);
        end else
        if I.Current.TagName = 'EXPORT' then
        begin
          ExportItem := TX3DExport.Create;
          ExportItem.PositionInParent := Position;
          ExportsList.Add(ExportItem);
          ExportItem.ParseXML(I.Current, Reader);
        end else
        if I.Current.TagName = 'ProtoDeclare' then
        begin
          Proto := TX3DPrototype.Create;
          Proto.PositionInParent := Position;
          Prototypes.Add(Proto);
          Proto.ParseXML(I.Current, Reader);
        end else
        if I.Current.TagName = 'ExternProtoDeclare' then
        begin
          ExternProto := TX3DExternalPrototype.Create;
          ExternProto.PositionInParent := Position;
          Prototypes.Add(ExternProto);
          ExternProto.ParseXML(I.Current, Reader);
        end else
        if I.Current.TagName = 'field' then
        begin
          IDecl := TX3DInterfaceDeclaration.Create(Self);
          try
            IDecl.ParseXML(I.Current, Reader, true);
            IDecl.PositionInParent := Position;
            if IDecl.AccessType in HasInterfaceDeclarations then
            begin
              InterfaceDeclarations.Add(IDecl);
              PostAddInterfaceDeclaration(IDecl);
            end else
            begin
              FreeAndNil(IDecl);
              OnWarning(wtMajor, 'VRML/X3D', 'X3D XML: specified <field> inside node, but this node doesn''t allow interface declaration with such accessType');
            end;
          except
            FreeAndNil(IDecl);
            raise;
          end;
        end else
        begin
          Child := ParseXMLNode(I.Current, ContainerField, Reader, true);
          if Child <> nil then
          try
            Child.PositionInParent := Position;
            FieldIndex := Fields.IndexOf(ContainerField);

            if (FieldIndex = -1) and
               (ContainerField <> Child.DefaultContainerField) and
               (Child.DefaultContainerField <> '') then
            begin
              { Retry with DefaultContainerField value, since it exists
                and is different than current ContainerField. }
              FieldIndex := Fields.IndexOf(Child.DefaultContainerField);
              if FieldIndex >= 0 then
                OnWarning(wtMajor, 'VRML/X3D', 'X3D XML: containerField indicated unknown field name ("' + ContainerField + '" by node "' + Child.NodeTypeName + '" inside node "' + NodeTypeName + '"), using the default containerField value "' + Child.DefaultContainerField + '" succeded');
            end;

            if FieldIndex >= 0 then
            begin
              if Fields[FieldIndex] is TSFNode then
              begin
                SF := Fields[FieldIndex] as TSFNode;

                if SF.Value <> nil then
                  OnWarning(wtMajor, 'VRML/X3D', 'X3D XML: More than one value specified for SFNode field ' + SF.NiceName);

                { Although field doesn't have a set position in XML X3D
                  encoding, when saving later in classic encoding we
                  need some order of fields. This is yet another problem
                  with non-unique names, something defined in XML X3D
                  may be not possible to save in other encoding:

                  <Group>
                    <Shape> ... <Appearance DEF="XXX" ....> </Shape>
                    <ROUTE ... using "XXX" name ...>
                    <Shape> ... <Appearance DEF="XXX" ....> </Shape>
                    <ROUTE ... using "XXX" name ...>
                  </Group>

                  This is uneasy to save in classic encoding, since
                  you cannot insert ROUTE in the middle of "children"
                  field of Group node in classic encoding.
                }
                Fields[FieldIndex].PositionInParent := Position;
                SF.Value := Child;
                SF.WarningIfChildNotAllowed(Child);
              end else
              if Fields[FieldIndex] is TMFNode then
              begin
                MF := Fields[FieldIndex] as TMFNode;
                Fields[FieldIndex].PositionInParent := Position;
                MF.Add(Child);
                MF.WarningIfChildNotAllowed(Child);
              end else
                OnWarning(wtMajor, 'VRML/X3D', 'X3D field "' + ContainerField + '" is not SFNode or MFNode, but a node value (XML element) is specified');
            end else
              OnWarning(wtMajor, 'VRML/X3D', 'Unknown X3D field name (indicated by containerField value) "' + ContainerField + '" by node "' + Child.NodeTypeName + '" inside node "' + NodeTypeName + '"');
          finally
            { Any OnWarning above makes the Child unused.
              Note that OnWarning may, but doesn't have, raise an exception. }
            Child.FreeIfUnused;
            Child := nil;
          end;
        end;
        Inc(Position);
      end;
    finally FreeAndNil(I) end;
  end;

  procedure ParseXMLCdata;
  var
    I: TXMLCDataIterator;
    CDataExists: boolean;
    CData: string;
  begin
    CDataExists := false;
    CData := '';

    I := TXMLCDataIterator.Create(Element);
    try
      if I.GetNext then
      begin
        CDataExists := true;
        repeat
          CData := CData + I.Current;
        until not I.GetNext;
      end;
    finally FreeAndNil(I) end;

    if CDataExists then
      if CDataField <> nil then
        CDataField.Items.Add(CData) else
        OnWarning(wtMajor, 'VRML/X3D', Format('VRML/X3D node %s doesn''t allow CDATA section, but it''s specified',
          [NodeTypeName]));
  end;

begin
  Position := 0;
  { The order below is important: first parse XML attributes,
    then elements, since VRML DEF mechanism says that DEF order
    is significant. }
  ParseXMLAttributes;
  ParseXMLChildrenNodes;
  { This must be called *after* parsing fields, to add CDATA at the *end*
    of "url" fields, like spec requires. }
  ParseXMLCdata;

  ParseAfter(Reader);
end;

procedure TX3DNode.ParseAfter(Reader: TX3DReaderNames);
begin
end;

procedure TX3DNode.CreateNode;
begin
end;

type
  TEnumerateNodes0Enumerator = class
    Proc: TX3DNodeProc;
    OnlyActive: boolean;
    procedure EnumerateChildrenFunction(Node, Child: TX3DNode);
  end;

  procedure TEnumerateNodes0Enumerator.EnumerateChildrenFunction(
    Node, Child: TX3DNode);
  begin
    Proc(Child);

    Child.DirectEnumerate(@EnumerateChildrenFunction, OnlyActive);
  end;

procedure TX3DNode.EnumerateNodes(
  Proc: TX3DNodeProc; OnlyActive: boolean);
var
  Enumerator: TEnumerateNodes0Enumerator;
begin
  Enumerator := TEnumerateNodes0Enumerator.Create;
  try
    Enumerator.Proc := Proc;
    Enumerator.OnlyActive := OnlyActive;
    Enumerator.EnumerateChildrenFunction(nil, Self);
  finally FreeAndNil(Enumerator) end;
end;

type
  TEnumerateNodes1Enumerator = class
    NodeClass: TX3DNodeClass;
    Proc: TX3DNodeProc;
    OnlyActive: boolean;
    procedure EnumerateChildrenFunction(Node, Child: TX3DNode);
  end;

  procedure TEnumerateNodes1Enumerator.EnumerateChildrenFunction(
    Node, Child: TX3DNode);
  begin
    if Child is NodeClass then Proc(Child);

    Child.DirectEnumerate(@EnumerateChildrenFunction, OnlyActive);
  end;

procedure TX3DNode.EnumerateNodes(nodeClass: TX3DNodeClass;
  Proc: TX3DNodeProc; OnlyActive: boolean);
var
  Enumerator: TEnumerateNodes1Enumerator;
begin
  Enumerator := TEnumerateNodes1Enumerator.Create;
  try
    Enumerator.NodeClass := NodeClass;
    Enumerator.Proc := Proc;
    Enumerator.OnlyActive := OnlyActive;
    Enumerator.EnumerateChildrenFunction(nil, Self);
  finally FreeAndNil(Enumerator) end;
end;

type
  TEnumerateNodes2Enumerator = class
    NodeClass: TX3DNodeClass;
    SeekNodeName: string;
    Proc: TX3DNodeProc;
    OnlyActive: boolean;
    procedure EnumerateChildrenFunction(Node, Child: TX3DNode);
  end;

  procedure TEnumerateNodes2Enumerator.EnumerateChildrenFunction(
    Node, Child: TX3DNode);
  begin
    if (Child is NodeClass) and
       (Child.NodeName = SeekNodeName) then
      Proc(Child);

    Child.DirectEnumerate(@EnumerateChildrenFunction, OnlyActive);
  end;

procedure TX3DNode.EnumerateNodes(NodeClass: TX3DNodeClass;
  const SeekNodeName: string;
  Proc: TX3DNodeProc; OnlyActive: boolean);
var
  Enumerator: TEnumerateNodes2Enumerator;
begin
  Enumerator := TEnumerateNodes2Enumerator.Create;
  try
    Enumerator.NodeClass := NodeClass;
    Enumerator.SeekNodeName := SeekNodeName;
    Enumerator.Proc := Proc;
    Enumerator.OnlyActive := OnlyActive;
    Enumerator.EnumerateChildrenFunction(nil, Self);
  finally FreeAndNil(Enumerator) end;
end;

type
  BreakTryFindNode = class(TCodeBreaker)
  public
    FoundNode: TX3DNode;
    constructor Create(AFoundNode: TX3DNode);
  end;

  constructor BreakTryFindNode.Create(AFoundNode: TX3DNode);
  begin
    inherited Create;
    FoundNode := AFoundNode;
  end;

procedure TX3DNode.TryFindNode_Found(Node: TX3DNode);
begin
  raise BreakTryFindNode.Create(Node);
end;

function TX3DNode.TryFindNode(FindClass: TX3DNodeClass;
  OnlyActive: boolean): TX3DNode;
begin
  try
    EnumerateNodes(FindClass, {$ifdef FPC_OBJFPC} @ {$endif}
      TryFindNode_Found, OnlyActive);
    Result := nil;
  except
    on B: BreakTryFindNode do Result := B.FoundNode;
  end;
end;

function TX3DNode.FindNode(FindClass: TX3DNodeClass; OnlyActive: boolean): TX3DNode;
begin
  result := TryFindNode(FindClass, OnlyActive);
  if Result = nil then
    raise EX3DNotFound.CreateFmt('Node class "%s" not found', [FindClass.ClassName]);
end;

function TX3DNode.TryFindNodeByName(
  FindClass: TX3DNodeClass; const FindName: string;
  OnlyActive: boolean): TX3DNode;
begin
  try
    EnumerateNodes(FindClass, FindName, {$ifdef FPC_OBJFPC} @ {$endif}
      TryFindNode_Found, OnlyActive);
    Result := nil;
  except
    on B: BreakTryFindNode do Result := B.FoundNode;
  end;
end;

function TX3DNode.FindNodeByName(
  FindClass: TX3DNodeClass; const FindName: string;
  OnlyActive: boolean): TX3DNode;
begin
  result := TryFindNodeByName(FindClass, FindName, OnlyActive);
  if Result = nil then
    raise EX3DNotFound.CreateFmt('Node name "%s" not found', [FindName]);
end;

{ TX3DNode.TryFindNodeState/Transform ----------------------------------------- }

  type
    PVRMLNode = ^TX3DNode;
    PVRMLGraphTraverseState = ^TX3DGraphTraverseState;
    BreakTryFindNodeState = class(TCodeBreaker);
    TTryFindNodeStateObj = class
      PNode: PVRMLNode;
      PState: PVRMLGraphTraverseState;
      procedure TraverseFunc(
        ANode: TX3DNode; StateStack: TX3DGraphTraverseStateStack;
        ParentInfo: PTraversingInfo; var TraverseIntoChildren: boolean);
    end;

  procedure TTryFindNodeStateObj.TraverseFunc(
    ANode: TX3DNode; StateStack: TX3DGraphTraverseStateStack;
    ParentInfo: PTraversingInfo; var TraverseIntoChildren: boolean);
  begin
    PNode^ := ANode;
    PState^ := TX3DGraphTraverseState.CreateCopy(StateStack.Top);
    raise BreakTryFindNodeState.Create;
  end;

function TX3DNode.TryFindNodeState(
  NodeClass: TX3DNodeClass;
  out Node: TX3DNode; out State: TX3DGraphTraverseState): boolean;
var
  Obj: TTryFindNodeStateObj;
begin
  Obj := TTryFindNodeStateObj.Create;
  try
    try
      Obj.PNode := @Node;
      Obj.PState := @State;
      Traverse(NodeClass, @Obj.TraverseFunc);
      result := false;
    except
      on BreakTryFindNodeState do result := true;
    end;
  finally Obj.Free end;
end;

  type
    TTryFindNodeTransformObj = class
      PNode: PVRMLNode;
      PTransform: PMatrix4Single;
      PTransformScale: PSingle;
      procedure TraverseFunc(
        ANode: TX3DNode; StateStack: TX3DGraphTraverseStateStack;
        ParentInfo: PTraversingInfo; var TraverseIntoChildren: boolean);
    end;

  procedure TTryFindNodeTransformObj.TraverseFunc(
    ANode: TX3DNode; StateStack: TX3DGraphTraverseStateStack;
    ParentInfo: PTraversingInfo; var TraverseIntoChildren: boolean);
  begin
    PNode^ := ANode;
    { to dlatego TryFindNodeTransform jest szybsze od TryFindNodeState :
      w TryFindNodeState trzeba tutaj kopiowac cale state,
      w TryFindNodeTransform wystarczy skopiowac transformacje. }
    PTransform^ := StateStack.Top.Transform;
    PTransformScale^ := StateStack.Top.TransformScale;
    raise BreakTryFindNodeState.Create;
  end;

function TX3DNode.TryFindNodeTransform(
  NodeClass: TX3DNodeClass;
  out Node: TX3DNode;
  out Transform: TMatrix4Single;
  out TransformScale: Single): boolean;
var
  Obj: TTryFindNodeTransformObj;
begin
  Obj := TTryFindNodeTransformObj.Create;
  try
    try
      Obj.PNode := @Node;
      Obj.PTransform := @Transform;
      Obj.PTransformScale := @TransformScale;
      Traverse(NodeClass, @Obj.TraverseFunc);
      Result := false;
    except
      on BreakTryFindNodeState do Result := true;
    end;
  finally Obj.Free end;
end;

function TX3DNode.TryFindParentByName(const FindName: string): TX3DNode;
var
  I: integer;
begin
  if NodeName = FindName then
    result := Self else
  begin
    result := nil;

    for I := 0 to VRML1ParentsCount - 1 do
    begin
      result := VRML1Parents[I].TryFindParentByName(FindName);
      if result <> nil then exit;
    end;

    for I := 0 to ParentFieldsCount - 1 do
    begin
      result := ParentFieldsNode[I].TryFindParentByName(FindName);
      if result <> nil then exit;
    end;
  end;
end;

function TX3DNode.FindParentByName(const FindName: string): TX3DNode;
begin
  result := TryFindParentByName(FindName);
  if Result = nil then
    raise EX3DNotFound.CreateFmt('Node name "%s" not found in parents', [FindName]);
end;

function TX3DNode.TryFindDirectParentByName(const FindName: string): TX3DNode;
var
  I: Integer;
begin
  for I := 0 to VRML1ParentsCount - 1 do
  begin
    Result := VRML1Parents[I];
    if Result.NodeName = FindName then Exit;
  end;

  for I := 0 to ParentFieldsCount - 1 do
  begin
    Result := ParentFieldsNode[I];
    if Result.NodeName = FindName then Exit;
  end;

  Result := nil;
end;

function TX3DNode.HasParent(Node: TX3DNode): boolean;
var
  I: integer;
begin
  if Self = Node then
    result := true else
  begin
    for i := 0 to VRML1ParentsCount - 1 do
      if VRML1Parents[i].HasParent(Node) then Exit(true);

    for i := 0 to ParentFieldsCount - 1 do
      if ParentFieldsNode[i].HasParent(Node) then Exit(true);

    result := False;
  end;
end;

type
  TIsNodePresentSeeker = class
    SeekNode: TX3DNode;
    procedure Seek(Node: TX3DNode);
  end;

  BreakIsNodePresent = class(TCodeBreaker);

  procedure TIsNodePresentSeeker.Seek(Node: TX3DNode);
  begin
    if Node = SeekNode then
      raise BreakIsNodePresent.Create;
  end;

function TX3DNode.IsNodePresent(Node: TX3DNode;
  OnlyActive: boolean): boolean;
var
  Seeker: TIsNodePresentSeeker;
begin
  Seeker := TIsNodePresentSeeker.Create;
  try
    Seeker.SeekNode := Node;
    try
      EnumerateNodes({$ifdef FPC_OBJFPC} @ {$endif} Seeker.Seek, OnlyActive);
      Result := false;
    except
      on BreakIsNodePresent do Result := true;
    end;
  finally FreeAndNil(Seeker) end;
end;

type
  TNodeCounter = class
    Counter: integer;
    procedure CountNode(node: TX3DNode);
  end;

  procedure TNodeCounter.CountNode(node: TX3DNode);
  begin Inc(Counter) end;

function TX3DNode.NodesCount(NodeClass: TX3DNodeClass;
  CountOnlyActiveNodes: boolean): integer;
var
  C: TNodeCounter;
begin
  C := TNodeCounter.Create;
  try
    EnumerateNodes(NodeClass,
      {$ifdef FPC_OBJFPC} @ {$endif} C.CountNode, CountOnlyActiveNodes);
    result := C.Counter;
  finally C.Free end;
end;

procedure TX3DNode.SaveToStream(Writer: TX3DWriter);
begin
  NodeSaveToStream(Writer);
  if Writer.Encoding = xeClassic then Writer.Writeln;
end;

procedure TX3DNode.NodeSaveToStream(Writer: TX3DWriter; const CurrentContainerField: string);

  { Collect node contents to save.
    You want to save here exactly what you read in ParseNodeBodyElement. }
  function ContentsToSave: TX3DFileItemList;
  var
    I: integer;
  begin
    Result := TX3DFileItemList.Create(false);
    try
      if HasInterfaceDeclarations <> [] then
      begin
        for I := 0 to InterfaceDeclarations.Count - 1 do
          Result.Add(InterfaceDeclarations[I]);
      end;

      for I := 0 to Prototypes.Count - 1 do
        Result.Add(Prototypes[I]);

      for I := 0 to Fields.Count - 1 do
      begin
        { Saving InterfaceDeclarations already handled saving fields
          with ParentInterfaceDeclaration <> nil, so no need to save them again. }
        if Fields[I].ParentInterfaceDeclaration = nil then
          Result.Add(Fields[I]);

        if Fields[I].Exposed then
        begin
          { exposed events may have their own IS clauses, save them }
          Result.Add(Fields[I].EventIn);
          Result.Add(Fields[I].EventOut);
        end;
      end;

      if VRML1ChildrenSaveToStream then
        for I := 0 to VRML1ChildrenCount - 1 do
          Result.Add(VRML1Children[I]);

      for I := 0 to Events.Count - 1 do
        if { Saving InterfaceDeclarations already handled saving events
             with ParentInterfaceDeclaration <> nil, so no need to save them again. }
           (Events[I].ParentInterfaceDeclaration = nil) then
          Result.Add(Events[I]);

      for I := 0 to Routes.Count - 1 do
        Result.Add(Routes[I]);

      for I := 0 to ImportsList.Count - 1 do
        Result.Add(ImportsList[I]);

      for I := 0 to ExportsList.Count - 1 do
        Result.Add(ExportsList[I]);
    except FreeAndNil(Result) end;
  end;

  { Gather IS clauses of fields/events.
    For XML encoding, also gather from fields/events inside interface
    declarations (for classic encoding,
    they are saved by TX3DInterfaceDeclaration.SaveToStream). }
  procedure CollectIsClauses(out NodeFields, ProtoFields: TCastleStringList);

    procedure AddIsClauses(Item: TX3DFieldOrEvent);
    var
      N: string;
      I: Integer;
    begin
      N := Item.NameForVersion(Writer.Version);
      if N = '' then Exit; { unnamed fields/events cannot be saved here }
      for I := 0 to Item.IsClauseNamesCount - 1 do
      begin
        NodeFields.Add(N);
        ProtoFields.Add(Item.IsClauseNames[I]);
      end;
    end;

  var
    I: Integer;
  begin
    NodeFields := TCastleStringList.Create;
    ProtoFields := TCastleStringList.Create;

    for I := 0 to Fields.Count - 1 do
    begin
      if (Writer.Encoding <> xeClassic) or
         (Fields[I].ParentInterfaceDeclaration = nil) then
        AddIsClauses(Fields[I]);

      if Fields[I].Exposed then
      begin
        { exposed events may have their own IS clauses, save them }
        AddIsClauses(Fields[I].EventIn);
        AddIsClauses(Fields[I].EventOut);
      end;
    end;

    for I := 0 to Events.Count - 1 do
      if (Writer.Encoding <> xeClassic) or
         (Events[I].ParentInterfaceDeclaration = nil) then
        AddIsClauses(Events[I]);
  end;

  procedure Classic;
  var
    FileItems: TX3DFileItemList;
    NodeFields, ProtoFields: TCastleStringList;
    I: Integer;
  begin
    if (Writer as TX3DWriterNames).NodeNames.Bound(Self) then
    begin
      Writer.WriteIndent('USE ' + NodeName);
    end else
    begin
      (Writer as TX3DWriterNames).NodeNames.Bind(Self, false);

      CollectIsClauses(NodeFields, ProtoFields);
      try
        Writer.WriteIndent('');
        if NodeName <> '' then Writer.Write('DEF ' +NodeName +' ');
        Writer.Writeln(NodeTypeName +' {');

        Writer.IncIndent;
        FileItems := ContentsToSave;
        try
          FileItems.SaveToStream(Writer);
        finally FreeAndNil(FileItems) end;

        { save IS clauses }
        for I := 0 to NodeFields.Count - 1 do
          Writer.WritelnIndent(Format('%s IS %s', [NodeFields[I], ProtoFields[I]]));
        Writer.DecIndent;

        Writer.WriteIndent('}');
      finally
        FreeAndNil(NodeFields);
        FreeAndNil(ProtoFields);
      end;

      (Writer as TX3DWriterNames).NodeNames.Bind(Self, true);
    end;
  end;

  procedure Xml;
  var
    FileItems: TX3DFileItemList;
    HasContent: boolean;
    I: Integer;
    WriteContainerField: string;
    ElementName: string;
    ProtoInstance: boolean;
    NodeFields, ProtoFields: TCastleStringList;
  begin
    { Knowing CurrentContainerField and DefaultContainerField,
      we can always correctly set containerField= ourselves. }
    if (CurrentContainerField <> '') and
       (CurrentContainerField <> DefaultContainerField) then
      WriteContainerField := ' containerField=' + StringToX3DXml(CurrentContainerField) else
      WriteContainerField := '';

    { For XML encoding, TX3DPrototypeNode is saved a little specially. }
    ProtoInstance := Self is TX3DPrototypeNode;

    if ProtoInstance then
      ElementName := 'ProtoInstance' else
      ElementName := NodeTypeName;

    if (Writer as TX3DWriterNames).NodeNames.Bound(Self) then
    begin
      Writer.WritelnIndent(Format('<%s USE=%s%s />',
        [ElementName, StringToX3DXml(NodeName), WriteContainerField]));
    end else
    begin
      (Writer as TX3DWriterNames).NodeNames.Bind(Self, false);

      CollectIsClauses(NodeFields, ProtoFields);
      try
        Writer.WriteIndent('<' + ElementName);
        if ProtoInstance then
          Writer.Write(' name=' + StringToX3DXml(NodeTypeName));
        if NodeName <> '' then Writer.Write(' DEF=' +StringToX3DXml(NodeName));
        Writer.Write(WriteContainerField);

        HasContent := false;
        FileItems := ContentsToSave;
        try
          FileItems.SortPositionInParent;

          Writer.IncIndent;
          for I := 0 to FileItems.Count - 1 do
            case FileItems[I].SaveToXml of
              sxAttribute, sxAttributeCustomQuotes:
                if ProtoInstance then
                  { for a prototype, every field must be wrapped in <fieldValue> }
                  HasContent := true else
                  FileItems[I].SaveToStream(Writer);
              sxChildElement: HasContent := true;
            end;
          Writer.DecIndent;

          if NodeFields.Count <> 0 then
            HasContent := true;

          if HasContent then
          begin
            Writer.Writeln('>');
            Writer.IncIndent;

            for I := 0 to FileItems.Count - 1 do
              if ProtoInstance and
                 (FileItems[I] is TX3DField) and
                 (FileItems[I].SaveToXml <> sxNone) then
              begin
                { prototype instance fields must be wrapped in <fieldValue> }
                Writer.WriteIndent('<fieldValue name=' +
                  StringToX3DXml((FileItems[I] as TX3DField).Name));
                if FileItems[I].SaveToXml = sxChildElement then
                begin
                  Writer.Writeln('>');
                  Writer.IncIndent;
                  FileItems[I].SaveToStream(Writer);
                  Writer.DecIndent;
                  Writer.WritelnIndent('</fieldValue>');
                end else
                begin
                  Assert(FileItems[I].SaveToXml in [sxAttribute, sxAttributeCustomQuotes]);
                  Writer.IncIndent;
                  Writer.Writeln;
                  Writer.WriteIndent('value=');
                  (FileItems[I]  as TX3DField).FieldSaveToStream(Writer, true, true);
                  Writer.DecIndent;
                  Writer.Writeln(' />');
                end;
              end else
              if FileItems[I].SaveToXml = sxChildElement then
                FileItems[I].SaveToStream(Writer);

            { save IS clauses }
            { TODO: should be before all, but *after* interface declarations and fieldValue }
            if NodeFields.Count <> 0 then
            begin
              Writer.WritelnIndent('<IS>');
              Writer.IncIndent;
              for I := 0 to NodeFields.Count - 1 do
                Writer.WritelnIndent(Format('<connect nodeField=%s protoField=%s />',
                  [ StringToX3DXml(NodeFields[I]),
                    StringToX3DXml(ProtoFields[I])]));
              Writer.DecIndent;
              Writer.WritelnIndent('</IS>');
            end;

            Writer.DecIndent;
            Writer.WritelnIndent('</' + ElementName + '>');
          end else
            Writer.Writeln(' />');
        finally FreeAndNil(FileItems) end;
      finally
        FreeAndNil(NodeFields);
        FreeAndNil(ProtoFields);
      end;

      (Writer as TX3DWriterNames).NodeNames.Bind(Self, true);
    end;
  end;

begin
  if PrototypeInstance and
     { TX3DPrototypeNode has somewhat different meaning of PrototypeInstance,
       we want to save it directly (otherwise
       PrototypeInstanceSourceNode.SaveToStream could cause another
       recursive PrototypeInstanceSourceNode.SaveToStream with
       nested proto). For example test read + save
       demo_models/x3d/key_sensor.x3dv, to see that check below is needed. }
     not (Self is TX3DPrototypeNode) then
  begin
    { If this is an expanded prototype, then delegate writing to the
      PrototypeInstanceSourceNode. }
    PrototypeInstanceSourceNode.NodeSaveToStream(Writer, CurrentContainerField);

    { What to do about
        NodeNames.Bind(Self)
      called from PrototypeInstanceSourceNode.SaveToStream ?
      This means that PrototypeInstanceSourceNode (TX3DPrototypeNode)
      is bound to given name.
      But when reading, we bound Self node (the actual expanded proto)
      to the same name.
      Routes when saving check this (to make sure correct names are bound).
      So we bind again Self, instead of PrototypeInstanceSourceNode,
      to this name. }

    (Writer as TX3DWriterNames).NodeNames.Bind(Self, true);
  end else
  case Writer.Encoding of
    xeClassic: Classic;
    xeXML    : Xml;
    else raise EInternalError.Create('TX3DNode.SaveToStream Encoding?');
  end;
end;

class function TX3DNode.VRML1StateNode(out StateNode: TVRML1StateNode): boolean;
var
  SN: TVRML1StateNode;
begin
  { We're in "class function", so Self = reference to our class.
    So simple comparison "Self = ..." is what we want. }
  for SN := Low(SN) to High(SN) do
    if TraverseStateLastNodesClasses[SN] = Self then
    begin
      StateNode := SN;
      Result := true;
      Exit;
    end;
  Result := false;
end;

class function TX3DNode.ForVRMLVersion(const Version: TX3DVersion): boolean;
begin
  Result := true;
end;

procedure TX3DNode.RemoveParentField(Field: TX3DField);
begin
  Check(FParentFields.Remove(Field) <> -1, 'RemoveParentField: parent not found');
  FreeIfUnused;
end;

procedure TX3DNode.AddParentField(Field: TX3DField);
begin
  FParentFields.Add(Field);
end;

class function TX3DNode.VRML1ChildrenSaveToStream: boolean;
begin
  Result := true;
end;

function TX3DNode.EnumerateReplaceChildren(
  Func: TEnumerateReplaceNodesFunction): Cardinal;
var
  I, J: Integer;
  SF: TSFNode;
  MF: TMFNode;
  NewNode: TX3DNode;
begin
  { I don't use EnumerateNodes since I have to enumerate them myself,
    since they may be removed during enumeration.
    The code below mimics TX3DNode.DirectEnumerateAll implementation,
    but it takes into account that nodes may be removed. }

  Result := 0;

  I := 0;
  while I < VRML1ChildrenCount do
  begin
    NewNode := VRML1Children[I];
    Func(Self, NewNode);
    if NewNode <> VRML1Children[I] then
    begin
      VRML1ChildRemove(I);
      Inc(Result);
      if NewNode <> nil then
      begin
        VRML1ChildAdd(I, NewNode);
        Inc(I);
      end;
    end else
    begin
      Result += VRML1Children[I].EnumerateReplaceChildren(Func);
      Inc(I);
    end;
  end;

  for I := 0 to Fields.Count - 1 do
  begin
    if Fields[I] is TSFNode then
    begin
      SF := TSFNode(Fields[I]);
      if SF.Value <> nil then
      begin
        NewNode := SF.Value;
        Func(Self, NewNode);
        if NewNode <> SF.Value then
        begin
          SF.Value := NewNode;
          Inc(Result);
        end else
        begin
          Result += SF.Value.EnumerateReplaceChildren(Func);
        end;
      end;
    end else
    if Fields[I] is TMFNode then
    begin
      MF := TMFNode(Fields[I]);
      J := 0;
      while J < MF.Items.Count do
      begin
        NewNode := MF.Items[J];
        Func(Self, NewNode);
        if NewNode <> MF.Items[J] then
        begin
          MF.Delete(J);
          Inc(Result);
          if NewNode <> nil then
          begin
            MF.Add(J, NewNode);
            Inc(J);
          end;
        end else
        begin
          Result += MF.Items[J].EnumerateReplaceChildren(Func);
          Inc(J);
        end;
      end;
    end;
  end;
end;

  type
    TRemoveChildrenWithMatchingNameHelper = class
      Wildcard: string;
      IgnoreCase: boolean;
      procedure DoIt(ParentNode: TX3DNode; var Node: TX3DNode);
    end;

  procedure TRemoveChildrenWithMatchingNameHelper.DoIt(
    ParentNode: TX3DNode; var Node: TX3DNode);
  begin
    if IsWild(Node.NodeName, Wildcard, IgnoreCase) then
      Node := nil;
  end;

function TX3DNode.RemoveChildrenWithMatchingName(
  const Wildcard: string; IgnoreCase: Boolean): Cardinal;
var
  Helper: TRemoveChildrenWithMatchingNameHelper;
begin
  Helper := TRemoveChildrenWithMatchingNameHelper.Create;
  try
    Helper.Wildcard := Wildcard;
    Helper.IgnoreCase := IgnoreCase;
    Result := EnumerateReplaceChildren(@Helper.DoIt);
  finally FreeAndNil(Helper) end;
end;

class function TX3DNode.URNMatching(const URN: string): boolean;
begin
  Result := false;
end;

function TX3DNode.FieldOrEvent(const Name: string): TX3DFieldOrEvent;
var
  I: Integer;
  ResultEvent: TX3DEvent;
begin
  I := Fields.IndexOf(Name);
  if I <> -1 then
    Exit(Fields[I]);

  { I use helper ResultEvent below, instead of passing
    "TX3DEvent(Result)" as last param: don't know why,
    but with FPC 2.2.0 this cast may fail (even though it shouldn't
    be checked at all?), testcase:
      view3dscene www.web3d.org/x3d/content/examples/Basic/CAD/CADGeometryPrototypes.x3d
  }

  I := Fields.IndexOfExposedEvent(Name, ResultEvent);
  if I <> -1 then
    Exit(ResultEvent);

  I := Events.IndexOf(Name);
  if I <> -1 then
    Exit(Events[I]);

  Result := nil; { not found }
end;

function TX3DNode.AnyEvent(const Name: string): TX3DEvent;
var
  I: Integer;
begin
  I := Fields.IndexOfExposedEvent(Name, Result);
  if I <> -1 then
    Exit; { Result is already set }

  I := Events.IndexOf(Name);
  if I <> -1 then
    Exit(Events[I]);

  Result := nil; { not found }
end;

procedure TX3DNode.SetHasInterfaceDeclarations(const Value: TX3DAccessTypes);
begin
  if Value <> HasInterfaceDeclarations then
  begin
    FHasInterfaceDeclarations := Value;
    if HasInterfaceDeclarations <> [] then
    begin
      { make sure InterfaceDeclarations is non-nil }
      if FInterfaceDeclarations = nil then
        FInterfaceDeclarations := TX3DInterfaceDeclarationList.Create(true);
    end else
    begin
      { make sure InterfaceDeclarations is nil }
      FreeAndNil(FInterfaceDeclarations);
    end;
  end;
end;

{ I couldn't implement this as TX3DField method, as X3DFields
  cannot declare TX3DNode in the interface, so also
  cannot declare TX3DNodeDeepCopyState. }
procedure FieldDeepCopyContents(Destination, Source: TX3DField;
  CopyState: TX3DNodeDeepCopyState);
var
  J: Integer;
  SF: TSFNode;
  MF: TMFNode;
begin
  { First make "shallow copy" of the field by simple Assign }
  Destination.Assign(Source);

  if Destination is TSFNode then
  begin
    SF := TSFNode(Destination);
    if SF.Value <> nil then
      SF.Value := CopyState.DeepCopy(SF.Value);
  end else
  if Destination is TMFNode then
  begin
    MF := TMFNode(Destination);
    for J := 0 to MF.Count - 1 do
      MF.Replace(J, CopyState.DeepCopy(MF.Items[J]));
  end;
end;

procedure EventDeepCopyContents(Destination, Source: TX3DEvent);
begin
  { For events, simple Assign does all copy we need --- at least for now. }
  Destination.Assign(Source);
end;

function TX3DNode.DeepCopyCreate(CopyState: TX3DNodeDeepCopyState): TX3DNode;
begin
  Result := TX3DNodeClass(ClassType).Create(NodeName, BaseUrl);
end;

function TX3DNode.DeepCopyCore(CopyState: TX3DNodeDeepCopyState): TX3DNode;
var
  I: Integer;
  IDecl: TX3DInterfaceDeclaration;
begin
  Result := DeepCopyCreate(CopyState);

  try

    { We expand CopyState arrays now, right after DeepCopyCreate.
      This is needed, as later during DeepCopyCore we may need this node
      in case of loops within hierarchy.

      For example, internal
      routes from TX3DPrototypeNode are established to handle "IS" clauses
      for events. There routes are to/from TX3DPrototypeNode, and are
      also placed within this TX3DPrototypeNode instance. So when copying
      node routes, this node must already be present in CopyState arrays.

      Also, in the future we will have to allow loops in Script nodes
      (USE within Script node may refer to the same node). So again loop
      will be created. }
    CopyState.Original.Add(Self);
    CopyState.New.Add(Result);

    for I := 0 to VRML1ChildrenCount - 1 do
      Result.VRML1ChildAdd(CopyState.DeepCopy(VRML1Children[I]));

    { Copy InterfaceDeclarations first, before copying Fields and Events
      (as some Fields and Events come from InterfaceDeclarations). }
    Result.HasInterfaceDeclarations := HasInterfaceDeclarations;

    if InterfaceDeclarations <> nil then
    begin
      for I := 0 to InterfaceDeclarations.Count - 1 do
      begin
        IDecl := InterfaceDeclarations[I].DeepCopy(Result, CopyState);
        Result.InterfaceDeclarations.Add(IDecl);
        Result.PostAddInterfaceDeclaration(IDecl);
      end;
    end;

    { TODO: No need to copy prototypes for now?

      This DeepCopy is used for now by protos expanding and by TCastlePrecalculatedAnimation.
      Neither need prototype links (as protos are already expanded when copying,
      and they don't need anything more).

      for I := 0 to Prototypes.Count - 1 do
        ...(Prototypes[I]);
    }

    Assert(Fields.Count = Result.Fields.Count);
    Assert(Events.Count = Result.Events.Count);

    for I := 0 to Fields.Count - 1 do
      { Copying InterfaceDeclarations field/event already handled. }
      if Fields[I].ParentInterfaceDeclaration = nil then
      begin
        FieldDeepCopyContents(Result.Fields[I], Fields[I], CopyState);

        if Result.Fields[I].Exposed then
        begin
          EventDeepCopyContents(Result.Fields[I].EventIn , Fields[I].EventIn );
          EventDeepCopyContents(Result.Fields[I].EventOut, Fields[I].EventOut);
        end;
      end;

    for I := 0 to Events.Count - 1 do
      { Copying InterfaceDeclarations field/event already handled. }
      if Events[I].ParentInterfaceDeclaration = nil then
        EventDeepCopyContents(Result.Events[I], Events[I]);

    for I := 0 to Routes.Count - 1 do
      Result.Routes.Add(Routes[I].DeepCopy(CopyState));

    for I := 0 to ImportsList.Count - 1 do
      Result.ImportsList.Add((ImportsList[I] as TX3DImport).DeepCopy(CopyState));

    for I := 0 to ExportsList.Count - 1 do
      Result.ExportsList.Add((ExportsList[I] as TX3DExport).DeepCopy(CopyState));

    if PrototypeInstance then
    begin
      Result.FPrototypeInstance := PrototypeInstance;
      Result.FPrototypeInstanceSourceNode :=
        CopyState.DeepCopy(PrototypeInstanceSourceNode) as TX3DPrototypeNode;
      if PrototypeInstanceHelpers <> nil then
        Result.FPrototypeInstanceHelpers := CopyState.DeepCopy(PrototypeInstanceHelpers);
    end;

    Result.DefaultContainerField := DefaultContainerField;
  except
    FreeAndNil(Result);
    raise;
  end;
end;

function TX3DNode.DeepCopy: TX3DNode;
var
  CopyState: TX3DNodeDeepCopyState;
begin
  CopyState := TX3DNodeDeepCopyState.Create;
  try
    Result := CopyState.DeepCopy(Self);
  finally FreeAndNil(CopyState); end;
end;

procedure TX3DNode.PostAddInterfaceDeclaration(IDecl: TX3DInterfaceDeclaration);
begin
  IDecl.AddFieldOrEvent(Self);
end;

procedure TX3DNode.AddCustomField(Field: TX3DField; const Exposed: boolean);
var
  IDecl: TX3DInterfaceDeclaration;
begin
  Field.Exposed := Exposed;

  IDecl := TX3DInterfaceDeclaration.Create(Self);
  IDecl.FieldOrEvent := Field;
  Field.ParentInterfaceDeclaration := IDecl;
  InterfaceDeclarations.Add(IDecl);
  PostAddInterfaceDeclaration(IDecl);
end;

function TX3DNode.TransformationChange: TNodeTransformationChange;
begin
  Result := ntcNone;
end;

function TX3DNode.NiceName: string;
begin
  Result := NodeTypeName;
  if NodeName <> '' then
    Result += '(' + NodeName + ')';
end;

{ TX3DNodeList ------------------------------------------------------------- }

function TX3DNodeList.FindName(const Name: string): TX3DNode;
var
  I: Integer;
begin
  if Name = '' then
    Exit(nil);

  for I := 0 to Count - 1 do
  begin
    Result := Items[I];
    if Result.NodeName = Name then
      Exit;
  end;
  Result := nil;
end;

function TX3DNodeList.IndexOfName(const Name: string): Integer;
begin
  if Name = '' then
    Exit(-1);

  for Result := 0 to Count - 1 do
    if Items[Result].NodeName = Name then
      Exit;
  Result := -1;
end;

procedure TX3DNodeList.AddIfNotExists(const Node: TX3DNode);
begin
  if IndexOf(Node) = -1 then
    Add(Node);
end;

function TX3DNodeList.Equals(SecondValue: TObject): boolean;
var
  I: Integer;
begin
  Result :=
    (SecondValue <> nil) and
    (SecondValue is TX3DNodeList) and
    (TX3DNodeList(SecondValue).Count = Count);

  if Result then
    for I := 0 to Count - 1 do
      if Items[I] <> TX3DNodeList(SecondValue)[I] then
        Exit(false);
end;

procedure X3DNodeList_FreeUnusedAndNil(var List: TX3DNodeList);
var
  I: Integer;
begin
  if List <> nil then
  begin
    for I := 0 to List.Count - 1 do
      if List.Items[I].VRML1ParentsCount + List.Items[I].ParentFieldsCount = 0 then
        List.Items[I].Free;
    FreeAndNil(List);
  end;
end;

{$endif read_implementation}