XFileParser.cs 42.2 KB
Newer Older
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
// Open Asset Import Library (assimp)
//
// Copyright (c) 2006-2016, assimp team, 2018, The openBVE Project
// All rights reserved.
//
// Redistribution and use of this software in source and binary forms,
// with or without modification, are permitted provided that the
// following conditions are met:
//
// * Redistributions of source code must retain the above
//   copyright notice, this list of conditions and the
//   following disclaimer.
//
// * Redistributions in binary form must reproduce the above
//   copyright notice, this list of conditions and the
//   following disclaimer in the documentation and/or other
//   materials provided with the distribution.
//
// * Neither the name of the assimp team, nor the names of its
//   contributors may be used to endorse or promote products
//   derived from this software without specific prior
//   written permission of the assimp team.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
//
//
// ******************************************************************************
//
// AN EXCEPTION applies to all files in the ./test/models-nonbsd folder.
// These are 3d models for testing purposes, from various free sources
// on the internet. They are - unless otherwise stated - copyright of
// their respective creators, which may impose additional requirements
// on the use of their work. For any of these models, see
// <model-name>.source.txt for more legal information. Contact us if you
// are a copyright holder and believe that we credited you inproperly or
// if you don't want your files to appear in the repository.
//
//
// ******************************************************************************
//
// Poly2Tri Copyright (c) 2009-2010, Poly2Tri Contributors
// http://code.google.com/p/poly2tri/
//
// All rights reserved.
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice,
//   this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright notice,
//   this list of conditions and the following disclaimer in the documentation
//   and/or other materials provided with the distribution.
// * Neither the name of Poly2Tri nor the names of its contributors may be
//   used to endorse or promote products derived from this software without specific
//   prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
// LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Diagnostics;
using System.Globalization;
using OpenTK;
using OpenTK.Graphics;
using ZlibWithDictionary;
using VectorKey = System.Collections.Generic.KeyValuePair<double, OpenTK.Vector3>;
using QuatKey = System.Collections.Generic.KeyValuePair<double, OpenTK.Quaternion>;
using MatrixKey = System.Collections.Generic.KeyValuePair<double, OpenTK.Matrix4>;

