File: LWOLoader.js

package info (click to toggle)
three.js 111%2Bdfsg1-2
  • links: PTS, VCS
  • area: main
  • in suites: bullseye
  • size: 15,184 kB
  • sloc: javascript: 133,174; makefile: 24; sh: 1
file content (3064 lines) | stat: -rw-r--r-- 69,329 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
/**
 * @version 1.1.1
 *
 * @author Lewy Blue https://github.com/looeee
 * @author Guilherme Avila https://github/sciecode
 *
 * @desc Load files in LWO3 and LWO2 format on Three.js
 *
 * LWO3 format specification:
 * 	http://static.lightwave3d.com/sdk/2018/html/filefmts/lwo3.html
 *
 * LWO2 format specification:
 * 	http://static.lightwave3d.com/sdk/2018/html/filefmts/lwo2.html
 *
 * Development and test repository:
 *	https://github.com/threejs/lwoloader
 *
 **/

import {
	AddOperation,
	BackSide,
	BufferAttribute,
	BufferGeometry,
	ClampToEdgeWrapping,
	Color,
	DoubleSide,
	EquirectangularReflectionMapping,
	EquirectangularRefractionMapping,
	FileLoader,
	Float32BufferAttribute,
	FrontSide,
	LineBasicMaterial,
	LineSegments,
	Loader,
	LoaderUtils,
	Mesh,
	MeshPhongMaterial,
	MeshPhysicalMaterial,
	MeshStandardMaterial,
	MirroredRepeatWrapping,
	Points,
	PointsMaterial,
	RepeatWrapping,
	TextureLoader,
	Vector2
} from "../../../build/three.module.js";

function LWO2Parser( IFFParser ) {

	this.IFF = IFFParser;

}

LWO2Parser.prototype = {

	constructor: LWO2Parser,

	parseBlock: function () {

		this.IFF.debugger.offset = this.IFF.reader.offset;
		this.IFF.debugger.closeForms();

		var blockID = this.IFF.reader.getIDTag();
		var length = this.IFF.reader.getUint32(); // size of data in bytes
		if ( length > this.IFF.reader.dv.byteLength - this.IFF.reader.offset ) {

			this.IFF.reader.offset -= 4;
			length = this.IFF.reader.getUint16();

		}

		this.IFF.debugger.dataOffset = this.IFF.reader.offset;
		this.IFF.debugger.length = length;

		// Data types may be found in either LWO2 OR LWO3 spec
		switch ( blockID ) {

			case 'FORM': // form blocks may consist of sub -chunks or sub-forms
				this.IFF.parseForm( length );
				break;

			// SKIPPED CHUNKS
			// if break; is called directly, the position in the lwoTree is not created
			// any sub chunks and forms are added to the parent form instead
			// MISC skipped
			case 'ICON': // Thumbnail Icon Image
			case 'VMPA': // Vertex Map Parameter
			case 'BBOX': // bounding box
			// case 'VMMD':
			// case 'VTYP':

			// normal maps can be specified, normally on models imported from other applications. Currently ignored
			case 'NORM':

			// ENVL FORM skipped
			case 'PRE ':
			case 'POST':
			case 'KEY ':
			case 'SPAN':

			// CLIP FORM skipped
			case 'TIME':
			case 'CLRS':
			case 'CLRA':
			case 'FILT':
			case 'DITH':
			case 'CONT':
			case 'BRIT':
			case 'SATR':
			case 'HUE ':
			case 'GAMM':
			case 'NEGA':
			case 'IFLT':
			case 'PFLT':

			// Image Map Layer skipped
			case 'PROJ':
			case 'AXIS':
			case 'AAST':
			case 'PIXB':
			case 'AUVO':
			case 'STCK':

			// Procedural Textures skipped
			case 'PROC':
			case 'VALU':
			case 'FUNC':

			// Gradient Textures skipped
			case 'PNAM':
			case 'INAM':
			case 'GRST':
			case 'GREN':
			case 'GRPT':
			case 'FKEY':
			case 'IKEY':

			// Texture Mapping Form skipped
			case 'CSYS':

			// Surface CHUNKs skipped
			case 'OPAQ': // top level 'opacity' checkbox
			case 'CMAP': // clip map

			// Surface node CHUNKS skipped
			// These mainly specify the node editor setup in LW
			case 'NLOC':
			case 'NZOM':
			case 'NVER':
			case 'NSRV':
			case 'NVSK': // unknown
			case 'NCRD':
			case 'WRPW': // image wrap w ( for cylindrical and spherical projections)
			case 'WRPH': // image wrap h
			case 'NMOD':
			case 'NPRW':
			case 'NPLA':
			case 'NODS':
			case 'VERS':
			case 'ENUM':
			case 'TAG ':
			case 'OPAC':

			// Car Material CHUNKS
			case 'CGMD':
			case 'CGTY':
			case 'CGST':
			case 'CGEN':
			case 'CGTS':
			case 'CGTE':
			case 'OSMP':
			case 'OMDE':
			case 'OUTR':
			case 'FLAG':

			case 'TRNL':
			case 'GLOW':
			case 'GVAL': // glow intensity
			case 'SHRP':
			case 'RFOP':
			case 'RSAN':
			case 'TROP':
			case 'RBLR':
			case 'TBLR':
			case 'CLRH':
			case 'CLRF':
			case 'ADTR':
			case 'LINE':
			case 'ALPH':
			case 'VCOL':
			case 'ENAB':
				this.IFF.debugger.skipped = true;
				this.IFF.reader.skip( length );
				break;

			case 'SURF':
				this.IFF.parseSurfaceLwo2( length );
				break;

			case 'CLIP':
				this.IFF.parseClipLwo2( length );
				break;

			// Texture node chunks (not in spec)
			case 'IPIX': // usePixelBlending
			case 'IMIP': // useMipMaps
			case 'IMOD': // imageBlendingMode
			case 'AMOD': // unknown
			case 'IINV': // imageInvertAlpha
			case 'INCR': // imageInvertColor
			case 'IAXS': // imageAxis ( for non-UV maps)
			case 'IFOT': // imageFallofType
			case 'ITIM': // timing for animated textures
			case 'IWRL':
			case 'IUTI':
			case 'IINX':
			case 'IINY':
			case 'IINZ':
			case 'IREF': // possibly a VX for reused texture nodes
				if ( length === 4 ) this.IFF.currentNode[ blockID ] = this.IFF.reader.getInt32();
				else this.IFF.reader.skip( length );
				break;

			case 'OTAG':
				this.IFF.parseObjectTag();
				break;

			case 'LAYR':
				this.IFF.parseLayer( length );
				break;

			case 'PNTS':
				this.IFF.parsePoints( length );
				break;

			case 'VMAP':
				this.IFF.parseVertexMapping( length );
				break;

			case 'AUVU':
			case 'AUVN':
				this.IFF.reader.skip( length - 1 );
				this.IFF.reader.getVariableLengthIndex(); // VX
				break;

			case 'POLS':
				this.IFF.parsePolygonList( length );
				break;

			case 'TAGS':
				this.IFF.parseTagStrings( length );
				break;

			case 'PTAG':
				this.IFF.parsePolygonTagMapping( length );
				break;

			case 'VMAD':
				this.IFF.parseVertexMapping( length, true );
				break;

			// Misc CHUNKS
			case 'DESC': // Description Line
				this.IFF.currentForm.description = this.IFF.reader.getString();
				break;

			case 'TEXT':
			case 'CMNT':
			case 'NCOM':
				this.IFF.currentForm.comment = this.IFF.reader.getString();
				break;

			// Envelope Form
			case 'NAME':
				this.IFF.currentForm.channelName = this.IFF.reader.getString();
				break;

			// Image Map Layer
			case 'WRAP':
				this.IFF.currentForm.wrap = { w: this.IFF.reader.getUint16(), h: this.IFF.reader.getUint16() };
				break;

			case 'IMAG':
				var index = this.IFF.reader.getVariableLengthIndex();
				this.IFF.currentForm.imageIndex = index;
				break;

			// Texture Mapping Form
			case 'OREF':
				this.IFF.currentForm.referenceObject = this.IFF.reader.getString();
				break;

			case 'ROID':
				this.IFF.currentForm.referenceObjectID = this.IFF.reader.getUint32();
				break;

			// Surface Blocks
			case 'SSHN':
				this.IFF.currentSurface.surfaceShaderName = this.IFF.reader.getString();
				break;

			case 'AOVN':
				this.IFF.currentSurface.surfaceCustomAOVName = this.IFF.reader.getString();
				break;

			// Nodal Blocks
			case 'NSTA':
				this.IFF.currentForm.disabled = this.IFF.reader.getUint16();
				break;

			case 'NRNM':
				this.IFF.currentForm.realName = this.IFF.reader.getString();
				break;

			case 'NNME':
				this.IFF.currentForm.refName = this.IFF.reader.getString();
				this.IFF.currentSurface.nodes[ this.IFF.currentForm.refName ] = this.IFF.currentForm;
				break;

			// Nodal Blocks : connections
			case 'INME':
				if ( ! this.IFF.currentForm.nodeName ) this.IFF.currentForm.nodeName = [];
				this.IFF.currentForm.nodeName.push( this.IFF.reader.getString() );
				break;

			case 'IINN':
				if ( ! this.IFF.currentForm.inputNodeName ) this.IFF.currentForm.inputNodeName = [];
				this.IFF.currentForm.inputNodeName.push( this.IFF.reader.getString() );
				break;

			case 'IINM':
				if ( ! this.IFF.currentForm.inputName ) this.IFF.currentForm.inputName = [];
				this.IFF.currentForm.inputName.push( this.IFF.reader.getString() );
				break;

			case 'IONM':
				if ( ! this.IFF.currentForm.inputOutputName ) this.IFF.currentForm.inputOutputName = [];
				this.IFF.currentForm.inputOutputName.push( this.IFF.reader.getString() );
				break;

			case 'FNAM':
				this.IFF.currentForm.fileName = this.IFF.reader.getString();
				break;

			case 'CHAN': // NOTE: ENVL Forms may also have CHAN chunk, however ENVL is currently ignored
				if ( length === 4 ) this.IFF.currentForm.textureChannel = this.IFF.reader.getIDTag();
				else this.IFF.reader.skip( length );
				break;

			// LWO2 Spec chunks: these are needed since the SURF FORMs are often in LWO2 format
			case 'SMAN':
				var maxSmoothingAngle = this.IFF.reader.getFloat32();
				this.IFF.currentSurface.attributes.smooth = ( maxSmoothingAngle < 0 ) ? false : true;
				break;

			// LWO2: Basic Surface Parameters
			case 'COLR':
				this.IFF.currentSurface.attributes.Color = { value: this.IFF.reader.getFloat32Array( 3 ) };
				this.IFF.reader.skip( 2 ); // VX: envelope
				break;

			case 'LUMI':
				this.IFF.currentSurface.attributes.Luminosity = { value: this.IFF.reader.getFloat32() };
				this.IFF.reader.skip( 2 );
				break;

			case 'SPEC':
				this.IFF.currentSurface.attributes.Specular = { value: this.IFF.reader.getFloat32() };
				this.IFF.reader.skip( 2 );
				break;

			case 'DIFF':
				this.IFF.currentSurface.attributes.Diffuse = { value: this.IFF.reader.getFloat32() };
				this.IFF.reader.skip( 2 );
				break;

			case 'REFL':
				this.IFF.currentSurface.attributes.Reflection = { value: this.IFF.reader.getFloat32() };
				this.IFF.reader.skip( 2 );
				break;

			case 'GLOS':
				this.IFF.currentSurface.attributes.Glossiness = { value: this.IFF.reader.getFloat32() };
				this.IFF.reader.skip( 2 );
				break;

			case 'TRAN':
				this.IFF.currentSurface.attributes.opacity = this.IFF.reader.getFloat32();
				this.IFF.reader.skip( 2 );
				break;

			case 'BUMP':
				this.IFF.currentSurface.attributes.bumpStrength = this.IFF.reader.getFloat32();
				this.IFF.reader.skip( 2 );
				break;

			case 'SIDE':
				this.IFF.currentSurface.attributes.side = this.IFF.reader.getUint16();
				break;

			case 'RIMG':
				this.IFF.currentSurface.attributes.reflectionMap = this.IFF.reader.getVariableLengthIndex();
				break;

			case 'RIND':
				this.IFF.currentSurface.attributes.refractiveIndex = this.IFF.reader.getFloat32();
				this.IFF.reader.skip( 2 );
				break;

			case 'TIMG':
				this.IFF.currentSurface.attributes.refractionMap = this.IFF.reader.getVariableLengthIndex();
				break;

			case 'IMAP':
				this.IFF.reader.skip( 2 );
				break;

			case 'TMAP':
				this.IFF.debugger.skipped = true;
				this.IFF.reader.skip( length ); // needs implementing
				break;

			case 'IUVI': // uv channel name
				this.IFF.currentNode.UVChannel = this.IFF.reader.getString( length );
				break;

			case 'IUTL': // widthWrappingMode: 0 = Reset, 1 = Repeat, 2 = Mirror, 3 = Edge
				this.IFF.currentNode.widthWrappingMode = this.IFF.reader.getUint32();
				break;
			case 'IVTL': // heightWrappingMode
				this.IFF.currentNode.heightWrappingMode = this.IFF.reader.getUint32();
				break;

			// LWO2 USE
			case 'BLOK':
				// skip
				break;

			default:
				this.IFF.parseUnknownCHUNK( blockID, length );

		}

		if ( blockID != 'FORM' ) {

			this.IFF.debugger.node = 1;
			this.IFF.debugger.nodeID = blockID;
			this.IFF.debugger.log();

		}

		if ( this.IFF.reader.offset >= this.IFF.currentFormEnd ) {

			this.IFF.currentForm = this.IFF.parentForm;

		}

	}

};

