XFileParser.cpp 34 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247
  1. /*
  2. ---------------------------------------------------------------------------
  3. Open Asset Import Library (ASSIMP)
  4. ---------------------------------------------------------------------------
  5. Copyright (c) 2006-2008, ASSIMP Development Team
  6. All rights reserved.
  7. Redistribution and use of this software in source and binary forms,
  8. with or without modification, are permitted provided that the following
  9. conditions are met:
  10. * Redistributions of source code must retain the above
  11. copyright notice, this list of conditions and the
  12. following disclaimer.
  13. * Redistributions in binary form must reproduce the above
  14. copyright notice, this list of conditions and the
  15. following disclaimer in the documentation and/or other
  16. materials provided with the distribution.
  17. * Neither the name of the ASSIMP team, nor the names of its
  18. contributors may be used to endorse or promote products
  19. derived from this software without specific prior
  20. written permission of the ASSIMP Development Team.
  21. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  22. "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  23. LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  24. A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  25. OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  26. SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  27. LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  28. DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  29. THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  30. (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  31. OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  32. ---------------------------------------------------------------------------
  33. */
  34. /** @file Implementation of the XFile parser helper class */
  35. #include "AssimpPCH.h"
  36. #include "XFileParser.h"
  37. #include "XFileHelper.h"
  38. #include "BaseImporter.h"
  39. #include "fast_atof.h"
  40. using namespace Assimp;
  41. using namespace Assimp::XFile;
  42. // ------------------------------------------------------------------------------------------------
  43. // Constructor. Creates a data structure out of the XFile given in the memory block.
  44. XFileParser::XFileParser( const std::vector<char>& pBuffer)
  45. {
  46. mMajorVersion = mMinorVersion = 0;
  47. mIsBinaryFormat = false;
  48. mBinaryNumCount = 0;
  49. P = End = NULL;
  50. mLineNumber = 0;
  51. mScene = NULL;
  52. // set up memory pointers
  53. P = &pBuffer.front();
  54. End = P + pBuffer.size();
  55. // check header
  56. if( strncmp( P, "xof ", 4) != 0)
  57. throw new ImportErrorException( "Header mismatch, file is not an XFile.");
  58. // read version. It comes in a four byte format such as "0302"
  59. mMajorVersion = (unsigned int)(P[4] - 48) * 10 + (unsigned int)(P[5] - 48);
  60. mMinorVersion = (unsigned int)(P[6] - 48) * 10 + (unsigned int)(P[7] - 48);
  61. // read format
  62. if( strncmp( P + 8, "txt ", 4) == 0)
  63. mIsBinaryFormat = false;
  64. else if( strncmp( P + 8, "bin ", 4) == 0)
  65. mIsBinaryFormat = true;
  66. else
  67. ThrowException( boost::str( boost::format( "Unsupported xfile format '%c%c%c%c'") % P[8] % P[9] % P[10] % P[11]));
  68. // float size
  69. mBinaryFloatSize = (unsigned int)(P[12] - 48) * 1000
  70. + (unsigned int)(P[13] - 48) * 100
  71. + (unsigned int)(P[14] - 48) * 10
  72. + (unsigned int)(P[15] - 48);
  73. if( mBinaryFloatSize != 32 && mBinaryFloatSize != 64)
  74. ThrowException( boost::str( boost::format( "Unknown float size %1% specified in xfile header.") % mBinaryFloatSize));
  75. // start reading here
  76. P += 16;
  77. ReadUntilEndOfLine();
  78. mScene = new Scene;
  79. ParseFile();
  80. // filter the imported hierarchy for some degenerated cases
  81. if( mScene->mRootNode)
  82. FilterHierarchy( mScene->mRootNode);
  83. }
  84. // ------------------------------------------------------------------------------------------------
  85. // Destructor. Destroys all imported data along with it
  86. XFileParser::~XFileParser()
  87. {
  88. // kill everything we created
  89. delete mScene;
  90. }
  91. // ------------------------------------------------------------------------------------------------
  92. void XFileParser::ParseFile()
  93. {
  94. while( 1)
  95. {
  96. // read name of next object
  97. std::string objectName = GetNextToken();
  98. if (objectName.length() == 0)
  99. break;
  100. // parse specific object
  101. if( objectName == "template")
  102. ParseDataObjectTemplate();
  103. else
  104. if( objectName == "Frame")
  105. ParseDataObjectFrame( NULL);
  106. else
  107. if( objectName == "Mesh")
  108. {
  109. // some meshes have no frames at all
  110. Mesh* mesh = new Mesh;
  111. ParseDataObjectMesh( mesh);
  112. mScene->mGlobalMeshes.push_back( mesh);
  113. } else
  114. if( objectName == "AnimTicksPerSecond")
  115. ParseDataObjectAnimTicksPerSecond();
  116. else
  117. if( objectName == "AnimationSet")
  118. ParseDataObjectAnimationSet();
  119. else
  120. if( objectName == "Material")
  121. {
  122. // Material outside of a mesh or node
  123. Material material;
  124. ParseDataObjectMaterial( &material);
  125. mScene->mGlobalMaterials.push_back( material);
  126. } else
  127. if( objectName == "}")
  128. {
  129. // whatever?
  130. DefaultLogger::get()->warn("} found in dataObject");
  131. } else
  132. {
  133. // unknown format
  134. DefaultLogger::get()->warn("Unknown data object in animation of .x file");
  135. ParseUnknownDataObject();
  136. }
  137. }
  138. }
  139. // ------------------------------------------------------------------------------------------------
  140. void XFileParser::ParseDataObjectTemplate()
  141. {
  142. // parse a template data object. Currently not stored.
  143. std::string name;
  144. readHeadOfDataObject( &name);
  145. // read GUID
  146. std::string guid = GetNextToken();
  147. // read and ignore data members
  148. while(true)
  149. {
  150. std::string s = GetNextToken();
  151. if( s == "}")
  152. break;
  153. if( s.length() == 0)
  154. ThrowException( "Unexpected end of file reached while parsing template definition");
  155. }
  156. }
  157. // ------------------------------------------------------------------------------------------------
  158. void XFileParser::ParseDataObjectFrame( Node* pParent)
  159. {
  160. // A coordinate frame, or "frame of reference." The Frame template
  161. // is open and can contain any object. The Direct3D extensions (D3DX)
  162. // mesh-loading functions recognize Mesh, FrameTransformMatrix, and
  163. // Frame template instances as child objects when loading a Frame
  164. // instance.
  165. std::string name;
  166. readHeadOfDataObject(&name);
  167. // create a named node and place it at its parent, if given
  168. Node* node = new Node( pParent);
  169. node->mName = name;
  170. if( pParent)
  171. {
  172. pParent->mChildren.push_back( node);
  173. } else
  174. {
  175. // there might be multiple root nodes
  176. if( mScene->mRootNode != NULL)
  177. {
  178. // place a dummy root if not there
  179. if( mScene->mRootNode->mName != "$dummy_root")
  180. {
  181. Node* exroot = mScene->mRootNode;
  182. mScene->mRootNode = new Node( NULL);
  183. mScene->mRootNode->mName = "$dummy_root";
  184. mScene->mRootNode->mChildren.push_back( exroot);
  185. exroot->mParent = mScene->mRootNode;
  186. }
  187. // put the new node as its child instead
  188. mScene->mRootNode->mChildren.push_back( node);
  189. node->mParent = mScene->mRootNode;
  190. } else
  191. {
  192. // it's the first node imported. place it as root
  193. mScene->mRootNode = node;
  194. }
  195. }
  196. // Now inside a frame.
  197. // read tokens until closing brace is reached.
  198. while(true)
  199. {
  200. std::string objectName = GetNextToken();
  201. if (objectName.size() == 0)
  202. ThrowException( "Unexpected end of file reached while parsing frame");
  203. if( objectName == "}")
  204. break; // frame finished
  205. else
  206. if( objectName == "Frame")
  207. ParseDataObjectFrame( node); // child frame
  208. else
  209. if( objectName == "FrameTransformMatrix")
  210. ParseDataObjectTransformationMatrix( node->mTrafoMatrix);
  211. else
  212. if( objectName == "Mesh")
  213. {
  214. Mesh* mesh = new Mesh;
  215. node->mMeshes.push_back( mesh);
  216. ParseDataObjectMesh( mesh);
  217. } else
  218. {
  219. DefaultLogger::get()->warn("Unknown data object in frame in x file");
  220. ParseUnknownDataObject();
  221. }
  222. }
  223. }
  224. // ------------------------------------------------------------------------------------------------
  225. void XFileParser::ParseDataObjectTransformationMatrix( aiMatrix4x4& pMatrix)
  226. {
  227. // read header, we're not interested if it has a name
  228. readHeadOfDataObject();
  229. // read its components
  230. pMatrix.a1 = ReadFloat(); pMatrix.b1 = ReadFloat();
  231. pMatrix.c1 = ReadFloat(); pMatrix.d1 = ReadFloat();
  232. pMatrix.a2 = ReadFloat(); pMatrix.b2 = ReadFloat();
  233. pMatrix.c2 = ReadFloat(); pMatrix.d2 = ReadFloat();
  234. pMatrix.a3 = ReadFloat(); pMatrix.b3 = ReadFloat();
  235. pMatrix.c3 = ReadFloat(); pMatrix.d3 = ReadFloat();
  236. pMatrix.a4 = ReadFloat(); pMatrix.b4 = ReadFloat();
  237. pMatrix.c4 = ReadFloat(); pMatrix.d4 = ReadFloat();
  238. // trailing symbols
  239. CheckForSemicolon();
  240. CheckForClosingBrace();
  241. }
  242. // ------------------------------------------------------------------------------------------------
  243. void XFileParser::ParseDataObjectMesh( Mesh* pMesh)
  244. {
  245. std::string name;
  246. readHeadOfDataObject( &name);
  247. // read vertex count
  248. unsigned int numVertices = ReadInt();
  249. pMesh->mPositions.resize( numVertices);
  250. // read vertices
  251. for( unsigned int a = 0; a < numVertices; a++)
  252. pMesh->mPositions[a] = ReadVector3();
  253. // read position faces
  254. unsigned int numPosFaces = ReadInt();
  255. pMesh->mPosFaces.resize( numPosFaces);
  256. for( unsigned int a = 0; a < numPosFaces; a++)
  257. {
  258. unsigned int numIndices = ReadInt();
  259. if( numIndices < 3)
  260. ThrowException( boost::str( boost::format( "Invalid index count %1% for face %2%.") % numIndices % a));
  261. // read indices
  262. Face& face = pMesh->mPosFaces[a];
  263. for( unsigned int b = 0; b < numIndices; b++)
  264. face.mIndices.push_back( ReadInt());
  265. CheckForSeparator();
  266. }
  267. // here, other data objects may follow
  268. while(true)
  269. {
  270. std::string objectName = GetNextToken();
  271. if( objectName.size() == 0)
  272. ThrowException( "Unexpected end of file while parsing mesh structure");
  273. else
  274. if( objectName == "}")
  275. break; // mesh finished
  276. else
  277. if( objectName == "MeshNormals")
  278. ParseDataObjectMeshNormals( pMesh);
  279. else
  280. if( objectName == "MeshTextureCoords")
  281. ParseDataObjectMeshTextureCoords( pMesh);
  282. else
  283. if( objectName == "MeshVertexColors")
  284. ParseDataObjectMeshVertexColors( pMesh);
  285. else
  286. if( objectName == "MeshMaterialList")
  287. ParseDataObjectMeshMaterialList( pMesh);
  288. else
  289. if( objectName == "VertexDuplicationIndices")
  290. ParseUnknownDataObject(); // we'll ignore vertex duplication indices
  291. else
  292. if( objectName == "XSkinMeshHeader")
  293. ParseDataObjectSkinMeshHeader( pMesh);
  294. else
  295. if( objectName == "SkinWeights")
  296. ParseDataObjectSkinWeights( pMesh);
  297. else
  298. {
  299. DefaultLogger::get()->warn("Unknown data object in mesh in x file");
  300. ParseUnknownDataObject();
  301. }
  302. }
  303. }
  304. // ------------------------------------------------------------------------------------------------
  305. void XFileParser::ParseDataObjectSkinWeights( Mesh *pMesh)
  306. {
  307. readHeadOfDataObject();
  308. std::string transformNodeName;
  309. GetNextTokenAsString( transformNodeName);
  310. pMesh->mBones.push_back( Bone());
  311. Bone& bone = pMesh->mBones.back();
  312. bone.mName = transformNodeName;
  313. // read vertex weights
  314. unsigned int numWeights = ReadInt();
  315. bone.mWeights.reserve( numWeights);
  316. for( unsigned int a = 0; a < numWeights; a++)
  317. {
  318. BoneWeight weight;
  319. weight.mVertex = ReadInt();
  320. bone.mWeights.push_back( weight);
  321. }
  322. // read vertex weights
  323. for( unsigned int a = 0; a < numWeights; a++)
  324. bone.mWeights[a].mWeight = ReadFloat();
  325. // read matrix offset
  326. bone.mOffsetMatrix.a1 = ReadFloat(); bone.mOffsetMatrix.b1 = ReadFloat();
  327. bone.mOffsetMatrix.c1 = ReadFloat(); bone.mOffsetMatrix.d1 = ReadFloat();
  328. bone.mOffsetMatrix.a2 = ReadFloat(); bone.mOffsetMatrix.b2 = ReadFloat();
  329. bone.mOffsetMatrix.c2 = ReadFloat(); bone.mOffsetMatrix.d2 = ReadFloat();
  330. bone.mOffsetMatrix.a3 = ReadFloat(); bone.mOffsetMatrix.b3 = ReadFloat();
  331. bone.mOffsetMatrix.c3 = ReadFloat(); bone.mOffsetMatrix.d3 = ReadFloat();
  332. bone.mOffsetMatrix.a4 = ReadFloat(); bone.mOffsetMatrix.b4 = ReadFloat();
  333. bone.mOffsetMatrix.c4 = ReadFloat(); bone.mOffsetMatrix.d4 = ReadFloat();
  334. CheckForSemicolon();
  335. CheckForClosingBrace();
  336. }
  337. // ------------------------------------------------------------------------------------------------
  338. void XFileParser::ParseDataObjectSkinMeshHeader( Mesh* pMesh)
  339. {
  340. readHeadOfDataObject();
  341. /*unsigned int maxSkinWeightsPerVertex =*/ ReadInt();
  342. /*unsigned int maxSkinWeightsPerFace =*/ ReadInt();
  343. /*unsigned int numBonesInMesh = */ReadInt();
  344. CheckForClosingBrace();
  345. }
  346. // ------------------------------------------------------------------------------------------------
  347. void XFileParser::ParseDataObjectMeshNormals( Mesh* pMesh)
  348. {
  349. readHeadOfDataObject();
  350. // read count
  351. unsigned int numNormals = ReadInt();
  352. pMesh->mNormals.resize( numNormals);
  353. // read normal vectors
  354. for( unsigned int a = 0; a < numNormals; a++)
  355. pMesh->mNormals[a] = ReadVector3();
  356. // read normal indices
  357. unsigned int numFaces = ReadInt();
  358. if( numFaces != pMesh->mPosFaces.size())
  359. ThrowException( "Normal face count does not match vertex face count.");
  360. for( unsigned int a = 0; a < numFaces; a++)
  361. {
  362. unsigned int numIndices = ReadInt();
  363. pMesh->mNormFaces.push_back( Face());
  364. Face& face = pMesh->mNormFaces.back();
  365. for( unsigned int b = 0; b < numIndices; b++)
  366. face.mIndices.push_back( ReadInt());
  367. CheckForSeparator();
  368. }
  369. CheckForClosingBrace();
  370. }
  371. // ------------------------------------------------------------------------------------------------
  372. void XFileParser::ParseDataObjectMeshTextureCoords( Mesh* pMesh)
  373. {
  374. readHeadOfDataObject();
  375. std::vector<aiVector2D>& coords = pMesh->mTexCoords[pMesh->mNumTextures++];
  376. unsigned int numCoords = ReadInt();
  377. if( numCoords != pMesh->mPositions.size())
  378. ThrowException( "Texture coord count does not match vertex count");
  379. coords.resize( numCoords);
  380. for( unsigned int a = 0; a < numCoords; a++)
  381. coords[a] = ReadVector2();
  382. CheckForClosingBrace();
  383. }
  384. // ------------------------------------------------------------------------------------------------
  385. void XFileParser::ParseDataObjectMeshVertexColors( Mesh* pMesh)
  386. {
  387. readHeadOfDataObject();
  388. std::vector<aiColor4D>& colors = pMesh->mColors[pMesh->mNumColorSets++];
  389. unsigned int numColors = ReadInt();
  390. if( numColors != pMesh->mPositions.size())
  391. ThrowException( "Vertex color count does not match vertex count");
  392. colors.resize( numColors, aiColor4D( 0, 0, 0, 1));
  393. for( unsigned int a = 0; a < numColors; a++)
  394. {
  395. unsigned int index = ReadInt();
  396. if( index >= pMesh->mPositions.size())
  397. ThrowException( "Vertex color index out of bounds");
  398. colors[index] = ReadRGBA();
  399. // HACK: (thom) Maxon Cinema XPort plugin puts a third separator here. Ignore gracefully
  400. if( !mIsBinaryFormat)
  401. {
  402. FindNextNoneWhiteSpace();
  403. if( *P == ';')
  404. P++;
  405. }
  406. }
  407. CheckForClosingBrace();
  408. }
  409. // ------------------------------------------------------------------------------------------------
  410. void XFileParser::ParseDataObjectMeshMaterialList( Mesh* pMesh)
  411. {
  412. readHeadOfDataObject();
  413. // read material count
  414. /*unsigned int numMaterials =*/ ReadInt();
  415. // read non triangulated face material index count
  416. unsigned int numMatIndices = ReadInt();
  417. // some models have a material index count of 1... to be able to read them we
  418. // replicate this single material index on every face
  419. if( numMatIndices != pMesh->mPosFaces.size() && numMatIndices != 1)
  420. ThrowException( "Per-Face material index count does not match face count.");
  421. // read per-face material indices
  422. for( unsigned int a = 0; a < numMatIndices; a++)
  423. pMesh->mFaceMaterials.push_back( ReadInt());
  424. // in version 03.02, the face indices end with two semicolons.
  425. // commented out version check, as version 03.03 exported from blender also has 2 semicolons
  426. if( !mIsBinaryFormat) // && MajorVersion == 3 && MinorVersion <= 2)
  427. {
  428. if( *P == ';')
  429. ++P;
  430. }
  431. // if there was only a single material index, replicate it on all faces
  432. while( pMesh->mFaceMaterials.size() < pMesh->mPosFaces.size())
  433. pMesh->mFaceMaterials.push_back( pMesh->mFaceMaterials.front());
  434. // read following data objects
  435. while(true)
  436. {
  437. std::string objectName = GetNextToken();
  438. if( objectName.size() == 0)
  439. ThrowException( "Unexpected end of file while parsing mesh material list.");
  440. else
  441. if( objectName == "}")
  442. break; // material list finished
  443. else
  444. if( objectName == "{")
  445. {
  446. // template materials
  447. std::string matName = GetNextToken();
  448. Material material;
  449. material.mIsReference = true;
  450. material.mName = matName;
  451. pMesh->mMaterials.push_back( material);
  452. CheckForClosingBrace(); // skip }
  453. } else
  454. if( objectName == "Material")
  455. {
  456. pMesh->mMaterials.push_back( Material());
  457. ParseDataObjectMaterial( &pMesh->mMaterials.back());
  458. } else
  459. if( objectName == ";")
  460. {
  461. // ignore
  462. } else
  463. {
  464. DefaultLogger::get()->warn("Unknown data object in material list in x file");
  465. ParseUnknownDataObject();
  466. }
  467. }
  468. }
  469. // ------------------------------------------------------------------------------------------------
  470. void XFileParser::ParseDataObjectMaterial( Material* pMaterial)
  471. {
  472. std::string matName;
  473. readHeadOfDataObject( &matName);
  474. pMaterial->mName = matName;
  475. pMaterial->mIsReference = false;
  476. // read material values
  477. pMaterial->mDiffuse = ReadRGBA();
  478. pMaterial->mSpecularExponent = ReadFloat();
  479. pMaterial->mSpecular = ReadRGB();
  480. pMaterial->mEmissive = ReadRGB();
  481. // read other data objects
  482. while(true)
  483. {
  484. std::string objectName = GetNextToken();
  485. if( objectName.size() == 0)
  486. ThrowException( "Unexpected end of file while parsing mesh material");
  487. else
  488. if( objectName == "}")
  489. break; // material finished
  490. else
  491. if( objectName == "TextureFilename" || objectName == "TextureFileName")
  492. {
  493. // some exporters write "TextureFileName" instead.
  494. std::string texname;
  495. ParseDataObjectTextureFilename( texname);
  496. pMaterial->mTextures.push_back( TexEntry( texname));
  497. } else
  498. if( objectName == "NormalmapFilename" || objectName == "NormalmapFileName")
  499. {
  500. // one exporter writes out the normal map in a separate filename tag
  501. std::string texname;
  502. ParseDataObjectTextureFilename( texname);
  503. pMaterial->mTextures.push_back( TexEntry( texname, true));
  504. } else
  505. {
  506. DefaultLogger::get()->warn("Unknown data object in material in x file");
  507. ParseUnknownDataObject();
  508. }
  509. }
  510. }
  511. // ------------------------------------------------------------------------------------------------
  512. void XFileParser::ParseDataObjectAnimTicksPerSecond()
  513. {
  514. readHeadOfDataObject();
  515. mScene->mAnimTicksPerSecond = ReadInt();
  516. CheckForClosingBrace();
  517. }
  518. // ------------------------------------------------------------------------------------------------
  519. void XFileParser::ParseDataObjectAnimationSet()
  520. {
  521. std::string animName;
  522. readHeadOfDataObject( &animName);
  523. Animation* anim = new Animation;
  524. mScene->mAnims.push_back( anim);
  525. anim->mName = animName;
  526. while(true)
  527. {
  528. std::string objectName = GetNextToken();
  529. if( objectName.length() == 0)
  530. ThrowException( "Unexpected end of file while parsing animation set.");
  531. else
  532. if( objectName == "}")
  533. break; // animation set finished
  534. else
  535. if( objectName == "Animation")
  536. ParseDataObjectAnimation( anim);
  537. else
  538. {
  539. DefaultLogger::get()->warn("Unknown data object in animation set in x file");
  540. ParseUnknownDataObject();
  541. }
  542. }
  543. }
  544. // ------------------------------------------------------------------------------------------------
  545. void XFileParser::ParseDataObjectAnimation( Animation* pAnim)
  546. {
  547. readHeadOfDataObject();
  548. AnimBone* banim = new AnimBone;
  549. pAnim->mAnims.push_back( banim);
  550. while(true)
  551. {
  552. std::string objectName = GetNextToken();
  553. if( objectName.length() == 0)
  554. ThrowException( "Unexpected end of file while parsing animation.");
  555. else
  556. if( objectName == "}")
  557. break; // animation finished
  558. else
  559. if( objectName == "AnimationKey")
  560. ParseDataObjectAnimationKey( banim);
  561. else
  562. if( objectName == "AnimationOptions")
  563. ParseUnknownDataObject(); // not interested
  564. else
  565. if( objectName == "{")
  566. {
  567. // read frame name
  568. banim->mBoneName = GetNextToken();
  569. CheckForClosingBrace();
  570. } else
  571. {
  572. DefaultLogger::get()->warn("Unknown data object in animation in x file");
  573. ParseUnknownDataObject();
  574. }
  575. }
  576. }
  577. // ------------------------------------------------------------------------------------------------
  578. void XFileParser::ParseDataObjectAnimationKey( AnimBone* pAnimBone)
  579. {
  580. readHeadOfDataObject();
  581. // read key type
  582. unsigned int keyType = ReadInt();
  583. // read number of keys
  584. unsigned int numKeys = ReadInt();
  585. for( unsigned int a = 0; a < numKeys; a++)
  586. {
  587. // read time
  588. unsigned int time = ReadInt();
  589. // read keys
  590. switch( keyType)
  591. {
  592. case 0: // rotation quaternion
  593. {
  594. // read count
  595. if( ReadInt() != 4)
  596. ThrowException( "Invalid number of arguments for quaternion key in animation");
  597. aiQuatKey key;
  598. key.mTime = double( time);
  599. key.mValue.w = ReadFloat();
  600. key.mValue.x = ReadFloat();
  601. key.mValue.y = ReadFloat();
  602. key.mValue.z = ReadFloat();
  603. pAnimBone->mRotKeys.push_back( key);
  604. CheckForSemicolon();
  605. break;
  606. }
  607. case 1: // scale vector
  608. case 2: // position vector
  609. {
  610. // read count
  611. if( ReadInt() != 3)
  612. ThrowException( "Invalid number of arguments for vector key in animation");
  613. aiVectorKey key;
  614. key.mTime = double( time);
  615. key.mValue = ReadVector3();
  616. if( keyType == 2)
  617. pAnimBone->mPosKeys.push_back( key);
  618. else
  619. pAnimBone->mScaleKeys.push_back( key);
  620. break;
  621. }
  622. case 3: // combined transformation matrix
  623. case 4: // denoted both as 3 or as 4
  624. {
  625. // read count
  626. if( ReadInt() != 16)
  627. ThrowException( "Invalid number of arguments for matrix key in animation");
  628. // read matrix
  629. MatrixKey key;
  630. key.mTime = double( time);
  631. key.mMatrix.a1 = ReadFloat(); key.mMatrix.b1 = ReadFloat();
  632. key.mMatrix.c1 = ReadFloat(); key.mMatrix.d1 = ReadFloat();
  633. key.mMatrix.a2 = ReadFloat(); key.mMatrix.b2 = ReadFloat();
  634. key.mMatrix.c2 = ReadFloat(); key.mMatrix.d2 = ReadFloat();
  635. key.mMatrix.a3 = ReadFloat(); key.mMatrix.b3 = ReadFloat();
  636. key.mMatrix.c3 = ReadFloat(); key.mMatrix.d3 = ReadFloat();
  637. key.mMatrix.a4 = ReadFloat(); key.mMatrix.b4 = ReadFloat();
  638. key.mMatrix.c4 = ReadFloat(); key.mMatrix.d4 = ReadFloat();
  639. pAnimBone->mTrafoKeys.push_back( key);
  640. CheckForSemicolon();
  641. break;
  642. }
  643. default:
  644. ThrowException( boost::str( boost::format( "Unknown key type %1% in animation.") % keyType));
  645. break;
  646. } // end switch
  647. // key separator
  648. CheckForSeparator();
  649. }
  650. CheckForClosingBrace();
  651. }
  652. // ------------------------------------------------------------------------------------------------
  653. void XFileParser::ParseDataObjectTextureFilename( std::string& pName)
  654. {
  655. readHeadOfDataObject();
  656. GetNextTokenAsString( pName);
  657. CheckForClosingBrace();
  658. // FIX: some files (e.g. AnimationTest.x) have "" as texture file name
  659. if (!pName.length())
  660. {
  661. DefaultLogger::get()->warn("Length of texture file name is zero. Skipping this texture.");
  662. }
  663. // some exporters write double backslash paths out. We simply replace them if we find them
  664. while( pName.find( "\\\\") != std::string::npos)
  665. pName.replace( pName.find( "\\\\"), 2, "\\");
  666. }
  667. // ------------------------------------------------------------------------------------------------
  668. void XFileParser::ParseUnknownDataObject()
  669. {
  670. // find opening delimiter
  671. while( true)
  672. {
  673. std::string t = GetNextToken();
  674. if( t.length() == 0)
  675. ThrowException( "Unexpected end of file while parsing unknown segment.");
  676. if( t == "{")
  677. break;
  678. }
  679. unsigned int counter = 1;
  680. // parse until closing delimiter
  681. while( counter > 0)
  682. {
  683. std::string t = GetNextToken();
  684. if( t.length() == 0)
  685. ThrowException( "Unexpected end of file while parsing unknown segment.");
  686. if( t == "{")
  687. ++counter;
  688. else
  689. if( t == "}")
  690. --counter;
  691. }
  692. }
  693. // ------------------------------------------------------------------------------------------------
  694. //! checks for closing curly brace
  695. void XFileParser::CheckForClosingBrace()
  696. {
  697. if( GetNextToken() != "}")
  698. ThrowException( "Closing brace expected.");
  699. }
  700. // ------------------------------------------------------------------------------------------------
  701. //! checks for one following semicolon
  702. void XFileParser::CheckForSemicolon()
  703. {
  704. if( mIsBinaryFormat)
  705. return;
  706. if( GetNextToken() != ";")
  707. ThrowException( "Semicolon expected.");
  708. }
  709. // ------------------------------------------------------------------------------------------------
  710. //! checks for a separator char, either a ',' or a ';'
  711. void XFileParser::CheckForSeparator()
  712. {
  713. if( mIsBinaryFormat)
  714. return;
  715. std::string token = GetNextToken();
  716. if( token != "," && token != ";")
  717. ThrowException( "Separator character (';' or ',') expected.");
  718. }
  719. // ------------------------------------------------------------------------------------------------
  720. void XFileParser::readHeadOfDataObject( std::string* poName)
  721. {
  722. std::string nameOrBrace = GetNextToken();
  723. if( nameOrBrace != "{")
  724. {
  725. if( poName)
  726. *poName = nameOrBrace;
  727. if( GetNextToken() != "{")
  728. ThrowException( "Opening brace expected.");
  729. }
  730. }
  731. // ------------------------------------------------------------------------------------------------
  732. std::string XFileParser::GetNextToken()
  733. {
  734. std::string s;
  735. // process binary-formatted file
  736. if( mIsBinaryFormat)
  737. {
  738. // in binary mode it will only return NAME and STRING token
  739. // and (correctly) skip over other tokens.
  740. unsigned int tok = ReadBinWord();
  741. unsigned int len;
  742. // standalone tokens
  743. switch( tok)
  744. {
  745. case 1:
  746. // name token
  747. len = ReadBinDWord();
  748. s = std::string(P, len);
  749. P += len;
  750. return s;
  751. case 2:
  752. // string token
  753. len = ReadBinDWord();
  754. s = std::string(P, len);
  755. P += (len + 2);
  756. return s;
  757. case 3:
  758. // integer token
  759. P += 4;
  760. return "<integer>";
  761. case 5:
  762. // GUID token
  763. P += 16;
  764. return "<guid>";
  765. case 6:
  766. len = ReadBinDWord();
  767. P += (len * 4);
  768. return "<int_list>";
  769. case 7:
  770. len = ReadBinDWord();
  771. P += (len * mBinaryFloatSize);
  772. return "<flt_list>";
  773. case 0x0a:
  774. return "{";
  775. case 0x0b:
  776. return "}";
  777. case 0x0c:
  778. return "(";
  779. case 0x0d:
  780. return ")";
  781. case 0x0e:
  782. return "[";
  783. case 0x0f:
  784. return "]";
  785. case 0x10:
  786. return "<";
  787. case 0x11:
  788. return ">";
  789. case 0x12:
  790. return ".";
  791. case 0x13:
  792. return ",";
  793. case 0x14:
  794. return ";";
  795. case 0x1f:
  796. return "template";
  797. case 0x28:
  798. return "WORD";
  799. case 0x29:
  800. return "DWORD";
  801. case 0x2a:
  802. return "FLOAT";
  803. case 0x2b:
  804. return "DOUBLE";
  805. case 0x2c:
  806. return "CHAR";
  807. case 0x2d:
  808. return "UCHAR";
  809. case 0x2e:
  810. return "SWORD";
  811. case 0x2f:
  812. return "SDWORD";
  813. case 0x30:
  814. return "void";
  815. case 0x31:
  816. return "string";
  817. case 0x32:
  818. return "unicode";
  819. case 0x33:
  820. return "cstring";
  821. case 0x34:
  822. return "array";
  823. }
  824. }
  825. // process text-formatted file
  826. else
  827. {
  828. FindNextNoneWhiteSpace();
  829. if( P >= End)
  830. return s;
  831. while( (P < End) && !isspace( (unsigned char) *P))
  832. {
  833. // either keep token delimiters when already holding a token, or return if first valid char
  834. if( *P == ';' || *P == '}' || *P == '{' || *P == ',')
  835. {
  836. if( !s.size())
  837. s.append( P++, 1);
  838. break; // stop for delimiter
  839. }
  840. s.append( P++, 1);
  841. }
  842. }
  843. return s;
  844. }
  845. // ------------------------------------------------------------------------------------------------
  846. void XFileParser::FindNextNoneWhiteSpace()
  847. {
  848. if( mIsBinaryFormat)
  849. return;
  850. while( true)
  851. {
  852. while( P < End && isspace( (unsigned char) *P))
  853. {
  854. if( *P == '\n')
  855. mLineNumber++;
  856. ++P;
  857. }
  858. if( P >= End)
  859. return;
  860. // check if this is a comment
  861. if( (P[0] == '/' && P[1] == '/') || P[0] == '#')
  862. ReadUntilEndOfLine();
  863. else
  864. break;
  865. }
  866. }
  867. // ------------------------------------------------------------------------------------------------
  868. void XFileParser::GetNextTokenAsString( std::string& poString)
  869. {
  870. if( mIsBinaryFormat)
  871. {
  872. poString = GetNextToken();
  873. return;
  874. }
  875. FindNextNoneWhiteSpace();
  876. if( P >= End)
  877. ThrowException( "Unexpected end of file while parsing string");
  878. if( *P != '"')
  879. ThrowException( "Expected quotation mark.");
  880. ++P;
  881. while( P < End && *P != '"')
  882. poString.append( P++, 1);
  883. if( P >= End-1)
  884. ThrowException( "Unexpected end of file while parsing string");
  885. if( P[1] != ';' || P[0] != '"')
  886. ThrowException( "Expected quotation mark and semicolon at the end of a string.");
  887. P+=2;
  888. }
  889. // ------------------------------------------------------------------------------------------------
  890. void XFileParser::ReadUntilEndOfLine()
  891. {
  892. if( mIsBinaryFormat)
  893. return;
  894. while( P < End)
  895. {
  896. if( *P == '\n' || *P == '\r')
  897. {
  898. ++P; mLineNumber++;
  899. return;
  900. }
  901. ++P;
  902. }
  903. }
  904. // ------------------------------------------------------------------------------------------------
  905. unsigned short XFileParser::ReadBinWord()
  906. {
  907. const unsigned char* q = (const unsigned char*) P;
  908. unsigned short tmp = q[0] | (q[1] << 8);
  909. P += 2;
  910. return tmp;
  911. }
  912. // ------------------------------------------------------------------------------------------------
  913. unsigned int XFileParser::ReadBinDWord()
  914. {
  915. const unsigned char* q = (const unsigned char*) P;
  916. unsigned int tmp = q[0] | (q[1] << 8) | (q[2] << 16) | (q[3] << 24);
  917. P += 4;
  918. return tmp;
  919. }
  920. // ------------------------------------------------------------------------------------------------
  921. unsigned int XFileParser::ReadInt()
  922. {
  923. if( mIsBinaryFormat)
  924. {
  925. if( mBinaryNumCount == 0)
  926. {
  927. unsigned short tmp = ReadBinWord(); // 0x06 or 0x03
  928. if( tmp == 0x06) // array of ints follows
  929. mBinaryNumCount = ReadBinDWord();
  930. else // single int follows
  931. mBinaryNumCount = 1;
  932. }
  933. --mBinaryNumCount;
  934. return ReadBinDWord();
  935. } else
  936. {
  937. FindNextNoneWhiteSpace();
  938. // check preceeding minus sign
  939. bool isNegative = false;
  940. if( *P == '-')
  941. {
  942. isNegative = true;
  943. P++;
  944. }
  945. // at least one digit expected
  946. if( !isdigit( *P))
  947. ThrowException( "Number expected.");
  948. // read digits
  949. unsigned int number = 0;
  950. while( P < End)
  951. {
  952. if( !isdigit( *P))
  953. break;
  954. number = number * 10 + (*P - 48);
  955. P++;
  956. }
  957. CheckForSeparator();
  958. return isNegative ? ((unsigned int) -int( number)) : number;
  959. }
  960. }
  961. // ------------------------------------------------------------------------------------------------
  962. float XFileParser::ReadFloat()
  963. {
  964. if( mIsBinaryFormat)
  965. {
  966. if( mBinaryNumCount == 0)
  967. {
  968. unsigned short tmp = ReadBinWord(); // 0x07 or 0x42
  969. if( tmp == 0x07) // array of floats following
  970. mBinaryNumCount = ReadBinDWord();
  971. else // single float following
  972. mBinaryNumCount = 1;
  973. }
  974. --mBinaryNumCount;
  975. if( mBinaryFloatSize == 8)
  976. {
  977. float result = (float) (*(double*) P);
  978. P += 8;
  979. return result;
  980. } else
  981. {
  982. float result = *(float*) P;
  983. P += 4;
  984. return result;
  985. }
  986. }
  987. // text version
  988. FindNextNoneWhiteSpace();
  989. // check for various special strings to allow reading files from faulty exporters
  990. // I mean you, Blender!
  991. if( strncmp( P, "-1.#IND00", 9) == 0)
  992. {
  993. P += 9;
  994. CheckForSeparator();
  995. return 0.0f;
  996. } else
  997. if( strncmp( P, "1.#QNAN0", 8) == 0)
  998. {
  999. P += 8;
  1000. CheckForSeparator();
  1001. return 0.0f;
  1002. }
  1003. float result = 0.0f;
  1004. P = fast_atof_move( P, result);
  1005. CheckForSeparator();
  1006. return result;
  1007. }
  1008. // ------------------------------------------------------------------------------------------------
  1009. aiVector2D XFileParser::ReadVector2()
  1010. {
  1011. aiVector2D vector;
  1012. vector.x = ReadFloat();
  1013. vector.y = ReadFloat();
  1014. CheckForSeparator();
  1015. return vector;
  1016. }
  1017. // ------------------------------------------------------------------------------------------------
  1018. aiVector3D XFileParser::ReadVector3()
  1019. {
  1020. aiVector3D vector;
  1021. vector.x = ReadFloat();
  1022. vector.y = ReadFloat();
  1023. vector.z = ReadFloat();
  1024. CheckForSeparator();
  1025. return vector;
  1026. }
  1027. // ------------------------------------------------------------------------------------------------
  1028. aiColor4D XFileParser::ReadRGBA()
  1029. {
  1030. aiColor4D color;
  1031. color.r = ReadFloat();
  1032. color.g = ReadFloat();
  1033. color.b = ReadFloat();
  1034. color.a = ReadFloat();
  1035. CheckForSeparator();
  1036. return color;
  1037. }
  1038. // ------------------------------------------------------------------------------------------------
  1039. aiColor3D XFileParser::ReadRGB()
  1040. {
  1041. aiColor3D color;
  1042. color.r = ReadFloat();
  1043. color.g = ReadFloat();
  1044. color.b = ReadFloat();
  1045. CheckForSeparator();
  1046. return color;
  1047. }
  1048. // Throws an exception with a line number and the given text.
  1049. void XFileParser::ThrowException( const std::string& pText)
  1050. {
  1051. if( mIsBinaryFormat)
  1052. throw new ImportErrorException( pText);
  1053. else
  1054. throw new ImportErrorException( boost::str( boost::format( "Line %d: %s") % mLineNumber % pText));
  1055. }
  1056. // ------------------------------------------------------------------------------------------------
  1057. // Filters the imported hierarchy for some degenerated cases that some exporters produce.
  1058. void XFileParser::FilterHierarchy( XFile::Node* pNode)
  1059. {
  1060. // if the node has just a single unnamed child containing a mesh, remove
  1061. // the anonymous node inbetween. The 3DSMax kwXport plugin seems to produce this
  1062. // mess in some cases
  1063. if( pNode->mChildren.size() == 1)
  1064. {
  1065. XFile::Node* child = pNode->mChildren.front();
  1066. if( child->mName.length() == 0 && child->mMeshes.size() > 0)
  1067. {
  1068. // transfer its meshes to us
  1069. for( unsigned int a = 0; a < child->mMeshes.size(); a++)
  1070. pNode->mMeshes.push_back( child->mMeshes[a]);
  1071. child->mMeshes.clear();
  1072. // then kill it
  1073. delete child;
  1074. pNode->mChildren.clear();
  1075. }
  1076. }
  1077. // recurse
  1078. for( unsigned int a = 0; a < pNode->mChildren.size(); a++)
  1079. FilterHierarchy( pNode->mChildren[a]);
  1080. }