3DSConverter.cpp 32 KB

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