function LWO3Parser( IFFParser ) {

	this.IFF = IFFParser;

}

LWO3Parser.prototype = {

	constructor: LWO3Parser,

	parseBlock: function () {

		this.IFF.debugger.offset = this.IFF.reader.offset;
		this.IFF.debugger.closeForms();

		var blockID = this.IFF.reader.getIDTag();
		var length = this.IFF.reader.getUint32(); // size of data in bytes

		this.IFF.debugger.dataOffset = this.IFF.reader.offset;
		this.IFF.debugger.length = length;

		// Data types may be found in either LWO2 OR LWO3 spec
		switch ( blockID ) {

			case 'FORM': // form blocks may consist of sub -chunks or sub-forms
				this.IFF.parseForm( length );
				break;

			// SKIPPED CHUNKS
			// MISC skipped
			case 'ICON': // Thumbnail Icon Image
			case 'VMPA': // Vertex Map Parameter
			case 'BBOX': // bounding box
			// case 'VMMD':
			// case 'VTYP':

			// normal maps can be specified, normally on models imported from other applications. Currently ignored
			case 'NORM':

			// ENVL FORM skipped
			case 'PRE ':
			case 'POST':
			case 'KEY ':
			case 'SPAN':

			// CLIP FORM skipped
			case 'TIME':
			case 'CLRS':
			case 'CLRA':
			case 'FILT':
			case 'DITH':
			case 'CONT':
			case 'BRIT':
			case 'SATR':
			case 'HUE ':
			case 'GAMM':
			case 'NEGA':
			case 'IFLT':
			case 'PFLT':

			// Image Map Layer skipped
			case 'PROJ':
			case 'AXIS':
			case 'AAST':
			case 'PIXB':
			case 'STCK':

			// Procedural Textures skipped
			case 'VALU':

			// Gradient Textures skipped
			case 'PNAM':
			case 'INAM':
			case 'GRST':
			case 'GREN':
			case 'GRPT':
			case 'FKEY':
			case 'IKEY':

			// Texture Mapping Form skipped
			case 'CSYS':

				// Surface CHUNKs skipped
			case 'OPAQ': // top level 'opacity' checkbox
			case 'CMAP': // clip map

			// Surface node CHUNKS skipped
			// These mainly specify the node editor setup in LW
			case 'NLOC':
			case 'NZOM':
			case 'NVER':
			case 'NSRV':
			case 'NCRD':
			case 'NMOD':
			case 'NSEL':
			case 'NPRW':
			case 'NPLA':
			case 'VERS':
			case 'ENUM':
			case 'TAG ':

			// Car Material CHUNKS
			case 'CGMD':
			case 'CGTY':
			case 'CGST':
			case 'CGEN':
			case 'CGTS':
			case 'CGTE':
			case 'OSMP':
			case 'OMDE':
			case 'OUTR':
			case 'FLAG':

			case 'TRNL':
			case 'SHRP':
			case 'RFOP':
			case 'RSAN':
			case 'TROP':
			case 'RBLR':
			case 'TBLR':
			case 'CLRH':
			case 'CLRF':
			case 'ADTR':
			case 'GLOW':
			case 'LINE':
			case 'ALPH':
			case 'VCOL':
			case 'ENAB':
				this.IFF.debugger.skipped = true;
				this.IFF.reader.skip( length );
				break;

			// Texture node chunks (not in spec)
			case 'IPIX': // usePixelBlending
			case 'IMIP': // useMipMaps
			case 'IMOD': // imageBlendingMode
			case 'AMOD': // unknown
			case 'IINV': // imageInvertAlpha
			case 'INCR': // imageInvertColor
			case 'IAXS': // imageAxis ( for non-UV maps)
			case 'IFOT': // imageFallofType
			case 'ITIM': // timing for animated textures
			case 'IWRL':
			case 'IUTI':
			case 'IINX':
			case 'IINY':
			case 'IINZ':
			case 'IREF': // possibly a VX for reused texture nodes
				if ( length === 4 ) this.IFF.currentNode[ blockID ] = this.IFF.reader.getInt32();
				else this.IFF.reader.skip( length );
				break;

			case 'OTAG':
				this.IFF.parseObjectTag();
				break;

			case 'LAYR':
				this.IFF.parseLayer( length );
				break;

			case 'PNTS':
				this.IFF.parsePoints( length );
				break;

			case 'VMAP':
				this.IFF.parseVertexMapping( length );
				break;

			case 'POLS':
				this.IFF.parsePolygonList( length );
				break;

			case 'TAGS':
				this.IFF.parseTagStrings( length );
				break;

			case 'PTAG':
				this.IFF.parsePolygonTagMapping( length );
				break;

			case 'VMAD':
				this.IFF.parseVertexMapping( length, true );
				break;

			// Misc CHUNKS
			case 'DESC': // Description Line
				this.IFF.currentForm.description = this.IFF.reader.getString();
				break;

			case 'TEXT':
			case 'CMNT':
			case 'NCOM':
				this.IFF.currentForm.comment = this.IFF.reader.getString();
				break;

			// Envelope Form
			case 'NAME':
				this.IFF.currentForm.channelName = this.IFF.reader.getString();
				break;

			// Image Map Layer
			case 'WRAP':
				this.IFF.currentForm.wrap = { w: this.IFF.reader.getUint16(), h: this.IFF.reader.getUint16() };
				break;

			case 'IMAG':
				var index = this.IFF.reader.getVariableLengthIndex();
				this.IFF.currentForm.imageIndex = index;
				break;

			// Texture Mapping Form
			case 'OREF':
				this.IFF.currentForm.referenceObject = this.IFF.reader.getString();
				break;

			case 'ROID':
				this.IFF.currentForm.referenceObjectID = this.IFF.reader.getUint32();
				break;

			// Surface Blocks
			case 'SSHN':
				this.IFF.currentSurface.surfaceShaderName = this.IFF.reader.getString();
				break;

			case 'AOVN':
				this.IFF.currentSurface.surfaceCustomAOVName = this.IFF.reader.getString();
				break;

			// Nodal Blocks
			case 'NSTA':
				this.IFF.currentForm.disabled = this.IFF.reader.getUint16();
				break;

			case 'NRNM':
				this.IFF.currentForm.realName = this.IFF.reader.getString();
				break;

			case 'NNME':
				this.IFF.currentForm.refName = this.IFF.reader.getString();
				this.IFF.currentSurface.nodes[ this.IFF.currentForm.refName ] = this.IFF.currentForm;
				break;

			// Nodal Blocks : connections
			case 'INME':
				if ( ! this.IFF.currentForm.nodeName ) this.IFF.currentForm.nodeName = [];
				this.IFF.currentForm.nodeName.push( this.IFF.reader.getString() );
				break;

			case 'IINN':
				if ( ! this.IFF.currentForm.inputNodeName ) this.IFF.currentForm.inputNodeName = [];
				this.IFF.currentForm.inputNodeName.push( this.IFF.reader.getString() );
				break;

			case 'IINM':
				if ( ! this.IFF.currentForm.inputName ) this.IFF.currentForm.inputName = [];
				this.IFF.currentForm.inputName.push( this.IFF.reader.getString() );
				break;

			case 'IONM':
				if ( ! this.IFF.currentForm.inputOutputName ) this.IFF.currentForm.inputOutputName = [];
				this.IFF.currentForm.inputOutputName.push( this.IFF.reader.getString() );
				break;

			case 'FNAM':
				this.IFF.currentForm.fileName = this.IFF.reader.getString();
				break;

			case 'CHAN': // NOTE: ENVL Forms may also have CHAN chunk, however ENVL is currently ignored
				if ( length === 4 ) this.IFF.currentForm.textureChannel = this.IFF.reader.getIDTag();
				else this.IFF.reader.skip( length );
				break;

			// LWO2 Spec chunks: these are needed since the SURF FORMs are often in LWO2 format
			case 'SMAN':
				var maxSmoothingAngle = this.IFF.reader.getFloat32();
				this.IFF.currentSurface.attributes.smooth = ( maxSmoothingAngle < 0 ) ? false : true;
				break;

			// LWO2: Basic Surface Parameters
			case 'COLR':
				this.IFF.currentSurface.attributes.Color = { value: this.IFF.reader.getFloat32Array( 3 ) };
				this.IFF.reader.skip( 2 ); // VX: envelope
				break;

			case 'LUMI':
				this.IFF.currentSurface.attributes.Luminosity = { value: this.IFF.reader.getFloat32() };
				this.IFF.reader.skip( 2 );
				break;

			case 'SPEC':
				this.IFF.currentSurface.attributes.Specular = { value: this.IFF.reader.getFloat32() };
				this.IFF.reader.skip( 2 );
				break;

			case 'DIFF':
				this.IFF.currentSurface.attributes.Diffuse = { value: this.IFF.reader.getFloat32() };
				this.IFF.reader.skip( 2 );
				break;

			case 'REFL':
				this.IFF.currentSurface.attributes.Reflection = { value: this.IFF.reader.getFloat32() };
				this.IFF.reader.skip( 2 );
				break;

			case 'GLOS':
				this.IFF.currentSurface.attributes.Glossiness = { value: this.IFF.reader.getFloat32() };
				this.IFF.reader.skip( 2 );
				break;

			case 'TRAN':
				this.IFF.currentSurface.attributes.opacity = this.IFF.reader.getFloat32();
				this.IFF.reader.skip( 2 );
				break;

			case 'BUMP':
				this.IFF.currentSurface.attributes.bumpStrength = this.IFF.reader.getFloat32();
				this.IFF.reader.skip( 2 );
				break;

			case 'SIDE':
				this.IFF.currentSurface.attributes.side = this.IFF.reader.getUint16();
				break;

			case 'RIMG':
				this.IFF.currentSurface.attributes.reflectionMap = this.IFF.reader.getVariableLengthIndex();
				break;

			case 'RIND':
				this.IFF.currentSurface.attributes.refractiveIndex = this.IFF.reader.getFloat32();
				this.IFF.reader.skip( 2 );
				break;

			case 'TIMG':
				this.IFF.currentSurface.attributes.refractionMap = this.IFF.reader.getVariableLengthIndex();
				break;

			case 'IMAP':
				this.IFF.currentSurface.attributes.imageMapIndex = this.IFF.reader.getUint32();
				break;

			case 'IUVI': // uv channel name
				this.IFF.currentNode.UVChannel = this.IFF.reader.getString( length );
				break;

			case 'IUTL': // widthWrappingMode: 0 = Reset, 1 = Repeat, 2 = Mirror, 3 = Edge
				this.IFF.currentNode.widthWrappingMode = this.IFF.reader.getUint32();
				break;
			case 'IVTL': // heightWrappingMode
				this.IFF.currentNode.heightWrappingMode = this.IFF.reader.getUint32();
				break;

			default:
				this.IFF.parseUnknownCHUNK( blockID, length );

		}

		if ( blockID != 'FORM' ) {

			this.IFF.debugger.node = 1;
			this.IFF.debugger.nodeID = blockID;
			this.IFF.debugger.log();

		}

		if ( this.IFF.reader.offset >= this.IFF.currentFormEnd ) {

			this.IFF.currentForm = this.IFF.parentForm;

		}

	}

};

