3DSConverter.cpp 32 KB

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