OgreImporter.cpp 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871
  1. /*
  2. Open Asset Import Library (ASSIMP)
  3. ----------------------------------------------------------------------
  4. Copyright (c) 2006-2010, ASSIMP Development Team
  5. All rights reserved.
  6. Redistribution and use of this software in source and binary forms,
  7. with or without modification, are permitted provided that the
  8. following conditions are met:
  9. * Redistributions of source code must retain the above
  10. copyright notice, this list of conditions and the
  11. following disclaimer.
  12. * Redistributions in binary form must reproduce the above
  13. copyright notice, this list of conditions and the
  14. following disclaimer in the documentation and/or other
  15. materials provided with the distribution.
  16. * Neither the name of the ASSIMP team, nor the names of its
  17. contributors may be used to endorse or promote products
  18. derived from this software without specific prior
  19. written permission of the ASSIMP Development Team.
  20. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  21. "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  22. LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  23. A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  24. OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  25. SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  26. LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  27. DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  28. THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  29. (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  30. OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  31. ----------------------------------------------------------------------
  32. */
  33. /** @file OgreImporter.cpp
  34. * @brief Implementation of the Ogre XML (.mesh.xml) loader.
  35. */
  36. #include "AssimpPCH.h"
  37. #ifndef ASSIMP_BUILD_NO_OGRE_IMPORTER
  38. #include <vector>
  39. #include <sstream>
  40. using namespace std;
  41. //#include "boost/format.hpp"
  42. //#include "boost/foreach.hpp"
  43. using namespace boost;
  44. #include "OgreImporter.h"
  45. #include "irrXMLWrapper.h"
  46. namespace Assimp
  47. {
  48. namespace Ogre
  49. {
  50. bool OgreImporter::CanRead(const std::string &pFile, Assimp::IOSystem *pIOHandler, bool checkSig) const
  51. {
  52. if(!checkSig)//Check File Extension
  53. {
  54. std::string extension("mesh.xml");
  55. int l=extension.length();
  56. return pFile.substr(pFile.length()-l, l)==extension;
  57. }
  58. else//Check file Header
  59. {
  60. const char* tokens[] = {"<mesh>"};
  61. return BaseImporter::SearchFileHeaderForToken(pIOHandler, pFile, tokens, 1);
  62. }
  63. }
  64. void OgreImporter::InternReadFile(const std::string &pFile, aiScene *pScene, Assimp::IOSystem *pIOHandler)
  65. {
  66. m_CurrentFilename=pFile;
  67. m_CurrentIOHandler=pIOHandler;
  68. m_CurrentScene=pScene;
  69. //Open the File:
  70. boost::scoped_ptr<IOStream> file(pIOHandler->Open(pFile));
  71. if( file.get() == NULL)
  72. throw DeadlyImportError("Failed to open file "+pFile+".");
  73. //Read the Mesh File:
  74. boost::scoped_ptr<CIrrXML_IOStreamReader> mIOWrapper( new CIrrXML_IOStreamReader( file.get()));
  75. XmlReader* MeshFile = irr::io::createIrrXMLReader(mIOWrapper.get());
  76. if(!MeshFile)//parse the xml file
  77. throw DeadlyImportError("Failed to create XML Reader for "+pFile);
  78. DefaultLogger::get()->debug("Mesh File opened");
  79. //Read root Node:
  80. if(!(XmlRead(MeshFile) && string(MeshFile->getNodeName())=="mesh"))
  81. {
  82. throw DeadlyImportError("Root Node is not <mesh>! "+pFile+" "+MeshFile->getNodeName());
  83. }
  84. //Go to the submeshs:
  85. if(!(XmlRead(MeshFile) && string(MeshFile->getNodeName())=="submeshes"))
  86. {
  87. throw DeadlyImportError("No <submeshes> node in <mesh> node! "+pFile);
  88. }
  89. //-------------------Read the submeshs and materials:-----------------------
  90. std::list<shared_ptr<SubMesh> > SubMeshes;
  91. vector<aiMaterial*> Materials;
  92. XmlRead(MeshFile);
  93. while(MeshFile->getNodeName()==string("submesh"))
  94. {
  95. SubMesh* theSubMesh=new SubMesh();
  96. theSubMesh->MaterialName=GetAttribute<string>(MeshFile, "material");
  97. DefaultLogger::get()->debug("Loading Submehs with Material: "+theSubMesh->MaterialName);
  98. ReadSubMesh(*theSubMesh, MeshFile);
  99. //just a index in a array, we add a mesh in each loop cycle, so we get indicies like 0, 1, 2 ... n;
  100. //so it is important to do this before pushing the mesh in the vector!
  101. theSubMesh->MaterialIndex=SubMeshes.size();
  102. SubMeshes.push_back(shared_ptr<SubMesh>(theSubMesh));
  103. //Load the Material:
  104. aiMaterial* MeshMat=LoadMaterial(theSubMesh->MaterialName);
  105. //Set the Material:
  106. Materials.push_back(MeshMat);
  107. }
  108. if(SubMeshes.empty())
  109. throw DeadlyImportError("no submesh loaded!");
  110. if(SubMeshes.size()!=Materials.size())
  111. throw DeadlyImportError("materialcount doesn't match mesh count!");
  112. //____________________________________________________________
  113. //----------------Load the skeleton: -------------------------------
  114. vector<Bone> Bones;
  115. vector<Animation> Animations;
  116. if(MeshFile->getNodeName()==string("skeletonlink"))
  117. {
  118. string SkeletonFile=GetAttribute<string>(MeshFile, "name");
  119. LoadSkeleton(SkeletonFile, Bones, Animations);
  120. }
  121. else
  122. {
  123. DefaultLogger::get()->warn("No skeleton file will be loaded");
  124. DefaultLogger::get()->warn(MeshFile->getNodeName());
  125. }
  126. //__________________________________________________________________
  127. //----------------- Now fill the Assimp scene ---------------------------
  128. //put the aiMaterials in the scene:
  129. m_CurrentScene->mMaterials=new aiMaterial*[Materials.size()];
  130. m_CurrentScene->mNumMaterials=Materials.size();
  131. for(unsigned int i=0; i<Materials.size(); ++i)
  132. m_CurrentScene->mMaterials[i]=Materials[i];
  133. //create the aiMehs...
  134. vector<aiMesh*> aiMeshes;
  135. BOOST_FOREACH(shared_ptr<SubMesh> theSubMesh, SubMeshes)
  136. {
  137. aiMeshes.push_back(CreateAssimpSubMesh(*theSubMesh, Bones));
  138. }
  139. //... and put them in the scene:
  140. m_CurrentScene->mNumMeshes=aiMeshes.size();
  141. m_CurrentScene->mMeshes=new aiMesh*[aiMeshes.size()];
  142. memcpy(m_CurrentScene->mMeshes, &(aiMeshes[0]), sizeof(aiMeshes[0])*aiMeshes.size());
  143. //Create the root node
  144. m_CurrentScene->mRootNode=new aiNode("root");
  145. //link the meshs with the root node:
  146. m_CurrentScene->mRootNode->mMeshes=new unsigned int[SubMeshes.size()];
  147. m_CurrentScene->mRootNode->mNumMeshes=SubMeshes.size();
  148. for(unsigned int i=0; i<SubMeshes.size(); ++i)
  149. m_CurrentScene->mRootNode->mMeshes[i]=i;
  150. CreateAssimpSkeleton(Bones, Animations);
  151. //___________________________________________________________
  152. }
  153. void OgreImporter::GetExtensionList(std::set<std::string>& extensions)
  154. {
  155. extensions.insert("mesh.xml");
  156. }
  157. void OgreImporter::SetupProperties(const Importer* pImp)
  158. {
  159. m_MaterialLibFilename=pImp->GetPropertyString(AI_CONFIG_IMPORT_OGRE_MATERIAL_FILE, "Scene.material");
  160. }
  161. void OgreImporter::ReadSubMesh(SubMesh &theSubMesh, XmlReader *Reader)
  162. {
  163. XmlRead(Reader);
  164. //TODO: maybe we have alsways just 1 faces and 1 geometry and always in this order. this loop will only work correct, wenn the order
  165. //of faces and geometry changed, and not if we habe more than one of one
  166. while(Reader->getNodeName()==string("faces") || string(Reader->getNodeName())=="geometry" || Reader->getNodeName()==string("boneassignments"))
  167. {
  168. if(string(Reader->getNodeName())=="faces")//Read the face list
  169. {
  170. //some info logging:
  171. unsigned int NumFaces=GetAttribute<int>(Reader, "count");
  172. stringstream ss; ss <<"Submesh has " << NumFaces << " Faces.";
  173. DefaultLogger::get()->debug(ss.str());
  174. while(XmlRead(Reader) && Reader->getNodeName()==string("face"))
  175. {
  176. Face NewFace;
  177. NewFace.VertexIndices[0]=GetAttribute<int>(Reader, "v1");
  178. NewFace.VertexIndices[1]=GetAttribute<int>(Reader, "v2");
  179. NewFace.VertexIndices[2]=GetAttribute<int>(Reader, "v3");
  180. if(Reader->getAttributeValue("v4"))//this should be supported in the future
  181. {
  182. throw DeadlyImportError("Submesh has quads, only traingles are supported!");
  183. }
  184. theSubMesh.FaceList.push_back(NewFace);
  185. }
  186. }//end of faces
  187. else if(string(Reader->getNodeName())=="geometry")//Read the vertexdata
  188. {
  189. //some info logging:
  190. unsigned int NumVertices=GetAttribute<int>(Reader, "vertexcount");
  191. stringstream ss; ss<<"VertexCount: "<<NumVertices;
  192. DefaultLogger::get()->debug(ss.str());
  193. //General Informations about vertices
  194. XmlRead(Reader);
  195. if(!(Reader->getNodeName()==string("vertexbuffer")))
  196. {
  197. throw DeadlyImportError("vertexbuffer node is not first in geometry node!");
  198. }
  199. theSubMesh.HasPositions=GetAttribute<bool>(Reader, "positions");
  200. theSubMesh.HasNormals=GetAttribute<bool>(Reader, "normals");
  201. if(!Reader->getAttributeValue("texture_coords"))//we can have 1 or 0 uv channels, and if the mesh has no uvs, it also doesn't have the attribute
  202. theSubMesh.NumUvs=0;
  203. else
  204. theSubMesh.NumUvs=GetAttribute<int>(Reader, "texture_coords");
  205. if(theSubMesh.NumUvs>1)
  206. throw DeadlyImportError("too many texcoords (just 1 supported!)");
  207. //read all the vertices:
  208. XmlRead(Reader);
  209. while(Reader->getNodeName()==string("vertex"))
  210. {
  211. //read all vertex attributes:
  212. //Position
  213. if(theSubMesh.HasPositions)
  214. {
  215. XmlRead(Reader);
  216. aiVector3D NewPos;
  217. NewPos.x=GetAttribute<float>(Reader, "x");
  218. NewPos.y=GetAttribute<float>(Reader, "y");
  219. NewPos.z=GetAttribute<float>(Reader, "z");
  220. theSubMesh.Positions.push_back(NewPos);
  221. }
  222. //Normal
  223. if(theSubMesh.HasNormals)
  224. {
  225. XmlRead(Reader);
  226. aiVector3D NewNormal;
  227. NewNormal.x=GetAttribute<float>(Reader, "x");
  228. NewNormal.y=GetAttribute<float>(Reader, "y");
  229. NewNormal.z=GetAttribute<float>(Reader, "z");
  230. theSubMesh.Normals.push_back(NewNormal);
  231. }
  232. //Uv:
  233. if(1==theSubMesh.NumUvs)
  234. {
  235. XmlRead(Reader);
  236. aiVector3D NewUv;
  237. NewUv.x=GetAttribute<float>(Reader, "u");
  238. NewUv.y=GetAttribute<float>(Reader, "v")*(-1)+1;//flip the uv vertikal, blender exports them so!
  239. theSubMesh.Uvs.push_back(NewUv);
  240. }
  241. XmlRead(Reader);
  242. }
  243. }//end of "geometry
  244. else if(string(Reader->getNodeName())=="boneassignments")
  245. {
  246. theSubMesh.Weights.resize(theSubMesh.Positions.size());
  247. while(XmlRead(Reader) && Reader->getNodeName()==string("vertexboneassignment"))
  248. {
  249. Weight NewWeight;
  250. unsigned int VertexId=GetAttribute<int>(Reader, "vertexindex");
  251. NewWeight.BoneId=GetAttribute<int>(Reader, "boneindex");
  252. NewWeight.Value=GetAttribute<float>(Reader, "weight");
  253. theSubMesh.BonesUsed=max(theSubMesh.BonesUsed, NewWeight.BoneId+1);//calculate the number of bones used (this is the highest id +1 becuase bone ids start at 0)
  254. theSubMesh.Weights[VertexId].push_back(NewWeight);
  255. //XmlRead(Reader);//Once i had this line, and than i got only every second boneassignment, but my first test models had even boneassignment counts, so i thougt, everything would work. And yes, i HATE irrXML!!!
  256. }
  257. }//end of boneassignments
  258. }
  259. DefaultLogger::get()->debug(str(format("Positionen: %1% Normale: %2% TexCoords: %3%")
  260. % theSubMesh.Positions.size() % theSubMesh.Normals.size() % theSubMesh.Uvs.size()));
  261. DefaultLogger::get()->warn(Reader->getNodeName());
  262. //---------------Make all Vertexes unique: (this is required by assimp)-----------------------
  263. vector<Face> UniqueFaceList(theSubMesh.FaceList.size());
  264. unsigned int UniqueVertexCount=theSubMesh.FaceList.size()*3;//*3 because each face consists of 3 vertexes, because we only support triangles^^
  265. vector<aiVector3D> UniquePositions(UniqueVertexCount);
  266. vector<aiVector3D> UniqueNormals(UniqueVertexCount);
  267. vector<aiVector3D> UniqueUvs(UniqueVertexCount);
  268. vector< vector<Weight> > UniqueWeights((theSubMesh.Weights.size() ? UniqueVertexCount : 0));
  269. for(unsigned int i=0; i<theSubMesh.FaceList.size(); ++i)
  270. {
  271. //We precalculate the index vlaues her, because we need them in all vertex attributes
  272. unsigned int Vertex1=theSubMesh.FaceList[i].VertexIndices[0];
  273. unsigned int Vertex2=theSubMesh.FaceList[i].VertexIndices[1];
  274. unsigned int Vertex3=theSubMesh.FaceList[i].VertexIndices[2];
  275. UniquePositions[3*i+0]=theSubMesh.Positions[Vertex1];
  276. UniquePositions[3*i+1]=theSubMesh.Positions[Vertex2];
  277. UniquePositions[3*i+2]=theSubMesh.Positions[Vertex3];
  278. UniqueNormals[3*i+0]=theSubMesh.Normals[Vertex1];
  279. UniqueNormals[3*i+1]=theSubMesh.Normals[Vertex2];
  280. UniqueNormals[3*i+2]=theSubMesh.Normals[Vertex3];
  281. if(1==theSubMesh.NumUvs)
  282. {
  283. UniqueUvs[3*i+0]=theSubMesh.Uvs[Vertex1];
  284. UniqueUvs[3*i+1]=theSubMesh.Uvs[Vertex2];
  285. UniqueUvs[3*i+2]=theSubMesh.Uvs[Vertex3];
  286. }
  287. if (theSubMesh.Weights.size()) {
  288. UniqueWeights[3*i+0]=theSubMesh.Weights[Vertex1];
  289. UniqueWeights[3*i+1]=theSubMesh.Weights[Vertex2];
  290. UniqueWeights[3*i+2]=theSubMesh.Weights[Vertex3];
  291. }
  292. //The indexvalues a just continuous numbers (0, 1, 2, 3, 4, 5, 6...)
  293. UniqueFaceList[i].VertexIndices[0]=3*i+0;
  294. UniqueFaceList[i].VertexIndices[1]=3*i+1;
  295. UniqueFaceList[i].VertexIndices[2]=3*i+2;
  296. }
  297. //_________________________________________________________________________________________
  298. //now we have the unique datas, but want them in the SubMesh, so we swap all the containers:
  299. theSubMesh.FaceList.swap(UniqueFaceList);
  300. theSubMesh.Positions.swap(UniquePositions);
  301. theSubMesh.Normals.swap(UniqueNormals);
  302. theSubMesh.Uvs.swap(UniqueUvs);
  303. theSubMesh.Weights.swap(UniqueWeights);
  304. //------------- normalize weights -----------------------------
  305. //The Blender exporter doesn't care about whether the sum of all boneweights for a single vertex equals 1 or not,
  306. //so we have to make this sure:
  307. for(unsigned int VertexId=0; VertexId<theSubMesh.Weights.size(); ++VertexId)//iterate over all vertices
  308. {
  309. float WeightSum=0.0f;
  310. for(unsigned int BoneId=0; BoneId<theSubMesh.Weights[VertexId].size(); ++BoneId)//iterate over all bones
  311. {
  312. WeightSum+=theSubMesh.Weights[VertexId][BoneId].Value;
  313. }
  314. //check if the sum is too far away from 1
  315. if(WeightSum<1.0f-0.05f || WeightSum>1.0f+0.05f)
  316. {
  317. //normalize all weights:
  318. for(unsigned int BoneId=0; BoneId<theSubMesh.Weights[VertexId].size(); ++BoneId)//iterate over all bones
  319. {
  320. theSubMesh.Weights[VertexId][BoneId].Value/=WeightSum;
  321. }
  322. }
  323. }
  324. //_________________________________________________________
  325. }
  326. aiMesh* OgreImporter::CreateAssimpSubMesh(const SubMesh& theSubMesh, const vector<Bone>& Bones) const
  327. {
  328. const aiScene* const m_CurrentScene=this->m_CurrentScene;//make sure, that we can access but not change the scene
  329. aiMesh* NewAiMesh=new aiMesh();
  330. //Positions
  331. NewAiMesh->mVertices=new aiVector3D[theSubMesh.Positions.size()];
  332. memcpy(NewAiMesh->mVertices, &theSubMesh.Positions[0], theSubMesh.Positions.size()*sizeof(aiVector3D));
  333. NewAiMesh->mNumVertices=theSubMesh.Positions.size();
  334. //Normals
  335. NewAiMesh->mNormals=new aiVector3D[theSubMesh.Normals.size()];
  336. memcpy(NewAiMesh->mNormals, &theSubMesh.Normals[0], theSubMesh.Normals.size()*sizeof(aiVector3D));
  337. //Uvs
  338. if(0!=theSubMesh.NumUvs)
  339. {
  340. NewAiMesh->mNumUVComponents[0]=2;
  341. NewAiMesh->mTextureCoords[0]= new aiVector3D[theSubMesh.Uvs.size()];
  342. memcpy(NewAiMesh->mTextureCoords[0], &theSubMesh.Uvs[0], theSubMesh.Uvs.size()*sizeof(aiVector3D));
  343. }
  344. //---------------------------------------- Bones --------------------------------------------
  345. //Copy the weights in in Bone-Vertices Struktur
  346. //(we have them in a Vertex-Bones Structur, this is much easier for making them unique, which is required by assimp
  347. vector< vector<aiVertexWeight> > aiWeights(theSubMesh.BonesUsed);//now the outer list are the bones, and the inner vector the vertices
  348. for(unsigned int VertexId=0; VertexId<theSubMesh.Weights.size(); ++VertexId)//iterate over all vertices
  349. {
  350. for(unsigned int BoneId=0; BoneId<theSubMesh.Weights[VertexId].size(); ++BoneId)//iterate over all bones
  351. {
  352. aiVertexWeight NewWeight;
  353. NewWeight.mVertexId=VertexId;//the current Vertex, we can't use the Id form the submehs weights, because they are bone id's
  354. NewWeight.mWeight=theSubMesh.Weights[VertexId][BoneId].Value;
  355. aiWeights[theSubMesh.Weights[VertexId][BoneId].BoneId].push_back(NewWeight);
  356. }
  357. }
  358. vector<aiBone*> aiBones;
  359. aiBones.reserve(theSubMesh.BonesUsed);//the vector might be smaller, because there might be empty bones (bones that are not attached to any vertex)
  360. //create all the bones and fill them with informations
  361. for(unsigned int i=0; i<theSubMesh.BonesUsed; ++i)
  362. {
  363. if(aiWeights[i].size()>0)
  364. {
  365. aiBone* NewBone=new aiBone();
  366. NewBone->mNumWeights=aiWeights[i].size();
  367. NewBone->mWeights=new aiVertexWeight[aiWeights[i].size()];
  368. memcpy(NewBone->mWeights, &(aiWeights[i][0]), sizeof(aiVertexWeight)*aiWeights[i].size());
  369. NewBone->mName=Bones[i].Name;//The bone list should be sorted after its id's, this was done in LoadSkeleton
  370. NewBone->mOffsetMatrix=Bones[i].BoneToWorldSpace;
  371. aiBones.push_back(NewBone);
  372. }
  373. }
  374. NewAiMesh->mNumBones=aiBones.size();
  375. // mBones must be NULL if mNumBones is non 0 or the validation fails.
  376. if (aiBones.size()) {
  377. NewAiMesh->mBones=new aiBone* [aiBones.size()];
  378. memcpy(NewAiMesh->mBones, &(aiBones[0]), aiBones.size()*sizeof(aiBone*));
  379. }
  380. //______________________________________________________________________________________________________
  381. //Faces
  382. NewAiMesh->mFaces=new aiFace[theSubMesh.FaceList.size()];
  383. for(unsigned int i=0; i<theSubMesh.FaceList.size(); ++i)
  384. {
  385. NewAiMesh->mFaces[i].mNumIndices=3;
  386. NewAiMesh->mFaces[i].mIndices=new unsigned int[3];
  387. NewAiMesh->mFaces[i].mIndices[0]=theSubMesh.FaceList[i].VertexIndices[0];
  388. NewAiMesh->mFaces[i].mIndices[1]=theSubMesh.FaceList[i].VertexIndices[1];
  389. NewAiMesh->mFaces[i].mIndices[2]=theSubMesh.FaceList[i].VertexIndices[2];
  390. }
  391. NewAiMesh->mNumFaces=theSubMesh.FaceList.size();
  392. //Link the material:
  393. NewAiMesh->mMaterialIndex=theSubMesh.MaterialIndex;//the index is set by the function who called ReadSubMesh
  394. return NewAiMesh;
  395. }
  396. void OgreImporter::LoadSkeleton(std::string FileName, vector<Bone> &Bones, vector<Animation> &Animations) const
  397. {
  398. const aiScene* const m_CurrentScene=this->m_CurrentScene;//make sure, that we can access but not change the scene
  399. //most likely the skeleton file will only end with .skeleton
  400. //But this is a xml reader, so we need: .skeleton.xml
  401. FileName+=".xml";
  402. DefaultLogger::get()->debug(string("Loading Skeleton: ")+FileName);
  403. //Open the File:
  404. boost::scoped_ptr<IOStream> File(m_CurrentIOHandler->Open(FileName));
  405. if(NULL==File.get())
  406. throw DeadlyImportError("Failed to open skeleton file "+FileName+".");
  407. //Read the Mesh File:
  408. boost::scoped_ptr<CIrrXML_IOStreamReader> mIOWrapper(new CIrrXML_IOStreamReader(File.get()));
  409. XmlReader* SkeletonFile = irr::io::createIrrXMLReader(mIOWrapper.get());
  410. if(!SkeletonFile)
  411. throw DeadlyImportError(string("Failed to create XML Reader for ")+FileName);
  412. //Quick note: Whoever read this should know this one thing: irrXml fucking sucks!!!
  413. XmlRead(SkeletonFile);
  414. if(string("skeleton")!=SkeletonFile->getNodeName())
  415. throw DeadlyImportError("No <skeleton> node in SkeletonFile: "+FileName);
  416. //------------------------------------load bones-----------------------------------------
  417. XmlRead(SkeletonFile);
  418. if(string("bones")!=SkeletonFile->getNodeName())
  419. throw DeadlyImportError("No bones node in skeleton "+FileName);
  420. XmlRead(SkeletonFile);
  421. while(string("bone")==SkeletonFile->getNodeName())
  422. {
  423. //TODO: Maybe we can have bone ids for the errrors, but normaly, they should never appear, so what....
  424. //read a new bone:
  425. Bone NewBone;
  426. NewBone.Id=GetAttribute<int>(SkeletonFile, "id");
  427. NewBone.Name=GetAttribute<string>(SkeletonFile, "name");
  428. //load the position:
  429. XmlRead(SkeletonFile);
  430. if(string("position")!=SkeletonFile->getNodeName())
  431. throw DeadlyImportError("Position is not first node in Bone!");
  432. NewBone.Position.x=GetAttribute<float>(SkeletonFile, "x");
  433. NewBone.Position.y=GetAttribute<float>(SkeletonFile, "y");
  434. NewBone.Position.z=GetAttribute<float>(SkeletonFile, "z");
  435. //Rotation:
  436. XmlRead(SkeletonFile);
  437. if(string("rotation")!=SkeletonFile->getNodeName())
  438. throw DeadlyImportError("Rotation is not the second node in Bone!");
  439. NewBone.RotationAngle=GetAttribute<float>(SkeletonFile, "angle");
  440. XmlRead(SkeletonFile);
  441. if(string("axis")!=SkeletonFile->getNodeName())
  442. throw DeadlyImportError("No axis specified for bone rotation!");
  443. NewBone.RotationAxis.x=GetAttribute<float>(SkeletonFile, "x");
  444. NewBone.RotationAxis.y=GetAttribute<float>(SkeletonFile, "y");
  445. NewBone.RotationAxis.z=GetAttribute<float>(SkeletonFile, "z");
  446. //append the newly loaded bone to the bone list
  447. Bones.push_back(NewBone);
  448. //Proceed to the next bone:
  449. XmlRead(SkeletonFile);
  450. }
  451. //The bones in the file a not neccesarly ordered by there id's so we do it now:
  452. std::sort(Bones.begin(), Bones.end());
  453. //now the id of each bone should be equal to its position in the vector:
  454. //so we do a simple check:
  455. {
  456. bool IdsOk=true;
  457. for(int i=0; i<static_cast<signed int>(Bones.size()); ++i)//i is signed, because all Id's are also signed!
  458. {
  459. if(Bones[i].Id!=i)
  460. IdsOk=false;
  461. }
  462. if(!IdsOk)
  463. throw DeadlyImportError("Bone Ids are not valid!"+FileName);
  464. }
  465. DefaultLogger::get()->debug(str(format("Number of bones: %1%") % Bones.size()));
  466. //________________________________________________________________________________
  467. //----------------------------load bonehierarchy--------------------------------
  468. if(string("bonehierarchy")!=SkeletonFile->getNodeName())
  469. throw DeadlyImportError("no bonehierarchy node in "+FileName);
  470. DefaultLogger::get()->debug("loading bonehierarchy...");
  471. XmlRead(SkeletonFile);
  472. while(string("boneparent")==SkeletonFile->getNodeName())
  473. {
  474. string Child, Parent;
  475. Child=GetAttribute<string>(SkeletonFile, "bone");
  476. Parent=GetAttribute<string>(SkeletonFile, "parent");
  477. unsigned int ChildId, ParentId;
  478. ChildId=find(Bones.begin(), Bones.end(), Child)->Id;
  479. ParentId=find(Bones.begin(), Bones.end(), Parent)->Id;
  480. Bones[ChildId].ParentId=ParentId;
  481. Bones[ParentId].Children.push_back(ChildId);
  482. XmlRead(SkeletonFile);//i once forget this line, which led to an endless loop, did i mentioned, that irrxml sucks??
  483. }
  484. //_____________________________________________________________________________
  485. //--------- Calculate the WorldToBoneSpace Matrix recursivly for all bones: ------------------
  486. BOOST_FOREACH(Bone theBone, Bones)
  487. {
  488. if(-1==theBone.ParentId) //the bone is a root bone
  489. {
  490. theBone.CalculateBoneToWorldSpaceMatrix(Bones);
  491. }
  492. }
  493. //_______________________________________________________________________
  494. //---------------------------load animations-----------------------------
  495. if(string("animations")==SkeletonFile->getNodeName())//animations are optional values
  496. {
  497. DefaultLogger::get()->debug("Loading Animations");
  498. XmlRead(SkeletonFile);
  499. while(string("animation")==SkeletonFile->getNodeName())
  500. {
  501. Animation NewAnimation;
  502. NewAnimation.Name=GetAttribute<string>(SkeletonFile, "name");
  503. NewAnimation.Length=GetAttribute<float>(SkeletonFile, "length");
  504. //Load all Tracks
  505. XmlRead(SkeletonFile);
  506. if(string("tracks")!=SkeletonFile->getNodeName())
  507. throw DeadlyImportError("no tracks node in animation");
  508. XmlRead(SkeletonFile);
  509. while(string("track")==SkeletonFile->getNodeName())
  510. {
  511. Track NewTrack;
  512. NewTrack.BoneName=GetAttribute<string>(SkeletonFile, "bone");
  513. //Load all keyframes;
  514. XmlRead(SkeletonFile);
  515. if(string("keyframes")!=SkeletonFile->getNodeName())
  516. throw DeadlyImportError("no keyframes node!");
  517. XmlRead(SkeletonFile);
  518. while(string("keyframe")==SkeletonFile->getNodeName())
  519. {
  520. Keyframe NewKeyframe;
  521. NewKeyframe.Time=GetAttribute<float>(SkeletonFile, "time");
  522. //Position:
  523. XmlRead(SkeletonFile);
  524. if(string("translate")!=SkeletonFile->getNodeName())
  525. throw DeadlyImportError("translate node not first in keyframe");
  526. NewKeyframe.Position.x=GetAttribute<float>(SkeletonFile, "x");
  527. NewKeyframe.Position.y=GetAttribute<float>(SkeletonFile, "y");
  528. NewKeyframe.Position.z=GetAttribute<float>(SkeletonFile, "z");
  529. //Rotation:
  530. XmlRead(SkeletonFile);
  531. if(string("rotate")!=SkeletonFile->getNodeName())
  532. throw DeadlyImportError("rotate is not second node in keyframe");
  533. float RotationAngle=GetAttribute<float>(SkeletonFile, "angle");
  534. aiVector3D RotationAxis;
  535. XmlRead(SkeletonFile);
  536. if(string("axis")!=SkeletonFile->getNodeName())
  537. throw DeadlyImportError("No axis for keyframe rotation!");
  538. RotationAxis.x=GetAttribute<float>(SkeletonFile, "x");
  539. RotationAxis.y=GetAttribute<float>(SkeletonFile, "y");
  540. RotationAxis.z=GetAttribute<float>(SkeletonFile, "z");
  541. NewKeyframe.Rotation=aiQuaternion(RotationAxis, RotationAngle);
  542. //Scaling:
  543. XmlRead(SkeletonFile);
  544. if(string("scale")!=SkeletonFile->getNodeName())
  545. throw DeadlyImportError("no scalling key in keyframe!");
  546. NewKeyframe.Scaling.x=GetAttribute<float>(SkeletonFile, "x");
  547. NewKeyframe.Scaling.y=GetAttribute<float>(SkeletonFile, "y");
  548. NewKeyframe.Scaling.z=GetAttribute<float>(SkeletonFile, "z");
  549. NewTrack.Keyframes.push_back(NewKeyframe);
  550. XmlRead(SkeletonFile);
  551. }
  552. NewAnimation.Tracks.push_back(NewTrack);
  553. }
  554. Animations.push_back(NewAnimation);
  555. }
  556. }
  557. //_____________________________________________________________________________
  558. }
  559. void OgreImporter::CreateAssimpSkeleton(const std::vector<Bone> &Bones, const std::vector<Animation> &Animations) const
  560. {
  561. const aiScene* const m_CurrentScene=this->m_CurrentScene;//make sure, that we can access but not change the scene
  562. //-----------------skeleton is completly loaded, now put it in the assimp scene:-------------------------------
  563. if(!m_CurrentScene->mRootNode)
  564. throw DeadlyImportError("No root node exists!!");
  565. if(0!=m_CurrentScene->mRootNode->mNumChildren)
  566. throw DeadlyImportError("Root Node already has childnodes!");
  567. //--------------Createt the assimp bone hierarchy-----------------
  568. DefaultLogger::get()->debug("Root Bones");
  569. vector<aiNode*> RootBoneNodes;
  570. BOOST_FOREACH(Bone theBone, Bones)
  571. {
  572. if(-1==theBone.ParentId) //the bone is a root bone
  573. {
  574. DefaultLogger::get()->debug(theBone.Name);
  575. RootBoneNodes.push_back(CreateAiNodeFromBone(theBone.Id, Bones, m_CurrentScene->mRootNode));//which will recursily add all other nodes
  576. }
  577. }
  578. m_CurrentScene->mRootNode->mNumChildren=RootBoneNodes.size();
  579. m_CurrentScene->mRootNode->mChildren=new aiNode*[RootBoneNodes.size()];
  580. memcpy(m_CurrentScene->mRootNode->mChildren, &RootBoneNodes[0], sizeof(aiNode*)*RootBoneNodes.size());
  581. //_______________________________________________________________
  582. }
  583. void OgreImporter::PutAnimationsInScene(const std::vector<Bone> &Bones, const std::vector<Animation> &Animations)
  584. {
  585. //-----------------Create the Assimp Animations --------------------
  586. if(Animations.size()>0)//Maybe the model had only a skeleton and no animations. (If it also has no skeleton, this function would'nt have benn called
  587. {
  588. m_CurrentScene->mNumAnimations=Animations.size();
  589. m_CurrentScene->mAnimations=new aiAnimation*[Animations.size()];
  590. for(unsigned int i=0; i<Animations.size(); ++i)//create all animations
  591. {
  592. aiAnimation* NewAnimation=new aiAnimation();
  593. NewAnimation->mName=Animations[i].Name;
  594. NewAnimation->mDuration=Animations[i].Length;
  595. NewAnimation->mTicksPerSecond=1.0f;
  596. //Create all tracks in this animation
  597. NewAnimation->mNumChannels=Animations[i].Tracks.size();
  598. NewAnimation->mChannels=new aiNodeAnim*[Animations[i].Tracks.size()];
  599. for(unsigned int j=0; j<Animations[i].Tracks.size(); ++j)
  600. {
  601. aiNodeAnim* NewNodeAnim=new aiNodeAnim();
  602. NewNodeAnim->mNodeName=Animations[i].Tracks[j].BoneName;
  603. //we need this, to acces the bones default pose, which we need to make keys absolute
  604. vector<Bone>::const_iterator CurBone=find(Bones.begin(), Bones.end(), NewNodeAnim->mNodeName);
  605. aiMatrix4x4 t0, t1;
  606. aiMatrix4x4 DefBonePose=//The default bone pose doesnt have a scaling value
  607. aiMatrix4x4::Rotation(CurBone->RotationAngle, CurBone->RotationAxis, t0)
  608. * aiMatrix4x4::Translation(CurBone->Position, t1);
  609. //Create the keyframe arrays...
  610. unsigned int KeyframeCount=Animations[i].Tracks[j].Keyframes.size();
  611. NewNodeAnim->mNumPositionKeys=KeyframeCount;
  612. NewNodeAnim->mPositionKeys=new aiVectorKey[KeyframeCount];
  613. NewNodeAnim->mNumRotationKeys=KeyframeCount;
  614. NewNodeAnim->mRotationKeys=new aiQuatKey[KeyframeCount];
  615. NewNodeAnim->mNumScalingKeys=KeyframeCount;
  616. NewNodeAnim->mScalingKeys=new aiVectorKey[KeyframeCount];
  617. //...and fill them
  618. for(unsigned int k=0; k<KeyframeCount; ++k)
  619. {
  620. aiMatrix4x4 t2, t3;
  621. //Create a matrix to transfrom a vector from the bones default pose to the bone bones in this animation key
  622. aiMatrix4x4 PoseToKey=aiMatrix4x4::Scaling(Animations[i].Tracks[j].Keyframes[k].Scaling, t2) //scale
  623. * aiMatrix4x4(Animations[i].Tracks[j].Keyframes[k].Rotation.GetMatrix()) //rot
  624. * aiMatrix4x4::Translation(Animations[i].Tracks[j].Keyframes[k].Position, t3); //pos
  625. //calculate the complete transformation from world space to bone space
  626. aiMatrix4x4 CompleteTransform=DefBonePose * PoseToKey;
  627. aiVector3D Pos;
  628. aiQuaternion Rot;
  629. aiVector3D Scale;
  630. CompleteTransform.Decompose(Scale, Rot, Pos);
  631. NewNodeAnim->mPositionKeys[k].mTime=Animations[i].Tracks[j].Keyframes[k].Time;
  632. NewNodeAnim->mPositionKeys[k].mValue=Pos;
  633. NewNodeAnim->mRotationKeys[k].mTime=Animations[i].Tracks[j].Keyframes[k].Time;
  634. NewNodeAnim->mRotationKeys[k].mValue=Rot;
  635. NewNodeAnim->mScalingKeys[k].mTime=Animations[i].Tracks[j].Keyframes[k].Time;
  636. NewNodeAnim->mScalingKeys[k].mValue=Scale;
  637. }
  638. NewAnimation->mChannels[j]=NewNodeAnim;
  639. }
  640. m_CurrentScene->mAnimations[i]=NewAnimation;
  641. }
  642. }
  643. //TODO: Auf nicht vorhandene Animationskeys achten!
  644. //#pragma warning (s.o.)
  645. //__________________________________________________________________
  646. }
  647. aiNode* OgreImporter::CreateAiNodeFromBone(int BoneId, const std::vector<Bone> &Bones, aiNode* ParentNode) const
  648. {
  649. const aiScene* const m_CurrentScene=this->m_CurrentScene;//make sure, that we can access but not change the scene
  650. //----Create the node for this bone and set its values-----
  651. aiNode* NewNode=new aiNode(Bones[BoneId].Name);
  652. NewNode->mParent=ParentNode;
  653. aiMatrix4x4 t0,t1;
  654. //create a matrix from the transformation values of the ogre bone
  655. NewNode->mTransformation=aiMatrix4x4::Rotation(Bones[BoneId].RotationAngle, Bones[BoneId].RotationAxis, t1)
  656. * aiMatrix4x4::Translation(Bones[BoneId].Position, t0)
  657. ;
  658. //__________________________________________________________
  659. //---------- recursivly create all children Nodes: ----------
  660. NewNode->mNumChildren=Bones[BoneId].Children.size();
  661. NewNode->mChildren=new aiNode*[Bones[BoneId].Children.size()];
  662. for(unsigned int i=0; i<Bones[BoneId].Children.size(); ++i)
  663. {
  664. NewNode->mChildren[i]=CreateAiNodeFromBone(Bones[BoneId].Children[i], Bones, NewNode);
  665. }
  666. //____________________________________________________
  667. return NewNode;
  668. }
  669. void Bone::CalculateBoneToWorldSpaceMatrix(vector<Bone> &Bones)
  670. {
  671. //Calculate the matrix for this bone:
  672. aiMatrix4x4 t0,t1;
  673. aiMatrix4x4 Transf=aiMatrix4x4::Translation(-Position, t0)
  674. * aiMatrix4x4::Rotation(-RotationAngle, RotationAxis, t1)
  675. ;
  676. if(-1==ParentId)
  677. {
  678. BoneToWorldSpace=Transf;
  679. }
  680. else
  681. {
  682. BoneToWorldSpace=Transf*Bones[ParentId].BoneToWorldSpace;
  683. }
  684. //and recursivly for all children:
  685. BOOST_FOREACH(int theChildren, Children)
  686. {
  687. Bones[theChildren].CalculateBoneToWorldSpaceMatrix(Bones);
  688. }
  689. }
  690. }//namespace Ogre
  691. }//namespace Assimp
  692. #endif // !! ASSIMP_BUILD_NO_OGRE_IMPORTER