/**
 * === IFFParser ===
 * - Parses data from the IFF buffer.
 * - LWO3 files are in IFF format and can contain the following data types, referred to by shorthand codes
 *
 * ATOMIC DATA TYPES
 *  ID Tag - 4x 7 bit uppercase ASCII chars: ID4
 *  signed integer, 1, 2, or 4 byte length: I1, I2, I4
 *  unsigned integer, 1, 2, or 4 byte length: U1, U2, U4
 *  float, 4 byte length: F4
 *  string, series of ASCII chars followed by null byte (If the length of the string including the null terminating byte is odd, an extra null is added so that the data that follows will begin on an even byte boundary): S0
 *
 * COMPOUND DATA TYPES
 *  Variable-length Index (index into an array or collection): U2 or U4 : VX
 *  Color (RGB): F4 + F4 + F4: COL12
 *  Coordinate (x, y, z): F4 + F4 + F4: VEC12
 *  Percentage F4 data type from 0->1 with 1 = 100%: FP4
 *  Angle in radian F4: ANG4
 *  Filename (string) S0: FNAM0
 *  XValue F4 + index (VX) + optional envelope( ENVL ): XVAL
 *  XValue vector VEC12 + index (VX) + optional envelope( ENVL ): XVAL3
 *
 *  The IFF file is arranged in chunks:
 *  CHUNK = ID4 + length (U4) + length X bytes of data + optional 0 pad byte
 *  optional 0 pad byte is there to ensure chunk ends on even boundary, not counted in size
 *
 * COMPOUND DATA TYPES
 * - Chunks are combined in Forms (collections of chunks)
 * - FORM = string 'FORM' (ID4) + length (U4) + type (ID4) + optional ( CHUNK | FORM )
 * - CHUNKS and FORMS are collectively referred to as blocks
 * - The entire file is contained in one top level FORM
 *
 **/

function IFFParser( ) {

	this.debugger = new Debugger();
	// this.debugger.enable(); // un-comment to log IFF hierarchy.

}

