3DSConverter.cpp 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837
  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 3ds importer class */
  35. #include "AssimpPCH.h"
  36. #ifndef ASSIMP_BUILD_NO_3DS_IMPORTER
  37. // internal headers
  38. #include "3DSLoader.h"
  39. #include "TargetAnimation.h"
  40. using namespace Assimp;
  41. // ------------------------------------------------------------------------------------------------
  42. // Setup final material indices, generae a default material if necessary
  43. void Discreet3DSImporter::ReplaceDefaultMaterial()
  44. {
  45. // Try to find an existing material that matches the
  46. // typical default material setting:
  47. // - no textures
  48. // - diffuse color (in grey!)
  49. // NOTE: This is here to workaround the fact that some
  50. // exporters are writing a default material, too.
  51. unsigned int idx = 0xcdcdcdcd;
  52. for (unsigned int i = 0; i < mScene->mMaterials.size();++i)
  53. {
  54. std::string s = mScene->mMaterials[i].mName;
  55. for (std::string::iterator it = s.begin(); it != s.end(); ++it)
  56. *it = ::tolower(*it);
  57. if (std::string::npos == s.find("default"))continue;
  58. if (mScene->mMaterials[i].mDiffuse.r !=
  59. mScene->mMaterials[i].mDiffuse.g ||
  60. mScene->mMaterials[i].mDiffuse.r !=
  61. mScene->mMaterials[i].mDiffuse.b)continue;
  62. if (mScene->mMaterials[i].sTexDiffuse.mMapName.length() != 0 ||
  63. mScene->mMaterials[i].sTexBump.mMapName.length() != 0 ||
  64. mScene->mMaterials[i].sTexOpacity.mMapName.length() != 0 ||
  65. mScene->mMaterials[i].sTexEmissive.mMapName.length() != 0 ||
  66. mScene->mMaterials[i].sTexSpecular.mMapName.length() != 0 ||
  67. mScene->mMaterials[i].sTexShininess.mMapName.length() != 0 )
  68. {
  69. continue;
  70. }
  71. idx = i;
  72. }
  73. if (0xcdcdcdcd == idx)idx = (unsigned int)mScene->mMaterials.size();
  74. // now iterate through all meshes and through all faces and
  75. // find all faces that are using the default material
  76. unsigned int cnt = 0;
  77. for (std::vector<D3DS::Mesh>::iterator
  78. i = mScene->mMeshes.begin();
  79. i != mScene->mMeshes.end();++i)
  80. {
  81. for (std::vector<unsigned int>::iterator
  82. a = (*i).mFaceMaterials.begin();
  83. a != (*i).mFaceMaterials.end();++a)
  84. {
  85. // NOTE: The additional check seems to be necessary,
  86. // some exporters seem to generate invalid data here
  87. if (0xcdcdcdcd == (*a))
  88. {
  89. (*a) = idx;
  90. ++cnt;
  91. }
  92. else if ( (*a) >= mScene->mMaterials.size())
  93. {
  94. (*a) = idx;
  95. DefaultLogger::get()->warn("Material index overflow in 3DS file. Using default material");
  96. ++cnt;
  97. }
  98. }
  99. }
  100. if (cnt && idx == mScene->mMaterials.size())
  101. {
  102. // We need to create our own default material
  103. D3DS::Material sMat;
  104. sMat.mDiffuse = aiColor3D(0.3f,0.3f,0.3f);
  105. sMat.mName = "%%%DEFAULT";
  106. mScene->mMaterials.push_back(sMat);
  107. DefaultLogger::get()->info("3DS: Generating default material");
  108. }
  109. }
  110. // ------------------------------------------------------------------------------------------------
  111. // Check whether all indices are valid. Otherwise we'd crash before the validation step is reached
  112. void Discreet3DSImporter::CheckIndices(D3DS::Mesh& sMesh)
  113. {
  114. for (std::vector< D3DS::Face >::iterator i = sMesh.mFaces.begin(); i != sMesh.mFaces.end();++i)
  115. {
  116. // check whether all indices are in range
  117. for (unsigned int a = 0; a < 3;++a)
  118. {
  119. if ((*i).mIndices[a] >= sMesh.mPositions.size())
  120. {
  121. DefaultLogger::get()->warn("3DS: Vertex index overflow)");
  122. (*i).mIndices[a] = (uint32_t)sMesh.mPositions.size()-1;
  123. }
  124. if ( !sMesh.mTexCoords.empty() && (*i).mIndices[a] >= sMesh.mTexCoords.size())
  125. {
  126. DefaultLogger::get()->warn("3DS: Texture coordinate index overflow)");
  127. (*i).mIndices[a] = (uint32_t)sMesh.mTexCoords.size()-1;
  128. }
  129. }
  130. }
  131. }
  132. // ------------------------------------------------------------------------------------------------
  133. // Generate out unique verbose format representation
  134. void Discreet3DSImporter::MakeUnique(D3DS::Mesh& sMesh)
  135. {
  136. // TODO: really necessary? I don't think. Just a waste of memory and time
  137. // to do it now in a separate buffer.
  138. // Allocate output storage
  139. std::vector<aiVector3D> vNew (sMesh.mFaces.size() * 3);
  140. std::vector<aiVector3D> vNew2;
  141. if (sMesh.mTexCoords.size())
  142. vNew2.resize(sMesh.mFaces.size() * 3);
  143. for (unsigned int i = 0, base = 0; i < sMesh.mFaces.size();++i)
  144. {
  145. D3DS::Face& face = sMesh.mFaces[i];
  146. // Positions
  147. for (unsigned int a = 0; a < 3;++a,++base)
  148. {
  149. vNew[base] = sMesh.mPositions[face.mIndices[a]];
  150. if (sMesh.mTexCoords.size())
  151. vNew2[base] = sMesh.mTexCoords[face.mIndices[a]];
  152. face.mIndices[a] = base;
  153. }
  154. }
  155. sMesh.mPositions = vNew;
  156. sMesh.mTexCoords = vNew2;
  157. }
  158. // ------------------------------------------------------------------------------------------------
  159. // Convert a 3DS texture to texture keys in an aiMaterial
  160. void CopyTexture(MaterialHelper& mat, D3DS::Texture& texture, aiTextureType type)
  161. {
  162. // Setup the texture name
  163. aiString tex;
  164. tex.Set( texture.mMapName);
  165. mat.AddProperty( &tex, AI_MATKEY_TEXTURE(type,0));
  166. // Setup the texture blend factor
  167. if (is_not_qnan(texture.mTextureBlend))
  168. mat.AddProperty<float>( &texture.mTextureBlend, 1, AI_MATKEY_TEXBLEND(type,0));
  169. // Setup the texture mapping mode
  170. mat.AddProperty<int>((int*)&texture.mMapMode,1,AI_MATKEY_MAPPINGMODE_U(type,0));
  171. mat.AddProperty<int>((int*)&texture.mMapMode,1,AI_MATKEY_MAPPINGMODE_V(type,0));
  172. // Mirroring - double the scaling values
  173. // FIXME: this is not really correct ...
  174. if (texture.mMapMode == aiTextureMapMode_Mirror)
  175. {
  176. texture.mScaleU *= 2.f;
  177. texture.mScaleV *= 2.f;
  178. texture.mOffsetU /= 2.f;
  179. texture.mOffsetV /= 2.f;
  180. }
  181. // Setup texture UV transformations
  182. mat.AddProperty<float>(&texture.mOffsetU,5,AI_MATKEY_UVTRANSFORM(type,0));
  183. }
  184. // ------------------------------------------------------------------------------------------------
  185. // Convert a 3DS material to an aiMaterial
  186. void Discreet3DSImporter::ConvertMaterial(D3DS::Material& oldMat,
  187. MaterialHelper& mat)
  188. {
  189. // NOTE: Pass the background image to the viewer by bypassing the
  190. // material system. This is an evil hack, never do it again!
  191. if (0 != mBackgroundImage.length() && bHasBG)
  192. {
  193. aiString tex;
  194. tex.Set( mBackgroundImage);
  195. mat.AddProperty( &tex, AI_MATKEY_GLOBAL_BACKGROUND_IMAGE);
  196. // Be sure this is only done for the first material
  197. mBackgroundImage = std::string("");
  198. }
  199. // At first add the base ambient color of the scene to the material
  200. oldMat.mAmbient.r += mClrAmbient.r;
  201. oldMat.mAmbient.g += mClrAmbient.g;
  202. oldMat.mAmbient.b += mClrAmbient.b;
  203. aiString name;
  204. name.Set( oldMat.mName);
  205. mat.AddProperty( &name, AI_MATKEY_NAME);
  206. // Material colors
  207. mat.AddProperty( &oldMat.mAmbient, 1, AI_MATKEY_COLOR_AMBIENT);
  208. mat.AddProperty( &oldMat.mDiffuse, 1, AI_MATKEY_COLOR_DIFFUSE);
  209. mat.AddProperty( &oldMat.mSpecular, 1, AI_MATKEY_COLOR_SPECULAR);
  210. mat.AddProperty( &oldMat.mEmissive, 1, AI_MATKEY_COLOR_EMISSIVE);
  211. // Phong shininess and shininess strength
  212. if (D3DS::Discreet3DS::Phong == oldMat.mShading ||
  213. D3DS::Discreet3DS::Metal == oldMat.mShading)
  214. {
  215. if (!oldMat.mSpecularExponent || !oldMat.mShininessStrength)
  216. {
  217. oldMat.mShading = D3DS::Discreet3DS::Gouraud;
  218. }
  219. else
  220. {
  221. mat.AddProperty( &oldMat.mSpecularExponent, 1, AI_MATKEY_SHININESS);
  222. mat.AddProperty( &oldMat.mShininessStrength, 1, AI_MATKEY_SHININESS_STRENGTH);
  223. }
  224. }
  225. // Opacity
  226. mat.AddProperty<float>( &oldMat.mTransparency,1,AI_MATKEY_OPACITY);
  227. // Bump height scaling
  228. mat.AddProperty<float>( &oldMat.mBumpHeight,1,AI_MATKEY_BUMPSCALING);
  229. // Two sided rendering?
  230. if (oldMat.mTwoSided)
  231. {
  232. int i = 1;
  233. mat.AddProperty<int>(&i,1,AI_MATKEY_TWOSIDED);
  234. }
  235. // Shading mode
  236. aiShadingMode eShading = aiShadingMode_NoShading;
  237. switch (oldMat.mShading)
  238. {
  239. case D3DS::Discreet3DS::Flat:
  240. eShading = aiShadingMode_Flat; break;
  241. // I don't know what "Wire" shading should be,
  242. // assume it is simple lambertian diffuse shading
  243. case D3DS::Discreet3DS::Wire:
  244. {
  245. // Set the wireframe flag
  246. unsigned int iWire = 1;
  247. mat.AddProperty<int>( (int*)&iWire,1,AI_MATKEY_ENABLE_WIREFRAME);
  248. }
  249. case D3DS::Discreet3DS::Gouraud:
  250. eShading = aiShadingMode_Gouraud; break;
  251. // assume cook-torrance shading for metals.
  252. case D3DS::Discreet3DS::Phong :
  253. eShading = aiShadingMode_Phong; break;
  254. case D3DS::Discreet3DS::Metal :
  255. eShading = aiShadingMode_CookTorrance; break;
  256. // FIX to workaround a warning with GCC 4 who complained
  257. // about a missing case Blinn: here - Blinn isn't a valid
  258. // value in the 3DS Loader, it is just needed for ASE
  259. case D3DS::Discreet3DS::Blinn :
  260. eShading = aiShadingMode_Blinn; break;
  261. }
  262. mat.AddProperty<int>( (int*)&eShading,1,AI_MATKEY_SHADING_MODEL);
  263. // DIFFUSE texture
  264. if( oldMat.sTexDiffuse.mMapName.length() > 0)
  265. CopyTexture(mat,oldMat.sTexDiffuse, aiTextureType_DIFFUSE);
  266. // SPECULAR texture
  267. if( oldMat.sTexSpecular.mMapName.length() > 0)
  268. CopyTexture(mat,oldMat.sTexSpecular, aiTextureType_SPECULAR);
  269. // OPACITY texture
  270. if( oldMat.sTexOpacity.mMapName.length() > 0)
  271. CopyTexture(mat,oldMat.sTexOpacity, aiTextureType_OPACITY);
  272. // EMISSIVE texture
  273. if( oldMat.sTexEmissive.mMapName.length() > 0)
  274. CopyTexture(mat,oldMat.sTexEmissive, aiTextureType_EMISSIVE);
  275. // BUMP texture
  276. if( oldMat.sTexBump.mMapName.length() > 0)
  277. CopyTexture(mat,oldMat.sTexBump, aiTextureType_HEIGHT);
  278. // SHININESS texture
  279. if( oldMat.sTexShininess.mMapName.length() > 0)
  280. CopyTexture(mat,oldMat.sTexShininess, aiTextureType_SHININESS);
  281. // REFLECTION texture
  282. if( oldMat.sTexReflective.mMapName.length() > 0)
  283. CopyTexture(mat,oldMat.sTexReflective, aiTextureType_REFLECTION);
  284. // Store the name of the material itself, too
  285. if( oldMat.mName.length()) {
  286. aiString tex;
  287. tex.Set( oldMat.mName);
  288. mat.AddProperty( &tex, AI_MATKEY_NAME);
  289. }
  290. }
  291. // ------------------------------------------------------------------------------------------------
  292. // Split meshes by their materials and generate output aiMesh'es
  293. void Discreet3DSImporter::ConvertMeshes(aiScene* pcOut)
  294. {
  295. std::vector<aiMesh*> avOutMeshes;
  296. avOutMeshes.reserve(mScene->mMeshes.size() * 2);
  297. unsigned int iFaceCnt = 0;
  298. // we need to split all meshes by their materials
  299. for (std::vector<D3DS::Mesh>::iterator i = mScene->mMeshes.begin();
  300. i != mScene->mMeshes.end();++i)
  301. {
  302. std::vector<unsigned int>* aiSplit = new std::vector<unsigned int>[
  303. mScene->mMaterials.size()];
  304. unsigned int iNum = 0;
  305. for (std::vector<unsigned int>::const_iterator a = (*i).mFaceMaterials.begin();
  306. a != (*i).mFaceMaterials.end();++a,++iNum)
  307. {
  308. aiSplit[*a].push_back(iNum);
  309. }
  310. // now generate submeshes
  311. for (unsigned int p = 0; p < mScene->mMaterials.size();++p)
  312. {
  313. if (aiSplit[p].size())
  314. {
  315. aiMesh* meshOut = new aiMesh();
  316. meshOut->mPrimitiveTypes = aiPrimitiveType_TRIANGLE;
  317. // be sure to setup the correct material index
  318. meshOut->mMaterialIndex = p;
  319. // use the color data as temporary storage
  320. meshOut->mColors[0] = (aiColor4D*)(&*i);
  321. avOutMeshes.push_back(meshOut);
  322. // convert vertices
  323. meshOut->mNumFaces = (unsigned int)aiSplit[p].size();
  324. meshOut->mNumVertices = meshOut->mNumFaces*3;
  325. // allocate enough storage for faces
  326. meshOut->mFaces = new aiFace[meshOut->mNumFaces];
  327. iFaceCnt += meshOut->mNumFaces;
  328. meshOut->mVertices = new aiVector3D[meshOut->mNumVertices];
  329. meshOut->mNormals = new aiVector3D[meshOut->mNumVertices];
  330. if ((*i).mTexCoords.size())
  331. {
  332. meshOut->mTextureCoords[0] = new aiVector3D[meshOut->mNumVertices];
  333. }
  334. for (unsigned int q = 0, base = 0; q < aiSplit[p].size();++q)
  335. {
  336. register unsigned int index = aiSplit[p][q];
  337. aiFace& face = meshOut->mFaces[q];
  338. face.mIndices = new unsigned int[3];
  339. face.mNumIndices = 3;
  340. for (unsigned int a = 0; a < 3;++a,++base)
  341. {
  342. unsigned int idx = (*i).mFaces[index].mIndices[a];
  343. meshOut->mVertices[base] = (*i).mPositions[idx];
  344. meshOut->mNormals [base] = (*i).mNormals[idx];
  345. if ((*i).mTexCoords.size())
  346. meshOut->mTextureCoords[0][base] = (*i).mTexCoords[idx];
  347. face.mIndices[a] = base;
  348. }
  349. }
  350. }
  351. }
  352. delete[] aiSplit;
  353. }
  354. // Copy them to the output array
  355. pcOut->mNumMeshes = (unsigned int)avOutMeshes.size();
  356. pcOut->mMeshes = new aiMesh*[pcOut->mNumMeshes]();
  357. for (unsigned int a = 0; a < pcOut->mNumMeshes;++a)
  358. pcOut->mMeshes[a] = avOutMeshes[a];
  359. // We should have at least one face here
  360. if (!iFaceCnt)
  361. throw DeadlyImportError("No faces loaded. The mesh is empty");
  362. }
  363. // ------------------------------------------------------------------------------------------------
  364. // Add a node to the scenegraph and setup its final transformation
  365. void Discreet3DSImporter::AddNodeToGraph(aiScene* pcSOut,aiNode* pcOut,
  366. D3DS::Node* pcIn, aiMatrix4x4& absTrafo)
  367. {
  368. std::vector<unsigned int> iArray;
  369. iArray.reserve(3);
  370. aiMatrix4x4 abs;
  371. // Find all meshes with the same name as the node
  372. for (unsigned int a = 0; a < pcSOut->mNumMeshes;++a)
  373. {
  374. const D3DS::Mesh* pcMesh = (const D3DS::Mesh*)pcSOut->mMeshes[a]->mColors[0];
  375. ai_assert(NULL != pcMesh);
  376. if (pcIn->mName == pcMesh->mName)
  377. iArray.push_back(a);
  378. }
  379. if (!iArray.empty())
  380. {
  381. // The matrix should be identical for all meshes with the
  382. // same name. It HAS to be identical for all meshes .....
  383. D3DS::Mesh* imesh = ((D3DS::Mesh*)pcSOut->mMeshes[iArray[0]]->mColors[0]);
  384. // Compute the inverse of the transformation matrix to move the
  385. // vertices back to their relative and local space
  386. aiMatrix4x4 mInv = imesh->mMat, mInvTransposed = imesh->mMat;
  387. mInv.Inverse();mInvTransposed.Transpose();
  388. aiVector3D pivot = pcIn->vPivot;
  389. pcOut->mNumMeshes = (unsigned int)iArray.size();
  390. pcOut->mMeshes = new unsigned int[iArray.size()];
  391. for (unsigned int i = 0;i < iArray.size();++i) {
  392. const unsigned int iIndex = iArray[i];
  393. aiMesh* const mesh = pcSOut->mMeshes[iIndex];
  394. // Transform the vertices back into their local space
  395. // fixme: consider computing normals after this, so we don't need to transform them
  396. const aiVector3D* const pvEnd = mesh->mVertices+mesh->mNumVertices;
  397. aiVector3D* pvCurrent = mesh->mVertices, *t2 = mesh->mNormals;
  398. for (;pvCurrent != pvEnd;++pvCurrent,++t2) {
  399. *pvCurrent = mInv * (*pvCurrent);
  400. *t2 = mInvTransposed * (*t2);
  401. }
  402. // Handle negative transformation matrix determinant -> invert vertex x
  403. if (imesh->mMat.Determinant() < 0.0f)
  404. {
  405. /* we *must* have normals */
  406. for (pvCurrent = mesh->mVertices,t2 = mesh->mNormals;pvCurrent != pvEnd;++pvCurrent,++t2) {
  407. pvCurrent->x *= -1.f;
  408. t2->x *= -1.f;
  409. }
  410. DefaultLogger::get()->info("3DS: Flipping mesh X-Axis");
  411. }
  412. // Handle pivot point
  413. if(pivot.x || pivot.y || pivot.z)
  414. {
  415. for (pvCurrent = mesh->mVertices;pvCurrent != pvEnd;++pvCurrent) {
  416. *pvCurrent -= pivot;
  417. }
  418. }
  419. // Setup the mesh index
  420. pcOut->mMeshes[i] = iIndex;
  421. }
  422. }
  423. // Setup the name of the node
  424. pcOut->mName.Set(pcIn->mName);
  425. // Now build the transformation matrix of the node
  426. // ROTATION
  427. if (pcIn->aRotationKeys.size()){
  428. // FIX to get to Assimp's quaternion conventions
  429. for (std::vector<aiQuatKey>::iterator it = pcIn->aRotationKeys.begin(); it != pcIn->aRotationKeys.end(); ++it) {
  430. (*it).mValue.w *= -1.f;
  431. }
  432. pcOut->mTransformation = aiMatrix4x4( pcIn->aRotationKeys[0].mValue.GetMatrix() );
  433. }
  434. else if (pcIn->aCameraRollKeys.size())
  435. {
  436. aiMatrix4x4::RotationZ(AI_DEG_TO_RAD(- pcIn->aCameraRollKeys[0].mValue),
  437. pcOut->mTransformation);
  438. }
  439. // SCALING
  440. aiMatrix4x4& m = pcOut->mTransformation;
  441. if (pcIn->aScalingKeys.size())
  442. {
  443. const aiVector3D& v = pcIn->aScalingKeys[0].mValue;
  444. m.a1 *= v.x; m.b1 *= v.x; m.c1 *= v.x;
  445. m.a2 *= v.y; m.b2 *= v.y; m.c2 *= v.y;
  446. m.a3 *= v.z; m.b3 *= v.z; m.c3 *= v.z;
  447. }
  448. // TRANSLATION
  449. if (pcIn->aPositionKeys.size())
  450. {
  451. const aiVector3D& v = pcIn->aPositionKeys[0].mValue;
  452. m.a4 += v.x;
  453. m.b4 += v.y;
  454. m.c4 += v.z;
  455. }
  456. // Generate animation channels for the node
  457. if (pcIn->aPositionKeys.size() > 1 || pcIn->aRotationKeys.size() > 1 ||
  458. pcIn->aScalingKeys.size() > 1 || pcIn->aCameraRollKeys.size() > 1 ||
  459. pcIn->aTargetPositionKeys.size() > 1)
  460. {
  461. aiAnimation* anim = pcSOut->mAnimations[0];
  462. ai_assert(NULL != anim);
  463. if (pcIn->aCameraRollKeys.size() > 1)
  464. {
  465. DefaultLogger::get()->debug("3DS: Converting camera roll track ...");
  466. // Camera roll keys - in fact they're just rotations
  467. // around the camera's z axis. The angles are given
  468. // in degrees (and they're clockwise).
  469. pcIn->aRotationKeys.resize(pcIn->aCameraRollKeys.size());
  470. for (unsigned int i = 0; i < pcIn->aCameraRollKeys.size();++i)
  471. {
  472. aiQuatKey& q = pcIn->aRotationKeys[i];
  473. aiFloatKey& f = pcIn->aCameraRollKeys[i];
  474. q.mTime = f.mTime;
  475. // FIX to get to Assimp quaternion conventions
  476. q.mValue = aiQuaternion(0.f,0.f,AI_DEG_TO_RAD( /*-*/ f.mValue));
  477. }
  478. }
  479. #if 0
  480. if (pcIn->aTargetPositionKeys.size() > 1)
  481. {
  482. DefaultLogger::get()->debug("3DS: Converting target track ...");
  483. // Camera or spot light - need to convert the separate
  484. // target position channel to our representation
  485. TargetAnimationHelper helper;
  486. if (pcIn->aPositionKeys.empty())
  487. {
  488. // We can just pass zero here ...
  489. helper.SetFixedMainAnimationChannel(aiVector3D());
  490. }
  491. else helper.SetMainAnimationChannel(&pcIn->aPositionKeys);
  492. helper.SetTargetAnimationChannel(&pcIn->aTargetPositionKeys);
  493. // Do the conversion
  494. std::vector<aiVectorKey> distanceTrack;
  495. helper.Process(&distanceTrack);
  496. // Now add a new node as child, name it <ourName>.Target
  497. // and assign the distance track to it. This is that the
  498. // information where the target is and how it moves is
  499. // not lost
  500. D3DS::Node* nd = new D3DS::Node();
  501. pcIn->push_back(nd);
  502. nd->mName = pcIn->mName + ".Target";
  503. aiNodeAnim* nda = anim->mChannels[anim->mNumChannels++] = new aiNodeAnim();
  504. nda->mNodeName.Set(nd->mName);
  505. nda->mNumPositionKeys = (unsigned int)distanceTrack.size();
  506. nda->mPositionKeys = new aiVectorKey[nda->mNumPositionKeys];
  507. ::memcpy(nda->mPositionKeys,&distanceTrack[0],
  508. sizeof(aiVectorKey)*nda->mNumPositionKeys);
  509. }
  510. #endif
  511. // Cameras or lights define their transformation in their parent node and in the
  512. // corresponding light or camera chunks. However, we read and process the latter
  513. // to to be able to return valid cameras/lights even if no scenegraph is given.
  514. for (unsigned int n = 0; n < pcSOut->mNumCameras;++n) {
  515. if (pcSOut->mCameras[n]->mName == pcOut->mName) {
  516. pcSOut->mCameras[n]->mLookAt = aiVector3D(0.f,0.f,1.f);
  517. }
  518. }
  519. for (unsigned int n = 0; n < pcSOut->mNumLights;++n) {
  520. if (pcSOut->mLights[n]->mName == pcOut->mName) {
  521. pcSOut->mLights[n]->mDirection = aiVector3D(0.f,0.f,1.f);
  522. }
  523. }
  524. // Allocate a new node anim and setup its name
  525. aiNodeAnim* nda = anim->mChannels[anim->mNumChannels++] = new aiNodeAnim();
  526. nda->mNodeName.Set(pcIn->mName);
  527. // POSITION keys
  528. if (pcIn->aPositionKeys.size() > 0)
  529. {
  530. nda->mNumPositionKeys = (unsigned int)pcIn->aPositionKeys.size();
  531. nda->mPositionKeys = new aiVectorKey[nda->mNumPositionKeys];
  532. ::memcpy(nda->mPositionKeys,&pcIn->aPositionKeys[0],
  533. sizeof(aiVectorKey)*nda->mNumPositionKeys);
  534. }
  535. // ROTATION keys
  536. if (pcIn->aRotationKeys.size() > 0)
  537. {
  538. nda->mNumRotationKeys = (unsigned int)pcIn->aRotationKeys.size();
  539. nda->mRotationKeys = new aiQuatKey[nda->mNumRotationKeys];
  540. // Rotations are quaternion offsets
  541. aiQuaternion abs;
  542. for (unsigned int n = 0; n < nda->mNumRotationKeys;++n)
  543. {
  544. const aiQuatKey& q = pcIn->aRotationKeys[n];
  545. abs = (n ? abs * q.mValue : q.mValue);
  546. nda->mRotationKeys[n].mTime = q.mTime;
  547. nda->mRotationKeys[n].mValue = abs.Normalize();
  548. }
  549. }
  550. // SCALING keys
  551. if (pcIn->aScalingKeys.size() > 0)
  552. {
  553. nda->mNumScalingKeys = (unsigned int)pcIn->aScalingKeys.size();
  554. nda->mScalingKeys = new aiVectorKey[nda->mNumScalingKeys];
  555. ::memcpy(nda->mScalingKeys,&pcIn->aScalingKeys[0],
  556. sizeof(aiVectorKey)*nda->mNumScalingKeys);
  557. }
  558. }
  559. // Allocate storage for children
  560. pcOut->mNumChildren = (unsigned int)pcIn->mChildren.size();
  561. pcOut->mChildren = new aiNode*[pcIn->mChildren.size()];
  562. // Recursively process all children
  563. const unsigned int size = pcIn->mChildren.size();
  564. for (unsigned int i = 0; i < size;++i)
  565. {
  566. pcOut->mChildren[i] = new aiNode();
  567. pcOut->mChildren[i]->mParent = pcOut;
  568. AddNodeToGraph(pcSOut,pcOut->mChildren[i],pcIn->mChildren[i],abs);
  569. }
  570. }
  571. // ------------------------------------------------------------------------------------------------
  572. // Find out how many node animation channels we'll have finally
  573. void CountTracks(D3DS::Node* node, unsigned int& cnt)
  574. {
  575. //////////////////////////////////////////////////////////////////////////////
  576. // We will never generate more than one channel for a node, so
  577. // this is rather easy here.
  578. if (node->aPositionKeys.size() > 1 || node->aRotationKeys.size() > 1 ||
  579. node->aScalingKeys.size() > 1 || node->aCameraRollKeys.size() > 1 ||
  580. node->aTargetPositionKeys.size() > 1)
  581. {
  582. ++cnt;
  583. // account for the additional channel for the camera/spotlight target position
  584. if (node->aTargetPositionKeys.size() > 1)++cnt;
  585. }
  586. // Recursively process all children
  587. for (unsigned int i = 0; i < node->mChildren.size();++i)
  588. CountTracks(node->mChildren[i],cnt);
  589. }
  590. // ------------------------------------------------------------------------------------------------
  591. // Generate the output node graph
  592. void Discreet3DSImporter::GenerateNodeGraph(aiScene* pcOut)
  593. {
  594. pcOut->mRootNode = new aiNode();
  595. if (0 == mRootNode->mChildren.size())
  596. {
  597. //////////////////////////////////////////////////////////////////////////////
  598. // It seems the file is so fucked up that it has not even a hierarchy.
  599. // generate a flat hiearachy which looks like this:
  600. //
  601. // ROOT_NODE
  602. // |
  603. // ----------------------------------------
  604. // | | | | |
  605. // MESH_0 MESH_1 MESH_2 ... MESH_N CAMERA_0 ....
  606. //
  607. DefaultLogger::get()->warn("No hierarchy information has been found in the file. ");
  608. pcOut->mRootNode->mNumChildren = pcOut->mNumMeshes +
  609. mScene->mCameras.size() + mScene->mLights.size();
  610. pcOut->mRootNode->mChildren = new aiNode* [ pcOut->mRootNode->mNumChildren ];
  611. pcOut->mRootNode->mName.Set("<3DSDummyRoot>");
  612. // Build dummy nodes for all meshes
  613. unsigned int a = 0;
  614. for (unsigned int i = 0; i < pcOut->mNumMeshes;++i,++a)
  615. {
  616. aiNode* pcNode = pcOut->mRootNode->mChildren[a] = new aiNode();
  617. pcNode->mParent = pcOut->mRootNode;
  618. pcNode->mMeshes = new unsigned int[1];
  619. pcNode->mMeshes[0] = i;
  620. pcNode->mNumMeshes = 1;
  621. // Build a name for the node
  622. pcNode->mName.length = sprintf(pcNode->mName.data,"3DSMesh_%i",i);
  623. }
  624. // Build dummy nodes for all cameras
  625. for (unsigned int i = 0; i < (unsigned int )mScene->mCameras.size();++i,++a)
  626. {
  627. aiNode* pcNode = pcOut->mRootNode->mChildren[a] = new aiNode();
  628. pcNode->mParent = pcOut->mRootNode;
  629. // Build a name for the node
  630. pcNode->mName = mScene->mCameras[i]->mName;
  631. }
  632. // Build dummy nodes for all lights
  633. for (unsigned int i = 0; i < (unsigned int )mScene->mLights.size();++i,++a)
  634. {
  635. aiNode* pcNode = pcOut->mRootNode->mChildren[a] = new aiNode();
  636. pcNode->mParent = pcOut->mRootNode;
  637. // Build a name for the node
  638. pcNode->mName = mScene->mLights[i]->mName;
  639. }
  640. }
  641. else
  642. {
  643. // First of all: find out how many scaling, rotation and translation
  644. // animation tracks we'll have afterwards
  645. unsigned int numChannel = 0;
  646. CountTracks(mRootNode,numChannel);
  647. if (numChannel)
  648. {
  649. // Allocate a primary animation channel
  650. pcOut->mNumAnimations = 1;
  651. pcOut->mAnimations = new aiAnimation*[1];
  652. aiAnimation* anim = pcOut->mAnimations[0] = new aiAnimation();
  653. anim->mName.Set("3DSMasterAnim");
  654. // Allocate enough storage for all node animation channels,
  655. // but don't set the mNumChannels member - we'll use it to
  656. // index into the array
  657. anim->mChannels = new aiNodeAnim*[numChannel];
  658. }
  659. aiMatrix4x4 m;
  660. AddNodeToGraph(pcOut, pcOut->mRootNode, mRootNode,m);
  661. }
  662. // We used the first vertex color set to store some emporary values so we need to cleanup here
  663. for (unsigned int a = 0; a < pcOut->mNumMeshes;++a)
  664. pcOut->mMeshes[a]->mColors[0] = NULL;
  665. // Now rotate the whole scene 90 degrees around the x axis to convert to internal coordinate system
  666. pcOut->mRootNode->mTransformation = aiMatrix4x4(1.f,0.f,0.f,0.f,
  667. 0.f,0.f,1.f,0.f,0.f,-1.f,0.f,0.f,0.f,0.f,0.f,1.f) * pcOut->mRootNode->mTransformation;
  668. // If the root node is unnamed name it "<3DSRoot>"
  669. if (::strstr( pcOut->mRootNode->mName.data, "UNNAMED" ) ||
  670. (pcOut->mRootNode->mName.data[0] == '$' && pcOut->mRootNode->mName.data[1] == '$') )
  671. {
  672. pcOut->mRootNode->mName.Set("<3DSRoot>");
  673. }
  674. }
  675. // ------------------------------------------------------------------------------------------------
  676. // Convert all meshes in the scene and generate the final output scene.
  677. void Discreet3DSImporter::ConvertScene(aiScene* pcOut)
  678. {
  679. // Allocate enough storage for all output materials
  680. pcOut->mNumMaterials = (unsigned int)mScene->mMaterials.size();
  681. pcOut->mMaterials = new aiMaterial*[pcOut->mNumMaterials];
  682. // ... and convert the 3DS materials to aiMaterial's
  683. for (unsigned int i = 0; i < pcOut->mNumMaterials;++i)
  684. {
  685. MaterialHelper* pcNew = new MaterialHelper();
  686. ConvertMaterial(mScene->mMaterials[i],*pcNew);
  687. pcOut->mMaterials[i] = pcNew;
  688. }
  689. // Generate the output mesh list
  690. ConvertMeshes(pcOut);
  691. // Now copy all light sources to the output scene
  692. pcOut->mNumLights = (unsigned int)mScene->mLights.size();
  693. if (pcOut->mNumLights)
  694. {
  695. pcOut->mLights = new aiLight*[pcOut->mNumLights];
  696. ::memcpy(pcOut->mLights,&mScene->mLights[0],sizeof(void*)*pcOut->mNumLights);
  697. }
  698. // Now copy all cameras to the output scene
  699. pcOut->mNumCameras = (unsigned int)mScene->mCameras.size();
  700. if (pcOut->mNumCameras)
  701. {
  702. pcOut->mCameras = new aiCamera*[pcOut->mNumCameras];
  703. ::memcpy(pcOut->mCameras,&mScene->mCameras[0],sizeof(void*)*pcOut->mNumCameras);
  704. }
  705. }
  706. #endif // !! ASSIMP_BUILD_NO_3DS_IMPORTER