3DSConverter.cpp 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873
  1. /*
  2. ---------------------------------------------------------------------------
  3. Open Asset Import Library (assimp)
  4. ---------------------------------------------------------------------------
  5. Copyright (c) 2006-2018, 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 <assimp/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. ASSIMP_LOG_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("%%%DEFAULT");
  112. sMat.mDiffuse = aiColor3D(0.3f,0.3f,0.3f);
  113. mScene->mMaterials.push_back(sMat);
  114. ASSIMP_LOG_INFO("3DS: Generating default material");
  115. }
  116. }
  117. // ------------------------------------------------------------------------------------------------
  118. // Check whether all indices are valid. Otherwise we'd crash before the validation step is reached
  119. void Discreet3DSImporter::CheckIndices(D3DS::Mesh& sMesh)
  120. {
  121. for (std::vector< D3DS::Face >::iterator i = sMesh.mFaces.begin(); i != sMesh.mFaces.end();++i)
  122. {
  123. // check whether all indices are in range
  124. for (unsigned int a = 0; a < 3;++a)
  125. {
  126. if ((*i).mIndices[a] >= sMesh.mPositions.size())
  127. {
  128. ASSIMP_LOG_WARN("3DS: Vertex index overflow)");
  129. (*i).mIndices[a] = (uint32_t)sMesh.mPositions.size()-1;
  130. }
  131. if ( !sMesh.mTexCoords.empty() && (*i).mIndices[a] >= sMesh.mTexCoords.size())
  132. {
  133. ASSIMP_LOG_WARN("3DS: Texture coordinate index overflow)");
  134. (*i).mIndices[a] = (uint32_t)sMesh.mTexCoords.size()-1;
  135. }
  136. }
  137. }
  138. }
  139. // ------------------------------------------------------------------------------------------------
  140. // Generate out unique verbose format representation
  141. void Discreet3DSImporter::MakeUnique(D3DS::Mesh& sMesh)
  142. {
  143. // TODO: really necessary? I don't think. Just a waste of memory and time
  144. // to do it now in a separate buffer.
  145. // Allocate output storage
  146. std::vector<aiVector3D> vNew (sMesh.mFaces.size() * 3);
  147. std::vector<aiVector3D> vNew2;
  148. if (sMesh.mTexCoords.size())
  149. vNew2.resize(sMesh.mFaces.size() * 3);
  150. for (unsigned int i = 0, base = 0; i < sMesh.mFaces.size();++i)
  151. {
  152. D3DS::Face& face = sMesh.mFaces[i];
  153. // Positions
  154. for (unsigned int a = 0; a < 3;++a,++base)
  155. {
  156. vNew[base] = sMesh.mPositions[face.mIndices[a]];
  157. if (sMesh.mTexCoords.size())
  158. vNew2[base] = sMesh.mTexCoords[face.mIndices[a]];
  159. face.mIndices[a] = base;
  160. }
  161. }
  162. sMesh.mPositions = vNew;
  163. sMesh.mTexCoords = vNew2;
  164. }
  165. // ------------------------------------------------------------------------------------------------
  166. // Convert a 3DS texture to texture keys in an aiMaterial
  167. void CopyTexture(aiMaterial& mat, D3DS::Texture& texture, aiTextureType type)
  168. {
  169. // Setup the texture name
  170. aiString tex;
  171. tex.Set( texture.mMapName);
  172. mat.AddProperty( &tex, AI_MATKEY_TEXTURE(type,0));
  173. // Setup the texture blend factor
  174. if (is_not_qnan(texture.mTextureBlend))
  175. mat.AddProperty<ai_real>( &texture.mTextureBlend, 1, AI_MATKEY_TEXBLEND(type,0));
  176. // Setup the texture mapping mode
  177. int mapMode = static_cast<int>(texture.mMapMode);
  178. mat.AddProperty<int>(&mapMode,1,AI_MATKEY_MAPPINGMODE_U(type,0));
  179. mat.AddProperty<int>(&mapMode,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. int eShading_ = static_cast<int>(eShading);
  271. mat.AddProperty<int>(&eShading_, 1, AI_MATKEY_SHADING_MODEL);
  272. // DIFFUSE texture
  273. if( oldMat.sTexDiffuse.mMapName.length() > 0)
  274. CopyTexture(mat,oldMat.sTexDiffuse, aiTextureType_DIFFUSE);
  275. // SPECULAR texture
  276. if( oldMat.sTexSpecular.mMapName.length() > 0)
  277. CopyTexture(mat,oldMat.sTexSpecular, aiTextureType_SPECULAR);
  278. // OPACITY texture
  279. if( oldMat.sTexOpacity.mMapName.length() > 0)
  280. CopyTexture(mat,oldMat.sTexOpacity, aiTextureType_OPACITY);
  281. // EMISSIVE texture
  282. if( oldMat.sTexEmissive.mMapName.length() > 0)
  283. CopyTexture(mat,oldMat.sTexEmissive, aiTextureType_EMISSIVE);
  284. // BUMP texture
  285. if( oldMat.sTexBump.mMapName.length() > 0)
  286. CopyTexture(mat,oldMat.sTexBump, aiTextureType_HEIGHT);
  287. // SHININESS texture
  288. if( oldMat.sTexShininess.mMapName.length() > 0)
  289. CopyTexture(mat,oldMat.sTexShininess, aiTextureType_SHININESS);
  290. // REFLECTION texture
  291. if( oldMat.sTexReflective.mMapName.length() > 0)
  292. CopyTexture(mat,oldMat.sTexReflective, aiTextureType_REFLECTION);
  293. // Store the name of the material itself, too
  294. if( oldMat.mName.length()) {
  295. aiString tex;
  296. tex.Set( oldMat.mName);
  297. mat.AddProperty( &tex, AI_MATKEY_NAME);
  298. }
  299. }
  300. // ------------------------------------------------------------------------------------------------
  301. // Split meshes by their materials and generate output aiMesh'es
  302. void Discreet3DSImporter::ConvertMeshes(aiScene* pcOut)
  303. {
  304. std::vector<aiMesh*> avOutMeshes;
  305. avOutMeshes.reserve(mScene->mMeshes.size() * 2);
  306. unsigned int iFaceCnt = 0,num = 0;
  307. aiString name;
  308. // we need to split all meshes by their materials
  309. for (std::vector<D3DS::Mesh>::iterator i = mScene->mMeshes.begin(); i != mScene->mMeshes.end();++i) {
  310. std::unique_ptr< std::vector<unsigned int>[] > aiSplit(new std::vector<unsigned int>[mScene->mMaterials.size()]);
  311. name.length = ASSIMP_itoa10(name.data,num++);
  312. unsigned int iNum = 0;
  313. for (std::vector<unsigned int>::const_iterator a = (*i).mFaceMaterials.begin();
  314. a != (*i).mFaceMaterials.end();++a,++iNum)
  315. {
  316. aiSplit[*a].push_back(iNum);
  317. }
  318. // now generate submeshes
  319. for (unsigned int p = 0; p < mScene->mMaterials.size();++p)
  320. {
  321. if (aiSplit[p].empty()) {
  322. continue;
  323. }
  324. aiMesh* meshOut = new aiMesh();
  325. meshOut->mName = name;
  326. meshOut->mPrimitiveTypes = aiPrimitiveType_TRIANGLE;
  327. // be sure to setup the correct material index
  328. meshOut->mMaterialIndex = p;
  329. // use the color data as temporary storage
  330. meshOut->mColors[0] = (aiColor4D*)(&*i);
  331. avOutMeshes.push_back(meshOut);
  332. // convert vertices
  333. meshOut->mNumFaces = (unsigned int)aiSplit[p].size();
  334. meshOut->mNumVertices = meshOut->mNumFaces*3;
  335. // allocate enough storage for faces
  336. meshOut->mFaces = new aiFace[meshOut->mNumFaces];
  337. iFaceCnt += meshOut->mNumFaces;
  338. meshOut->mVertices = new aiVector3D[meshOut->mNumVertices];
  339. meshOut->mNormals = new aiVector3D[meshOut->mNumVertices];
  340. if ((*i).mTexCoords.size())
  341. {
  342. meshOut->mTextureCoords[0] = new aiVector3D[meshOut->mNumVertices];
  343. }
  344. for (unsigned int q = 0, base = 0; q < aiSplit[p].size();++q)
  345. {
  346. unsigned int index = aiSplit[p][q];
  347. aiFace& face = meshOut->mFaces[q];
  348. face.mIndices = new unsigned int[3];
  349. face.mNumIndices = 3;
  350. for (unsigned int a = 0; a < 3;++a,++base)
  351. {
  352. unsigned int idx = (*i).mFaces[index].mIndices[a];
  353. meshOut->mVertices[base] = (*i).mPositions[idx];
  354. meshOut->mNormals [base] = (*i).mNormals[idx];
  355. if ((*i).mTexCoords.size())
  356. meshOut->mTextureCoords[0][base] = (*i).mTexCoords[idx];
  357. face.mIndices[a] = base;
  358. }
  359. }
  360. }
  361. }
  362. // Copy them to the output array
  363. pcOut->mNumMeshes = (unsigned int)avOutMeshes.size();
  364. pcOut->mMeshes = new aiMesh*[pcOut->mNumMeshes]();
  365. for (unsigned int a = 0; a < pcOut->mNumMeshes;++a) {
  366. pcOut->mMeshes[a] = avOutMeshes[a];
  367. }
  368. // We should have at least one face here
  369. if (!iFaceCnt) {
  370. throw DeadlyImportError("No faces loaded. The mesh is empty");
  371. }
  372. }
  373. // ------------------------------------------------------------------------------------------------
  374. // Add a node to the scenegraph and setup its final transformation
  375. void Discreet3DSImporter::AddNodeToGraph(aiScene* pcSOut,aiNode* pcOut,
  376. D3DS::Node* pcIn, aiMatrix4x4& /*absTrafo*/)
  377. {
  378. std::vector<unsigned int> iArray;
  379. iArray.reserve(3);
  380. aiMatrix4x4 abs;
  381. // Find all meshes with the same name as the node
  382. for (unsigned int a = 0; a < pcSOut->mNumMeshes;++a)
  383. {
  384. const D3DS::Mesh* pcMesh = (const D3DS::Mesh*)pcSOut->mMeshes[a]->mColors[0];
  385. ai_assert(NULL != pcMesh);
  386. if (pcIn->mName == pcMesh->mName)
  387. iArray.push_back(a);
  388. }
  389. if (!iArray.empty())
  390. {
  391. // The matrix should be identical for all meshes with the
  392. // same name. It HAS to be identical for all meshes .....
  393. D3DS::Mesh* imesh = ((D3DS::Mesh*)pcSOut->mMeshes[iArray[0]]->mColors[0]);
  394. // Compute the inverse of the transformation matrix to move the
  395. // vertices back to their relative and local space
  396. aiMatrix4x4 mInv = imesh->mMat, mInvTransposed = imesh->mMat;
  397. mInv.Inverse();mInvTransposed.Transpose();
  398. aiVector3D pivot = pcIn->vPivot;
  399. pcOut->mNumMeshes = (unsigned int)iArray.size();
  400. pcOut->mMeshes = new unsigned int[iArray.size()];
  401. for (unsigned int i = 0;i < iArray.size();++i) {
  402. const unsigned int iIndex = iArray[i];
  403. aiMesh* const mesh = pcSOut->mMeshes[iIndex];
  404. if (mesh->mColors[1] == NULL)
  405. {
  406. // Transform the vertices back into their local space
  407. // fixme: consider computing normals after this, so we don't need to transform them
  408. const aiVector3D* const pvEnd = mesh->mVertices + mesh->mNumVertices;
  409. aiVector3D* pvCurrent = mesh->mVertices, *t2 = mesh->mNormals;
  410. for (; pvCurrent != pvEnd; ++pvCurrent, ++t2) {
  411. *pvCurrent = mInv * (*pvCurrent);
  412. *t2 = mInvTransposed * (*t2);
  413. }
  414. // Handle negative transformation matrix determinant -> invert vertex x
  415. if (imesh->mMat.Determinant() < 0.0f)
  416. {
  417. /* we *must* have normals */
  418. for (pvCurrent = mesh->mVertices, t2 = mesh->mNormals; pvCurrent != pvEnd; ++pvCurrent, ++t2) {
  419. pvCurrent->x *= -1.f;
  420. t2->x *= -1.f;
  421. }
  422. ASSIMP_LOG_INFO("3DS: Flipping mesh X-Axis");
  423. }
  424. // Handle pivot point
  425. if (pivot.x || pivot.y || pivot.z)
  426. {
  427. for (pvCurrent = mesh->mVertices; pvCurrent != pvEnd; ++pvCurrent) {
  428. *pvCurrent -= pivot;
  429. }
  430. }
  431. mesh->mColors[1] = (aiColor4D*)1;
  432. }
  433. else
  434. mesh->mColors[1] = (aiColor4D*)1;
  435. // Setup the mesh index
  436. pcOut->mMeshes[i] = iIndex;
  437. }
  438. }
  439. // Setup the name of the node
  440. // First instance keeps its name otherwise something might break, all others will be postfixed with their instance number
  441. if (pcIn->mInstanceNumber > 1)
  442. {
  443. char tmp[12];
  444. ASSIMP_itoa10(tmp, pcIn->mInstanceNumber);
  445. std::string tempStr = pcIn->mName + "_inst_";
  446. tempStr += tmp;
  447. pcOut->mName.Set(tempStr);
  448. }
  449. else
  450. pcOut->mName.Set(pcIn->mName);
  451. // Now build the transformation matrix of the node
  452. // ROTATION
  453. if (pcIn->aRotationKeys.size()){
  454. // FIX to get to Assimp's quaternion conventions
  455. for (std::vector<aiQuatKey>::iterator it = pcIn->aRotationKeys.begin(); it != pcIn->aRotationKeys.end(); ++it) {
  456. (*it).mValue.w *= -1.f;
  457. }
  458. pcOut->mTransformation = aiMatrix4x4( pcIn->aRotationKeys[0].mValue.GetMatrix() );
  459. }
  460. else if (pcIn->aCameraRollKeys.size())
  461. {
  462. aiMatrix4x4::RotationZ(AI_DEG_TO_RAD(- pcIn->aCameraRollKeys[0].mValue),
  463. pcOut->mTransformation);
  464. }
  465. // SCALING
  466. aiMatrix4x4& m = pcOut->mTransformation;
  467. if (pcIn->aScalingKeys.size())
  468. {
  469. const aiVector3D& v = pcIn->aScalingKeys[0].mValue;
  470. m.a1 *= v.x; m.b1 *= v.x; m.c1 *= v.x;
  471. m.a2 *= v.y; m.b2 *= v.y; m.c2 *= v.y;
  472. m.a3 *= v.z; m.b3 *= v.z; m.c3 *= v.z;
  473. }
  474. // TRANSLATION
  475. if (pcIn->aPositionKeys.size())
  476. {
  477. const aiVector3D& v = pcIn->aPositionKeys[0].mValue;
  478. m.a4 += v.x;
  479. m.b4 += v.y;
  480. m.c4 += v.z;
  481. }
  482. // Generate animation channels for the node
  483. if (pcIn->aPositionKeys.size() > 1 || pcIn->aRotationKeys.size() > 1 ||
  484. pcIn->aScalingKeys.size() > 1 || pcIn->aCameraRollKeys.size() > 1 ||
  485. pcIn->aTargetPositionKeys.size() > 1)
  486. {
  487. aiAnimation* anim = pcSOut->mAnimations[0];
  488. ai_assert(nullptr != anim);
  489. if (pcIn->aCameraRollKeys.size() > 1)
  490. {
  491. ASSIMP_LOG_DEBUG("3DS: Converting camera roll track ...");
  492. // Camera roll keys - in fact they're just rotations
  493. // around the camera's z axis. The angles are given
  494. // in degrees (and they're clockwise).
  495. pcIn->aRotationKeys.resize(pcIn->aCameraRollKeys.size());
  496. for (unsigned int i = 0; i < pcIn->aCameraRollKeys.size();++i)
  497. {
  498. aiQuatKey& q = pcIn->aRotationKeys[i];
  499. aiFloatKey& f = pcIn->aCameraRollKeys[i];
  500. q.mTime = f.mTime;
  501. // FIX to get to Assimp quaternion conventions
  502. q.mValue = aiQuaternion(0.f,0.f,AI_DEG_TO_RAD( /*-*/ f.mValue));
  503. }
  504. }
  505. #if 0
  506. if (pcIn->aTargetPositionKeys.size() > 1)
  507. {
  508. ASSIMP_LOG_DEBUG("3DS: Converting target track ...");
  509. // Camera or spot light - need to convert the separate
  510. // target position channel to our representation
  511. TargetAnimationHelper helper;
  512. if (pcIn->aPositionKeys.empty())
  513. {
  514. // We can just pass zero here ...
  515. helper.SetFixedMainAnimationChannel(aiVector3D());
  516. }
  517. else helper.SetMainAnimationChannel(&pcIn->aPositionKeys);
  518. helper.SetTargetAnimationChannel(&pcIn->aTargetPositionKeys);
  519. // Do the conversion
  520. std::vector<aiVectorKey> distanceTrack;
  521. helper.Process(&distanceTrack);
  522. // Now add a new node as child, name it <ourName>.Target
  523. // and assign the distance track to it. This is that the
  524. // information where the target is and how it moves is
  525. // not lost
  526. D3DS::Node* nd = new D3DS::Node();
  527. pcIn->push_back(nd);
  528. nd->mName = pcIn->mName + ".Target";
  529. aiNodeAnim* nda = anim->mChannels[anim->mNumChannels++] = new aiNodeAnim();
  530. nda->mNodeName.Set(nd->mName);
  531. nda->mNumPositionKeys = (unsigned int)distanceTrack.size();
  532. nda->mPositionKeys = new aiVectorKey[nda->mNumPositionKeys];
  533. ::memcpy(nda->mPositionKeys,&distanceTrack[0],
  534. sizeof(aiVectorKey)*nda->mNumPositionKeys);
  535. }
  536. #endif
  537. // Cameras or lights define their transformation in their parent node and in the
  538. // corresponding light or camera chunks. However, we read and process the latter
  539. // to to be able to return valid cameras/lights even if no scenegraph is given.
  540. for (unsigned int n = 0; n < pcSOut->mNumCameras;++n) {
  541. if (pcSOut->mCameras[n]->mName == pcOut->mName) {
  542. pcSOut->mCameras[n]->mLookAt = aiVector3D(0.f,0.f,1.f);
  543. }
  544. }
  545. for (unsigned int n = 0; n < pcSOut->mNumLights;++n) {
  546. if (pcSOut->mLights[n]->mName == pcOut->mName) {
  547. pcSOut->mLights[n]->mDirection = aiVector3D(0.f,0.f,1.f);
  548. }
  549. }
  550. // Allocate a new node anim and setup its name
  551. aiNodeAnim* nda = anim->mChannels[anim->mNumChannels++] = new aiNodeAnim();
  552. nda->mNodeName.Set(pcIn->mName);
  553. // POSITION keys
  554. if (pcIn->aPositionKeys.size() > 0)
  555. {
  556. nda->mNumPositionKeys = (unsigned int)pcIn->aPositionKeys.size();
  557. nda->mPositionKeys = new aiVectorKey[nda->mNumPositionKeys];
  558. ::memcpy(nda->mPositionKeys,&pcIn->aPositionKeys[0],
  559. sizeof(aiVectorKey)*nda->mNumPositionKeys);
  560. }
  561. // ROTATION keys
  562. if (pcIn->aRotationKeys.size() > 0)
  563. {
  564. nda->mNumRotationKeys = (unsigned int)pcIn->aRotationKeys.size();
  565. nda->mRotationKeys = new aiQuatKey[nda->mNumRotationKeys];
  566. // Rotations are quaternion offsets
  567. aiQuaternion abs1;
  568. for (unsigned int n = 0; n < nda->mNumRotationKeys;++n)
  569. {
  570. const aiQuatKey& q = pcIn->aRotationKeys[n];
  571. abs1 = (n ? abs1 * q.mValue : q.mValue);
  572. nda->mRotationKeys[n].mTime = q.mTime;
  573. nda->mRotationKeys[n].mValue = abs1.Normalize();
  574. }
  575. }
  576. // SCALING keys
  577. if (pcIn->aScalingKeys.size() > 0)
  578. {
  579. nda->mNumScalingKeys = (unsigned int)pcIn->aScalingKeys.size();
  580. nda->mScalingKeys = new aiVectorKey[nda->mNumScalingKeys];
  581. ::memcpy(nda->mScalingKeys,&pcIn->aScalingKeys[0],
  582. sizeof(aiVectorKey)*nda->mNumScalingKeys);
  583. }
  584. }
  585. // Allocate storage for children
  586. pcOut->mNumChildren = (unsigned int)pcIn->mChildren.size();
  587. pcOut->mChildren = new aiNode*[pcIn->mChildren.size()];
  588. // Recursively process all children
  589. const unsigned int size = static_cast<unsigned int>(pcIn->mChildren.size());
  590. for (unsigned int i = 0; i < size;++i)
  591. {
  592. pcOut->mChildren[i] = new aiNode();
  593. pcOut->mChildren[i]->mParent = pcOut;
  594. AddNodeToGraph(pcSOut,pcOut->mChildren[i],pcIn->mChildren[i],abs);
  595. }
  596. }
  597. // ------------------------------------------------------------------------------------------------
  598. // Find out how many node animation channels we'll have finally
  599. void CountTracks(D3DS::Node* node, unsigned int& cnt)
  600. {
  601. //////////////////////////////////////////////////////////////////////////////
  602. // We will never generate more than one channel for a node, so
  603. // this is rather easy here.
  604. if (node->aPositionKeys.size() > 1 || node->aRotationKeys.size() > 1 ||
  605. node->aScalingKeys.size() > 1 || node->aCameraRollKeys.size() > 1 ||
  606. node->aTargetPositionKeys.size() > 1)
  607. {
  608. ++cnt;
  609. // account for the additional channel for the camera/spotlight target position
  610. if (node->aTargetPositionKeys.size() > 1)++cnt;
  611. }
  612. // Recursively process all children
  613. for (unsigned int i = 0; i < node->mChildren.size();++i)
  614. CountTracks(node->mChildren[i],cnt);
  615. }
  616. // ------------------------------------------------------------------------------------------------
  617. // Generate the output node graph
  618. void Discreet3DSImporter::GenerateNodeGraph(aiScene* pcOut)
  619. {
  620. pcOut->mRootNode = new aiNode();
  621. if (0 == mRootNode->mChildren.size())
  622. {
  623. //////////////////////////////////////////////////////////////////////////////
  624. // It seems the file is so messed up that it has not even a hierarchy.
  625. // generate a flat hiearachy which looks like this:
  626. //
  627. // ROOT_NODE
  628. // |
  629. // ----------------------------------------
  630. // | | | | |
  631. // MESH_0 MESH_1 MESH_2 ... MESH_N CAMERA_0 ....
  632. //
  633. ASSIMP_LOG_WARN("No hierarchy information has been found in the file. ");
  634. pcOut->mRootNode->mNumChildren = pcOut->mNumMeshes +
  635. static_cast<unsigned int>(mScene->mCameras.size() + mScene->mLights.size());
  636. pcOut->mRootNode->mChildren = new aiNode* [ pcOut->mRootNode->mNumChildren ];
  637. pcOut->mRootNode->mName.Set("<3DSDummyRoot>");
  638. // Build dummy nodes for all meshes
  639. unsigned int a = 0;
  640. for (unsigned int i = 0; i < pcOut->mNumMeshes;++i,++a)
  641. {
  642. aiNode* pcNode = pcOut->mRootNode->mChildren[a] = new aiNode();
  643. pcNode->mParent = pcOut->mRootNode;
  644. pcNode->mMeshes = new unsigned int[1];
  645. pcNode->mMeshes[0] = i;
  646. pcNode->mNumMeshes = 1;
  647. // Build a name for the node
  648. pcNode->mName.length = ai_snprintf(pcNode->mName.data, MAXLEN, "3DSMesh_%u",i);
  649. }
  650. // Build dummy nodes for all cameras
  651. for (unsigned int i = 0; i < (unsigned int )mScene->mCameras.size();++i,++a)
  652. {
  653. aiNode* pcNode = pcOut->mRootNode->mChildren[a] = new aiNode();
  654. pcNode->mParent = pcOut->mRootNode;
  655. // Build a name for the node
  656. pcNode->mName = mScene->mCameras[i]->mName;
  657. }
  658. // Build dummy nodes for all lights
  659. for (unsigned int i = 0; i < (unsigned int )mScene->mLights.size();++i,++a)
  660. {
  661. aiNode* pcNode = pcOut->mRootNode->mChildren[a] = new aiNode();
  662. pcNode->mParent = pcOut->mRootNode;
  663. // Build a name for the node
  664. pcNode->mName = mScene->mLights[i]->mName;
  665. }
  666. }
  667. else
  668. {
  669. // First of all: find out how many scaling, rotation and translation
  670. // animation tracks we'll have afterwards
  671. unsigned int numChannel = 0;
  672. CountTracks(mRootNode,numChannel);
  673. if (numChannel)
  674. {
  675. // Allocate a primary animation channel
  676. pcOut->mNumAnimations = 1;
  677. pcOut->mAnimations = new aiAnimation*[1];
  678. aiAnimation* anim = pcOut->mAnimations[0] = new aiAnimation();
  679. anim->mName.Set("3DSMasterAnim");
  680. // Allocate enough storage for all node animation channels,
  681. // but don't set the mNumChannels member - we'll use it to
  682. // index into the array
  683. anim->mChannels = new aiNodeAnim*[numChannel];
  684. }
  685. aiMatrix4x4 m;
  686. AddNodeToGraph(pcOut, pcOut->mRootNode, mRootNode,m);
  687. }
  688. // We used the first and second vertex color set to store some temporary values so we need to cleanup here
  689. for (unsigned int a = 0; a < pcOut->mNumMeshes; ++a)
  690. {
  691. pcOut->mMeshes[a]->mColors[0] = NULL;
  692. pcOut->mMeshes[a]->mColors[1] = NULL;
  693. }
  694. pcOut->mRootNode->mTransformation = aiMatrix4x4(
  695. 1.f,0.f,0.f,0.f,
  696. 0.f,0.f,1.f,0.f,
  697. 0.f,-1.f,0.f,0.f,
  698. 0.f,0.f,0.f,1.f) * pcOut->mRootNode->mTransformation;
  699. // If the root node is unnamed name it "<3DSRoot>"
  700. if (::strstr( pcOut->mRootNode->mName.data, "UNNAMED" ) ||
  701. (pcOut->mRootNode->mName.data[0] == '$' && pcOut->mRootNode->mName.data[1] == '$') )
  702. {
  703. pcOut->mRootNode->mName.Set("<3DSRoot>");
  704. }
  705. }
  706. // ------------------------------------------------------------------------------------------------
  707. // Convert all meshes in the scene and generate the final output scene.
  708. void Discreet3DSImporter::ConvertScene(aiScene* pcOut)
  709. {
  710. // Allocate enough storage for all output materials
  711. pcOut->mNumMaterials = (unsigned int)mScene->mMaterials.size();
  712. pcOut->mMaterials = new aiMaterial*[pcOut->mNumMaterials];
  713. // ... and convert the 3DS materials to aiMaterial's
  714. for (unsigned int i = 0; i < pcOut->mNumMaterials;++i)
  715. {
  716. aiMaterial* pcNew = new aiMaterial();
  717. ConvertMaterial(mScene->mMaterials[i],*pcNew);
  718. pcOut->mMaterials[i] = pcNew;
  719. }
  720. // Generate the output mesh list
  721. ConvertMeshes(pcOut);
  722. // Now copy all light sources to the output scene
  723. pcOut->mNumLights = (unsigned int)mScene->mLights.size();
  724. if (pcOut->mNumLights)
  725. {
  726. pcOut->mLights = new aiLight*[pcOut->mNumLights];
  727. ::memcpy(pcOut->mLights,&mScene->mLights[0],sizeof(void*)*pcOut->mNumLights);
  728. }
  729. // Now copy all cameras to the output scene
  730. pcOut->mNumCameras = (unsigned int)mScene->mCameras.size();
  731. if (pcOut->mNumCameras)
  732. {
  733. pcOut->mCameras = new aiCamera*[pcOut->mNumCameras];
  734. ::memcpy(pcOut->mCameras,&mScene->mCameras[0],sizeof(void*)*pcOut->mNumCameras);
  735. }
  736. }
  737. #endif // !! ASSIMP_BUILD_NO_3DS_IMPORTER