IFFParser.prototype = {

	constructor: IFFParser,

	parse: function ( buffer ) {

		this.reader = new DataViewReader( buffer );

		this.tree = {
			materials: {},
			layers: [],
			tags: [],
			textures: [],
		};

		// start out at the top level to add any data before first layer is encountered
		this.currentLayer = this.tree;
		this.currentForm = this.tree;

		this.parseTopForm();

		if ( this.tree.format === undefined ) return;

		if ( this.tree.format === 'LWO2' ) {

			this.parser = new LWO2Parser( this );
			while ( ! this.reader.endOfFile() ) this.parser.parseBlock();

		} else if ( this.tree.format === 'LWO3' ) {

			this.parser = new LWO3Parser( this );
			while ( ! this.reader.endOfFile() ) this.parser.parseBlock();

		}

		this.debugger.offset = this.reader.offset;
		this.debugger.closeForms();

		return this.tree;

	},

	parseTopForm() {

		this.debugger.offset = this.reader.offset;

		var topForm = this.reader.getIDTag();

		if ( topForm !== 'FORM' ) {

			console.warn( "LWOLoader: Top-level FORM missing." );
			return;

		}

		var length = this.reader.getUint32();

		this.debugger.dataOffset = this.reader.offset;
		this.debugger.length = length;

		var type = this.reader.getIDTag();

		if ( type === 'LWO2' ) {

			this.tree.format = type;

		} else if ( type === 'LWO3' ) {

			this.tree.format = type;

		}

		this.debugger.node = 0;
		this.debugger.nodeID = type;
		this.debugger.log();

		return;

	},


	///
	// FORM PARSING METHODS
	///

	// Forms are organisational and can contain any number of sub chunks and sub forms
	// FORM ::= 'FORM'[ID4], length[U4], type[ID4], ( chunk[CHUNK] | form[FORM] ) * }
	parseForm( length ) {

		var type = this.reader.getIDTag();

		switch ( type ) {

			// SKIPPED FORMS
			// if skipForm( length ) is called, the entire form and any sub forms and chunks are skipped

			case 'ISEQ': // Image sequence
			case 'ANIM': // plug in animation
			case 'STCC': // Color-cycling Still
			case 'VPVL':
			case 'VPRM':
			case 'NROT':
			case 'WRPW': // image wrap w ( for cylindrical and spherical projections)
			case 'WRPH': // image wrap h
			case 'FUNC':
			case 'FALL':
			case 'OPAC':
			case 'GRAD': // gradient texture
			case 'ENVS':
			case 'VMOP':
			case 'VMBG':

			// Car Material FORMS
			case 'OMAX':
			case 'STEX':
			case 'CKBG':
			case 'CKEY':
			case 'VMLA':
			case 'VMLB':
				this.debugger.skipped = true;
				this.skipForm( length ); // not currently supported
				break;

			// if break; is called directly, the position in the lwoTree is not created
			// any sub chunks and forms are added to the parent form instead
			case 'META':
			case 'NNDS':
			case 'NODS':
			case 'NDTA':
			case 'ADAT':
			case 'AOVS':
			case 'BLOK':

			// used by texture nodes
			case 'IBGC': // imageBackgroundColor
			case 'IOPC': // imageOpacity
			case 'IIMG': // hold reference to image path
			case 'TXTR':
				// this.setupForm( type, length );
				this.debugger.length = 4;
				this.debugger.skipped = true;
				break;

			case 'IFAL': // imageFallof
			case 'ISCL': // imageScale
			case 'IPOS': // imagePosition
			case 'IROT': // imageRotation
			case 'IBMP':
			case 'IUTD':
			case 'IVTD':
				this.parseTextureNodeAttribute( type );
				break;

			case 'ENVL':
				this.parseEnvelope( length );
				break;

				// CLIP FORM AND SUB FORMS

			case 'CLIP':
				if ( this.tree.format === 'LWO2' ) {

					this.parseForm( length );

				} else {

					this.parseClip( length );

				}
				break;

			case 'STIL':
				this.parseImage();
				break;

			case 'XREF': // clone of another STIL
				this.reader.skip( 8 ); // unknown
				this.currentForm.referenceTexture = {
					index: this.reader.getUint32(),
					refName: this.reader.getString() // internal unique ref
				};
				break;

				// Not in spec, used by texture nodes

			case 'IMST':
				this.parseImageStateForm( length );
				break;

				// SURF FORM AND SUB FORMS

			case 'SURF':
				this.parseSurfaceForm( length );
				break;

			case 'VALU': // Not in spec
				this.parseValueForm( length );
				break;

			case 'NTAG':
				this.parseSubNode( length );
				break;

			case 'ATTR': // BSDF Node Attributes
			case 'SATR': // Standard Node Attributes
				this.setupForm( 'attributes', length );
				break;

			case 'NCON':
				this.parseConnections( length );
				break;

			case 'SSHA':
				this.parentForm = this.currentForm;
				this.currentForm = this.currentSurface;
				this.setupForm( 'surfaceShader', length );
				break;

			case 'SSHD':
				this.setupForm( 'surfaceShaderData', length );
				break;

			case 'ENTR': // Not in spec
				this.parseEntryForm( length );
				break;

				// Image Map Layer

			case 'IMAP':
				this.parseImageMap( length );
				break;

			case 'TAMP':
				this.parseXVAL( 'amplitude', length );
				break;

				//Texture Mapping Form

			case 'TMAP':
				this.setupForm( 'textureMap', length );
				break;

			case 'CNTR':
				this.parseXVAL3( 'center', length );
				break;

			case 'SIZE':
				this.parseXVAL3( 'scale', length );
				break;

			case 'ROTA':
				this.parseXVAL3( 'rotation', length );
				break;

			default:
				this.parseUnknownForm( type, length );

		}

		this.debugger.node = 0;
		this.debugger.nodeID = type;
		this.debugger.log();

	},

	setupForm( type, length ) {

		if ( ! this.currentForm ) this.currentForm = this.currentNode;

		this.currentFormEnd = this.reader.offset + length;
		this.parentForm = this.currentForm;

		if ( ! this.currentForm[ type ] ) {

			this.currentForm[ type ] = {};
			this.currentForm = this.currentForm[ type ];


		} else {

			// should never see this unless there's a bug in the reader
			console.warn( 'LWOLoader: form already exists on parent: ', type, this.currentForm );

			this.currentForm = this.currentForm[ type ];

		}


	},

	skipForm( length ) {

		this.reader.skip( length - 4 );

	},

	parseUnknownForm( type, length ) {

		console.warn( 'LWOLoader: unknown FORM encountered: ' + type, length );

		printBuffer( this.reader.dv.buffer, this.reader.offset, length - 4 );
		this.reader.skip( length - 4 );

	},

	parseSurfaceForm( length ) {

		this.reader.skip( 8 ); // unknown Uint32 x2

		var name = this.reader.getString();

		var surface = {
			attributes: {}, // LWO2 style non-node attributes will go here
			connections: {},
			name: name,
			inputName: name,
			nodes: {},
			source: this.reader.getString(),
		};

		this.tree.materials[ name ] = surface;
		this.currentSurface = surface;

		this.parentForm = this.tree.materials;
		this.currentForm = surface;
		this.currentFormEnd = this.reader.offset + length;

	},

	parseSurfaceLwo2( length ) {

		var name = this.reader.getString();

		var surface = {
			attributes: {}, // LWO2 style non-node attributes will go here
			connections: {},
			name: name,
			nodes: {},
			source: this.reader.getString(),
		};

		this.tree.materials[ name ] = surface;
		this.currentSurface = surface;

		this.parentForm = this.tree.materials;
		this.currentForm = surface;
		this.currentFormEnd = this.reader.offset + length;

	},

	parseSubNode( length ) {

		// parse the NRNM CHUNK of the subnode FORM to get
		// a meaningful name for the subNode
		// some subnodes can be renamed, but Input and Surface cannot

		this.reader.skip( 8 ); // NRNM + length
		var name = this.reader.getString();

		var node = {
			name: name
		};
		this.currentForm = node;
		this.currentNode = node;

		this.currentFormEnd = this.reader.offset + length;


	},

	// collect attributes from all nodes at the top level of a surface
	parseConnections( length ) {

		this.currentFormEnd = this.reader.offset + length;
		this.parentForm = this.currentForm;

		this.currentForm = this.currentSurface.connections;

	},

	// surface node attribute data, e.g. specular, roughness etc
	parseEntryForm( length ) {

		this.reader.skip( 8 ); // NAME + length
		var name = this.reader.getString();
		this.currentForm = this.currentNode.attributes;

		this.setupForm( name, length );

	},

	// parse values from material - doesn't match up to other LWO3 data types
	// sub form of entry form
	parseValueForm() {

		this.reader.skip( 8 ); // unknown + length

		var valueType = this.reader.getString();

		if ( valueType === 'double' ) {

			this.currentForm.value = this.reader.getUint64();

		} else if ( valueType === 'int' ) {

			this.currentForm.value = this.reader.getUint32();

		} else if ( valueType === 'vparam' ) {

			this.reader.skip( 24 );
			this.currentForm.value = this.reader.getFloat64();

		} else if ( valueType === 'vparam3' ) {

			this.reader.skip( 24 );
			this.currentForm.value = this.reader.getFloat64Array( 3 );

		}

	},

	// holds various data about texture node image state
	// Data other thanmipMapLevel unknown
	parseImageStateForm() {

		this.reader.skip( 8 ); // unknown

		this.currentForm.mipMapLevel = this.reader.getFloat32();

	},

	// LWO2 style image data node OR LWO3 textures defined at top level in editor (not as SURF node)
	parseImageMap( length ) {

		this.currentFormEnd = this.reader.offset + length;
		this.parentForm = this.currentForm;

		if ( ! this.currentForm.maps ) this.currentForm.maps = [];

		var map = {};
		this.currentForm.maps.push( map );
		this.currentForm = map;

		this.reader.skip( 10 ); // unknown, could be an issue if it contains a VX

	},

	parseTextureNodeAttribute( type ) {

		this.reader.skip( 28 ); // FORM + length + VPRM + unknown + Uint32 x2 + float32

		this.reader.skip( 20 ); // FORM + length + VPVL + float32 + Uint32

		switch ( type ) {

			case 'ISCL':
				this.currentNode.scale = this.reader.getFloat32Array( 3 );
				break;
			case 'IPOS':
				this.currentNode.position = this.reader.getFloat32Array( 3 );
				break;
			case 'IROT':
				this.currentNode.rotation = this.reader.getFloat32Array( 3 );
				break;
			case 'IFAL':
				this.currentNode.falloff = this.reader.getFloat32Array( 3 );
				break;

			case 'IBMP':
				this.currentNode.amplitude = this.reader.getFloat32();
				break;
			case 'IUTD':
				this.currentNode.uTiles = this.reader.getFloat32();
				break;
			case 'IVTD':
				this.currentNode.vTiles = this.reader.getFloat32();
				break;

		}

		this.reader.skip( 2 ); // unknown


	},

	// ENVL forms are currently ignored
	parseEnvelope( length ) {

		this.reader.skip( length - 4 ); // skipping  entirely for now

	},

	///
	// CHUNK PARSING METHODS
	///

	// clips can either be defined inside a surface node, or at the top
	// level and they have a different format in each case
	parseClip( length ) {

		var tag = this.reader.getIDTag();

		// inside surface node
		if ( tag === 'FORM' ) {

			this.reader.skip( 16 );

			this.currentNode.fileName = this.reader.getString();

			return;

		}

		// otherwise top level
		this.reader.setOffset( this.reader.offset - 4 );

		this.currentFormEnd = this.reader.offset + length;
		this.parentForm = this.currentForm;

		this.reader.skip( 8 ); // unknown

		var texture = {
			index: this.reader.getUint32()
		};
		this.tree.textures.push( texture );
		this.currentForm = texture;

	},

	parseClipLwo2( length ) {

		var texture = {
			index: this.reader.getUint32(),
			fileName: ""
		};

		// seach STIL block
		while ( true ) {

			var tag = this.reader.getIDTag();
			var n_length = this.reader.getUint16();
			if ( tag === 'STIL' ) {

				texture.fileName = this.reader.getString();
				break;

			}

			if ( n_length >= length ) {

				break;

			}

		}

		this.tree.textures.push( texture );
		this.currentForm = texture;

	},

	parseImage() {

		this.reader.skip( 8 ); // unknown
		this.currentForm.fileName = this.reader.getString();

	},

	parseXVAL( type, length ) {

		var endOffset = this.reader.offset + length - 4;
		this.reader.skip( 8 );

		this.currentForm[ type ] = this.reader.getFloat32();

		this.reader.setOffset( endOffset ); // set end offset directly to skip optional envelope

	},

	parseXVAL3( type, length ) {

		var endOffset = this.reader.offset + length - 4;
		this.reader.skip( 8 );

		this.currentForm[ type ] = {
			x: this.reader.getFloat32(),
			y: this.reader.getFloat32(),
			z: this.reader.getFloat32(),
		};

		this.reader.setOffset( endOffset );

	},

	// Tags associated with an object
	// OTAG { type[ID4], tag-string[S0] }
	parseObjectTag() {

		if ( ! this.tree.objectTags ) this.tree.objectTags = {};

		this.tree.objectTags[ this.reader.getIDTag() ] = {
			tagString: this.reader.getString()
		};

	},

	// Signals the start of a new layer. All the data chunks which follow will be included in this layer until another layer chunk is encountered.
	// LAYR: number[U2], flags[U2], pivot[VEC12], name[S0], parent[U2]
	parseLayer( length ) {

		var layer = {
			number: this.reader.getUint16(),
			flags: this.reader.getUint16(), // If the least significant bit of flags is set, the layer is hidden.
			pivot: this.reader.getFloat32Array( 3 ), // Note: this seems to be superflous, as the geometry is translated when pivot is present
			name: this.reader.getString(),
		};

		this.tree.layers.push( layer );
		this.currentLayer = layer;

		var parsedLength = 16 + stringOffset( this.currentLayer.name ); // index ( 2 ) + flags( 2 ) + pivot( 12 ) + stringlength

		// if we have not reached then end of the layer block, there must be a parent defined
		this.currentLayer.parent = ( parsedLength < length ) ? this.reader.getUint16() : - 1; // omitted or -1 for no parent

	},

	// VEC12 * ( F4 + F4 + F4 ) array of x,y,z vectors
	// Converting from left to right handed coordinate system:
	// x -> -x and switch material FrontSide -> BackSide
	parsePoints( length ) {

		this.currentPoints = [];
		for ( var i = 0; i < length / 4; i += 3 ) {

			// z -> -z to match three.js right handed coords
			this.currentPoints.push( this.reader.getFloat32(), this.reader.getFloat32(), - this.reader.getFloat32() );

		}

	},

	// parse VMAP or VMAD
	// Associates a set of floating-point vectors with a set of points.
	// VMAP: { type[ID4], dimension[U2], name[S0], ( vert[VX], value[F4] # dimension ) * }

	// VMAD Associates a set of floating-point vectors with the vertices of specific polygons.
	// Similar to VMAP UVs, but associates with polygon vertices rather than points
	// to solve to problem of UV seams:  VMAD chunks are paired with VMAPs of the same name,
	// if they exist. The vector values in the VMAD will then replace those in the
	// corresponding VMAP, but only for calculations involving the specified polygons.
	// VMAD { type[ID4], dimension[U2], name[S0], ( vert[VX], poly[VX], value[F4] # dimension ) * }
	parseVertexMapping( length, discontinuous ) {

		var finalOffset = this.reader.offset + length;

		var channelName = this.reader.getString();

		if ( this.reader.offset === finalOffset ) {

			// then we are in a texture node and the VMAP chunk is just a reference to a UV channel name
			this.currentForm.UVChannel = channelName;
			return;

		}

		// otherwise reset to initial length and parse normal VMAP CHUNK
		this.reader.setOffset( this.reader.offset - stringOffset( channelName ) );

		var type = this.reader.getIDTag();

		this.reader.getUint16(); // dimension
		var name = this.reader.getString();

		var remainingLength = length - 6 - stringOffset( name );

		switch ( type ) {

			case 'TXUV':
				this.parseUVMapping( name, finalOffset, discontinuous );
				break;
			case 'MORF':
			case 'SPOT':
				this.parseMorphTargets( name, finalOffset, type ); // can't be discontinuous
				break;
			// unsupported VMAPs
			case 'APSL':
			case 'NORM':
			case 'WGHT':
			case 'MNVW':
			case 'PICK':
			case 'RGB ':
			case 'RGBA':
				this.reader.skip( remainingLength );
				break;
			default:
				console.warn( 'LWOLoader: unknown vertex map type: ' + type );
				this.reader.skip( remainingLength );

		}

	},

	parseUVMapping( name, finalOffset, discontinuous ) {

		var uvIndices = [];
		var polyIndices = [];
		var uvs = [];

		while ( this.reader.offset < finalOffset ) {

			uvIndices.push( this.reader.getVariableLengthIndex() );

			if ( discontinuous ) polyIndices.push( this.reader.getVariableLengthIndex() );

			uvs.push( this.reader.getFloat32(), this.reader.getFloat32() );

		}

		if ( discontinuous ) {

			if ( ! this.currentLayer.discontinuousUVs ) this.currentLayer.discontinuousUVs = {};

			this.currentLayer.discontinuousUVs[ name ] = {
				uvIndices: uvIndices,
				polyIndices: polyIndices,
				uvs: uvs,
			};

		} else {

			if ( ! this.currentLayer.uvs ) this.currentLayer.uvs = {};

			this.currentLayer.uvs[ name ] = {
				uvIndices: uvIndices,
				uvs: uvs,
			};

		}

	},

	parseMorphTargets( name, finalOffset, type ) {

		var indices = [];
		var points = [];

		type = ( type === 'MORF' ) ? 'relative' : 'absolute';

		while ( this.reader.offset < finalOffset ) {

			indices.push( this.reader.getVariableLengthIndex() );
			// z -> -z to match three.js right handed coords
			points.push( this.reader.getFloat32(), this.reader.getFloat32(), - this.reader.getFloat32() );

		}

		if ( ! this.currentLayer.morphTargets ) this.currentLayer.morphTargets = {};

		this.currentLayer.morphTargets[ name ] = {
			indices: indices,
			points: points,
			type: type,
		};

	},

	// A list of polygons for the current layer.
	// POLS { type[ID4], ( numvert+flags[U2], vert[VX] # numvert ) * }
	parsePolygonList( length ) {

		var finalOffset = this.reader.offset + length;
		var type = this.reader.getIDTag();

		var indices = [];

		// hold a list of polygon sizes, to be split up later
		var polygonDimensions = [];

		while ( this.reader.offset < finalOffset ) {

			var numverts = this.reader.getUint16();

			//var flags = numverts & 64512; // 6 high order bits are flags - ignoring for now
			numverts = numverts & 1023; // remaining ten low order bits are vertex num
			polygonDimensions.push( numverts );

			for ( var j = 0; j < numverts; j ++ ) indices.push( this.reader.getVariableLengthIndex() );

		}

		var geometryData = {
			type: type,
			vertexIndices: indices,
			polygonDimensions: polygonDimensions,
			points: this.currentPoints
		};

		// Note: assuming that all polys will be lines or points if the first is
		if ( polygonDimensions[ 0 ] === 1 ) geometryData.type = 'points';
		else if ( polygonDimensions[ 0 ] === 2 ) geometryData.type = 'lines';

		this.currentLayer.geometry = geometryData;

	},

	// Lists the tag strings that can be associated with polygons by the PTAG chunk.
	// TAGS { tag-string[S0] * }
	parseTagStrings( length ) {

		this.tree.tags = this.reader.getStringArray( length );

	},

	// Associates tags of a given type with polygons in the most recent POLS chunk.
	// PTAG { type[ID4], ( poly[VX], tag[U2] ) * }
	parsePolygonTagMapping( length ) {

		var finalOffset = this.reader.offset + length;
		var type = this.reader.getIDTag();
		if ( type === 'SURF' ) this.parseMaterialIndices( finalOffset );
		else { //PART, SMGP, COLR not supported

			this.reader.skip( length - 4 );

		}

	},

	parseMaterialIndices( finalOffset ) {

		// array holds polygon index followed by material index
		this.currentLayer.geometry.materialIndices = [];

		while ( this.reader.offset < finalOffset ) {

			var polygonIndex = this.reader.getVariableLengthIndex();
			var materialIndex = this.reader.getUint16();

			this.currentLayer.geometry.materialIndices.push( polygonIndex, materialIndex );

		}

	},

	parseUnknownCHUNK( blockID, length ) {

		console.warn( 'LWOLoader: unknown chunk type: ' + blockID + ' length: ' + length );

		// print the chunk plus some bytes padding either side
		// printBuffer( this.reader.dv.buffer, this.reader.offset - 20, length + 40 );

		var data = this.reader.getString( length );

		this.currentForm[ blockID ] = data;

	}

};