94
namespace AssimpNET.X
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
{
	public class XFileParser
	{
		// Magic identifier for MSZIP compressed data
		private const uint MSZIP_MAGIC = 0x4B43;
		private const uint MSZIP_BLOCK = 32786;

		private readonly byte[] Buffer;

		protected uint MajorVersion, MinorVersion; // version numbers
		protected readonly bool IsBinaryFormat; // true if the file is in binary, false if it's in text form
		protected readonly uint BinaryFloatSize; // float size in bytes, either 4 or 8
		// counter for number arrays in binary format
		protected uint BinaryNumCount;

		protected int P;
		protected int End;

		/// Line number when reading in text format
		protected uint LineNumber;

		/// Imported data
		protected Scene Scene;

		// Constructor. Creates a data structure out of the XFile given in the memory block.
		public XFileParser(byte[] buffer)
		{
			Buffer = buffer;
			MajorVersion = MinorVersion = 0;
			IsBinaryFormat = false;
			BinaryNumCount = 0;
			P = End = -1;
			LineNumber = 0;
			Scene = null;

			// set up memory pointers
			P = 0;
			//End = P + Buffer.Length - 1;
			End = P + Buffer.Length;

			// check header
			if (Buffer.Length < 16)
			{
				throw new Exception("Header mismatch, file is not an XFile.");
			}

			ASCIIEncoding Ascii = new ASCIIEncoding();
			string header = new string(Ascii.GetChars(Buffer, 0, 12));

			if (header.Substring(0, 4) != "xof ")
			{
				throw new Exception("Header mismatch, file is not an XFile.");
			}

			// read version. It comes in a four byte format such as "0302"
			MajorVersion = (uint)(Buffer[4] - 48) * 10 + (uint)(Buffer[5] - 48);
			MinorVersion = (uint)(Buffer[6] - 48) * 10 + (uint)(Buffer[7] - 48);

			bool compressed = false;

			// txt - pure ASCII text format
			if (header.Substring(8, 4) == "txt ")
			{
				IsBinaryFormat = false;
			}
			// bin - Binary format
			else if (header.Substring(8, 4) == "bin ")
			{
				IsBinaryFormat = true;
			}
			// tzip - Inflate compressed text format
			else if (header.Substring(8, 4) == "tzip")
			{
				IsBinaryFormat = false;
				compressed = true;
			}
			// bzip - Inflate compressed binary format
			else if (header.Substring(8, 4) == "bzip")
			{
				IsBinaryFormat = true;
				compressed = true;
			}
			else
			{
				throw new Exception("Unsupported xfile format '" + header.Substring(8, 4) + "'");
			}

			// float size
			BinaryFloatSize = (uint)(Buffer[12] - 48) * 1000 + (uint)(Buffer[13] - 48) * 100 + (uint)(Buffer[14] - 48) * 10 + (uint)(Buffer[15] - 48);

			if (BinaryFloatSize != 32 && BinaryFloatSize != 64)
			{
				throw new Exception("Unknown float size " + BinaryFloatSize + " specified in xfile header.");
			}

			// The x format specifies size in bits, but we work in bytes
			BinaryFloatSize /= 8;

			P += 16;

			// If this is a compressed X file, apply the inflate algorithm to it
			if (compressed)
			{
				/* ///////////////////////////////////////////////////////////////////////
				 * COMPRESSED X FILE FORMAT
				 * ///////////////////////////////////////////////////////////////////////
				 *    [xhead]
				 *    2 major
				 *    2 minor
				 *    4 type    // bzip,tzip
				 *    [mszip_master_head]
				 *    4 unkn    // checksum?
				 *    2 unkn    // flags? (seems to be constant)
				 *    [mszip_head]
				 *    2 ofs     // offset to next section
				 *    2 magic   // 'CK'
				 *    ... ofs bytes of data
				 *    ... next mszip_head
				 *
				 *  http://www.kdedevelopers.org/node/3181 has been very helpful.
				 * ///////////////////////////////////////////////////////////////////////
				 */

				// Read file size after decompression excluding header
				uint uncompressedFinalSize = BitConverter.ToUInt32(Buffer, P) - 16;
				P += 4;

				// Preparing for decompression
				MemoryStream inputStream = new MemoryStream(Buffer);
				MemoryStream outputStream = new MemoryStream();
				int currentBlock = 0;
				byte[] previousBlockBytes = new byte[(int)MSZIP_BLOCK];
				byte[] blockBytes;
				while (P + 3 < End)
				{
					// Read compressed block size after decompression
					ushort uncompressedBlockSize = BitConverter.ToUInt16(Buffer, P);
					P += 2;

					// Read compressed block size
					ushort compressedBlockSize = BitConverter.ToUInt16(Buffer, P);
					P += 2;

					// Check compressed block size
					if (compressedBlockSize > MSZIP_BLOCK)
					{
						throw new Exception("Compressed block size is larger than MSZIP standard.");
					}

					if (P + compressedBlockSize > End + 2)
					{
						throw new Exception("X: Unexpected EOF in compressed chunk");
					}

					// Check MSZIP signature of compressed block
					ushort signature = BitConverter.ToUInt16(Buffer, P);

					if (signature != MSZIP_MAGIC)
					{
						throw new Exception("The compressed block's signature is incorrect.");
					}

					// Skip MSZIP signature
					inputStream.Position = P + 2;

					// Decompress the compressed block
					blockBytes = new byte[compressedBlockSize - 2];
					inputStream.Read(blockBytes, 0, compressedBlockSize - 2);
					byte[] decompressedBytes;

					if (currentBlock == 0)
					{
						decompressedBytes = DeflateCompression.ZlibDecompressWithDictionary(blockBytes, null);
					}
					else
					{
						decompressedBytes = DeflateCompression.ZlibDecompressWithDictionary(blockBytes, previousBlockBytes);
					}

					outputStream.Write(decompressedBytes, 0, decompressedBytes.Length);
					previousBlockBytes = decompressedBytes;

					// Preparing to move to the next data block
					P += compressedBlockSize;
					currentBlock++;
				}

				// ok, update pointers to point to the uncompressed file data
				Buffer = outputStream.ToArray();
				P = 0;
				End = Buffer.Length;

				if (Buffer.Length != uncompressedFinalSize)
				{
					throw new Exception("The size after uncompression is incorrect.");
				}
			}
			else
			{
				// start reading here
				ReadUntilEndOfLine();
			}

			Scene = new Scene();
			ParseFile();

			// filter the imported hierarchy for some degenerated cases
			if (Scene.RootNode != null)
			{
				FilterHierarchy(Scene.RootNode);
			}
		}

		/** Returns the temporary representation of the imported data */
		public Scene GetImportedData()
		{
			return Scene;
		}

		protected void ParseFile()
		{
			while (true)
			{
				// read name of next object
				string objectName = GetNextToken();
				if (objectName.Length == 0)
				{
					break;
				}

				switch (objectName.ToLowerInvariant())
				{
					// parse specific object
					case "template":
						ParseDataObjectTemplate();
						break;
					case "frame":
						ParseDataObjectFrame(null);
						break;
					case "mesh":
						{
							// some meshes have no frames at all
							Mesh mesh;
							ParseDataObjectMesh(out mesh);
							Scene.GlobalMeshes.Add(mesh);
							break;
						}
					case "animtickspersecond":
						ParseDataObjectAnimTicksPerSecond();
						break;
					case "animationset":
						ParseDataObjectAnimationSet();
						break;
					case "material":
						{
							// Material outside of a mesh or node
							Material material;
							ParseDataObjectMaterial(out material);
							Scene.GlobalMaterials.Add(material);
							break;
						}
					case "}":
						// whatever?
						Debug.WriteLine("} found in dataObject");
						break;
					default:
						// unknown format
						Debug.WriteLine("Unknown data object in animation of .x file");
						ParseUnknownDataObject();
						break;
				}
			}
		}

		protected void ParseDataObjectTemplate()
		{
			// parse a template data object. Currently not stored.
			// ReSharper disable once NotAccessedVariable
			string name;
			ReadHeadOfDataObject(out name);

			// read GUID
			string guid = GetNextToken();

			// read and ignore data members
			while (true)
			{
				string s = GetNextToken();

				if (s == "}")
				{
					break;
				}

				if (s.Length == 0)
				{
					ThrowException("Unexpected end of file reached while parsing template definition");
				}
			}
		}

		protected void ParseDataObjectFrame(Node parent)
		{
			// A coordinate frame, or "frame of reference." The Frame template
			// is open and can contain any object. The Direct3D extensions (D3DX)
			// mesh-loading functions recognize Mesh, FrameTransformMatrix, and
			// Frame template instances as child objects when loading a Frame
			// instance.
			string name;
			ReadHeadOfDataObject(out name);

			// create a named node and place it at its parent, if given
			Node node = new Node(parent);
			node.Name = name;

			if (parent != null)
			{
				parent.Children.Add(node);
			}
			else
			{
				// there might be multiple root nodes
				if (Scene.RootNode != null)
				{
					// place a dummy root if not there
					if (Scene.RootNode.Name != "$dummy_root")
					{
						Node exroot = Scene.RootNode;
						Scene.RootNode = new Node();
						Scene.RootNode.Name = "$dummy_root";
						Scene.RootNode.Children.Add(exroot);
						exroot.Parent = Scene.RootNode;
					}
					// put the new node as its child instead
					Scene.RootNode.Children.Add(node);
					node.Parent = Scene.RootNode;
				}
				else
				{
					// it's the first node imported. place it as root
					Scene.RootNode = node;
				}
			}

			// Now inside a frame.
			// read tokens until closing brace is reached.
			bool frameFinished = false;
			while (true)
			{
				string objectName = GetNextToken();
				if (objectName.Length == 0)
				{
					ThrowException("Unexpected end of file reached while parsing frame");
				}

				switch (objectName.ToLowerInvariant())
				{
					case "}":
						frameFinished = true;
						break;
					case "frame":
						ParseDataObjectFrame(node); // child frame
						break;
					case "frametransformmatrix":
						ParseDataObjectTransformationMatrix(out node.TrafoMatrix);
						break;
					case "mesh":
						{
							Mesh mesh;
							ParseDataObjectMesh(out mesh);
							node.Meshes.Add(mesh);
							break;
						}
					default:
						Debug.WriteLine("Unknown data object in frame in x file");
						ParseUnknownDataObject();
						break;
				}

				if (frameFinished)
				{
					break;
				}
			}
		}

		protected void ParseDataObjectTransformationMatrix(out Matrix4 matrix)
		{
			// read header, we're not interested if it has a name
			ReadHeadOfDataObject();

			// read its components
			matrix = new Matrix4();
			matrix.M11 = ReadFloat();
			matrix.M21 = ReadFloat();
			matrix.M31 = ReadFloat();
			matrix.M41 = ReadFloat();
			matrix.M12 = ReadFloat();
			matrix.M22 = ReadFloat();
			matrix.M32 = ReadFloat();
			matrix.M42 = ReadFloat();
			matrix.M13 = ReadFloat();
			matrix.M23 = ReadFloat();
			matrix.M33 = ReadFloat();
			matrix.M43 = ReadFloat();
			matrix.M14 = ReadFloat();
			matrix.M24 = ReadFloat();
			matrix.M34 = ReadFloat();
			matrix.M44 = ReadFloat();

			// trailing symbols
			CheckForSemicolon();
			CheckForClosingBrace();
		}

		protected void ParseDataObjectMesh(out Mesh mesh)
		{
			mesh = new Mesh();

			// ReSharper disable once NotAccessedVariable
			string name;
			ReadHeadOfDataObject(out name);

			// read vertex count
			uint numVertices = ReadInt();
			mesh.Positions = new List<Vector3>((int)numVertices);

			// read vertices
			for (int a = 0; a < (int)numVertices; a++)
			{
				mesh.Positions.Add(ReadVector3());
			}

			if ((int) numVertices == 0)
			{
				TestForSeparator();
			}

			// read position faces
			uint numPosFaces = ReadInt();
			mesh.PosFaces = new List<Face>((int)numPosFaces);
			for (int a = 0; a < (int)numPosFaces; a++)
			{
				// read indices
				uint numIndices = ReadInt();
				Face face = new Face();
				for (int b = 0; b < (int)numIndices; b++)
				{
					face.Indices.Add(ReadInt());
				}
				mesh.PosFaces.Add(face);
				TestForSeparator();
			}

			if ((int) numPosFaces == 0)
			{
				TestForSeparator();
			}

			// here, other data objects may follow
			bool meshFinished = false;
			while (true)
			{
				string objectName = GetNextToken();
				switch (objectName.ToLowerInvariant())
				{
					case "":
						ThrowException("Unexpected end of file while parsing mesh structure");
						break;
					case "}":
						meshFinished = true;
						break;
					case "meshnormals":
						ParseDataObjectMeshNormals(ref mesh);
						break;
					case "meshtexturecoords":
						ParseDataObjectMeshTextureCoords(ref mesh);
						break;
					case "meshvertexcolors":
						ParseDataObjectMeshVertexColors(ref mesh);
						break;
					case "meshmateriallist":
						ParseDataObjectMeshMaterialList(ref mesh);
						break;
					case "vertexduplicationindices":
						ParseUnknownDataObject(); // we'll ignore vertex duplication indices
						break;
					case "xskinmeshheader":
						ParseDataObjectSkinMeshHeader(ref mesh);
						break;
					case "skinweights":
						ParseDataObjectSkinWeights(ref mesh);
						break;
					default:
						Debug.WriteLine("Unknown data object in mesh in x file");
						ParseUnknownDataObject();
						break;
				}
				if (meshFinished)
				{
					break;
				}
			}
		}

		protected void ParseDataObjectSkinWeights(ref Mesh mesh)
		{
			ReadHeadOfDataObject();

			string transformNodeName;
			GetNextTokenAsString(out transformNodeName);

			Bone bone = new Bone();
			bone.Name = transformNodeName;

			// read vertex weights
			uint numWeights = ReadInt();
			bone.Weights = new List<BoneWeight>((int)numWeights);

			for (int a = 0; a < (int)numWeights; a++)
			{
				BoneWeight weight = new BoneWeight();
				weight.Vertex = ReadInt();
				bone.Weights.Add(weight);
			}

			// read vertex weights
			for (int a = 0; a < (int)numWeights; a++)
			{
				bone.Weights[a].Weight = ReadFloat();
			}

			// read matrix offset
			bone.OffsetMatrix.M11 = ReadFloat();
			bone.OffsetMatrix.M21 = ReadFloat();
			bone.OffsetMatrix.M31 = ReadFloat();
			bone.OffsetMatrix.M41 = ReadFloat();
			bone.OffsetMatrix.M12 = ReadFloat();
			bone.OffsetMatrix.M22 = ReadFloat();
			bone.OffsetMatrix.M32 = ReadFloat();
			bone.OffsetMatrix.M42 = ReadFloat();
			bone.OffsetMatrix.M13 = ReadFloat();
			bone.OffsetMatrix.M23 = ReadFloat();
			bone.OffsetMatrix.M33 = ReadFloat();
			bone.OffsetMatrix.M43 = ReadFloat();
			bone.OffsetMatrix.M14 = ReadFloat();
			bone.OffsetMatrix.M24 = ReadFloat();
			bone.OffsetMatrix.M34 = ReadFloat();
			bone.OffsetMatrix.M44 = ReadFloat();

			mesh.Bones.Add(bone);

			CheckForSemicolon();
			CheckForClosingBrace();
		}

		protected void ParseDataObjectSkinMeshHeader(ref Mesh mesh)
		{
			ReadHeadOfDataObject();

			/*unsigned int maxSkinWeightsPerVertex =*/
			ReadInt();
			/*unsigned int maxSkinWeightsPerFace =*/
			ReadInt();
			/*unsigned int numBonesInMesh = */
			ReadInt();

			CheckForClosingBrace();
		}

		protected void ParseDataObjectMeshNormals(ref Mesh mesh)
		{
			ReadHeadOfDataObject();

			// read count
			uint numNormals = ReadInt();
			mesh.Normals = new List<Vector3>((int)numNormals);

			// read normal vectors
			for (int a = 0; a < (int)numNormals; a++)
			{
				mesh.Normals.Add(ReadVector3());
			}

			if ((int) numNormals == 0)
			{
				TestForSeparator();
			}

			// read normal indices
			uint numFaces = ReadInt();
			if (numFaces != (uint)mesh.PosFaces.Count)
			{
				ThrowException("Normal face count does not match vertex face count.");
			}

			for (int a = 0; a < (int)numFaces; a++)
			{
				uint numIndices = ReadInt();
				Face face = new Face();

				for (int b = 0; b < (int)numIndices; b++)
				{
					face.Indices.Add(ReadInt());
				}
				mesh.NormFaces.Add(face);

				TestForSeparator();
			}

			if ((int) numFaces == 0)
			{
				TestForSeparator();
			}
			CheckForClosingBrace();
		}

		protected void ParseDataObjectMeshTextureCoords(ref Mesh mesh)
		{
			ReadHeadOfDataObject();

			if (mesh.NumTextures + 1 > Mesh.AI_MAX_NUMBER_OF_TEXTURECOORDS)
			{
				ThrowException("Too many sets of texture coordinates");
			}

			uint numCoords = ReadInt();
			if (numCoords != mesh.Positions.Count)
			{
				ThrowException("Texture coord count does not match vertex count");
			}

			List<Vector2> coords = new List<Vector2>((int)numCoords);
			for (int a = 0; a < (int)numCoords; a++)
			{
				coords.Add(ReadVector2());
			}
			mesh.TexCoords[(int)mesh.NumTextures++] = coords;

			if ((int) numCoords == 0)
			{
				TestForSeparator();
			}
			CheckForClosingBrace();
		}

		protected void ParseDataObjectMeshVertexColors(ref Mesh mesh)
		{
			ReadHeadOfDataObject();
			if (mesh.NumColorSets + 1 > Mesh.AI_MAX_NUMBER_OF_COLOR_SETS)
			{
				ThrowException("Too many colorsets");
			}

			uint numColors = ReadInt();
			if (numColors != mesh.Positions.Count)
			{
				ThrowException("Vertex color count does not match vertex count");
			}

			List<Color4> colors = Enumerable.Repeat(new Color4(0.0f, 0.0f, 0.0f, 1.0f), (int)numColors).ToList();
			for (int a = 0; a < (int)numColors; a++)
			{
				uint index = ReadInt();
				if (index >= mesh.Positions.Count)
				{
					ThrowException("Vertex color index out of bounds");
				}
				colors[(int)index] = ReadRGBA();
				// HACK: (thom) Maxon Cinema XPort plugin puts a third separator here, kwxPort puts a comma.
				// Ignore gracefully.
				if (!IsBinaryFormat)
				{
					FindNextNoneWhiteSpace();
					if (Buffer[P] == ';' || Buffer[P] == ',')
					{
						P++;
					}
				}
			}
			mesh.Colors[(int)mesh.NumColorSets++] = colors;

			if ((int) numColors == 0)
			{
				TestForSeparator();
			}
			CheckForClosingBrace();
		}

		protected void ParseDataObjectMeshMaterialList(ref Mesh mesh)
		{
			ReadHeadOfDataObject();

			// read material count
			/*unsigned int numMaterials =*/
			ReadInt();
			// read non triangulated face material index count
			uint numMatIndices = ReadInt();

			// some models have a material index count of 1... to be able to read them we
			// replicate this single material index on every face
			if (numMatIndices != mesh.PosFaces.Count && numMatIndices != 1)
			{
				ThrowException("Per-Face material index count does not match face count.");
			}

			// read per-face material indices
			for (int a = 0; a < (int)numMatIndices; a++)
			{
				mesh.FaceMaterials.Add(ReadInt());
			}

			// in version 03.02, the face indices end with two semicolons.
			// commented out version check, as version 03.03 exported from blender also has 2 semicolons
			if (!IsBinaryFormat) // && MajorVersion == 3 && MinorVersion <= 2)
			{
				if (P < End && Buffer[P] == ';')
				{
					++P;
				}
			}

			// if there was only a single material index, replicate it on all faces
			while (mesh.FaceMaterials.Count < mesh.PosFaces.Count)
			{
				mesh.FaceMaterials.Add(mesh.FaceMaterials.First());
			}

			// read following data objects
			while (true)
			{
				string objectName = GetNextToken();
				if (objectName.Length == 0)
				{
					ThrowException("Unexpected end of file while parsing mesh material list.");
				}
				else if (objectName == "}")
				{
					break; // material list finished
				}
				else if (objectName == "{")
				{
					// template materials
					string matName = GetNextToken();
					Material material = new Material();
					material.IsReference = true;
					material.Name = matName;
					mesh.Materials.Add(material);

					CheckForClosingBrace(); // skip }
				}
				else if (objectName == "Material")
				{
					Material material;
					ParseDataObjectMaterial(out material);
					mesh.Materials.Add(material);
				}
				else if (objectName == ";")
				{
					// ignore
				}
				else
				{
					Debug.WriteLine("Unknown data object in material list in x file");
					ParseUnknownDataObject();
				}
			}
		}

		protected void ParseDataObjectMaterial(out Material material)
		{
			material = new Material();

			string matName;
			ReadHeadOfDataObject(out matName);
			if (matName.Length == 0)
			{
				matName = "material" + LineNumber;
			}
			material.Name = matName;
			material.IsReference = false;

			// read material values
			material.Diffuse = ReadRGBA();
			material.SpecularExponent = ReadFloat();
			material.Specular = ReadRGB();
			material.Emissive = ReadRGB();

			// read other data objects
			while (true)
			{
				string objectName = GetNextToken();
				if (objectName.Length == 0)
				{
					ThrowException("Unexpected end of file while parsing mesh material");
				}
				else if (objectName == "}")
				{
					break; // material finished
				}
				else if (objectName == "TextureFilename" || objectName == "TextureFileName")
				{
					// some exporters write "TextureFileName" instead.
					string texname;
					ParseDataObjectTextureFilename(out texname);
					material.Textures.Add(new TexEntry(texname));
				}
				else if (objectName == "NormalmapFilename" || objectName == "NormalmapFileName")
				{
					// one exporter writes out the normal map in a separate filename tag
					string texname;
					ParseDataObjectTextureFilename(out texname);
					material.Textures.Add(new TexEntry(texname, true));
				}
				else
				{
					Debug.WriteLine("Unknown data object in material in x file");
					ParseUnknownDataObject();
				}
			}
		}

		protected void ParseDataObjectAnimTicksPerSecond()
		{
			ReadHeadOfDataObject();
			Scene.AnimTicksPerSecond = ReadInt();
			CheckForClosingBrace();
		}

		protected void ParseDataObjectAnimationSet()
		{
			string animName;
			ReadHeadOfDataObject(out animName);

			Animation anim = new Animation();
			anim.Name = animName;

			while (true)
			{
				string objectName = GetNextToken();
				if (objectName.Length == 0)
				{
					ThrowException("Unexpected end of file while parsing animation set.");
				}
				else if (objectName == "}")
				{
					break; // animation set finished
				}
				else if (objectName == "Animation")
				{
					ParseDataObjectAnimation(ref anim);
				}
				else
				{
					Debug.WriteLine("Unknown data object in animation set in x file");
					ParseUnknownDataObject();
				}
			}

			Scene.Anims.Add(anim);
		}

		protected void ParseDataObjectAnimation(ref Animation anim)
		{
			ReadHeadOfDataObject();
			AnimBone banim = new AnimBone();

			while (true)
			{
				string objectName = GetNextToken();

				if (objectName.Length == 0)
				{
					ThrowException("Unexpected end of file while parsing animation.");
				}
				else if (objectName == "}")
				{
					break; // animation finished
				}
				else if (objectName == "AnimationKey")
				{
					ParseDataObjectAnimationKey(ref banim);
				}
				else if (objectName == "AnimationOptions")
				{
					ParseUnknownDataObject(); // not interested
				}
				else if (objectName == "{")
				{
					// read frame name
					banim.BoneName = GetNextToken();
					CheckForClosingBrace();
				}
				else
				{
					Debug.WriteLine("Unknown data object in animation in x file");
					ParseUnknownDataObject();
				}
			}

			anim.Anims.Add(banim);
		}

		protected void ParseDataObjectAnimationKey(ref AnimBone animBone)
		{
			ReadHeadOfDataObject();

			// read key type
			uint keyType = ReadInt();

			// read number of keys
			uint numKeys = ReadInt();

			for (int a = 0; a < (int)numKeys; a++)
			{
				// read time
				uint time = ReadInt();

				// read keys
				switch (keyType)
				{
					case 0: // rotation quaternion
						{
							// read count
							if (ReadInt() != 4)
							{
								ThrowException("Invalid number of arguments for quaternion key in animation");
							}
							Quaternion quat = new Quaternion();
							quat.W = ReadFloat();
							quat.X = ReadFloat();
							quat.Y = ReadFloat();
							quat.Z = ReadFloat();

							QuatKey key = new QuatKey((double)time, quat);
							animBone.RotKeys.Add(key);

							CheckForSemicolon();
						}
						break;
					case 1: // scale vector
					case 2: // position vector
						{
							// read count
							if (ReadInt() != 3)
							{
								ThrowException("Invalid number of arguments for vector key in animation");
							}
							VectorKey key = new VectorKey((double)time, ReadVector3());

							if (keyType == 2)
							{
								animBone.PosKeys.Add(key);
							}
							else
							{
								animBone.ScaleKeys.Add(key);
							}
						}
						break;
					case 3: // combined transformation matrix
					case 4: // denoted both as 3 or as 4
						{
							// read count
							if (ReadInt() != 16)
							{
								ThrowException("Invalid number of arguments for matrix key in animation");
							}

							// read matrix
							Matrix4 matrix = new Matrix4();
							matrix.M11 = ReadFloat();
							matrix.M21 = ReadFloat();
							matrix.M31 = ReadFloat();
							matrix.M41 = ReadFloat();
							matrix.M12 = ReadFloat();
							matrix.M22 = ReadFloat();
							matrix.M32 = ReadFloat();
							matrix.M42 = ReadFloat();
							matrix.M13 = ReadFloat();
							matrix.M23 = ReadFloat();
							matrix.M33 = ReadFloat();
							matrix.M43 = ReadFloat();
							matrix.M14 = ReadFloat();
							matrix.M24 = ReadFloat();
							matrix.M34 = ReadFloat();
							matrix.M44 = ReadFloat();

							MatrixKey key = new MatrixKey((double)time, matrix);
							animBone.TrafoKeys.Add(key);

							CheckForSemicolon();
						}
						break;
					default:
						ThrowException("Unknown key type " + keyType + " in animation.");
						break;
				} // end switch

				// key separator
				CheckForSeparator();
			}

			CheckForClosingBrace();
		}

		protected void ParseDataObjectTextureFilename(out string name)
		{
			ReadHeadOfDataObject();
			GetNextTokenAsString(out name);
			CheckForClosingBrace();

			// FIX: some files (e.g. AnimationTest.x) have "" as texture file name
			if (name.Length == 0)
			{
				Debug.WriteLine("Length of texture file name is zero. Skipping this texture.");
			}

			// some exporters write double backslash paths out. We simply replace them if we find them
			name = name.Replace("\\\\", "\\");
		}

		protected void ParseUnknownDataObject()
		{
			// find opening delimiter
			while (true)
			{
				string t = GetNextToken();
				if (t.Length == 0)
				{
					ThrowException("Unexpected end of file while parsing unknown segment.");
				}

				if (t == "{")
				{
					break;
				}
			}

			uint counter = 1;

			// parse until closing delimiter
			while (counter > 0)
			{
				string t = GetNextToken();
				if (t.Length == 0)
				{
					ThrowException("Unexpected end of file while parsing unknown segment.");
				}

				if (t == "{")
				{
					++counter;
				}
				else if (t == "}")
				{
					--counter;
				}
			}
		}

		//! places pointer to next begin of a token, and ignores comments
		protected void FindNextNoneWhiteSpace()
		{
			if (IsBinaryFormat)
			{
				return;
			}

			while (true)
			{
				while (P < End && char.IsWhiteSpace((char)Buffer[P]))
				{
					if (Buffer[P] == '\n')
					{
						LineNumber++;
					}
					++P;
				}

				if (P >= End)
				{
					return;
				}

				// check if this is a comment
				if ((Buffer[P] == '/' && Buffer[P + 1] == '/') || Buffer[P] == '#')
				{
					ReadUntilEndOfLine();
				}
				else
				{
					break;
				}
			}
		}

		//! returns next parseable token. Returns empty string if no token there
		protected string GetNextToken()
		{
			string s = string.Empty;

			// process binary-formatted file
			if (IsBinaryFormat)
			{
				// in binary mode it will only return NAME and STRING token
				// and (correctly) skip over other tokens.
				if (End - P < 2)
				{
					return s;
				}
				uint tok = ReadBinWord();
				uint len;
				ASCIIEncoding Ascii = new ASCIIEncoding();

				// standalone tokens
				switch (tok)
				{
					case 1:
						// name token
						if (End - P < 4)
						{
							return s;
						}
						len = ReadBinDWord();
						if (End - P < (int)len)
						{
							return s;
						}
						s = Ascii.GetString(Buffer, P, (int)len);
						P += (int)len;
						return s;
					case 2:
						// string token
						if (End - P < 4)
						{
							return s;
						}
						len = ReadBinDWord();
						if (End - P < (int)len)
						{
							return s;
						}
						s = Ascii.GetString(Buffer, P, (int)len);
						P += (int)(len + 2);
						return s;
					case 3:
						// integer token
						P += 4;
						return "<integer>";
					case 5:
						// GUID token
						P += 16;
						return "<guid>";
					case 6:
						if (End - P < 4) return s;
						len = ReadBinDWord();
						P += (int)(len * 4);
						return "<int_list>";
					case 7:
						if (End - P < 4) return s;
						len = ReadBinDWord();
						P += (int)(len * BinaryFloatSize);
						return "<flt_list>";
					case 0x0a:
						return "{";
					case 0x0b:
						return "}";
					case 0x0c:
						return "(";
					case 0x0d:
						return ")";
					case 0x0e:
						return "[";
					case 0x0f:
						return "]";
					case 0x10:
						return "<";
					case 0x11:
						return ">";
					case 0x12:
						return ".";
					case 0x13:
						return ",";
					case 0x14:
						return ";";
					case 0x1f:
						return "template";
					case 0x28:
						return "WORD";
					case 0x29:
						return "DWORD";
					case 0x2a:
						return "FLOAT";
					case 0x2b:
						return "DOUBLE";
					case 0x2c:
						return "CHAR";
					case 0x2d:
						return "UCHAR";
					case 0x2e:
						return "SWORD";
					case 0x2f:
						return "SDWORD";
					case 0x30:
						return "void";
					case 0x31:
						return "string";
					case 0x32:
						return "unicode";
					case 0x33:
						return "cstring";
					case 0x34:
						return "array";
				}
			}
			// process text-formatted file
			else
			{
				FindNextNoneWhiteSpace();
				if (P > End)
				{
					return s;
				}

				while (P < End && !char.IsWhiteSpace((char)Buffer[P]))
				{
					// either keep token delimiters when already holding a token, or return if first valid char
					if (Buffer[P] == ';' || Buffer[P] == '}' || Buffer[P] == '{' || Buffer[P] == ',')
					{
						if (s.Length == 0)
						{
							s += (char)Buffer[P++];
						}
						break; // stop for delimiter
					}
					s += (char)Buffer[P++];
				}
			}
			return s;
		}

		protected void ReadHeadOfDataObject()
		{
			string nameOrBrace = GetNextToken();
			if (nameOrBrace != "{")
			{
				if (GetNextToken() != "{")
				{
					ThrowException("Opening brace expected.");
				}
			}
		}

		protected void ReadHeadOfDataObject(out string name)
		{
			name = string.Empty;

			string nameOrBrace = GetNextToken();
			if (nameOrBrace != "{")
			{
				name = nameOrBrace;

				if (GetNextToken() != "{")
				{
					ThrowException("Opening brace expected.");
				}
			}
		}

		//! checks for closing curly brace
		protected void CheckForClosingBrace()
		{
			if (GetNextToken() != "}")
			{
				ThrowException("Closing brace expected.");
			}
		}

		//! checks for one following semicolon
		protected void CheckForSemicolon()
		{
			if (IsBinaryFormat)
			{
				return;
			}

			if (GetNextToken() != ";")
			{
				ThrowException("Semicolon expected.");
			}
		}

		//! checks for a separator char, either a ',' or a ';'
		protected void CheckForSeparator()
		{
			if (IsBinaryFormat)
			{
				return;
			}

			string token = GetNextToken();
			if (token != "," && token != ";")
			{
				ThrowException("Separator character (';' or ',') expected.");
			}
		}

		// tests and possibly consumes a separator char, but does nothing if there was no separator
		protected void TestForSeparator()
		{
			if (IsBinaryFormat)
			{
				return;
			}

			FindNextNoneWhiteSpace();
			if (P > End)
			{
				return;
			}

			// test and skip
			if (Buffer[P] == ';' || Buffer[P] == ',')
			{
				P++;
			}
		}

		protected void GetNextTokenAsString(out string token)
		{
			token = string.Empty;

			if (IsBinaryFormat)
			{
				token = GetNextToken();
				return;
			}

			FindNextNoneWhiteSpace();
			if (P >= End)
			{
				ThrowException("Unexpected end of file while parsing string");
			}

			if (Buffer[P] != '"')
			{
				ThrowException("Expected quotation mark.");
			}
			++P;

			while (P < End && Buffer[P] != '"')
			{
				token += (char)Buffer[P++];
			}

			if (P >= End - 1)
			{
				ThrowException("Unexpected end of file while parsing string");
			}

			if (Buffer[P + 1] != ';' || Buffer[P] != '"')
			{
				ThrowException("Expected quotation mark and semicolon at the end of a string.");
			}
			P += 2;
		}

		protected void ReadUntilEndOfLine()
		{
			if (IsBinaryFormat)
			{
				return;
			}

			while (P < End)
			{
				if (Buffer[P] == '\n' || Buffer[P] == '\r')
				{
					++P;
					LineNumber++;
					return;
				}

				++P;
			}
		}

		protected ushort ReadBinWord()
		{
			Debug.Assert(End - P >= 2);
			ushort tmp = BitConverter.ToUInt16(Buffer, P);
			P += 2;
			return tmp;
		}

		protected uint ReadBinDWord()
		{
			Debug.Assert(End - P >= 4);
			uint tmp = BitConverter.ToUInt32(Buffer, P);
			P += 4;
			return tmp;
		}

		protected uint ReadInt()
		{
			if (IsBinaryFormat)
			{
				if (BinaryNumCount == 0 && End - P >= 2)
				{
					ushort tmp = ReadBinWord(); // 0x06 or 0x03
					// array of ints follows
					if (tmp == 0x06 && End - P >= 4)
					{
						BinaryNumCount = ReadBinDWord();
					}
					// single int follows
					else
					{
						BinaryNumCount = 1;
					}
				}

				--BinaryNumCount;
				if (End - P >= 4)
				{
					return ReadBinDWord();
				}
				else
				{
					P = End;
					return 0;
				}
			}
			else
			{
				FindNextNoneWhiteSpace();

				// TODO: consider using strtol10 instead???

				// check preceding minus sign
				bool isNegative = false;
				if (Buffer[P] == '-')
				{
					isNegative = true;
					P++;
				}

				// at least one digit expected
				if (!char.IsDigit((char)Buffer[P]))
				{
					ThrowException("Number expected.");
				}

				// read digits
				uint number = 0;
				while (P < End)
				{
					if (!char.IsDigit((char)Buffer[P]))
					{
						break;
					}
					number = number * 10 + (uint)(Buffer[P] - 48);
					P++;
				}

				CheckForSeparator();
				return isNegative ? (uint)(-(int)number) : number;
			}
		}

		protected float ReadFloat()
		{
			float result = 0.0f;

			if (IsBinaryFormat)
			{
				if (BinaryNumCount == 0 && End - P >= 2)
				{
					ushort tmp = ReadBinWord(); // 0x07 or 0x42
					// array of floats following
					if (tmp == 0x07 && End - P >= 4)
					{
						BinaryNumCount = ReadBinDWord();
					}
					// single float following
					else
					{
						BinaryNumCount = 1;
					}
				}

				--BinaryNumCount;
				if (BinaryFloatSize == 8)
				{
					if (End - P >= 8)
					{
						result = (float)BitConverter.ToDouble(Buffer, P);
						P += 8;
						return result;
					}
					else
					{
						P = End;
						return 0.0f;
					}
				}
				else
				{
					if (End - P >= 4)
					{
						result = BitConverter.ToSingle(Buffer, P);
						P += 4;
						return result;
					}
					else
					{
						P = End;
						return 0.0f;
					}
				}
			}

			// text version
			FindNextNoneWhiteSpace();
			// check for various special strings to allow reading files from faulty exporters
			// I mean you, Blender!
			// Reading is safe because of the terminating zero
			ASCIIEncoding Ascii = new ASCIIEncoding();
			if (Ascii.GetString(Buffer, P, 9) == "-1.#IND00" || Ascii.GetString(Buffer, P, 8) == "1.#IND00")
			{
				P += 9;
				CheckForSeparator();
				return 0.0f;
			}
			else if (Ascii.GetString(Buffer, P, 8) == "1.#QNAN0")
			{
				P += 8;
				CheckForSeparator();
				return 0.0f;
			}

			P = ConvertToFloat(P, out result);

			CheckForSeparator();

			return result;
		}

		protected Vector2 ReadVector2()
		{
			Vector2 vector;
			vector.X = ReadFloat();
			vector.Y = ReadFloat();
			TestForSeparator();

			return vector;
		}

		protected Vector3 ReadVector3()
		{
			Vector3 vector;
			vector.X = ReadFloat();
			vector.Y = ReadFloat();
			vector.Z = ReadFloat();
			TestForSeparator();

			return vector;
		}

		protected Color4 ReadRGBA()
		{
			Color4 color;
			color.R = ReadFloat();
			color.G = ReadFloat();
			color.B = ReadFloat();
			color.A = ReadFloat();
			TestForSeparator();

			return color;
		}

		protected Color4 ReadRGB()
		{
			Color4 color;
			color.R = ReadFloat();
			color.G = ReadFloat();
			color.B = ReadFloat();
			color.A = 1.0f;
			TestForSeparator();

			return color;
		}

		protected void ThrowException(string text)
		{
			if (IsBinaryFormat)
			{
				throw new Exception(text);
			}
			else
			{
				throw new Exception("Line " + LineNumber + ": " + text);
			}
		}

		// Filters the imported hierarchy for some degenerated cases that some exporters produce.
		protected void FilterHierarchy(Node node)
		{
			// if the node has just a single unnamed child containing a mesh, remove
			// the anonymous node between. The 3DSMax kwXport plugin seems to produce this
			// mess in some cases
			if (node.Children.Count == 1 && node.Meshes.Count == 0)
			{
				Node child = node.Children.First();
				if (child.Name.Length == 0 && child.Meshes.Count > 0)
				{
					// transfer its meshes to us
					for (int a = 0; a < child.Meshes.Count; a++)
					{
						node.Meshes.Add(child.Meshes[a]);
					}
					child.Meshes.Clear();

					// transfer the transform as well
					node.TrafoMatrix = node.TrafoMatrix * child.TrafoMatrix;

					// then kill it
					node.Children.Clear();
				}
			}

			// recurse
			for (int a = 0; a < node.Children.Count; a++)
			{
				FilterHierarchy(node.Children[a]);
			}
		}

		protected int ConvertToFloat(int position, out float result, bool check_comma = true)
		{
			ASCIIEncoding Ascii = new ASCIIEncoding();

			float f = 0.0f;

			bool inv = (Buffer[position] == '-');
			if (inv || Buffer[position] == '+')
			{
				++position;
			}

			if (string.Compare(Ascii.GetString(Buffer, position, 3), "nan", true, CultureInfo.InvariantCulture) == 0)
			{
				result = float.NaN;
				position += 3;
				return position;
			}

			if (string.Compare(Ascii.GetString(Buffer, position, 3), "inf", true, CultureInfo.InvariantCulture) == 0)
			{
				result = float.PositiveInfinity;
				if (inv)
				{
					result = -result;
				}
				position += 3;
				if (string.Compare(Ascii.GetString(Buffer, position, 5), "inity", true, CultureInfo.InvariantCulture) == 0)
				{
					position += 5;
				}
				return position;
			}

			if (!char.IsDigit((char)Buffer[position]) && !((Buffer[position] == '.' || (check_comma && Buffer[position] == ',')) && char.IsDigit((char)Buffer[position + 1])))
			{
				ThrowException("Cannot parse string as real number: does not start with digit or decimal point followed by digit.");
			}

			string tmp = string.Empty;

			while (position < End)
			{
				if (char.IsDigit((char)Buffer[position]) || Buffer[position] == '.' || Buffer[position] == 'e' || Buffer[position] == 'E' || Buffer[position] == '+' || Buffer[position] == '-')
				{
					tmp += (char)Buffer[position];
					++position;
				}
				else
				{
					break;
				}
			}

			try
			{
				f = float.Parse(tmp);
			}
			catch (Exception e)
			{
				ThrowException(e.Message);
			}

			if (inv)
			{
				f = -f;
			}

			result = f;
			return position;
		}
	}
}