This file is indexed.

/usr/src/castle-game-engine-5.0.0/x3d/x3dloadinternalcollada.pas 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
{
  Copyright 2008-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.

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

{ Load Collada. }
unit X3DLoadInternalCollada;

{$I castleconf.inc}

interface

uses X3DNodes;

{ Load Collada file as X3D.

  Written based on Collada 1.3.1 and 1.4.1 specifications.
  Should handle any Collada 1.3.x or 1.4.x or 1.5.x version.
  http://www.gamasutra.com/view/feature/1580/introduction_to_collada.php?page=6
  suggests that "specification stayed quite stable between 1.1 and 1.3.1",
  which means that older versions (< 1.3.1) may be handled too.

  @param(AllowKambiExtensions If @true we may use some of our engine specific
    extensions. For example, Material.mirror may be <> 0,
    see [http://castle-engine.sourceforge.net/x3d_extensions.php#section_ext_material_mirror].) }
function LoadCollada(const URL: string;
  const AllowKambiExtensions: boolean = false): TX3DRootNode;

implementation

uses SysUtils, CastleUtils, CastleStringUtils, CastleVectors, CastleColors,
  DOM, XMLRead, CastleXMLUtils, CastleWarnings, Classes, CastleClassUtils,
  FGL, Math, X3DLoadInternalUtils, CastleDownload, CastleURIUtils, URIParser;

{ Large missing stuff:

  - GPU shaders. We fully support the equivalent X3D nodes (for GLSL),
    so importing this from Collada (converting to X3D) is possible.

  - Animations. As an argument for supporting it, Blender *can* export
    some animations to Collada:

    - Transformation animation: Blender exports it,
      in a format that is close to Blender animation curves.
      There's a separate info about location.x, location.y etc. animation.
      Animation of rotation is animating angle of rotation around the X axis, etc.
      Animations are connected to Collada nodes by

        <channel source="#Cube_rotation_euler_Z-sampler" target="Cube/rotationZ.ANGLE"/>

      "target" attribute uses Collada id path.
      We'd have to group such animations of a vector components into a single
      animation (in X3D, you cannot animate translation.x separately,
      you only animate whole 3D translation vector).
      This is doable for our importer.

    - Shape keys animation from Blender is not exported to Collada, it seems.

    - Armature animation: Blender exports armature bones animation.
      Also, armature hierarchy is exported as Collada nodes.
      Armature bone names and weights are exported too.

      So armature is exported --- in a format reflecting armature setup in Blender,
      not as a processed effect it has on a model skin.
      Rendering it means performing bones+skin animation at runtime.
      X3D equivalent of this is H-Anim with skin, which we support fully.
      So importing such Collada is possible.

      It depends on importing first normal transformation animation
      (as the bones are animated just like normal transformations;
      there's no point in importing skin stuff if you can't import bones animation).

  These are all doable ideas, but also not trivial.
  Since Blender can export animations to Collada (and not yet to X3D),
  it would be quite useful.
  Contributions are welcome!
}

{ TCollada* helper containers ------------------------------------------------ }

type
  TColladaController = class
    Name: string;
    Source: string;
    BoundShapeMatrix: TMatrix4Single;
    BoundShapeMatrixIdentity: boolean;
  end;

  TColladaControllerList = class(specialize TFPGObjectList<TColladaController>)
  public
    { Find a TColladaController with given Name, @nil if not found. }
    function Find(const Name: string): TColladaController;
  end;

function TColladaControllerList.Find(const Name: string): TColladaController;
var
  I: Integer;
begin
  for I := 0 to Count - 1 do
    if Items[I].Name = Name then
      Exit(Items[I]);

  Result := nil;
end;

type
  TColladaEffect = class
    Appearance: TAppearanceNode;
    { If this effect contains a texture for diffuse, this is the name
      of texture coordinates in Collada.
      For now not used (we always take first input with TEXCOORD semantic
      to control the main texture, that affects the look (after lighting
      calculation, so not only diffuse). }
    DiffuseTexCoordName: string;
    destructor Destroy; override;
  end;

destructor TColladaEffect.Destroy;
begin
  FreeIfUnusedAndNil(Appearance);
  inherited;
end;

type
  TColladaEffectList = class(specialize TFPGObjectList<TColladaEffect>)
    { Find a TColladaEffect with given Name, @nil if not found. }
    function Find(const Name: string): TColladaEffect;
  end;

function TColladaEffectList.Find(const Name: string): TColladaEffect;
var
  I: Integer;
begin
  for I := 0 to Count - 1 do
    if Items[I].Appearance.NodeName = Name then
      Exit(Items[I]);
  Result := nil;
end;

type
  { Collada primitive (item handled by ReadPrimitiveCommon,
    from <poly*> or <tri*> or <lines*> elements within <mesh>),
    which are X3D geometries with a material name. }
  TColladaPrimitive = class
    { Collada material name (from "material" attribute of primitive element).
      For Collada 1.3.x, this is just a name of material in material library.
      For Collada 1.4.x, when instantiating geometry you specify which material
      name (inside geometry) corresponds to which material name on Materials
      list. }
    Material: string;
    X3DGeometry: TAbstractGeometryNode;
    destructor Destroy; override;
  end;

  TColladaPrimitiveList = specialize TFPGObjectList<TColladaPrimitive>;

destructor TColladaPrimitive.Destroy;
begin
  FreeIfUnusedAndNil(X3DGeometry);
  inherited;
end;

type
  TColladaGeometry = class
    { Collada geometry id. }
    Name: string;
    Primitives: TColladaPrimitiveList;
    constructor Create;
    destructor Destroy; override;
  end;

constructor TColladaGeometry.Create;
begin
  Primitives := TColladaPrimitiveList.Create;
end;

destructor TColladaGeometry.Destroy;
begin
  FreeAndNil(Primitives);
  inherited;
end;

type
  TColladaGeometryList = class (specialize TFPGObjectList<TColladaGeometry>)
  public
    { Find item with given Name, @nil if not found. }
    function Find(const Name: string): TColladaGeometry;
  end;

function TColladaGeometryList.Find(const Name: string): TColladaGeometry;
var
  I: Integer;
begin
  for I := 0 to Count - 1 do
    if Items[I].Name = Name then
      Exit(Items[I]);

  Result := nil;
end;

type
  TStringTextureNodeMap = class(specialize TFPGMap<string, TAbstractTextureNode>)
    { For given Key return it's data, or @nil if not found.
      In our usage, we never insert @nil node as data, so this is
      not ambiguous. }
    function Find(const Key: string): TAbstractTextureNode;
  end;

function TStringTextureNodeMap.Find(const Key: string): TAbstractTextureNode;
var
  Index: Integer;
begin
  { do not use "inherited Find", it expects list is sorted }
  Index := IndexOf(Key);
  if Index <> -1 then
    Result := Data[Index] else
    Result := nil;
end;

type
  { Collada materials. Data contains TColladaEffect, which is a reference
    to Effects list (it is not owned by this TColladaMaterialsMap). }
  TColladaMaterialsMap = class(specialize TFPGMap<string, TColladaEffect>)
    { For given Key return it's data, or @nil if not found.
      In our usage, we never insert @nil effect as data, so this is
      not ambiguous. }
    function Find(const Key: string): TColladaEffect;
  end;

function TColladaMaterialsMap.Find(const Key: string): TColladaEffect;
var
  Index: Integer;
begin
  { do not use "inherited Find", it expects list is sorted }
  Index := IndexOf(Key);
  if Index <> -1 then
    Result := Data[Index] else
    Result := nil;
end;

type
  { Collada <source>. This is a named container keeping a series of floats
    in Collada. It may contain only data for some specific purpose (like positions
    or normals or tex coords) or be interleaved with other data. }
  TColladaSource = class
    Name: string;
    Floats: TFloatList;
    Params: TCastleStringList;
    { Collada <accessor> description of vectors inside Floats.
      Note that Count here refers to count of whole vectors (so it's usually
      < than Floats.Count). }
    Count, Stride, Offset: Integer;

    constructor Create;
    destructor Destroy; override;

    { Check components and counts before AssignToVectorXYZ.
      It @false, a warning is done, and some parameters are adjusted.
      You can then abort using this vector
      (if it can be reasonably ignored, e.g. for normals),
      or try AssignToVectorXYZ anyway
      (if it's necessary, e.g. when this is for vertex positions). }
    function CheckXYZ(out XIndex, YIndex, ZIndex: Integer): boolean;
    function CheckST(out SIndex, TIndex: Integer): boolean;

    { Extract from source an array of TVector3Single.
      Params will be checked to contain at least three vector components
      'X', 'Y', 'Z'. (These should be specified in <param name="..." type="float"/>).

      Order of X, Y, Z params (and thus order of components in our Floats)
      may be different, we will reorder them to XYZ anyway.
      This way Collada data may have XYZ or ST in a different order,
      and this method will reorder this suitable for X3D.

      Returns if components were fully correct (no warnings). }
    function AssignToVectorXYZ(const Value: TVector3SingleList): boolean;

    { Extract from source an array of TVector2Single, for texture coordinates.
      Like AssignToVectorXYZ, but for 2D vectors, with component names 'S' and 'T'
      (or 'U' and 'V'). }
    function AssignToVectorST(const Value: TVector2SingleList): boolean;
  end;

constructor TColladaSource.Create;
begin
  inherited;
  Params := TCastleStringList.Create;
  Floats := TFloatList.Create;
end;

destructor TColladaSource.Destroy;
begin
  FreeAndNil(Params);
  FreeAndNil(Floats);
  inherited;
end;

function TColladaSource.CheckXYZ(out XIndex, YIndex, ZIndex: Integer): boolean;
var
  MinCount: Integer;
begin
  XIndex := Params.IndexOf('X');
  if XIndex = -1 then
  begin
    OnWarning(wtMajor, 'Collada', 'Missing "X" parameter (for 3D vector) in this <source>');
    Exit(false);
  end;

  YIndex := Params.IndexOf('Y');
  if YIndex = -1 then
  begin
    OnWarning(wtMajor, 'Collada', 'Missing "Y" parameter (for 3D vector) in this <source>');
    Exit(false);
  end;

  ZIndex := Params.IndexOf('Z');
  if ZIndex = -1 then
  begin
    OnWarning(wtMajor, 'Collada', 'Missing "Z" parameter (for 3D vector) in this <source>');
    Exit(false);
  end;

  MinCount := Offset + Stride * (Count - 1) + CastleUtils.Max(XIndex, YIndex, ZIndex) + 1;
  Result := Floats.Count >= MinCount;
  if not Result then
  begin
    OnWarning(wtMinor, 'Collada', Format('<accessor> count requires at least %d float values in <float_array>, but only %d are avilable',
      [MinCount, Floats.Count]));
    { force Count smaller, also force other params to common values }
    Stride := Max(Stride, 1);
    XIndex := 0;
    YIndex := 1;
    ZIndex := 2;
    Count := (Floats.Count - Offset) div Stride;
  end;
end;

function TColladaSource.AssignToVectorXYZ(const Value: TVector3SingleList): boolean;
var
  XIndex, YIndex, ZIndex, I: Integer;
begin
  Result := CheckXYZ(XIndex, YIndex, ZIndex);
  Value.Count := Count;
  for I := 0 to Count - 1 do
  begin
    Value.L[I][0] := Floats.L[Offset + Stride * I + XIndex];
    Value.L[I][1] := Floats.L[Offset + Stride * I + YIndex];
    Value.L[I][2] := Floats.L[Offset + Stride * I + ZIndex];
  end;
end;

function TColladaSource.CheckST(out SIndex, TIndex: Integer): boolean;
var
  MinCount: Integer;
begin
  SIndex := Params.IndexOf('S');
  if SIndex = -1 then
  begin
    SIndex := Params.IndexOf('U');
    if SIndex = -1 then
    begin
      OnWarning(wtMajor, 'Collada', 'Missing "S" or "U" parameter (1st component of 2D tex coord) in this <source>');
      Exit(false);
    end;
  end;

  TIndex := Params.IndexOf('T');
  if TIndex = -1 then
  begin
    TIndex := Params.IndexOf('V');
    if TIndex = -1 then
    begin
      OnWarning(wtMajor, 'Collada', 'Missing "T" or "V" parameter (2nd component of 2D tex coord) in this <source>');
      Exit(false);
    end;
  end;

  MinCount := Offset + Stride * (Count - 1) + Max(SIndex, TIndex) + 1;
  Result := Floats.Count >= MinCount;
  if not Result then
  begin
    OnWarning(wtMinor, 'Collada', Format('<accessor> count requires at least %d float values in <float_array>, but only %d are avilable',
      [MinCount, Floats.Count]));
    { force Count smaller, also force other params to common values }
    Stride := Max(Stride, 1);
    SIndex := 0;
    TIndex := 1;
    Count := (Floats.Count - Offset) div Stride;
  end;
end;

function TColladaSource.AssignToVectorST(const Value: TVector2SingleList): boolean;
var
  SIndex, TIndex, I: Integer;
begin
  Result := CheckST(SIndex, TIndex);
  Value.Count := Count;
  for I := 0 to Count - 1 do
  begin
    Value.L[I][0] := Floats.L[Offset + Stride * I + SIndex];
    Value.L[I][1] := Floats.L[Offset + Stride * I + TIndex];
  end;
end;

type
  TColladaSourceList = class(specialize TFPGObjectList<TColladaSource>)
  public
    { Find a TColladaSource with given Name, @nil if not found. }
    function Find(const Name: string): TColladaSource;
  end;

function TColladaSourceList.Find(const Name: string): TColladaSource;
var
  I: Integer;
begin
  for I := 0 to Count - 1 do
    if Items[I].Name = Name then
      Exit(Items[I]);
  Result := nil;
end;

type
  { Parse a sequence of integeres inside a string inside an XML element. }
  TIntegersParser = class
  private
    Content: string;
    FCurrent: Int64;
    SeekPos: Integer;
    Ended: boolean;
  public
    constructor Create(const PElement: TDOMElement);
    function GetNext: boolean;
    property Current: Int64 read FCurrent;
  end;

constructor TIntegersParser.Create(const PElement: TDOMElement);
begin
  inherited Create;
  Content := DOMGetTextData(PElement);
  SeekPos := 1;
end;

function TIntegersParser.GetNext: boolean;
var
  Token: string;
begin
  if Ended then Exit(false);

  Token := NextToken(Content, SeekPos);
  if Token = '' then
  begin
    Ended := true;
    Result := false;
  end else
  try
    FCurrent := StrToInt(Token);
    Result := true;
  except
    on E: EConvertError do
    begin
      OnWarning(wtMajor, 'Collada', 'Invalid integer: ' + E.Message);
      Ended := true; { don't read further }
      Result := false;
    end;
  end;
end;

type
  { Indexes of a single vertex. Used only together with TColladaIndexes,
    that knows which ones are relevant (Coord is always relevant,
    but TexCoord is relevant only if TexCoordIndexOffset <> -1,
    and Normal is relevant only if NormalIndexOffset <> -1). }
  TIndex = record Coord, TexCoord, Normal: Integer end;

  { Handling Collada <p> (indexes inside primitives) to fill X3D geometry indexes.
    Accepted geometry types are TIndexedFaceSetNode and TIndexedLineSetNode,
    as only such may be created for Collada primitives. }
  TColladaIndexes = class
  private
    Ints: TIntegersParser;
    FGeometry: TAbstractGeometryNode;
    FInputsCount, FCoordIndexOffset, FTexCoordIndexOffset, FNormalIndexOffset: Integer;
  public
    constructor Create(const Geometry: TAbstractGeometryNode;
      const InputsCount, CoordIndexOffset, TexCoordIndexOffset, NormalIndexOffset: Integer);
    destructor Destroy; override;
    procedure BeginElement(const PElement: TDOMElement);
    function ReadVertex(out Index: TIndex): boolean;
    function ReadAddVertex(out Index: TIndex): boolean;
    function ReadAddVertex: boolean;
    procedure AddVertex(const Index: TIndex);
    procedure PolygonEnd;
  end;

constructor TColladaIndexes.Create(
  const Geometry: TAbstractGeometryNode;
  const InputsCount, CoordIndexOffset, TexCoordIndexOffset, NormalIndexOffset: Integer);
begin
  inherited Create;
  FGeometry := Geometry;
  FInputsCount := InputsCount;
  FCoordIndexOffset := CoordIndexOffset;
  FTexCoordIndexOffset := TexCoordIndexOffset;
  FNormalIndexOffset := NormalIndexOffset;
end;

procedure TColladaIndexes.BeginElement(const PElement: TDOMElement);
begin
  FreeAndNil(Ints);
  Ints := TIntegersParser.Create(PElement);
end;

destructor TColladaIndexes.Destroy;
begin
  FreeAndNil(Ints);
  inherited;
end;

const
  EmptyIndex: TIndex = (Coord: -1; TexCoord: -1; Normal: -1);

function TColladaIndexes.ReadVertex(out Index: TIndex): boolean;
var
  I: Integer;
begin
  Index := EmptyIndex;

  for I := 0 to FInputsCount - 1 do
  begin
    if not Ints.GetNext then
    begin
      if I <> 0 then
        OnWarning(wtMajor, 'Collada', 'Indexes in <p> suddenly end, in the middle of a vertex');
      Exit(false);
    end;

    if I = FCoordIndexOffset then
      Index.Coord := Ints.Current else
    if I = FTexCoordIndexOffset then
      Index.TexCoord := Ints.Current else
    if I = FNormalIndexOffset then
      Index.Normal := Ints.Current;
  end;

  Result := true;
end;

function TColladaIndexes.ReadAddVertex(out Index: TIndex): boolean;
begin
  Result := ReadVertex(Index);
  if Result then
    AddVertex(Index);
end;

function TColladaIndexes.ReadAddVertex: boolean;
var
  IgnoreIndex: TIndex;
begin
  Result := ReadAddVertex(IgnoreIndex);
end;

procedure TColladaIndexes.AddVertex(const Index: TIndex);
begin
  if FGeometry is TIndexedFaceSetNode then
  begin
    TIndexedFaceSetNode(FGeometry).FdCoordIndex.Items.Add(Index.Coord);
    if FTexCoordIndexOffset <> -1 then
      TIndexedFaceSetNode(FGeometry).FdTexCoordIndex.Items.Add(Index.TexCoord);
    if FNormalIndexOffset <> -1 then
      TIndexedFaceSetNode(FGeometry).FdNormalIndex.Items.Add(Index.Normal);
  end else
  begin
    Assert(FGeometry is TIndexedLineSetNode);
    TIndexedLineSetNode(FGeometry).FdCoordIndex.Items.Add(Index.Coord);
  end;
end;

procedure TColladaIndexes.PolygonEnd;
begin
  AddVertex(EmptyIndex);
end;

{ LoadCollada ---------------------------------------------------------------- }

function LoadCollada(const URL: string;
  const AllowKambiExtensions: boolean): TX3DRootNode;
var
  BaseUrl: string;

  { List of Collada effects. Each contains an X3D Appearance node,
    with a name equal to Collada effect name. }
  Effects: TColladaEffectList;

  { List of Collada materials. Collada material is just a reference
    to Collada effect with a name.
    This way we handle instance_effect in <material> node.
    Many materials may refer to a single effect. }
  Materials: TColladaMaterialsMap;

  { List of Collada geometries. }
  Geometries: TColladaGeometryList;

  { List of Collada visual scenes, for <visual_scene> Collada elements.
    Every visual scene is X3D TAbstractX3DGroupingNode instance.
    This is for Collada >= 1.4.x (for Collada < 1.4.x,
    the <scene> element is directly placed as a rendered scene). }
  VisualScenes: TX3DNodeList;

  { List of Collada controllers. Read from library_controllers, used by
    instance_controller. }
  Controllers: TColladaControllerList;

  { List of Collada images (TAbstractTextureNode). NodeName of every instance
    comes from Collada "id" of <image> element (these are referred to
    by <init_from> contents from <surface>). }
  Images: TX3DNodeList;

  Cameras: TX3DNodeList;
  Lights: TX3DNodeList;

  ResultModel: TGroupNode absolute Result;

  Version14: boolean; //< Collada version >= 1.4.x

  { Read elements of type "common_color_or_texture_type" in Collada >= 1.4.x.
    If we have <color>, return this color (texture and coord names are then set to empty).
    If we have <texture>, return white color (and the appropriate texture
    and coord names; if texture name was empty, you want to treat it like not
    existing anyway). }
  function ReadColorOrTexture(Element: TDOMElement; out TextureName, TexCoordName: string): TVector3Single;
  var
    Child: TDOMElement;
  begin
    TextureName := '';
    TexCoordName := '';
    Result := White3Single;
    Child := DOMGetChildElement(Element, 'color', false);
    if Child <> nil then
    begin
      { I simply drop 4th color component, I don't know what's the use of this
        (alpha is exposed by effect/materials parameter transparency, so color
        alpha is supposed to mean something else ?). }
      Result := Vector3SingleCut(Vector4SingleFromStr(DOMGetTextData(Child)));
    end else
    begin
      Child := DOMGetChildElement(Element, 'texture', false);
      if Child <> nil then
      begin
        DOMGetAttribute(Child, 'texture', TextureName);
        DOMGetAttribute(Child, 'texcoord', TexCoordName);
      end;
    end;
  end;

  { Read elements of type "common_color_or_texture_type" in Collada >= 1.4.x,
    but allow only color specification. }
  function ReadColor(Element: TDOMElement): TVector3Single;
  var
    IgnoreTextureName, IgnoreTexCoordName: string;
  begin
    Result := ReadColorOrTexture(Element, IgnoreTextureName, IgnoreTexCoordName);
  end;

  { Read elements of type "common_float_or_param_type" in Collada >= 1.4.x. }
  function ReadFloatOrParam(Element: TDOMElement): Float;
  var
    FloatElement: TDOMElement;
  begin
    FloatElement := DOMGetChildElement(Element, 'float', false);
    if FloatElement <> nil then
    begin
      Result := StrToFloat(DOMGetTextData(FloatElement));
    end else
      { We don't support anything else than <float> here, just use
        default 1 eventually. }
      Result := 1.0;
  end;

  { Read the contents of the text data inside single child ChildTagName.
    Useful to handle things like <init_from> and <source> elements in Collada.
    Returns empty string if ChildTagName not present (or present present more
    than once) in Element. }
  function ReadChildText(Element: TDOMElement; const ChildTagName: string): string;
  var
    Child: TDOMElement;
  begin
    Child := DOMGetChildElement(Element, ChildTagName, false);
    if Child <> nil then
      Result := DOMGetTextData(Child) else
      Result := '';
  end;

  { Read the contents of the text data inside single child ChildTagName,
    interpret them as Float.

    Returns false when such child not found (or occurs more than once),
    or when text cannot be converted to float.
    In this case, Value is guaranteed not to be modified. }
  function ReadChildFloat(Element: TDOMElement; const ChildTagName: string;
    var Value: Float): boolean;
  var
    Child: TDOMElement;
  begin
    Child := DOMGetChildElement(Element, ChildTagName, false);
    Result := Child <> nil;
    if Result then
    try
      Value := StrToFloat(DOMGetTextData(Child));
    except on EConvertError do Result := false; end;
  end;

  function ReadChildFloat(Element: TDOMElement; const ChildTagName: string;
    var Value: Single): boolean;
  var
    ValueFloat: Float;
  begin
    ValueFloat := 0; { avoid uninitialized warnings }
    Result := ReadChildFloat(Element, ChildTagName, ValueFloat);
    if Result then
      Value := ValueFloat;
  end;

  { Read the contents of the text data inside single child ChildTagName,
    interpret them as TVector3Single.

    Returns false when such child not found (or occurs more than once),
    or when cannot be converted to float.
    In this case, Value is guaranteed not to be modified. }
  function ReadChildVector(Element: TDOMElement; const ChildTagName: string;
    var Value: TVector3Single): boolean;
  var
    Child: TDOMElement;
  begin
    Child := DOMGetChildElement(Element, ChildTagName, false);
    Result := Child <> nil;
    if Result then
    try
      Value := Vector3SingleFromStr(DOMGetTextData(Child));
    except on EConvertError do Result := false; end;
  end;

  { Read <effect>. Only for Collada >= 1.4.x.
    Adds effect to the Effects list. }
  procedure ReadEffect(EffectElement: TDOMElement);
  var
    { Effect instance and nodes, available to local procedures inside ReadEffect. }
    Effect: TColladaEffect;
    Appearance: TAppearanceNode;
    Mat: TMaterialNode;

    { Map of <surface> names to images (references from Images list) }
    Surfaces: TStringTextureNodeMap;
    { Map of <sampler2D> names to images (references from Images list) }
    Samplers2D: TStringTextureNodeMap;

    procedure ReadTechnique(TechniqueElement: TDOMElement);
    var
      Image: TAbstractTextureNode;
      TechniqueChild: TDOMElement;
      I: TXMLElementIterator;
      DiffuseTextureName, DiffuseTexCoordName: string;
      Transparency: Single;
      HasTransparency: boolean;
    begin
      { We actually treat <phong> and <blinn> and even <lambert> elements the same.
        X3D lighting equations specify that always Blinn
        (half-vector) technique is used. What's much more practically
        important, OpenGL uses Blinn method. So actually I always do
        blinn method (at least for real-time rendering). }
      TechniqueChild := DOMGetChildElement(TechniqueElement, 'phong', false);
      if TechniqueChild = nil then
        TechniqueChild := DOMGetChildElement(TechniqueElement, 'blinn', false);
      if TechniqueChild = nil then
        TechniqueChild := DOMGetChildElement(TechniqueElement, 'lambert', false);

      if TechniqueChild <> nil then
      begin
        { <transparent> (color) and <transparency> (float) should
          be multiplied with each other. So says the Collada spec
          ("Determining Transparency (Opacity)" in Chapter 7,
          and forum https://collada.org/public_forum/viewtopic.php?t=386).
          When only one is specified, the other is like 1.
          However, when neither one is specified, we obviously want to leave
          the model opaque (transparency = 0) so we need boolean HasTransparency. }
        Transparency := 1;
        HasTransparency := false;

        I := TXMLElementIterator.Create(TechniqueChild);
        try
          while I.GetNext do
          begin
            if I.Current.TagName = 'emission' then
              Mat.FdEmissiveColor.Value :=  ReadColor(I.Current) else
            if I.Current.TagName = 'ambient' then
              Mat.FdAmbientIntensity.Value := VectorAverage(ReadColor(I.Current)) else
            if I.Current.TagName = 'diffuse' then
            begin
              Mat.FdDiffuseColor.Value := ReadColorOrTexture(I.Current,
                DiffuseTextureName, DiffuseTexCoordName);
              if DiffuseTextureName <> '' then
              begin
                Image := Samplers2D.Find(DiffuseTextureName);
                if Image <> nil then
                begin
                  Effect.DiffuseTexCoordName := DiffuseTexCoordName;
                  Appearance.FdTexture.Value := Image;
                end else
                begin
                  Image := Images.FindName(DiffuseTextureName) as TAbstractTextureNode;
                  if Image <> nil then
                  begin
                    Effect.DiffuseTexCoordName := DiffuseTexCoordName;
                    Appearance.FdTexture.Value := Image;
                    { Happens e.g. on "Private Section/Faerie_Forrest_DAY/Faerie_Forrest_DAY.dae"
                      from collada.org/owl models. }
                    OnWarning(wtMajor, 'Collada', Format('<diffuse> texture refers to missing sampler2D name "%s". Found <image> with the same id, will use it',
                      [DiffuseTextureName]));
                  end else
                    OnWarning(wtMajor, 'Collada', Format('<diffuse> texture refers to missing sampler2D name "%s"',
                      [DiffuseTextureName]));
                end;
              end;
            end else
            if I.Current.TagName = 'specular' then
              Mat.FdSpecularColor.Value := ReadColor(I.Current) else
            if I.Current.TagName = 'shininess' then
              Mat.FdShininess.Value := ReadFloatOrParam(I.Current) / 128.0 else
            if I.Current.TagName = 'reflective' then
              {Mat.FdMirrorColor.Value := } ReadColor(I.Current) else
            if I.Current.TagName = 'reflectivity' then
            begin
              if AllowKambiExtensions then
                Mat.FdMirror.Value := ReadFloatOrParam(I.Current) else
                ReadFloatOrParam(I.Current);
            end else
            if I.Current.TagName = 'transparent' then
            begin
              Transparency *= VectorAverage(ReadColor(I.Current));
              HasTransparency := true;
            end else
            if I.Current.TagName = 'transparency' then
            begin
              Transparency *= ReadFloatOrParam(I.Current);
              HasTransparency := true;
            end else
            if I.Current.TagName = 'index_of_refraction' then
              {Mat.FdIndexOfRefraction.Value := } ReadFloatOrParam(I.Current);
          end;
        finally FreeAndNil(I) end;

        if HasTransparency then
          Mat.FdTransparency.Value := Transparency;
      end;
    end;

    { Read <newparam>. }
    procedure ReadNewParam(Element: TDOMElement);
    var
      Child: TDOMElement;
      Name, RefersTo: string;
      Image: TAbstractTextureNode;
    begin
      if DOMGetAttribute(Element, 'sid', Name) then
      begin
        Child := DOMGetChildElement(Element, 'surface', false);
        if Child <> nil then
        begin
          { Read <surface>. It has <init_from>, referring to name on Images. }
          RefersTo := ReadChildText(Child, 'init_from');
          Image := Images.FindName(RefersTo) as TAbstractTextureNode;
          if Image <> nil then
            Surfaces[Name] := Image else
            OnWarning(wtMajor, 'Collada', Format('<surface> refers to missing image name "%s"',
              [RefersTo]));
        end else
        begin
          Child := DOMGetChildElement(Element, 'sampler2D', false);
          if Child <> nil then
          begin
            { Read <sampler2D>. It has <source>, referring to name on Surfaces. }
            RefersTo := ReadChildText(Child, 'source');
            Image := Surfaces.Find(RefersTo);
            if Image <> nil then
              Samplers2D[Name] := Image else
              OnWarning(wtMajor, 'Collada', Format('<sampler2D> refers to missing surface name "%s"',
                [RefersTo]));
          end; { else not handled <newparam> }
        end;
      end;
    end;

  var
    Id: string;
    I: TXMLElementIterator;
    ProfileElement: TDOMElement;
  begin
    if not DOMGetAttribute(EffectElement, 'id', Id) then
      Id := '';

    Effect := TColladaEffect.Create;
    Effects.Add(Effect);

    Appearance := TAppearanceNode.Create(Id, BaseUrl);
    Effect.Appearance := Appearance;

    Mat := TMaterialNode.Create('', BaseUrl);
    Appearance.FdMaterial.Value := Mat;

    ProfileElement := DOMGetChildElement(EffectElement, 'profile_COMMON', false);
    if ProfileElement <> nil then
    begin
      Surfaces := TStringTextureNodeMap.Create;
      Samplers2D := TStringTextureNodeMap.Create;
      try
        I := TXMLElementIterator.Create(ProfileElement);
        try
          while I.GetNext do
            if I.Current.TagName = 'technique' then
              { Actually only one <technique> within <profile_COMMON> is allowed.
                But, since we loop anyway, it's not a problem to handle many. }
              ReadTechnique(I.Current) else
            if I.Current.TagName = 'newparam' then
              ReadNewParam(I.Current);
        finally FreeAndNil(I) end;
      finally
        FreeAndNil(Surfaces);
        FreeAndNil(Samplers2D);
      end;
    end;
  end;

  { Read <library_effects>. Only for Collada >= 1.4.x.
    All effects are added to the Effects list. }
  procedure ReadLibraryEffects(LibraryElement: TDOMElement);
  var
    I: TXMLElementFilteringIterator;
  begin
    I := TXMLElementFilteringIterator.Create(LibraryElement, 'effect');
    try
      while I.GetNext do
        ReadEffect(I.Current);
        { other I.Current.TagName not supported for now }
    finally FreeAndNil(I) end;
  end;

  { Read <material>. It is added to the Materials list. }
  procedure ReadMaterial(MatElement: TDOMElement);

    function ReadParamAsVector3(Element: TDOMElement): TVector3Single;
    var
      AType: string;
    begin
      if not DOMGetAttribute(Element, 'type', AType) then
      begin
        OnWarning(wtMinor, 'Collada', '<param> has no type attribute');
        Result := ZeroVector3Single;
      end else
      if AType <> 'float3' then
      begin
        OnWarning(wtMinor, 'Collada', 'Expected <param> with type "float3"');
        Result := ZeroVector3Single;
      end else
        Result := Vector3SingleFromStr(DOMGetTextData(Element));
    end;

    function ReadParamAsFloat(Element: TDOMElement): Float;
    var
      AType: string;
    begin
      if not DOMGetAttribute(Element, 'type', AType) then
      begin
        OnWarning(wtMinor, 'Collada', '<param> has no type attribute');
        Result := 0;
      end else
      if AType <> 'float' then
      begin
        OnWarning(wtMinor, 'Collada', 'Expected <param> with type "float"');
        Result := 0;
      end else
        Result := StrToFloat(DOMGetTextData(Element));
    end;

  var
    MatId: string;

    { For Collada < 1.4.x }
    procedure TryCollada13;
    var
      ShaderElement, TechniqueElement, PassElement, ProgramElement: TDOMElement;
      ParamName: string;
      I: TXMLElementFilteringIterator;
      Effect: TColladaEffect;
      Appearance: TAppearanceNode;
      Mat: TMaterialNode;
    begin
      Effect := TColladaEffect.Create;
      Effects.Add(Effect);

      Appearance := TAppearanceNode.Create(MatId, BaseUrl);
      Effect.Appearance := Appearance;

      Mat := TMaterialNode.Create('', BaseUrl);
      Appearance.FdMaterial.Value := Mat;

      { Collada 1.3 doesn't really have a concept of effects used by materials.
        But to be consistent, we add one effect (to Effects list)
        and one reference to it (to Materials list). }
      Materials[MatId] := Effect;

      ShaderElement := DOMGetChildElement(MatElement, 'shader', false);
      if ShaderElement <> nil then
      begin
         TechniqueElement := DOMGetChildElement(ShaderElement, 'technique', false);
         if TechniqueElement <> nil then
         begin
           PassElement := DOMGetChildElement(TechniqueElement, 'pass', false);
           if PassElement <> nil then
           begin
             ProgramElement := DOMGetChildElement(PassElement, 'program', false);
             if ProgramElement <> nil then
             begin
               I := TXMLElementFilteringIterator.Create(ProgramElement, 'param');
               try
                 while I.GetNext do
                   if DOMGetAttribute(I.Current, 'name', ParamName) then
                   begin
                     if ParamName = 'EMISSION' then
                       Mat.FdEmissiveColor.Value := ReadParamAsVector3(I.Current) else
                     if ParamName = 'AMBIENT' then
                       Mat.FdAmbientIntensity.Value := VectorAverage(ReadParamAsVector3(I.Current)) else
                     if ParamName = 'DIFFUSE' then
                       Mat.FdDiffuseColor.Value := ReadParamAsVector3(I.Current) else
                     if ParamName = 'SPECULAR' then
                       Mat.FdSpecularColor.Value := ReadParamAsVector3(I.Current) else
                     if ParamName = 'SHININESS' then
                       Mat.FdShininess.Value := ReadParamAsFloat(I.Current) / 128.0 else
                     if ParamName = 'REFLECTIVE' then
                       {Mat.FdMirrorColor.Value := } ReadParamAsVector3(I.Current) else
                     if ParamName = 'REFLECTIVITY' then
                     begin
                       if AllowKambiExtensions then
                         Mat.FdMirror.Value := ReadParamAsFloat(I.Current) else
                         ReadParamAsFloat(I.Current);
                     end else
                     (*
                     Blender Collada 1.3.1 exporter bug: it sets
                     type of TRANSPARENT param as "float".
                     Although content inicates "float3",
                     like Collada 1.3.1 spec requires (page 129),
                     and consistently with what is in Collada 1.4.1 spec.

                     I don't handle this anyway, so I just ignore it for now.
                     Should be reported to Blender.

                     if ParamName = 'TRANSPARENT' then
                       {Mat.FdTransparencyColor.Value := } ReadParamAsVector3(I.Current) else
                     *)
                     if ParamName = 'TRANSPARENCY' then
                       Mat.FdTransparency.Value := ReadParamAsFloat(I.Current);
                     { other ParamName not handled }
                   end;
               finally FreeAndNil(I) end;
             end;
           end;
         end;
      end;
    end;

    { For Collada >= 1.4.x }
    procedure TryCollada14;
    var
      InstanceEffect: TDOMElement;
      EffectId: string;
      Effect: TColladaEffect;
    begin
      if MatId = '' then Exit;

      InstanceEffect := DOMGetChildElement(MatElement, 'instance_effect', false);
      if InstanceEffect <> nil then
      begin
        if DOMGetAttribute(InstanceEffect, 'url', EffectId) and
           SCharIs(EffectId, 1, '#') then
        begin
          Delete(EffectId, 1, 1); { delete initial '#' char }
          Effect := Effects.Find(EffectId);
          if Effect <> nil then
            Materials[MatId] := Effect else
            OnWarning(wtMinor, 'Collada', Format('Material "%s" references ' +
              'non-existing effect "%s"', [MatId, EffectId]));
        end;
      end;
    end;

  begin
    if not DOMGetAttribute(MatElement, 'id', MatId) then
      MatId := '';

    if Version14 then
      TryCollada14 else
      TryCollada13;
  end;

  { Read <library_materials> (Collada >= 1.4.x) or
    <library type="MATERIAL"> (Collada < 1.4.x). }
  procedure ReadLibraryMaterials(LibraryElement: TDOMElement);
  var
    I: TXMLElementFilteringIterator;
  begin
    I := TXMLElementFilteringIterator.Create(LibraryElement, 'material');
    try
      while I.GetNext do
        ReadMaterial(I.Current);
        { other I.Current.TagName not supported for now }
    finally FreeAndNil(I) end;
  end;

  { Read <geometry>. It is added to the Geometries list. }
  procedure ReadGeometry(GeometryElement: TDOMElement);
  var
    { Collada Geometry constructed, available to all Read* primitives local procedures. }
    Geometry: TColladaGeometry;

    Sources: TColladaSourceList;

    { Read "double sided" geometry property.

      There is no standard for this it seems, only some special MAYA markers:
      <extra><technique profile="MAYA"><double_sided>1</double_sided></technique></extra>
      Blender Collada 1.4 exporter, as well as various models from collada.org/owl
      use this, so it seems like a standard in practice. }
    function ReadDoubleSided(GeometryE: TDOMElement): boolean;
    var
      Child: TDOMElement;
      Profile: string;
    begin
      Result := false;

      Child := DOMGetChildElement(GeometryE, 'extra', false);
      if Child = nil then Exit;

      Child := DOMGetChildElement(Child, 'technique', false);
      if Child = nil then Exit;

      if not (DOMGetAttribute(Child, 'profile', Profile) and
              (Profile = 'MAYA')) then
        Exit;

      Child := DOMGetChildElement(Child, 'double_sided', false);
      if Child = nil then Exit;

      Result := StrToIntDef(DOMGetTextData(Child), 0) <> 0;
    end;

    { Read <source> within <mesh>. }
    procedure ReadSource(SourceElement: TDOMElement);
    var
      FloatArray, Technique, Accessor: TDOMElement;
      SeekPos, FloatArrayCount, I: Integer;
      FloatArrayContents, Token, AccessorSource, ParamName, ParamType, FloatArrayId: string;
      Source: TColladaSource;
      It: TXMLElementFilteringIterator;
    begin
      Source := TColladaSource.Create;
      Sources.Add(Source);

      if not DOMGetAttribute(SourceElement, 'id', Source.Name) then
        Source.Name := '';

      FloatArray := DOMGetChildElement(SourceElement, 'float_array', false);
      if FloatArray <> nil then
      begin
        if not DOMGetIntegerAttribute(FloatArray, 'count', FloatArrayCount) then
        begin
          FloatArrayCount := 0;
          OnWarning(wtMinor, 'Collada', '<float_array> without a count attribute');
        end;

        if not DOMGetAttribute(FloatArray, 'id', FloatArrayId) then
          FloatArrayId := '';

        Source.Floats.Count := FloatArrayCount;
        FloatArrayContents := DOMGetTextData(FloatArray);

        SeekPos := 1;
        for I := 0 to FloatArrayCount - 1 do
        begin
          Token := NextToken(FloatArrayContents, SeekPos);
          if Token = '' then
          begin
            OnWarning(wtMinor, 'Collada', 'Actual number of tokens in <float_array>' +
              ' less than declated in the count attribute');
            Break;
          end;
          Source.Floats.L[I] := StrToFloat(Token);
        end;

        Technique := DOMGetChildElement(SourceElement, 'technique_common', false);
        if Technique = nil then
        begin
          Technique := DOMGetChildElement(SourceElement, 'technique', false);
          { TODO: actually, I should search for technique with profile="COMMON"
            in this case, right ? }
        end;

        if Technique <> nil then
        begin
          Accessor := DOMGetChildElement(Technique, 'accessor', false);

          { read <accessor> attributes }

          if not DOMGetIntegerAttribute(Accessor, 'count', Source.Count) then
          begin
            OnWarning(wtMinor, 'Collada', '<accessor> has no count attribute');
            Source.Count := 0;
          end;

          if not DOMGetIntegerAttribute(Accessor, 'stride', Source.Stride) then
            { default, according to Collada spec }
            Source.Stride := 1;

          if not DOMGetIntegerAttribute(Accessor, 'offset', Source.Offset) then
            { default, according to Collada spec }
            Source.Offset := 0;

          if not DOMGetAttribute(Accessor, 'source', AccessorSource) then
          begin
            OnWarning(wtMinor, 'Collada', '<accessor> has no source attribute');
            AccessorSource := '';
          end;

          { We read AccessorSource only to check here }
          if AccessorSource <> '#' + FloatArrayId then
            OnWarning(wtMajor, 'Collada', '<accessor> source does not refer to <float_array> in the same <source>, this is not supported');

          It := TXMLElementFilteringIterator.Create(Accessor, 'param');
          try
            while It.GetNext do
            begin
              if not DOMGetAttribute(It.Current, 'name', ParamName) then
              begin
                OnWarning(wtMajor, 'Collada', 'Missing "name" of <param>');
                { TODO: this should not be required? }
                Continue;
              end;

              if not DOMGetAttribute(It.Current, 'type', ParamType) then
              begin
                OnWarning(wtMajor, 'Collada', 'Missing "type" of <param>');
                Continue;
              end;

              if ParamType <> 'float' then
              begin
                OnWarning(wtMajor, 'Collada', Format('<param> type "%s" is not supported',
                  [ParamType]));
                Continue;
              end;

              Source.Params.Add(ParamName);
            end;
          finally FreeAndNil(It) end;
        end;
      end;
    end;

  var
    { We take care to share coordinates, tex coordinates and normal vectors,
      so that they are stored efficiently in memory and can be saved using
      X3D DEF/USE mechanism. Coordinates are always shared by all primitives
      within the geometry. Each primitive may potentially have different tex coords
      or normals arrays, or they may share the same. }

    { Collada coordinates.
      Based on <source> indicated by last <vertices> element. }
    Coord: TCoordinateNode;
    { Assigning to Coord using AssignToVectorXYZ went without trouble. }
    CoordCorrect: boolean;

    { Collada texture coords used by last primitive.
      Based on <source> indicated by <input semantic="TEXCOORD"> element within
      primitive. NodeName corresponds to <source> id. }
    LastTexCoord: TTextureCoordinateNode;

    { Collada normal used by last primitive.
      Based on <source> indicated by <input semantic="NORMAL"> element within
      primitive. NodeName corresponds to <source> id. }
    LastNormal: TNormalNode;

    { DoubleSided, should be used by ReadPrimitiveCommon to set X3D solid field. }
    DoubleSided: boolean;

    { Read <vertices> within <mesh> }
    procedure ReadVertices(VerticesElement: TDOMElement);
    var
      I: TXMLElementFilteringIterator;
      InputSemantic, InputSourceName, Id: string;
      InputSource: TColladaSource;
    begin
      if Coord <> nil then
      begin
        OnWarning(wtMajor, 'Collada', '<vertices> specified multiple times within a geometry');
        FreeIfUnusedAndNil(Coord);
      end;

      if not DOMGetAttribute(VerticesElement, 'id', Id) then
        Id := '';

      Coord := TCoordinateNode.Create(Id, BaseUrl);
      CoordCorrect := true;

      I := TXMLElementFilteringIterator.Create(VerticesElement, 'input');
      try
        while I.GetNext do
          if DOMGetAttribute(I.Current, 'semantic', InputSemantic) and
             (InputSemantic = 'POSITION') and
             DOMGetAttribute(I.Current, 'source', InputSourceName) and
             SCharIs(InputSourceName, 1, '#') then
          begin
            Delete(InputSourceName, 1, 1); { delete leading '#' char }
            InputSource := Sources.Find(InputSourceName);
            if InputSource <> nil then
            begin
              CoordCorrect := InputSource.AssignToVectorXYZ(Coord.FdPoint.Items);
              Exit;
            end else
            begin
              OnWarning(wtMinor, 'Collada', Format('Source attribute ' +
                '(of <input> element within <vertices>) ' +
                'references non-existing source "%s"', [InputSourceName]));
            end;
          end;
      finally FreeAndNil(I) end;

      OnWarning(wtMinor, 'Collada', '<vertices> element has no <input> child' +
        ' with semantic="POSITION" and some source attribute');
    end;

    { Read common things of primitive (<poly*>, <tri*>, <lines*>) within <mesh>.
      - Creates X3D geometry node, initializes it's coordinates
        and other fiels (but leaves *Index fields empty).
      - Adds it to Geometry.Primitives.
      - Returns Indexes instance, to parse indexes of this primitive. }
    function ReadPrimitiveCommon(PrimitiveE: TDOMElement): TColladaIndexes;
    var
      I: TXMLElementFilteringIterator;
      InputSemantic, InputSourceId, X3DGeometryName: string;
      Primitive: TColladaPrimitive;
      InputSource: TColladaSource;
      IndexedFaceSet: TIndexedFaceSetNode;
      IndexedLineSet: TIndexedLineSetNode;
      InputsCount, CoordIndexOffset, TexCoordIndexOffset, NormalIndexOffset: Integer;
    begin
      CoordIndexOffset := 0;
      TexCoordIndexOffset := -1;
      NormalIndexOffset := -1;

      Primitive := TColladaPrimitive.Create;
      Geometry.Primitives.Add(Primitive);

      IndexedFaceSet := nil;
      IndexedLineSet := nil;

      X3DGeometryName := Format('%s_collada_primitive_%d',
        { There may be multiple primitives inside a single Collada <geometry> node,
          so use Geometry.Primitives.Count to name them uniquely for X3D. }
        [Geometry.Name, Geometry.Primitives.Count]);

      if (PrimitiveE.TagName = 'lines') or
         (PrimitiveE.TagName = 'linestrips') then
      begin
        IndexedLineSet := TIndexedLineSetNode.Create(X3DGeometryName, BaseUrl);
        IndexedLineSet.FdCoord.Value := Coord;
        Primitive.X3DGeometry := IndexedLineSet;
      end else
      begin
        IndexedFaceSet := TIndexedFaceSetNode.Create(X3DGeometryName, BaseUrl);
        IndexedFaceSet.FdSolid.Value := not DoubleSided;
        { For VRML >= 2.0, creaseAngle is 0 by default.
          TODO: what is the default normal generation for Collada? }
        IndexedFaceSet.FdCreaseAngle.Value := NiceCreaseAngle;
        IndexedFaceSet.FdCoord.Value := Coord;
        Primitive.X3DGeometry := IndexedFaceSet;
      end;

      if DOMGetAttribute(PrimitiveE, 'material', Primitive.Material) then
      begin
        { Collada 1.4.1 spec says that this is just material name.
          Collada 1.3.1 spec says that this is URL. }
        if (not Version14) and SCharIs(Primitive.Material, 1, '#') then
          Delete(Primitive.Material, 1, 1);
      end; { else leave Primitive.Material as '' }

      InputsCount := 0;

      I := TXMLElementFilteringIterator.Create(PrimitiveE, 'input');
      try
        while I.GetNext do
        begin
          { we must count all inputs, since parsing <p> elements depends
            on InputsCount }
          Inc(InputsCount);
          if DOMGetAttribute(I.Current, 'semantic', InputSemantic) then
          begin
            if InputSemantic = 'VERTEX' then
            begin
              if not (DOMGetAttribute(I.Current, 'source', InputSourceId) and
                      (Coord <> nil) and
                      (InputSourceId = '#' + Coord.NodeName))  then
                OnWarning(wtMinor, 'Collada', '<input> with semantic="VERTEX" (of primitive element within <mesh>) does not reference <vertices> element within the same <mesh>');

              { Collada requires offset in this case.
                For us, if there's no offset, just leave CoordIndexOffset default. }
              DOMGetIntegerAttribute(I.Current, 'offset', CoordIndexOffset);
            end else
            if InputSemantic = 'TEXCOORD' then
            begin
              DOMGetIntegerAttribute(I.Current, 'offset', TexCoordIndexOffset);

              { Only for IndexedFaceSet.
                In case of trouble with coordinates, don't use texCoord,
                they may be invalid (this is for invalid Blender 1.3 exporter) }
              if (IndexedFaceSet = nil) or (not CoordCorrect) then Continue;

              if DOMGetAttribute(I.Current, 'source', InputSourceId) then
              begin
                if SCharIs(InputSourceId, 1, '#') then
                  Delete(InputSourceId, 1, 1);
                if ((LastTexCoord <> nil) and
                    (LastTexCoord.NodeName = InputSourceId)) then
                  { we can reuse last X3D tex coord node }
                  IndexedFaceSet.FdTexCoord.Value := LastTexCoord else
                begin
                  InputSource := Sources.Find(InputSourceId);
                  if InputSource <> nil then
                  begin
                    { create and use new X3D tex coord node }
                    FreeIfUnusedAndNil(LastTexCoord);
                    LastTexCoord := TTextureCoordinateNode.Create(InputSourceId, BaseUrl);
                    InputSource.AssignToVectorST(LastTexCoord.FdPoint.Items);
                    IndexedFaceSet.FdTexCoord.Value := LastTexCoord;
                  end else
                    OnWarning(wtMinor, 'Collada', Format('<source> with id "%s" for texture coordinates not found',
                      [InputSourceId]));
                end;
              end else
                OnWarning(wtMinor, 'Collada', 'Missing source for <input> with semantic="TEXCOORD". We have texture coord indexes, but they will be ignored, since we have no actual texture coords');
            end else
            if InputSemantic = 'NORMAL' then
            begin
              DOMGetIntegerAttribute(I.Current, 'offset', NormalIndexOffset);

              { Only for IndexedFaceSet.
                In case of trouble with coordinates, don't use normals,
                they may be invalid (this is for invalid Blender 1.3 exporter) }
              if (IndexedFaceSet = nil) or (not CoordCorrect) then Continue;

              if DOMGetAttribute(I.Current, 'source', InputSourceId) then
              begin
                if SCharIs(InputSourceId, 1, '#') then
                  Delete(InputSourceId, 1, 1);
                if ((LastNormal <> nil) and
                    (LastNormal.NodeName = InputSourceId)) then
                  { we can reuse last X3D normal node }
                  IndexedFaceSet.FdNormal.Value := LastNormal else
                begin
                  InputSource := Sources.Find(InputSourceId);
                  if InputSource <> nil then
                  begin
                    { create and use new X3D normal node }
                    FreeIfUnusedAndNil(LastNormal);
                    LastNormal := TNormalNode.Create(InputSourceId, BaseUrl);
                    InputSource.AssignToVectorXYZ(LastNormal.FdVector.Items);
                    IndexedFaceSet.FdNormal.Value := LastNormal;
                  end else
                    OnWarning(wtMinor, 'Collada', Format('<source> with id "%s" for normals not found',
                      [InputSourceId]));
                end;
              end else
                OnWarning(wtMinor, 'Collada', 'Missing source for <input> with semantic="NORMAL". We have normal indexes, but they will be ignored, since we have no actual normals');
            end;
          end;
        end;
      finally FreeAndNil(I) end;

      Result := TColladaIndexes.Create(Primitive.X3DGeometry,
        InputsCount, CoordIndexOffset, TexCoordIndexOffset, NormalIndexOffset);
    end;

    { Read <polygons> within <mesh> }
    procedure ReadPolygons(PrimitiveE: TDOMElement);
    var
      I: TXMLElementFilteringIterator;
      Indexes: TColladaIndexes;
    begin
      Indexes := ReadPrimitiveCommon(PrimitiveE);
      try
        I := TXMLElementFilteringIterator.Create(PrimitiveE, 'p');
        try
          while I.GetNext do
          begin
            Indexes.BeginElement(I.Current);
            while Indexes.ReadAddVertex do ;
            Indexes.PolygonEnd;
          end;
        finally FreeAndNil(I) end;
      finally FreeAndNil(Indexes) end;
    end;

    { Read <polylist> within <mesh> }
    procedure ReadPolylist(PrimitiveE: TDOMElement);
    var
      VCountE, P: TDOMElement;
      I: Integer;
      Indexes: TColladaIndexes;
      VCount: TIntegersParser;
    begin
      Indexes := ReadPrimitiveCommon(PrimitiveE);
      try
        VCountE := DOMGetChildElement(PrimitiveE, 'vcount', false);
        P := DOMGetChildElement(PrimitiveE, 'p', false);

        if (VCountE <> nil) and (P <> nil) then
        begin
          Indexes.BeginElement(P);
          VCount := TIntegersParser.Create(VCountE);
          try
            { we will parse both VCount and Indexes now, at the same time }
            while VCount.GetNext do
            begin
              for I := 0 to VCount.Current - 1 do
                if not Indexes.ReadAddVertex then
                begin
                  OnWarning(wtMinor, 'Collada', 'Unexpected end of <p> data in <polylist>');
                  Exit;
                end;
              Indexes.PolygonEnd;
            end;
          finally FreeAndNil(VCount) end;
        end;
      finally FreeAndNil(Indexes) end;
    end;

    { Read <triangles> within <mesh> }
    procedure ReadTriangles(PrimitiveE: TDOMElement);
    var
      P: TDOMElement;
      Indexes: TColladaIndexes;
    begin
      Indexes := ReadPrimitiveCommon(PrimitiveE);
      try
        P := DOMGetChildElement(PrimitiveE, 'p', false);
        if P <> nil then
        begin
          Indexes.BeginElement(P);
          repeat
            if not Indexes.ReadAddVertex then Break;
            if not Indexes.ReadAddVertex then Break;
            if not Indexes.ReadAddVertex then Break;
            Indexes.PolygonEnd;
          until false;
        end;
      finally FreeAndNil(Indexes) end;
    end;

    { Read <trifans> within <mesh> }
    procedure ReadTriFans(PrimitiveE: TDOMElement);
    var
      I: TXMLElementFilteringIterator;
      Indexes: TColladaIndexes;
      Vertex1, Vertex2, VertexPrevious, VertexNext: TIndex;
    begin
      Indexes := ReadPrimitiveCommon(PrimitiveE);
      try
        I := TXMLElementFilteringIterator.Create(PrimitiveE, 'p');
        try
          while I.GetNext do
          begin
            Indexes.BeginElement(I.Current);
            if Indexes.ReadVertex(Vertex1) and
               Indexes.ReadVertex(Vertex2) and
               Indexes.ReadVertex(VertexPrevious) then
            begin
              Indexes.AddVertex(Vertex1);
              Indexes.AddVertex(Vertex2);
              Indexes.AddVertex(VertexPrevious);
              Indexes.PolygonEnd;
              while Indexes.ReadVertex(VertexNext) do
              begin
                Indexes.AddVertex(Vertex1);
                Indexes.AddVertex(VertexPrevious);
                Indexes.AddVertex(VertexNext);
                Indexes.PolygonEnd;
                VertexPrevious := VertexNext;
              end;
            end;
          end;
        finally FreeAndNil(I) end;
      finally FreeAndNil(Indexes) end;
    end;

    { Read <tristrips> within <mesh> }
    procedure ReadTriStrips(PrimitiveE: TDOMElement);
    var
      I: TXMLElementFilteringIterator;
      Indexes: TColladaIndexes;
      Vertex1, Vertex2, Vertex3, VertexNext: TIndex;
      Turn: boolean;
    begin
      Indexes := ReadPrimitiveCommon(PrimitiveE);
      try
        I := TXMLElementFilteringIterator.Create(PrimitiveE, 'p');
        try
          while I.GetNext do
          begin
            Turn := true;
            Indexes.BeginElement(I.Current);
            if Indexes.ReadVertex(Vertex1) and
               Indexes.ReadVertex(Vertex2) and
               Indexes.ReadVertex(Vertex3) then
            begin
              Indexes.AddVertex(Vertex1);
              Indexes.AddVertex(Vertex2);
              Indexes.AddVertex(Vertex3);
              Indexes.PolygonEnd;
              while Indexes.ReadVertex(VertexNext) do
              begin
                Indexes.AddVertex(Vertex3);
                Indexes.AddVertex(Vertex2);
                Indexes.AddVertex(VertexNext);
                Indexes.PolygonEnd;
                if Turn then
                  Vertex2 := VertexNext else
                  Vertex3 := VertexNext;
                Turn := not Turn;
              end;
            end;
          end;
        finally FreeAndNil(I) end;
      finally FreeAndNil(Indexes) end;
    end;

    { Read <lines> within <mesh> }
    procedure ReadLines(PrimitiveE: TDOMElement);
    var
      P: TDOMElement;
      Indexes: TColladaIndexes;
    begin
      Indexes := ReadPrimitiveCommon(PrimitiveE);
      try
        P := DOMGetChildElement(PrimitiveE, 'p', false);
        if P <> nil then
        begin
          Indexes.BeginElement(P);
          repeat
            if not Indexes.ReadAddVertex then Break;
            if not Indexes.ReadAddVertex then Break;
            Indexes.PolygonEnd;
          until false;
        end;
      finally FreeAndNil(Indexes) end;
    end;

    { TODO: <linestrips> should work fine, but untested }
    { Read <linestrips> within <mesh> }
    procedure ReadLineStrips(PrimitiveE: TDOMElement);
    var
      I: TXMLElementFilteringIterator;
      Indexes: TColladaIndexes;
    begin
      Indexes := ReadPrimitiveCommon(PrimitiveE);
      try
        I := TXMLElementFilteringIterator.Create(PrimitiveE, 'p');
        try
          while I.GetNext do
          begin
            Indexes.BeginElement(I.Current);
            while Indexes.ReadAddVertex do ;
            Indexes.PolygonEnd;
          end;
        finally FreeAndNil(I) end;
      finally FreeAndNil(Indexes) end;
    end;

  var
    Mesh: TDOMElement;
    I: TXMLElementIterator;
    GeometryId: string;
  begin
    if not DOMGetAttribute(GeometryElement, 'id', GeometryId) then
      GeometryId := '';

    DoubleSided := ReadDoubleSided(GeometryElement);

    Geometry := TColladaGeometry.Create;
    Geometry.Name := GeometryId;
    Geometries.Add(Geometry);

    Mesh := DOMGetChildElement(GeometryElement, 'mesh', false);
    if Mesh <> nil then
    begin
      Coord := nil;
      LastTexCoord := nil;
      LastNormal := nil;
      Sources := TColladaSourceList.Create;
      try
        I := TXMLElementIterator.Create(Mesh);
        try
          while I.GetNext do
            if I.Current.TagName = 'source' then
              ReadSource(I.Current) else
            if I.Current.TagName = 'vertices' then
              ReadVertices(I.Current) else
            if I.Current.TagName = 'polygons' then
              ReadPolygons(I.Current) else
            if I.Current.TagName = 'polylist' then
              ReadPolylist(I.Current) else
            if I.Current.TagName = 'triangles' then
              ReadTriangles(I.Current) else
            if I.Current.TagName = 'trifans' then
              ReadTriFans(I.Current) else
            if I.Current.TagName = 'tristrips' then
              ReadTriStrips(I.Current) else
            if I.Current.TagName = 'lines' then
              ReadLines(I.Current) else
            if I.Current.TagName = 'linestrips' then
              ReadLineStrips(I.Current) else
              OnWarning(wtMajor, 'Collada', Format('Element "%s" within <mesh> not supported',
                [I.Current.TagName]));
        finally FreeAndNil(I) end;
      finally
        FreeAndNil(Sources);
        FreeIfUnusedAndNil(Coord);
        { actually LastTexCoord is for sure used by something,
          we don't really have to finalize it here }
        FreeIfUnusedAndNil(LastTexCoord);
      end;
    end;
  end;

  { Read <library_geometries> (Collada >= 1.4.x) or
    <library type="GEOMETRY"> (Collada < 1.4.x). }
  procedure ReadLibraryGeometries(LibraryElement: TDOMElement);
  var
    I: TXMLElementFilteringIterator;
  begin
    I := TXMLElementFilteringIterator.Create(LibraryElement, 'geometry');
    try
      while I.GetNext do
        ReadGeometry(I.Current);
        { other I.Current.TagName not supported for now }
    finally FreeAndNil(I) end;
  end;

  { Read <library> element.
    Only for Collada < 1.4.x (Collada >= 1.4.x has  <library_xxx> elements). }
  procedure ReadLibrary(LibraryElement: TDOMElement);
  var
    LibraryType: string;
  begin
    if DOMGetAttribute(LibraryElement, 'type', LibraryType) then
    begin
      if LibraryType = 'MATERIAL' then
        ReadLibraryMaterials(LibraryElement) else
      if LibraryType = 'GEOMETRY' then
        ReadLibraryGeometries(LibraryElement);
        { other LibraryType not supported for now }
    end;
  end;

  { Read <matrix> or <bind_shape_matrix> element to given Matrix. }
  function ReadMatrix(MatrixElement: TDOMElement): TMatrix4Single; overload;
  var
    SeekPos: Integer;
    Row, Col: Integer;
    Token, Content: string;
  begin
    Content := DOMGetTextData(MatrixElement);

    SeekPos := 1;

    for Row := 0 to 3 do
      for Col := 0 to 3 do
      begin
        Token := NextToken(Content, SeekPos);
        if Token = '' then
        begin
          OnWarning(wtMinor, 'Collada', 'Matrix (<matrix> or <bind_shape_matrix> ' +
            'element) has not enough items');
          Break;
        end;
        Result[Col, Row] := StrToFloat(Token);
      end;
  end;

  { Read <lookat> element, return appropriate matrix. }
  function ReadLookAt(MatrixElement: TDOMElement): TMatrix4Single;
  var
    SeekPos: Integer;
    Content: string;

    function ReadVector(out Vector: TVector3Single): boolean;
    var
      Token: string;
      I: Integer;
    begin
      Result := true;

      for I := 0 to 2 do
      begin
        Token := NextToken(Content, SeekPos);
        if Token = '' then
        begin
          OnWarning(wtMinor, 'Collada', 'Unexpected end of data of <lookat>');
          Exit(false);
        end;
        Vector[I] := StrToFloat(Token);
      end;
    end;

  var
    Eye, Center, Up: TVector3Single;
  begin
    Content := DOMGetTextData(MatrixElement);

    SeekPos := 1;

    if ReadVector(Eye) and
       ReadVector(Center) and
       ReadVector(Up) then
      Result := LookAtMatrix(Eye, Center, Up);
  end;

  { Read <node> element, add it to ParentGroup. }
  procedure ReadNodeElement(ParentGroup: TAbstractX3DGroupingNode;
    NodeElement: TDOMElement);

    { For Collada material id, return the X3D Appearance (or @nil if not found). }
    function MaterialToX3D(MaterialId: string;
      InstantiatingElement: TDOMElement): TAppearanceNode;
    var
      BindMaterial, Technique: TDOMElement;
      InstanceMaterialSymbol, InstanceMaterialTarget: string;
      I: TXMLElementFilteringIterator;
      Effect: TColladaEffect;
    begin
      if MaterialId = '' then Exit(nil);

      { For InstantiatingElement = instance_geometry (Collada 1.4.x), this
        must be present.
        For InstantiatingElement = instance (Collada 1.3.x), this must not
        be present.
        (But we actually don't check these conditions, just handle any case.) }
      BindMaterial := DOMGetChildElement(InstantiatingElement, 'bind_material', false);
      if BindMaterial <> nil then
      begin
        Technique := DOMGetChildElement(BindMaterial, 'technique_common', false);
        if Technique <> nil then
        begin
          { read <instance_material list inside.
            This may contain multiple materials, but actually we're only
            interested in a single material, so we look for material with
            symbol = MaterialId. }
          I := TXMLElementFilteringIterator.Create(Technique, 'instance_material');
          try
            while I.GetNext do
              if DOMGetAttribute(I.Current, 'symbol', InstanceMaterialSymbol) and
                 (InstanceMaterialSymbol = MaterialId) and
                 DOMGetAttribute(I.Current, 'target', InstanceMaterialTarget) then
              begin
                { this should be true, target is URL }
                if SCharIs(InstanceMaterialTarget, 1, '#') then
                  Delete(InstanceMaterialTarget, 1, 1);

                { replace MaterialId with what is indicated by
                    <instance_material target="..."> }
                MaterialId := InstanceMaterialTarget;
              end;
          finally FreeAndNil(I) end;
        end;
      end;

      Effect := Materials.Find(MaterialId);
      if Effect = nil then
      begin
        OnWarning(wtMinor, 'Collada', Format('Referencing non-existing material name "%s"',
          [MaterialId]));
        Result := nil;
      end else
      begin
        Result := Effect.Appearance;
      end;
    end;

    { Add Collada geometry instance (many X3D Shape nodes) to given X3D Group. }
    procedure AddGeometryInstance(Group: TAbstractX3DGroupingNode;
      Geometry: TColladaGeometry; InstantiatingElement: TDOMElement);
    var
      Shape: TShapeNode;
      I: Integer;
      Primitive: TColladaPrimitive;
    begin
      for I := 0 to Geometry.Primitives.Count - 1 do
      begin
        Primitive := Geometry.Primitives[I];
        Shape := TShapeNode.Create('', BaseUrl);
        Group.FdChildren.Add(Shape);
        Shape.FdGeometry.Value := Primitive.X3DGeometry;
        Shape.Appearance := MaterialToX3D(Primitive.Material, InstantiatingElement);
      end;
    end;

    { Read <instance_geometry>, adding resulting X3D nodes into
      ParentGroup. Actually, this is also for reading <instance> in Collada 1.3.1. }
    procedure ReadInstanceGeometry(ParentGroup: TAbstractX3DGroupingNode;
      InstantiatingElement: TDOMElement);
    var
      GeometryId: string;
      Geometry: TColladaGeometry;
    begin
      if DOMGetAttribute(InstantiatingElement, 'url', GeometryId) and
         SCharIs(GeometryId, 1, '#') then
      begin
        Delete(GeometryId, 1, 1);
        Geometry := Geometries.Find(GeometryId);
        if Geometry = nil then
          OnWarning(wtMinor, 'Collada', Format('<node> instantiates non-existing <geometry> element "%s"',
            [GeometryId])) else
          AddGeometryInstance(ParentGroup, Geometry, InstantiatingElement);
      end else
        OnWarning(wtMajor, 'Collada', Format('Element <%s> missing url attribute (that has to start with #)',
          [InstantiatingElement.TagName]));
    end;

    { Read <instance_*>, adding resulting X3D nodes into ParentGroup. }
    procedure ReadInstance(ParentGroup: TAbstractX3DGroupingNode;
      InstantiatingElement: TDOMElement; List: TX3DNodeList);
    var
      Id: string;
      Node: TX3DNode;
    begin
      if DOMGetAttribute(InstantiatingElement, 'url', Id) and
         SCharIs(Id, 1, '#') then
      begin
        Delete(Id, 1, 1);
        Node := List.FindName(Id);
        if Node = nil then
          OnWarning(wtMinor, 'Collada', Format('<node> instantiates non-existing element "%s"',
            [Id])) else
          ParentGroup.FdChildren.Add(Node);
      end else
        OnWarning(wtMajor, 'Collada', Format('Element <%s> missing url attribute (that has to start with #)',
          [InstantiatingElement.TagName]));
    end;

    { Read <instance_controller>, adding resulting X3D node into
      ParentGroup. }
    procedure ReadInstanceController(ParentGroup: TAbstractX3DGroupingNode;
      InstantiatingElement: TDOMElement);
    var
      ControllerId: string;
      Controller: TColladaController;
      Group: TAbstractX3DGroupingNode;
      Geometry: TColladaGeometry;
    begin
      if DOMGetAttribute(InstantiatingElement, 'url', ControllerId) and
         SCharIs(ControllerId, 1, '#') then
      begin
        Delete(ControllerId, 1, 1);
        Controller := Controllers.Find(ControllerId);
        if Controller = nil then
        begin
          OnWarning(wtMinor, 'Collada', Format('<node> instantiates non-existing ' +
            '<controller> element "%s"', [ControllerId]));
        end else
        begin
          Geometry := Geometries.Find(Controller.Source);
          if Geometry = nil then
          begin
            OnWarning(wtMinor, 'Collada', Format('<controller> references non-existing ' +
              '<geometry> element "%s"', [Controller.Source]));
          end else
          begin
            if Controller.BoundShapeMatrixIdentity then
            begin
              Group := TGroupNode.Create('', BaseUrl);
            end else
            begin
              Group := TMatrixTransformNode.Create('', BaseUrl);
              TMatrixTransformNode(Group).FdMatrix.Value := Controller.BoundShapeMatrix;
            end;
            ParentGroup.FdChildren.Add(Group);
            AddGeometryInstance(Group, Geometry, InstantiatingElement);
          end;
        end;
      end else
        OnWarning(wtMajor, 'Collada', Format('Element <%s> missing url attribute (that has to start with #)',
          [InstantiatingElement.TagName]));
    end;

  var
    { This is either TTransformNode or TMatrixTransformNode. }
    NodeTransform: TAbstractX3DGroupingNode;

    { Create new Transform node, place it as a child of current Transform node
      and switch current Transform node to the new one.

      The idea is that each
      Collada transformation creates new nested VRML Transform node
      (since Collada transformations may represent any transformation,
      not necessarily representable by a single VRML Transform node).

      Returns NodeTransform, typecasted to TTransformNode, for your comfort. }
    function NestedTransform: TTransformNode;
    var
      NewNodeTransform: TTransformNode;
    begin
      NewNodeTransform := TTransformNode.Create('', BaseUrl);
      NodeTransform.FdChildren.Add(NewNodeTransform);

      NodeTransform := NewNodeTransform;
      Result := NewNodeTransform;
    end;

    function NestedMatrixTransform: TMatrixTransformNode;
    var
      NewNodeTransform: TMatrixTransformNode;
    begin
      NewNodeTransform := TMatrixTransformNode.Create('', BaseUrl);
      NodeTransform.FdChildren.Add(NewNodeTransform);

      NodeTransform := NewNodeTransform;
      Result := NewNodeTransform;
    end;

  var
    I: TXMLElementIterator;
    NodeId: string;
    V3: TVector3Single;
    V4: TVector4Single;
  begin
    if not DOMGetAttribute(NodeElement, 'id', NodeId) then
      NodeId := '';

    NodeTransform := TTransformNode.Create(NodeId, BaseUrl);
    ParentGroup.FdChildren.Add(NodeTransform);

    { First iterate to gather all transformations.

      For Collada 1.4, this shouldn't be needed (spec says that
      transforms must be before all instantiations).

      But Collada 1.3.1 specification doesn't say anything about the order.
      And e.g. Blender Collada 1.3 exporter in fact generates files
      with <instantiate> first, then <matrix>, and yes: it expects matrix
      should affect instantiated object. So the bottom line is that for
      Collada 1.3, I must first gather all transforms, then do instantiations. }

    I := TXMLElementIterator.Create(NodeElement);
    try
      while I.GetNext do
      begin
        if I.Current.TagName = 'matrix' then
        begin
          NestedMatrixTransform.FdMatrix.Value := ReadMatrix(I.Current);
        end else
        if I.Current.TagName = 'rotate' then
        begin
          V4 := Vector4SingleFromStr(DOMGetTextData(I.Current));
          if V4[3] <> 0.0 then
          begin
            NestedTransform.FdRotation.ValueDeg := V4;
          end;
        end else
        if I.Current.TagName = 'scale' then
        begin
          V3 := Vector3SingleFromStr(DOMGetTextData(I.Current));
          if not VectorsPerfectlyEqual(V3, Vector3Single(1, 1, 1)) then
          begin
            NestedTransform.FdScale.Value := V3;
          end;
        end else
        if I.Current.TagName = 'lookat' then
        begin
          NestedMatrixTransform.FdMatrix.Value := ReadLookAt(I.Current);
        end else
        if I.Current.TagName = 'skew' then
        begin
          { TODO }
        end else
        if I.Current.TagName = 'translate' then
        begin
          V3 := Vector3SingleFromStr(DOMGetTextData(I.Current));
          if not VectorsPerfectlyEqual(V3, ZeroVector3Single) then
          begin
            NestedTransform.FdTranslation.Value := V3;
          end;
        end;
      end;
    finally FreeAndNil(I); end;

    { Now iterate to read instantiations and recursive nodes. }

    I := TXMLElementIterator.Create(NodeElement);
    try
      while I.GetNext do
      begin
        if (I.Current.TagName = 'instance') or
           (I.Current.TagName = 'instance_geometry') then
          ReadInstanceGeometry(NodeTransform, I.Current) else
        if I.Current.TagName = 'instance_controller' then
          ReadInstanceController(NodeTransform, I.Current) else
        if I.Current.TagName = 'instance_camera' then
          ReadInstance(NodeTransform, I.Current, Cameras) else
        if I.Current.TagName = 'instance_light' then
          ReadInstance(NodeTransform, I.Current, Lights) else
        if I.Current.TagName = 'node' then
          ReadNodeElement(NodeTransform, I.Current);
      end;
    finally FreeAndNil(I) end;
  end;

  { Read <node> sequence within given SceneElement, adding nodes to Group.
    This is used to handle <visual_scene> for Collada 1.4.x
    and <scene> for Collada 1.3.x. }
  procedure ReadNodesSequence(Group: TAbstractX3DGroupingNode;
    SceneElement: TDOMElement);
  var
    I: TXMLElementFilteringIterator;
  begin
    I := TXMLElementFilteringIterator.Create(SceneElement, 'node');
    try
      while I.GetNext do
        ReadNodeElement(Group, I.Current);
    finally FreeAndNil(I) end;
  end;

  { Read <scene> element. }
  procedure ReadSceneElement(SceneElement: TDOMElement);
  var
    SceneId: string;

    procedure Collada14;
    var
      InstanceVisualScene: TDOMElement;
      VisualSceneId: string;
      VisualScene: TX3DNode;
    begin
      InstanceVisualScene := DOMGetChildElement(SceneElement,
        'instance_visual_scene', false);
      if InstanceVisualScene <> nil then
      begin
        if DOMGetAttribute(InstanceVisualScene, 'url', VisualSceneId) and
           SCharIs(VisualSceneId, 1, '#') then
        begin
          Delete(VisualSceneId, 1, 1);
          VisualScene := VisualScenes.FindName(VisualSceneId);
          if VisualScene = nil then
            OnWarning(wtMinor, 'Collada', Format('<instance_visual_scene> instantiates non-existing ' +
              '<visual_scene> element "%s"', [VisualSceneId])) else
            ResultModel.FdChildren.Add(VisualScene);
        end;
      end;
    end;

    procedure Collada13;
    var
      Group: TGroupNode;
    begin
      Group := TGroupNode.Create(SceneId, BaseUrl);
      ResultModel.FdChildren.Add(Group);

      ReadNodesSequence(Group, SceneElement);
    end;

  begin
    if not DOMGetAttribute(SceneElement, 'id', SceneId) then
      SceneId := '';

    { <scene> element is different in two Collada versions, it's most clear
      to just branch and do different procedure depending on Collada version. }

    if Version14 then
      Collada14 else
      Collada13;
  end;

  { Read <visual_scene>. Obtained scene X3D node is added both
    to VisualScenes list and VisualScenesSwitch.choice. }
  procedure ReadVisualScene(VisualScenesSwitch: TSwitchNode;
    VisualSceneElement: TDOMElement);
  var
    VisualSceneId: string;
    Group: TGroupNode;
  begin
    if not DOMGetAttribute(VisualSceneElement, 'id', VisualSceneId) then
      VisualSceneId := '';

    Group := TGroupNode.Create(VisualSceneId, BaseUrl);
    VisualScenes.Add(Group);
    VisualScenesSwitch.FdChildren.Add(Group);

    ReadNodesSequence(Group, VisualSceneElement);
  end;

  { Read <library_visual_scenes> from Collada 1.4.x }
  procedure ReadLibraryVisualScenes(LibraryElement: TDOMElement);
  var
    I: TXMLElementFilteringIterator;
    LibraryId: string;
    VisualScenesSwitch: TSwitchNode;
  begin
    if not DOMGetAttribute(LibraryElement, 'id', LibraryId) then
      LibraryId := '';

    { Library of visual scenes is simply a VRML Switch, with each
      scene inside as one choice. This way we export to VRML all
      scenes from Collada, even those not chosen as current scene.
      That's good --- it's always nice to keep some data when
      converting. }

    VisualScenesSwitch := TSwitchNode.Create(LibraryId, BaseUrl);
    ResultModel.FdChildren.Add(VisualScenesSwitch);

    I := TXMLElementFilteringIterator.Create(LibraryElement, 'visual_scene');
    try
      while I.GetNext do
        ReadVisualScene(VisualScenesSwitch, I.Current);
        { other I.Current.TagName not supported for now }
    finally FreeAndNil(I) end;
  end;

  { Read <controller> from Collada 1.4.x }
  procedure ReadController(ControllerElement: TDOMElement);
  var
    Controller: TColladaController;
    Skin, BindShapeMatrix: TDOMElement;
  begin
    Controller := TColladaController.Create;
    Controllers.Add(Controller);
    Controller.BoundShapeMatrixIdentity := true;

    if not DOMGetAttribute(ControllerElement, 'id', Controller.Name) then
      Controller.Name := '';

    Skin := DOMGetChildElement(ControllerElement, 'skin', false);
    if Skin <> nil then
    begin
      if DOMGetAttribute(Skin, 'source', Controller.Source) then
      begin
        { this should be true, controller.source is URL }
        if SCharIs(Controller.Source, 1, '#') then
          Delete(Controller.Source, 1, 1);
      end;

      BindShapeMatrix := DOMGetChildElement(Skin, 'bind_shape_matrix', false);
      if BindShapeMatrix <> nil then
      begin
        Controller.BoundShapeMatrixIdentity := false;
        Controller.BoundShapeMatrix := ReadMatrix(BindShapeMatrix);
      end;
    end;
  end;

  { Read <library_images> (Collada 1.4.x). Fills Images list. }
  procedure ReadLibraryImages(LibraryElement: TDOMElement);
  var
    I: TXMLElementFilteringIterator;
    Image: TImageTextureNode;
    ImageId, ImageUrl: string;
  begin
    I := TXMLElementFilteringIterator.Create(LibraryElement, 'image');
    try
      while I.GetNext do
        if DOMGetAttribute(I.Current, 'id', ImageId) then
        begin
          Image := TImageTextureNode.Create(ImageId, BaseUrl);
          Images.Add(Image);
          ImageUrl := ReadChildText(I.Current, 'init_from');
          if ImageUrl <> '' then
            Image.FdUrl.Items.Add(ImageUrl);
        end;
    finally FreeAndNil(I) end;
  end;

  { Read <library_controllers> from Collada 1.4.x }
  procedure ReadLibraryControllers(LibraryElement: TDOMElement);
  var
    I: TXMLElementFilteringIterator;
  begin
    I := TXMLElementFilteringIterator.Create(LibraryElement, 'controller');
    try
      while I.GetNext do
        ReadController(I.Current);
        { other I.Current.TagName not supported for now }
    finally FreeAndNil(I) end;
  end;

  { Read <library_cameras> (Collada 1.4.x). Fills Cameras list. }
  procedure ReadLibraryCameras(LibraryE: TDOMElement);
  var
    Id: string;
    CameraGroup: TGroupNode;

    procedure InitializeNavigationInfo(E: TDOMElement);
    var
      Navigation: TNavigationInfoNode;
      ZNear, ZFar: Float;
    begin
      Navigation := TNavigationInfoNode.Create(Id + '_navigation_info', BaseUrl);
      CameraGroup.FdChildren.Add(Navigation);

      if ReadChildFloat(E, 'znear', ZNear) then
        Navigation.FdAvatarSize.Items[0] := ZNear * 2;

      if ReadChildFloat(E, 'zfar', ZFar) then
        Navigation.FdVisibilityLimit.Value := ZFar;
    end;

  var
    I: TXMLElementFilteringIterator;
    Viewpoint: TViewpointNode;
    OrthoViewpoint: TOrthoViewpointNode;
    OpticsE, TechniqueE, PerspectiveE, OrthographicE: TDOMElement;
    XFov, YFov, XMag, YMag, AspectRatio: Float;
  begin
    I := TXMLElementFilteringIterator.Create(LibraryE, 'camera');
    try
      while I.GetNext do
        if DOMGetAttribute(I.Current, 'id', Id) then
        begin
          CameraGroup := TGroupNode.Create(Id, BaseUrl);
          Cameras.Add(CameraGroup);

          OpticsE := DOMGetChildElement(I.Current, 'optics', false);
          if OpticsE <> nil then
          begin
            TechniqueE := DOMGetChildElement(OpticsE, 'technique_common', false);
            if TechniqueE <> nil then
            begin
              PerspectiveE := DOMGetChildElement(TechniqueE, 'perspective', false);
              if PerspectiveE <> nil then
              begin
                Viewpoint := TViewpointNode.Create(Id + '_viewpoint', BaseUrl);
                Viewpoint.FdPosition.Value := ZeroVector3Single;
                CameraGroup.FdChildren.Add(Viewpoint);

                { Try to get YFov, and use it as X3D fieldOfView.
                  It's not a perfect translation, the idea of fieldOfView
                  is just different (X3D doesn't force aspect ratio). }
                if ReadChildFloat(PerspectiveE, 'yfov', YFov) then
                  Viewpoint.FdFieldOfView.Value := DegToRad(YFov) else
                if ReadChildFloat(PerspectiveE, 'xfov', XFov) and
                   ReadChildFloat(PerspectiveE, 'aspect_ratio', AspectRatio) and
                   (AspectRatio > SingleEqualityEpsilon) then
                  { aspect_ratio = xfov / yfov, so we can calculate yfov }
                  Viewpoint.FdFieldOfView.Value := DegToRad(XFov) / AspectRatio;

                InitializeNavigationInfo(PerspectiveE);
              end else
              begin
                OrthographicE := DOMGetChildElement(TechniqueE, 'orthographic', false);
                if OrthographicE <> nil then
                begin
                  OrthoViewpoint := TOrthoViewpointNode.Create(Id + '_viewpoint', BaseUrl);
                  OrthoViewpoint.FdPosition.Value := ZeroVector3Single;
                  CameraGroup.FdChildren.Add(OrthoViewpoint);

                  { Translation to X3D cannot be perfect, as fieldOfView
                    just works differently, and X3D automatically preserves
                    aspect ratio. We concentrate on setting vertical angle
                    right (as this one is usually smaller, and so determines
                    horizontal angle). }
                  if ReadChildFloat(OrthographicE, 'ymag', YMag) then
                  begin
                    OrthoViewpoint.FdFieldOfView.Items[1] := -YMag;
                    OrthoViewpoint.FdFieldOfView.Items[3] :=  YMag;
                  end else
                  if ReadChildFloat(OrthographicE, 'xmag', XMag) then
                  begin
                    if ReadChildFloat(OrthographicE, 'aspect_ratio', AspectRatio) and
                       (AspectRatio > SingleEqualityEpsilon) then
                    begin
                      { aspect_ratio = xmag / ymag, so we can calculate ymag }
                      YMag := XMag / AspectRatio;
                      OrthoViewpoint.FdFieldOfView.Items[1] := -YMag;
                      OrthoViewpoint.FdFieldOfView.Items[3] :=  YMag;
                    end else
                    begin
                      OrthoViewpoint.FdFieldOfView.Items[0] := -XMag;
                      OrthoViewpoint.FdFieldOfView.Items[2] :=  XMag;
                    end;
                  end;

                  InitializeNavigationInfo(OrthographicE);
                end else
                  OnWarning(wtMinor, 'Collada', 'No supported camera inside <technique_common>');
              end;
            end else
              OnWarning(wtMinor, 'Collada', 'No supported camera technique inside <optics>');
          end else
            OnWarning(wtMinor, 'Collada', 'No <optics> inside camera');
        end;
    finally FreeAndNil(I) end;
  end;

  { Read <library_lights> (Collada 1.4.x). Fills Lights list. }
  procedure ReadLibraryLights(LibraryE: TDOMElement);

    function ReadAttenuation(E: TDOMElement): TVector3Single;
    begin
      Result := Vector3Single(1, 0, 0);
      ReadChildFloat(E, 'constant_attenuation', Result[0]);
      ReadChildFloat(E, 'linear_attenuation', Result[1]);
      ReadChildFloat(E, 'quadratic_attenuation', Result[2]);
    end;

  var
    I: TXMLElementFilteringIterator;
    Light: TAbstractLightNode;
    Point: TPointLightNode;
    Directional: TDirectionalLightNode;
    Spot: TSpotLightNode;
    Id, Profile: string;
    TechniqueE, LightE, ExtraE: TDOMElement;
    FalloffAngle, Radius: Float;
    LightColor: TVector3Single;
  begin
    I := TXMLElementFilteringIterator.Create(LibraryE, 'light');
    try
      while I.GetNext do
        if DOMGetAttribute(I.Current, 'id', Id) then
        begin
          Light := nil;

          TechniqueE := DOMGetChildElement(I.Current, 'technique_common', false);
          if TechniqueE <> nil then
          begin
            LightE := DOMGetChildElement(TechniqueE, 'point', false);
            if LightE <> nil then
            begin
              Point := TPointLightNode.Create(Id, BaseUrl);
              Point.FdAttenuation.Value := ReadAttenuation(LightE);
              Light := Point;
            end else
            begin
              LightE := DOMGetChildElement(TechniqueE, 'directional', false);
              if LightE <> nil then
              begin
                Directional := TDirectionalLightNode.Create(Id, BaseUrl);
                { default X3D light direction is -Z, matches Collada }
                Light := Directional;
              end else
              begin
                LightE := DOMGetChildElement(TechniqueE, 'spot', false);
                if LightE <> nil then
                begin
                  Spot := TSpotLightNode.Create(Id, BaseUrl);
                  Spot.FdAttenuation.Value := ReadAttenuation(LightE);
                  { default X3D spot direction is -Z, matches Collada }
                  if not ReadChildFloat(LightE, 'falloff_angle', FalloffAngle) then
                    FalloffAngle := 180; { Collada default }
                  Spot.FdCutOffAngle.Value := DegToRad(FalloffAngle);
                  { falloff_exponent cannot be nicely translated to X3D beamWidth,
                    see notes about SpotLight.beamWidth at VRML/X3D renderer. }
                  Light := Spot;
                end else
                begin
                  LightE := DOMGetChildElement(TechniqueE, 'ambient', false);
                  if LightE <> nil then
                  begin
                    Point := TPointLightNode.Create(Id, BaseUrl);
                    { ambient light can be translated to normal PointLight with
                      intensity = 0 (this scales diffuse and specular to zero). }
                    Point.FdIntensity.Value := 0;
                    Point.FdAmbientIntensity.Value := 1;
                    Light := Point;
                  end else
                    OnWarning(wtMinor, 'Collada', 'No supported light inside <technique_common>');
                end;
              end;
            end;
          end else
            OnWarning(wtMinor, 'Collada', 'No supported technique inside <light>');

          if Light <> nil then
          begin
            Light.FdGlobal.Value := true;
            if ReadChildVector(LightE, 'color', LightColor) then
              Light.FdColor.Value := LightColor;
            if Light is TAbstractPositionalLightNode then
            begin
              { calculate light radius }
              Radius := MaxSingle;
              ExtraE := DOMGetChildElement(I.Current, 'extra', false);
              if ExtraE <> nil then
              begin
                TechniqueE := DOMGetChildElement(ExtraE, 'technique', false);
                if (TechniqueE <> nil) and
                   DOMGetAttribute(TechniqueE, 'profile', Profile) and
                   (Profile = 'blender') then
                  ReadChildFloat(TechniqueE, 'dist', Radius);
              end;
              TAbstractPositionalLightNode(Light).FdRadius.Value := Radius;
            end;
            Lights.Add(Light);
          end;
        end;
    finally FreeAndNil(I) end;
  end;

var
  Doc: TXMLDocument;
  Version: string;
  I: TXMLElementIterator;
  LibraryE: TDOMElement;
  Stream: TStream;
begin
  Effects := nil;
  Materials := nil;
  Geometries := nil;
  VisualScenes := nil;
  Controllers := nil;
  Images := nil;
  Cameras := nil;
  Lights := nil;
  Result := nil;

  try
    Stream := Download(URL);
    try
      ReadXMLFile(Doc, Stream);
    finally FreeAndNil(Stream) end;

    try
      Check(Doc.DocumentElement.TagName = 'COLLADA',
        'Root node of Collada file must be <COLLADA>');

      if not DOMGetAttribute(Doc.DocumentElement, 'version', Version) then
      begin
        Version := '';
        Version14 := false;
        OnWarning(wtMinor, 'Collada', '<COLLADA> element misses "version" attribute');
      end else
      begin
        { TODO: uhm, terrible hack... I should move my lazy ass and tokenize
          Version properly. }
        Version14 := IsPrefix('1.4.', Version) or IsPrefix('1.5.', Version);
      end;

      { honour COLLADA.base (exactly for the same purpose as our BaseUrl),
        but only if it's absolute }
      if not (DOMGetAttribute(Doc.DocumentElement, 'base', BaseUrl) and
              IsAbsoluteURI(BaseUrl)) then
        BaseUrl := AbsoluteURI(URL);

      Effects := TColladaEffectList.Create;
      Materials := TColladaMaterialsMap.Create;
      Geometries := TColladaGeometryList.Create;
      VisualScenes := TX3DNodeList.Create(false);
      Controllers := TColladaControllerList.Create;
      Images := TX3DNodeList.Create(false);
      Cameras := TX3DNodeList.Create(false);
      Lights := TX3DNodeList.Create(false);

      Result := TX3DRootNode.Create('', BaseUrl);
      Result.HasForceVersion := true;
      Result.ForceVersion := X3DVersion;

      { Read library_images. These may be referred to inside effects. }
      LibraryE := DOMGetChildElement(Doc.DocumentElement, 'library_images', false);
      if LibraryE <> nil then
        ReadLibraryImages(LibraryE);

      { Read library_effects.
        Effects may be referenced by materials,
        and there's no guarantee that library_effects will occur before
        library_materials. Testcase: "COLLLADA 1.4.1 Basic Samples/Cube/cube.dae". }
      LibraryE := DOMGetChildElement(Doc.DocumentElement, 'library_effects', false);
      if LibraryE <> nil then
        ReadLibraryEffects(LibraryE);

      { Read libraries of things that may be referenced within library_visual_scenes.
        For some models, <library_visual_scenes> may be before them (test from
        collada.org/owl/ : "New Uploads/COLLADA 1.5.0 Kinematics/COLLADA 1.5.0 Kinematics/COLLADA/KR150/kr150.dae") }
      I := TXMLElementIterator.Create(Doc.DocumentElement);
      try
        while I.GetNext do
          if I.Current.TagName = 'library' then { only Collada < 1.4.x }
            ReadLibrary(I.Current) else
          if I.Current.TagName = 'library_materials' then { only Collada >= 1.4.x }
            ReadLibraryMaterials(I.Current) else
          if I.Current.TagName = 'library_geometries' then { only Collada >= 1.4.x }
            ReadLibraryGeometries(I.Current) else
          if I.Current.TagName = 'library_cameras' then { only Collada >= 1.4.x }
            ReadLibraryCameras(I.Current) else
          if I.Current.TagName = 'library_lights' then { only Collada >= 1.4.x }
            ReadLibraryLights(I.Current) else
          if I.Current.TagName = 'library_controllers' then { only Collada >= 1.4.x }
            ReadLibraryControllers(I.Current);
      finally FreeAndNil(I); end;

      I := TXMLElementIterator.Create(Doc.DocumentElement);
      try
        while I.GetNext do
          if I.Current.TagName = 'library_visual_scenes' then { only Collada >= 1.4.x }
            ReadLibraryVisualScenes(I.Current) else
          if I.Current.TagName = 'scene' then
            ReadSceneElement(I.Current);
      finally FreeAndNil(I); end;

      Result.Meta.PutPreserve('source', ExtractURIName(URL));
      Result.Meta['source-collada-version'] := Version;
    finally
      FreeAndNil(Doc);

      { Free unused Images before freeing Effects.
        That's because image may be used inside an effect,
        and would be invalid reference after freeing effect. }
      X3DNodeList_FreeUnusedAndNil(Images);

      FreeAndNil(Materials);

      { Note: if some effect will be used by some geometry, but the
        geometry will not be used, everything will be still Ok
        (no memory leak). First freeing over Effects will not free this
        effect (since it's used), but then freeing over Geometries will
        free the geometry together with effect (since effect usage will
        drop to zero).

        This means that also other complicated case, when one effect is
        used twice, once by unused geometry node, second time by used geometry
        node, is also Ok. }
      FreeAndNil(Effects);
      FreeAndNil(Geometries);

      X3DNodeList_FreeUnusedAndNil(Lights);
      X3DNodeList_FreeUnusedAndNil(Cameras);
      X3DNodeList_FreeUnusedAndNil(VisualScenes);
      FreeAndNil(Controllers);
    end;
    { eventually free Result *after* freeing other lists, to make sure references
      on Images, Materials etc. are valid when their unused items are freed. }
  except FreeAndNil(Result); raise; end;
end;

end.