function DataViewReader( buffer ) {

	this.dv = new DataView( buffer );
	this.offset = 0;

}

DataViewReader.prototype = {

	constructor: DataViewReader,

	size: function () {

		return this.dv.buffer.byteLength;

	},

	setOffset( offset ) {

		if ( offset > 0 && offset < this.dv.buffer.byteLength ) {

			this.offset = offset;

		} else {

			console.error( 'LWOLoader: invalid buffer offset' );

		}

	},

	endOfFile: function () {

		if ( this.offset >= this.size() ) return true;
		return false;

	},

	skip: function ( length ) {

		this.offset += length;

	},

	getUint8: function () {

		var value = this.dv.getUint8( this.offset );
		this.offset += 1;
		return value;

	},

	getUint16: function () {

		var value = this.dv.getUint16( this.offset );
		this.offset += 2;
		return value;

	},

	getInt32: function () {

		var value = this.dv.getInt32( this.offset, false );
		this.offset += 4;
		return value;

	},

	getUint32: function () {

		var value = this.dv.getUint32( this.offset, false );
		this.offset += 4;
		return value;

	},

	getUint64: function () {

		var low, high;

		high = this.getUint32();
		low = this.getUint32();
		return high * 0x100000000 + low;

	},

	getFloat32: function () {

		var value = this.dv.getFloat32( this.offset, false );
		this.offset += 4;
		return value;

	},

	getFloat32Array: function ( size ) {

		var a = [];

		for ( var i = 0; i < size; i ++ ) {

			a.push( this.getFloat32() );

		}

		return a;

	},

	getFloat64: function () {

		var value = this.dv.getFloat64( this.offset, this.littleEndian );
		this.offset += 8;
		return value;

	},

	getFloat64Array: function ( size ) {

		var a = [];

		for ( var i = 0; i < size; i ++ ) {

			a.push( this.getFloat64() );

		}

		return a;

	},

	// get variable-length index data type
	// VX ::= index[U2] | (index + 0xFF000000)[U4]
	// If the index value is less than 65,280 (0xFF00),then VX === U2
	// otherwise VX === U4 with bits 24-31 set
	// When reading an index, if the first byte encountered is 255 (0xFF), then
	// the four-byte form is being used and the first byte should be discarded or masked out.
	getVariableLengthIndex() {

		var firstByte = this.getUint8();

		if ( firstByte === 255 ) {

			return this.getUint8() * 65536 + this.getUint8() * 256 + this.getUint8();

		}

		return firstByte * 256 + this.getUint8();

	},

	// An ID tag is a sequence of 4 bytes containing 7-bit ASCII values
	getIDTag() {

		return this.getString( 4 );

	},

	getString: function ( size ) {

		if ( size === 0 ) return;

		// note: safari 9 doesn't support Uint8Array.indexOf; create intermediate array instead
		var a = [];

		if ( size ) {

			for ( var i = 0; i < size; i ++ ) {

				a[ i ] = this.getUint8();

			}

		} else {

			var currentChar;
			var len = 0;

			while ( currentChar !== 0 ) {

				currentChar = this.getUint8();
				if ( currentChar !== 0 ) a.push( currentChar );
				len ++;

			}

			if ( ! isEven( len + 1 ) ) this.getUint8(); // if string with terminating nullbyte is uneven, extra nullbyte is added

		}

		return LoaderUtils.decodeText( new Uint8Array( a ) );

	},

	getStringArray: function ( size ) {

		var a = this.getString( size );
		a = a.split( '\0' );

		return a.filter( Boolean ); // return array with any empty strings removed

	}

};

