3DSConverter.cpp 31 KB

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