3DSConverter.cpp 32 KB

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