// ************** DEBUGGER  **************

function Debugger( ) {

	this.active = false;
	this.depth = 0;
	this.formList = [];

}

Debugger.prototype = {

	constructor: Debugger,

	enable: function () {

		this.active = true;

	},

	log: function () {

		if ( ! this.active ) return;

		var nodeType;

		switch ( this.node ) {

			case 0:
				nodeType = "FORM";
				break;

			case 1:
				nodeType = "CHK";
				break;

			case 2:
				nodeType = "S-CHK";
				break;

		}

		console.log(
			"| ".repeat( this.depth ) +
			nodeType,
			this.nodeID,
			`( ${this.offset} ) -> ( ${this.dataOffset + this.length} )`,
			( ( this.node == 0 ) ? " {" : "" ),
			( ( this.skipped ) ? "SKIPPED" : "" ),
			( ( this.node == 0 && this.skipped ) ? "}" : "" )
		);

		if ( this.node == 0 && ! this.skipped ) {

			this.depth += 1;
			this.formList.push( this.dataOffset + this.length );

		}

		this.skipped = false;

	},

	closeForms: function () {

		if ( ! this.active ) return;

		for ( var i = this.formList.length - 1; i >= 0; i -- ) {

			if ( this.offset >= this.formList[ i ] ) {

				this.depth -= 1;
				console.log( "| ".repeat( this.depth ) + "}" );
				this.formList.splice( - 1, 1 );

			}

		}

	}

};

// ************** UTILITY FUNCTIONS **************

function isEven( num ) {

	return num % 2;

}

// calculate the length of the string in the buffer
// this will be string.length + nullbyte + optional padbyte to make the length even
function stringOffset( string ) {

	return string.length + 1 + ( isEven( string.length + 1 ) ? 1 : 0 );

}

// for testing purposes, dump buffer to console
// printBuffer( this.reader.dv.buffer, this.reader.offset, length );
function printBuffer( buffer, from, to ) {

	console.log( LoaderUtils.decodeText( new Uint8Array( buffer, from, to ) ) );

}

var lwoTree;

var LWOLoader = function ( manager, parameters ) {

	Loader.call( this, manager );

	parameters = parameters || {};

	this.resourcePath = ( parameters.resourcePath !== undefined ) ? parameters.resourcePath : '';

};

LWOLoader.prototype = Object.assign( Object.create( Loader.prototype ), {

	constructor: LWOLoader,

	load: function ( url, onLoad, onProgress, onError ) {

		var self = this;

		var path = ( self.path === '' ) ? extractParentUrl( url, 'Objects' ) : self.path;

		// give the mesh a default name based on the filename
		var modelName = url.split( path ).pop().split( '.' )[ 0 ];

		var loader = new FileLoader( this.manager );
		loader.setPath( self.path );
		loader.setResponseType( 'arraybuffer' );

		loader.load( url, function ( buffer ) {

			// console.time( 'Total parsing: ' );
			onLoad( self.parse( buffer, path, modelName ) );
			// console.timeEnd( 'Total parsing: ' );

		}, onProgress, onError );

	},

	parse: function ( iffBuffer, path, modelName ) {

		lwoTree = new IFFParser().parse( iffBuffer );

		// console.log( 'lwoTree', lwoTree );

		var textureLoader = new TextureLoader( this.manager ).setPath( this.resourcePath || path ).setCrossOrigin( this.crossOrigin );

		return new LWOTreeParser( textureLoader ).parse( modelName );

	}

} );

// Parse the lwoTree object
function LWOTreeParser( textureLoader ) {

	this.textureLoader = textureLoader;

}

LWOTreeParser.prototype = {

	constructor: LWOTreeParser,

	parse: function ( modelName ) {

		this.materials = new MaterialParser( this.textureLoader ).parse();
		this.defaultLayerName = modelName;

		this.meshes = this.parseLayers();

		return {
			materials: this.materials,
			meshes: this.meshes,
		};

	},

	parseLayers() {

		// array of all meshes for building hierarchy
		var meshes = [];

		// final array containing meshes with scene graph hierarchy set up
		var finalMeshes = [];

		var geometryParser = new GeometryParser();

		var self = this;
		lwoTree.layers.forEach( function ( layer ) {

			var geometry = geometryParser.parse( layer.geometry, layer );

			var mesh = self.parseMesh( geometry, layer );

			meshes[ layer.number ] = mesh;

			if ( layer.parent === - 1 ) finalMeshes.push( mesh );
			else meshes[ layer.parent ].add( mesh );


		} );

		this.applyPivots( finalMeshes );

		return finalMeshes;

	},

	parseMesh( geometry, layer ) {

		var mesh;

		var materials = this.getMaterials( geometry.userData.matNames, layer.geometry.type );

		this.duplicateUVs( geometry, materials );

		if ( layer.geometry.type === 'points' ) mesh = new Points( geometry, materials );
		else if ( layer.geometry.type === 'lines' ) mesh = new LineSegments( geometry, materials );
		else mesh = new Mesh( geometry, materials );

		if ( layer.name ) mesh.name = layer.name;
		else mesh.name = this.defaultLayerName + '_layer_' + layer.number;

		mesh.userData.pivot = layer.pivot;

		return mesh;

	},

	// TODO: may need to be reversed in z to convert LWO to three.js coordinates
	applyPivots( meshes ) {

		meshes.forEach( function ( mesh ) {

			mesh.traverse( function ( child ) {

				var pivot = child.userData.pivot;

				child.position.x += pivot[ 0 ];
				child.position.y += pivot[ 1 ];
				child.position.z += pivot[ 2 ];

				if ( child.parent ) {

					var parentPivot = child.parent.userData.pivot;

					child.position.x -= parentPivot[ 0 ];
					child.position.y -= parentPivot[ 1 ];
					child.position.z -= parentPivot[ 2 ];

				}

			} );

		} );

	},

	getMaterials( namesArray, type ) {

		var materials = [];

		var self = this;

		namesArray.forEach( function ( name, i ) {

			materials[ i ] = self.getMaterialByName( name );

		} );

		// convert materials to line or point mats if required
		if ( type === 'points' || type === 'lines' ) {

			materials.forEach( function ( mat, i ) {

				var spec = {
					color: mat.color,
				};

				if ( type === 'points' ) {

					spec.size = 0.1;
					spec.map = mat.map;
					spec.morphTargets = mat.morphTargets;
					materials[ i ] = new PointsMaterial( spec );

				} else if ( type === 'lines' ) {

					materials[ i ] = new LineBasicMaterial( spec );

				}

			} );

		}

		// if there is only one material, return that directly instead of array
		var filtered = materials.filter( Boolean );
		if ( filtered.length === 1 ) return filtered[ 0 ];

		return materials;

	},

	getMaterialByName( name ) {

		return this.materials.filter( function ( m ) {

			return m.name === name;

		} )[ 0 ];

	},

	// If the material has an aoMap, duplicate UVs
	duplicateUVs( geometry, materials ) {

		var duplicateUVs = false;

		if ( ! Array.isArray( materials ) ) {

			if ( materials.aoMap ) duplicateUVs = true;

		} else {

			materials.forEach( function ( material ) {

				if ( material.aoMap ) duplicateUVs = true;

			} );

		}

		if ( ! duplicateUVs ) return;

		geometry.setAttribute( 'uv2', new BufferAttribute( geometry.attributes.uv.array, 2 ) );

	},

};

