3DSConverter.cpp 32 KB

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