function MaterialParser( textureLoader ) {

	this.textureLoader = textureLoader;

}

MaterialParser.prototype = {

	constructor: MaterialParser,

	parse: function () {

		var materials = [];
		this.textures = {};

		for ( var name in lwoTree.materials ) {

			if ( lwoTree.format === 'LWO3' ) {

				materials.push( this.parseMaterial( lwoTree.materials[ name ], name, lwoTree.textures ) );

			} else if ( lwoTree.format === 'LWO2' ) {

				materials.push( this.parseMaterialLwo2( lwoTree.materials[ name ], name, lwoTree.textures ) );

			}

		}

		return materials;

	},

	parseMaterial( materialData, name, textures ) {

		var params = {
			name: name,
			side: this.getSide( materialData.attributes ),
			flatShading: this.getSmooth( materialData.attributes ),
		};

		var connections = this.parseConnections( materialData.connections, materialData.nodes );

		var maps = this.parseTextureNodes( connections.maps );

		this.parseAttributeImageMaps( connections.attributes, textures, maps, materialData.maps );

		var attributes = this.parseAttributes( connections.attributes, maps );

		this.parseEnvMap( connections, maps, attributes );

		params = Object.assign( maps, params );
		params = Object.assign( params, attributes );

		var materialType = this.getMaterialType( connections.attributes );

		return new materialType( params );

	},

	parseMaterialLwo2( materialData, name/*, textures*/ ) {

		var params = {
			name: name,
			side: this.getSide( materialData.attributes ),
			flatShading: this.getSmooth( materialData.attributes ),
		};

		var attributes = this.parseAttributes( materialData.attributes, {} );
		params = Object.assign( params, attributes );
		return new MeshPhongMaterial( params );

	},

	// Note: converting from left to right handed coords by switching x -> -x in vertices, and
	// then switching mat FrontSide -> BackSide
	// NB: this means that FrontSide and BackSide have been switched!
	getSide( attributes ) {

		if ( ! attributes.side ) return BackSide;

		switch ( attributes.side ) {

			case 0:
			case 1:
				return BackSide;
			case 2: return FrontSide;
			case 3: return DoubleSide;

		}

	},

	getSmooth( attributes ) {

		if ( ! attributes.smooth ) return true;
		return ! attributes.smooth;

	},

	parseConnections( connections, nodes ) {

		var materialConnections = {
			maps: {}
		};

		var inputName = connections.inputName;
		var inputNodeName = connections.inputNodeName;
		var nodeName = connections.nodeName;

		var self = this;
		inputName.forEach( function ( name, index ) {

			if ( name === 'Material' ) {

				var matNode = self.getNodeByRefName( inputNodeName[ index ], nodes );
				materialConnections.attributes = matNode.attributes;
				materialConnections.envMap = matNode.fileName;
				materialConnections.name = inputNodeName[ index ];

			}

		} );

		nodeName.forEach( function ( name, index ) {

			if ( name === materialConnections.name ) {

				materialConnections.maps[ inputName[ index ] ] = self.getNodeByRefName( inputNodeName[ index ], nodes );

			}

		} );

		return materialConnections;

	},

	getNodeByRefName( refName, nodes ) {

		for ( var name in nodes ) {

			if ( nodes[ name ].refName === refName ) return nodes[ name ];

		}

	},

	parseTextureNodes( textureNodes ) {

		var maps = {};

		for ( var name in textureNodes ) {

			var node = textureNodes[ name ];
			var path = node.fileName;

			if ( ! path ) return;

			var texture = this.loadTexture( path );

			if ( node.widthWrappingMode !== undefined ) texture.wrapS = this.getWrappingType( node.widthWrappingMode );
			if ( node.heightWrappingMode !== undefined ) texture.wrapT = this.getWrappingType( node.heightWrappingMode );

			switch ( name ) {

				case 'Color':
					maps.map = texture;
					break;
				case 'Roughness':
					maps.roughnessMap = texture;
					maps.roughness = 0.5;
					break;
				case 'Specular':
					maps.specularMap = texture;
					maps.specular = 0xffffff;
					break;
				case 'Luminous':
					maps.emissiveMap = texture;
					maps.emissive = 0x808080;
					break;
				case 'Luminous Color':
					maps.emissive = 0x808080;
					break;
				case 'Metallic':
					maps.metalnessMap = texture;
					maps.metalness = 0.5;
					break;
				case 'Transparency':
				case 'Alpha':
					maps.alphaMap = texture;
					maps.transparent = true;
					break;
				case 'Normal':
					maps.normalMap = texture;
					if ( node.amplitude !== undefined ) maps.normalScale = new Vector2( node.amplitude, node.amplitude );
					break;
				case 'Bump':
					maps.bumpMap = texture;
					break;

			}

		}

		// LWO BSDF materials can have both spec and rough, but this is not valid in three
		if ( maps.roughnessMap && maps.specularMap ) delete maps.specularMap;

		return maps;

	},

	// maps can also be defined on individual material attributes, parse those here
	// This occurs on Standard (Phong) surfaces
	parseAttributeImageMaps( attributes, textures, maps ) {

		for ( var name in attributes ) {

			var attribute = attributes[ name ];

			if ( attribute.maps ) {

				var mapData = attribute.maps[ 0 ];

				var path = this.getTexturePathByIndex( mapData.imageIndex, textures );
				if ( ! path ) return;

				var texture = this.loadTexture( path );

				if ( mapData.wrap !== undefined ) texture.wrapS = this.getWrappingType( mapData.wrap.w );
				if ( mapData.wrap !== undefined ) texture.wrapT = this.getWrappingType( mapData.wrap.h );

				switch ( name ) {

					case 'Color':
						maps.map = texture;
						break;
					case 'Diffuse':
						maps.aoMap = texture;
						break;
					case 'Roughness':
						maps.roughnessMap = texture;
						maps.roughness = 1;
						break;
					case 'Specular':
						maps.specularMap = texture;
						maps.specular = 0xffffff;
						break;
					case 'Luminosity':
						maps.emissiveMap = texture;
						maps.emissive = 0x808080;
						break;
					case 'Metallic':
						maps.metalnessMap = texture;
						maps.metalness = 1;
						break;
					case 'Transparency':
					case 'Alpha':
						maps.alphaMap = texture;
						maps.transparent = true;
						break;
					case 'Normal':
						maps.normalMap = texture;
						break;
					case 'Bump':
						maps.bumpMap = texture;
						break;

				}

			}

		}

	},

	parseAttributes( attributes, maps ) {

		var params = {};

		// don't use color data if color map is present
		if ( attributes.Color && ! maps.map ) {

			params.color = new Color().fromArray( attributes.Color.value );

		} else params.color = new Color();


		if ( attributes.Transparency && attributes.Transparency.value !== 0 ) {

			params.opacity = 1 - attributes.Transparency.value;
			params.transparent = true;

		}

		if ( attributes[ 'Bump Height' ] ) params.bumpScale = attributes[ 'Bump Height' ].value * 0.1;

		if ( attributes[ 'Refraction Index' ] ) params.refractionRatio = 1 / attributes[ 'Refraction Index' ].value;

		this.parsePhysicalAttributes( params, attributes, maps );
		this.parseStandardAttributes( params, attributes, maps );
		this.parsePhongAttributes( params, attributes, maps );

		return params;

	},

	parsePhysicalAttributes( params, attributes/*, maps*/ ) {

		if ( attributes.Clearcoat && attributes.Clearcoat.value > 0 ) {

			params.clearcoat = attributes.Clearcoat.value;

			if ( attributes[ 'Clearcoat Gloss' ] ) {

				params.clearcoatRoughness = 0.5 * ( 1 - attributes[ 'Clearcoat Gloss' ].value );

			}

		}

	},

	parseStandardAttributes( params, attributes, maps ) {


		if ( attributes.Luminous ) {

			params.emissiveIntensity = attributes.Luminous.value;

			if ( attributes[ 'Luminous Color' ] && ! maps.emissive ) {

				params.emissive = new Color().fromArray( attributes[ 'Luminous Color' ].value );

			} else {

				params.emissive = new Color( 0x808080 );

			}

		}

		if ( attributes.Roughness && ! maps.roughnessMap ) params.roughness = attributes.Roughness.value;
		if ( attributes.Metallic && ! maps.metalnessMap ) params.metalness = attributes.Metallic.value;

	},

	parsePhongAttributes( params, attributes, maps ) {

		if ( attributes.Diffuse ) params.color.multiplyScalar( attributes.Diffuse.value );

		if ( attributes.Reflection ) {

			params.reflectivity = attributes.Reflection.value;
			params.combine = AddOperation;

		}

		if ( attributes.Luminosity ) {

			params.emissiveIntensity = attributes.Luminosity.value;

			if ( ! maps.emissiveMap && ! maps.map ) {

				params.emissive = params.color;

			} else {

				params.emissive = new Color( 0x808080 );

			}

		}

		// parse specular if there is no roughness - we will interpret the material as 'Phong' in this case
		if ( ! attributes.Roughness && attributes.Specular && ! maps.specularMap ) {

			if ( attributes[ 'Color Highlight' ] ) {

				params.specular = new Color().setScalar( attributes.Specular.value ).lerp( params.color.clone().multiplyScalar( attributes.Specular.value ), attributes[ 'Color Highlight' ].value );

			} else {

				params.specular = new Color().setScalar( attributes.Specular.value );

			}

		}

		if ( params.specular && attributes.Glossiness ) params.shininess = 7 + Math.pow( 2, attributes.Glossiness.value * 12 + 2 );

	},

	parseEnvMap( connections, maps, attributes ) {

		if ( connections.envMap ) {

			var envMap = this.loadTexture( connections.envMap );

			if ( attributes.transparent && attributes.opacity < 0.999 ) {

				envMap.mapping = EquirectangularRefractionMapping;

				// Reflectivity and refraction mapping don't work well together in Phong materials
				if ( attributes.reflectivity !== undefined ) {

					delete attributes.reflectivity;
					delete attributes.combine;

				}

				if ( attributes.metalness !== undefined ) {

					delete attributes.metalness;

				}

			} else envMap.mapping = EquirectangularReflectionMapping;

			maps.envMap = envMap;

		}

	},

	// get texture defined at top level by its index
	getTexturePathByIndex( index ) {

		var fileName = '';

		if ( ! lwoTree.textures ) return fileName;

		lwoTree.textures.forEach( function ( texture ) {

			if ( texture.index === index ) fileName = texture.fileName;

		} );

		return fileName;

	},

	loadTexture( path ) {

		if ( ! path ) return null;

		var texture;

		texture = this.textureLoader.load(
			path,
			undefined,
			undefined,
			function () {

				console.warn( 'LWOLoader: non-standard resource hierarchy. Use \`resourcePath\` parameter to specify root content directory.' );

			}
		);

		return texture;

	},

	// 0 = Reset, 1 = Repeat, 2 = Mirror, 3 = Edge
	getWrappingType( num ) {

		switch ( num ) {

			case 0:
				console.warn( 'LWOLoader: "Reset" texture wrapping type is not supported in three.js' );
				return ClampToEdgeWrapping;
			case 1: return RepeatWrapping;
			case 2: return MirroredRepeatWrapping;
			case 3: return ClampToEdgeWrapping;

		}

	},

	getMaterialType( nodeData ) {

		if ( nodeData.Clearcoat && nodeData.Clearcoat.value > 0 ) return MeshPhysicalMaterial;
		if ( nodeData.Roughness ) return MeshStandardMaterial;
		return MeshPhongMaterial;

	}

};

function GeometryParser() {}

GeometryParser.prototype = {

	constructor: GeometryParser,

	parse( geoData, layer ) {

		var geometry = new BufferGeometry();

		geometry.setAttribute( 'position', new Float32BufferAttribute( geoData.points, 3 ) );

		var indices = this.splitIndices( geoData.vertexIndices, geoData.polygonDimensions );
		geometry.setIndex( indices );

		this.parseGroups( geometry, geoData );

		geometry.computeVertexNormals();

		this.parseUVs( geometry, layer, indices );
		this.parseMorphTargets( geometry, layer, indices );

		// TODO: z may need to be reversed to account for coordinate system change
		geometry.translate( - layer.pivot[ 0 ], - layer.pivot[ 1 ], - layer.pivot[ 2 ] );

		// var userData = geometry.userData;
		// geometry = geometry.toNonIndexed()
		// geometry.userData = userData;

		return geometry;

	},

	// split quads into tris
	splitIndices( indices, polygonDimensions ) {

		var remappedIndices = [];

		var i = 0;
		polygonDimensions.forEach( function ( dim ) {

			if ( dim < 4 ) {

				for ( var k = 0; k < dim; k ++ ) remappedIndices.push( indices[ i + k ] );

			} else if ( dim === 4 ) {

				remappedIndices.push(
					indices[ i ],
					indices[ i + 1 ],
					indices[ i + 2 ],

					indices[ i ],
					indices[ i + 2 ],
					indices[ i + 3 ]

				);

			} else if ( dim > 4 ) {

				for ( var k = 1; k < dim - 1; k ++ ) {

					remappedIndices.push( indices[ i ], indices[ i + k ], indices[ i + k + 1 ] );

				}

				console.warn( 'LWOLoader: polygons with greater than 4 sides are not supported' );

			}

			i += dim;

		} );

		return remappedIndices;

	},

	// NOTE: currently ignoring poly indices and assuming that they are intelligently ordered
	parseGroups( geometry, geoData ) {

		var tags = lwoTree.tags;
		var matNames = [];

		var elemSize = 3;
		if ( geoData.type === 'lines' ) elemSize = 2;
		if ( geoData.type === 'points' ) elemSize = 1;

		var remappedIndices = this.splitMaterialIndices( geoData.polygonDimensions, geoData.materialIndices );

		var indexNum = 0; // create new indices in numerical order
		var indexPairs = {}; // original indices mapped to numerical indices

		var prevMaterialIndex;

		var prevStart = 0;
		var currentCount = 0;

		for ( var i = 0; i < remappedIndices.length; i += 2 ) {

			var materialIndex = remappedIndices[ i + 1 ];

			if ( i === 0 ) matNames[ indexNum ] = tags[ materialIndex ];

			if ( prevMaterialIndex === undefined ) prevMaterialIndex = materialIndex;

			if ( materialIndex !== prevMaterialIndex ) {

				var currentIndex;
				if ( indexPairs[ tags[ prevMaterialIndex ] ] ) {

					currentIndex = indexPairs[ tags[ prevMaterialIndex ] ];

				} else {

					currentIndex = indexNum;
					indexPairs[ tags[ prevMaterialIndex ] ] = indexNum;
					matNames[ indexNum ] = tags[ prevMaterialIndex ];
					indexNum ++;

				}

				geometry.addGroup( prevStart, currentCount, currentIndex );

				prevStart += currentCount;

				prevMaterialIndex = materialIndex;
				currentCount = 0;

			}

			currentCount += elemSize;

		}

		// the loop above doesn't add the last group, do that here.
		if ( geometry.groups.length > 0 ) {

			var currentIndex;
			if ( indexPairs[ tags[ materialIndex ] ] ) {

				currentIndex = indexPairs[ tags[ materialIndex ] ];

			} else {

				currentIndex = indexNum;
				indexPairs[ tags[ materialIndex ] ] = indexNum;
				matNames[ indexNum ] = tags[ materialIndex ];

			}

			geometry.addGroup( prevStart, currentCount, currentIndex );

		}

		// Mat names from TAGS chunk, used to build up an array of materials for this geometry
		geometry.userData.matNames = matNames;

	},

	splitMaterialIndices( polygonDimensions, indices ) {

		var remappedIndices = [];

		polygonDimensions.forEach( function ( dim, i ) {

			if ( dim <= 3 ) {

				remappedIndices.push( indices[ i * 2 ], indices[ i * 2 + 1 ] );

			} else if ( dim === 4 ) {

				remappedIndices.push( indices[ i * 2 ], indices[ i * 2 + 1 ], indices[ i * 2 ], indices[ i * 2 + 1 ] );

			} else {

				 // ignore > 4 for now
				for ( var k = 0; k < dim - 2; k ++ ) {

					remappedIndices.push( indices[ i * 2 ], indices[ i * 2 + 1 ] );

				}

			}

		} );

		return remappedIndices;

	},

	// UV maps:
	// 1: are defined via index into an array of points, not into a geometry
	// - the geometry is also defined by an index into this array, but the indexes may not match
	// 2: there can be any number of UV maps for a single geometry. Here these are combined,
	// 	with preference given to the first map encountered
	// 3: UV maps can be partial - that is, defined for only a part of the geometry
	// 4: UV maps can be VMAP or VMAD (discontinuous, to allow for seams). In practice, most
	// UV maps are defined as partially VMAP and partially VMAD
	// VMADs are currently not supported
	parseUVs( geometry, layer ) {

		// start by creating a UV map set to zero for the whole geometry
		var remappedUVs = Array.from( Array( geometry.attributes.position.count * 2 ), function () {

			return 0;

		} );

		for ( var name in layer.uvs ) {

			var uvs = layer.uvs[ name ].uvs;
			var uvIndices = layer.uvs[ name ].uvIndices;

			uvIndices.forEach( function ( i, j ) {

				remappedUVs[ i * 2 ] = uvs[ j * 2 ];
				remappedUVs[ i * 2 + 1 ] = uvs[ j * 2 + 1 ];

			} );

		}

		geometry.setAttribute( 'uv', new Float32BufferAttribute( remappedUVs, 2 ) );

	},

	parseMorphTargets( geometry, layer ) {

		var num = 0;
		for ( var name in layer.morphTargets ) {

			var remappedPoints = geometry.attributes.position.array.slice();

			if ( ! geometry.morphAttributes.position ) geometry.morphAttributes.position = [];

			var morphPoints = layer.morphTargets[ name ].points;
			var morphIndices = layer.morphTargets[ name ].indices;
			var type = layer.morphTargets[ name ].type;

			morphIndices.forEach( function ( i, j ) {

				if ( type === 'relative' ) {

					remappedPoints[ i * 3 ] += morphPoints[ j * 3 ];
					remappedPoints[ i * 3 + 1 ] += morphPoints[ j * 3 + 1 ];
					remappedPoints[ i * 3 + 2 ] += morphPoints[ j * 3 + 2 ];

				} else {

					remappedPoints[ i * 3 ] = morphPoints[ j * 3 ];
					remappedPoints[ i * 3 + 1 ] = morphPoints[ j * 3 + 1 ];
					remappedPoints[ i * 3 + 2 ] = morphPoints[ j * 3 + 2 ];

				}

			} );

			geometry.morphAttributes.position[ num ] = new Float32BufferAttribute( remappedPoints, 3 );
			geometry.morphAttributes.position[ num ].name = name;

			num ++;

		}

		geometry.morphTargetsRelative = false;

	},

};


// ************** UTILITY FUNCTIONS **************

function extractParentUrl( url, dir ) {

	var index = url.indexOf( dir );

	if ( index === - 1 ) return './';

	return url.substr( 0, index );

}

export { LWOLoader };