3DSLoader.cpp 46 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336
  1. /*
  2. ---------------------------------------------------------------------------
  3. Open Asset Import Library (assimp)
  4. ---------------------------------------------------------------------------
  5. Copyright (c) 2006-2022, 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 3DSLoader.cpp
  35. * @brief Implementation of the 3ds importer class
  36. *
  37. * http://www.the-labs.com/Blender/3DS-details.html
  38. */
  39. #ifndef ASSIMP_BUILD_NO_3DS_IMPORTER
  40. #include "3DSLoader.h"
  41. #include <assimp/StringComparison.h>
  42. #include <assimp/importerdesc.h>
  43. #include <assimp/scene.h>
  44. #include <assimp/DefaultLogger.hpp>
  45. #include <assimp/IOSystem.hpp>
  46. using namespace Assimp;
  47. static const aiImporterDesc desc = {
  48. "Discreet 3DS Importer",
  49. "",
  50. "",
  51. "Limited animation support",
  52. aiImporterFlags_SupportBinaryFlavour,
  53. 0,
  54. 0,
  55. 0,
  56. 0,
  57. "3ds prj"
  58. };
  59. // ------------------------------------------------------------------------------------------------
  60. // Begins a new parsing block
  61. // - Reads the current chunk and validates it
  62. // - computes its length
  63. #define ASSIMP_3DS_BEGIN_CHUNK() \
  64. while (true) { \
  65. if (stream->GetRemainingSizeToLimit() < sizeof(Discreet3DS::Chunk)) { \
  66. return; \
  67. } \
  68. Discreet3DS::Chunk chunk; \
  69. ReadChunk(&chunk); \
  70. int chunkSize = chunk.Size - sizeof(Discreet3DS::Chunk); \
  71. if (chunkSize <= 0) \
  72. continue; \
  73. const unsigned int oldReadLimit = stream->SetReadLimit( \
  74. stream->GetCurrentPos() + chunkSize);
  75. // ------------------------------------------------------------------------------------------------
  76. // End a parsing block
  77. // Must follow at the end of each parsing block, reset chunk end marker to previous value
  78. #define ASSIMP_3DS_END_CHUNK() \
  79. stream->SkipToReadLimit(); \
  80. stream->SetReadLimit(oldReadLimit); \
  81. if (stream->GetRemainingSizeToLimit() == 0) \
  82. return; \
  83. }
  84. // ------------------------------------------------------------------------------------------------
  85. // Constructor to be privately used by Importer
  86. Discreet3DSImporter::Discreet3DSImporter() :
  87. stream(), mLastNodeIndex(), mCurrentNode(), mRootNode(), mScene(), mMasterScale(), bHasBG(), bIsPrj() {
  88. // empty
  89. }
  90. // ------------------------------------------------------------------------------------------------
  91. // Destructor, private as well
  92. Discreet3DSImporter::~Discreet3DSImporter() {
  93. // empty
  94. }
  95. // ------------------------------------------------------------------------------------------------
  96. // Returns whether the class can handle the format of the given file.
  97. bool Discreet3DSImporter::CanRead(const std::string &pFile, IOSystem *pIOHandler, bool /*checkSig*/) const {
  98. static const uint16_t token[] = { 0x4d4d, 0x3dc2 /*, 0x3daa */ };
  99. return CheckMagicToken(pIOHandler, pFile, token, AI_COUNT_OF(token), 0, sizeof token[0]);
  100. }
  101. // ------------------------------------------------------------------------------------------------
  102. // Loader registry entry
  103. const aiImporterDesc *Discreet3DSImporter::GetInfo() const {
  104. return &desc;
  105. }
  106. // ------------------------------------------------------------------------------------------------
  107. // Setup configuration properties
  108. void Discreet3DSImporter::SetupProperties(const Importer * /*pImp*/) {
  109. // nothing to be done for the moment
  110. }
  111. // ------------------------------------------------------------------------------------------------
  112. // Imports the given file into the given scene structure.
  113. void Discreet3DSImporter::InternReadFile(const std::string &pFile,
  114. aiScene *pScene, IOSystem *pIOHandler) {
  115. auto theFile = pIOHandler->Open(pFile, "rb");
  116. if (!theFile) {
  117. throw DeadlyImportError("3DS: Could not open ", pFile);
  118. }
  119. StreamReaderLE theStream(theFile);
  120. // We should have at least one chunk
  121. if (theStream.GetRemainingSize() < 16) {
  122. throw DeadlyImportError("3DS file is either empty or corrupt: ", pFile);
  123. }
  124. this->stream = &theStream;
  125. // Allocate our temporary 3DS representation
  126. D3DS::Scene _scene;
  127. mScene = &_scene;
  128. // Initialize members
  129. D3DS::Node _rootNode("UNNAMED");
  130. mLastNodeIndex = -1;
  131. mCurrentNode = &_rootNode;
  132. mRootNode = mCurrentNode;
  133. mRootNode->mHierarchyPos = -1;
  134. mRootNode->mHierarchyIndex = -1;
  135. mRootNode->mParent = nullptr;
  136. mMasterScale = 1.0f;
  137. mBackgroundImage = std::string();
  138. bHasBG = false;
  139. bIsPrj = false;
  140. // Parse the file
  141. ParseMainChunk();
  142. // Process all meshes in the file. First check whether all
  143. // face indices have valid values. The generate our
  144. // internal verbose representation. Finally compute normal
  145. // vectors from the smoothing groups we read from the
  146. // file.
  147. for (auto &mesh : mScene->mMeshes) {
  148. if (mesh.mFaces.size() > 0 && mesh.mPositions.size() == 0) {
  149. throw DeadlyImportError("3DS file contains faces but no vertices: ", pFile);
  150. }
  151. CheckIndices(mesh);
  152. MakeUnique(mesh);
  153. ComputeNormalsWithSmoothingsGroups<D3DS::Face>(mesh);
  154. }
  155. // Replace all occurrences of the default material with a
  156. // valid material. Generate it if no material containing
  157. // DEFAULT in its name has been found in the file
  158. ReplaceDefaultMaterial();
  159. // Convert the scene from our internal representation to an
  160. // aiScene object. This involves copying all meshes, lights
  161. // and cameras to the scene
  162. ConvertScene(pScene);
  163. // Generate the node graph for the scene. This is a little bit
  164. // tricky since we'll need to split some meshes into sub-meshes
  165. GenerateNodeGraph(pScene);
  166. // Now apply the master scaling factor to the scene
  167. ApplyMasterScale(pScene);
  168. // Our internal scene representation and the root
  169. // node will be automatically deleted, so the whole hierarchy will follow
  170. AI_DEBUG_INVALIDATE_PTR(mRootNode);
  171. AI_DEBUG_INVALIDATE_PTR(mScene);
  172. AI_DEBUG_INVALIDATE_PTR(this->stream);
  173. }
  174. // ------------------------------------------------------------------------------------------------
  175. // Applies a master-scaling factor to the imported scene
  176. void Discreet3DSImporter::ApplyMasterScale(aiScene *pScene) {
  177. // There are some 3DS files with a zero scaling factor
  178. if (!mMasterScale)
  179. mMasterScale = 1.0f;
  180. else
  181. mMasterScale = 1.0f / mMasterScale;
  182. // Construct an uniform scaling matrix and multiply with it
  183. pScene->mRootNode->mTransformation *= aiMatrix4x4(
  184. mMasterScale, 0.0f, 0.0f, 0.0f,
  185. 0.0f, mMasterScale, 0.0f, 0.0f,
  186. 0.0f, 0.0f, mMasterScale, 0.0f,
  187. 0.0f, 0.0f, 0.0f, 1.0f);
  188. // Check whether a scaling track is assigned to the root node.
  189. }
  190. // ------------------------------------------------------------------------------------------------
  191. // Reads a new chunk from the file
  192. void Discreet3DSImporter::ReadChunk(Discreet3DS::Chunk *pcOut) {
  193. ai_assert(pcOut != nullptr);
  194. pcOut->Flag = stream->GetI2();
  195. pcOut->Size = stream->GetI4();
  196. if (pcOut->Size - sizeof(Discreet3DS::Chunk) > stream->GetRemainingSize()) {
  197. throw DeadlyImportError("Chunk is too large");
  198. }
  199. if (pcOut->Size - sizeof(Discreet3DS::Chunk) > stream->GetRemainingSizeToLimit()) {
  200. ASSIMP_LOG_ERROR("3DS: Chunk overflow");
  201. }
  202. }
  203. // ------------------------------------------------------------------------------------------------
  204. // Skip a chunk
  205. void Discreet3DSImporter::SkipChunk() {
  206. Discreet3DS::Chunk psChunk;
  207. ReadChunk(&psChunk);
  208. stream->IncPtr(psChunk.Size - sizeof(Discreet3DS::Chunk));
  209. return;
  210. }
  211. // ------------------------------------------------------------------------------------------------
  212. // Process the primary chunk of the file
  213. void Discreet3DSImporter::ParseMainChunk() {
  214. ASSIMP_3DS_BEGIN_CHUNK();
  215. // get chunk type
  216. switch (chunk.Flag) {
  217. case Discreet3DS::CHUNK_PRJ:
  218. bIsPrj = true;
  219. break;
  220. case Discreet3DS::CHUNK_MAIN:
  221. ParseEditorChunk();
  222. break;
  223. };
  224. ASSIMP_3DS_END_CHUNK();
  225. // recursively continue processing this hierarchy level
  226. return ParseMainChunk();
  227. }
  228. // ------------------------------------------------------------------------------------------------
  229. void Discreet3DSImporter::ParseEditorChunk() {
  230. ASSIMP_3DS_BEGIN_CHUNK();
  231. // get chunk type
  232. switch (chunk.Flag) {
  233. case Discreet3DS::CHUNK_OBJMESH:
  234. ParseObjectChunk();
  235. break;
  236. // NOTE: In several documentations in the internet this
  237. // chunk appears at different locations
  238. case Discreet3DS::CHUNK_KEYFRAMER:
  239. ParseKeyframeChunk();
  240. break;
  241. case Discreet3DS::CHUNK_VERSION: {
  242. // print the version number
  243. char buff[10];
  244. ASSIMP_itoa10(buff, stream->GetI2());
  245. ASSIMP_LOG_INFO("3DS file format version: ", buff);
  246. } break;
  247. };
  248. ASSIMP_3DS_END_CHUNK();
  249. }
  250. // ------------------------------------------------------------------------------------------------
  251. void Discreet3DSImporter::ParseObjectChunk() {
  252. ASSIMP_3DS_BEGIN_CHUNK();
  253. // get chunk type
  254. switch (chunk.Flag) {
  255. case Discreet3DS::CHUNK_OBJBLOCK: {
  256. unsigned int cnt = 0;
  257. const char *sz = (const char *)stream->GetPtr();
  258. // Get the name of the geometry object
  259. while (stream->GetI1())
  260. ++cnt;
  261. ParseChunk(sz, cnt);
  262. } break;
  263. case Discreet3DS::CHUNK_MAT_MATERIAL:
  264. // Add a new material to the list
  265. mScene->mMaterials.push_back(D3DS::Material(std::string("UNNAMED_" + ai_to_string(mScene->mMaterials.size()))));
  266. ParseMaterialChunk();
  267. break;
  268. case Discreet3DS::CHUNK_AMBCOLOR:
  269. // This is the ambient base color of the scene.
  270. // We add it to the ambient color of all materials
  271. ParseColorChunk(&mClrAmbient, true);
  272. if (is_qnan(mClrAmbient.r)) {
  273. // We failed to read the ambient base color.
  274. ASSIMP_LOG_ERROR("3DS: Failed to read ambient base color");
  275. mClrAmbient.r = mClrAmbient.g = mClrAmbient.b = 0.0f;
  276. }
  277. break;
  278. case Discreet3DS::CHUNK_BIT_MAP: {
  279. // Specifies the background image. The string should already be
  280. // properly 0 terminated but we need to be sure
  281. unsigned int cnt = 0;
  282. const char *sz = (const char *)stream->GetPtr();
  283. while (stream->GetI1())
  284. ++cnt;
  285. mBackgroundImage = std::string(sz, cnt);
  286. } break;
  287. case Discreet3DS::CHUNK_BIT_MAP_EXISTS:
  288. bHasBG = true;
  289. break;
  290. case Discreet3DS::CHUNK_MASTER_SCALE:
  291. // Scene master scaling factor
  292. mMasterScale = stream->GetF4();
  293. break;
  294. };
  295. ASSIMP_3DS_END_CHUNK();
  296. }
  297. // ------------------------------------------------------------------------------------------------
  298. void Discreet3DSImporter::ParseChunk(const char *name, unsigned int num) {
  299. ASSIMP_3DS_BEGIN_CHUNK();
  300. // IMPLEMENTATION NOTE;
  301. // Cameras or lights define their transformation in their parent node and in the
  302. // corresponding light or camera chunks. However, we read and process the latter
  303. // to to be able to return valid cameras/lights even if no scenegraph is given.
  304. // get chunk type
  305. switch (chunk.Flag) {
  306. case Discreet3DS::CHUNK_TRIMESH: {
  307. // this starts a new triangle mesh
  308. mScene->mMeshes.push_back(D3DS::Mesh(std::string(name, num)));
  309. // Read mesh chunks
  310. ParseMeshChunk();
  311. } break;
  312. case Discreet3DS::CHUNK_LIGHT: {
  313. // This starts a new light
  314. aiLight *light = new aiLight();
  315. mScene->mLights.push_back(light);
  316. light->mName.Set(std::string(name, num));
  317. // First read the position of the light
  318. light->mPosition.x = stream->GetF4();
  319. light->mPosition.y = stream->GetF4();
  320. light->mPosition.z = stream->GetF4();
  321. light->mColorDiffuse = aiColor3D(1.f, 1.f, 1.f);
  322. // Now check for further subchunks
  323. if (!bIsPrj) /* fixme */
  324. ParseLightChunk();
  325. // The specular light color is identical the the diffuse light color. The ambient light color
  326. // is equal to the ambient base color of the whole scene.
  327. light->mColorSpecular = light->mColorDiffuse;
  328. light->mColorAmbient = mClrAmbient;
  329. if (light->mType == aiLightSource_UNDEFINED) {
  330. // It must be a point light
  331. light->mType = aiLightSource_POINT;
  332. }
  333. } break;
  334. case Discreet3DS::CHUNK_CAMERA: {
  335. // This starts a new camera
  336. aiCamera *camera = new aiCamera();
  337. mScene->mCameras.push_back(camera);
  338. camera->mName.Set(std::string(name, num));
  339. // First read the position of the camera
  340. camera->mPosition.x = stream->GetF4();
  341. camera->mPosition.y = stream->GetF4();
  342. camera->mPosition.z = stream->GetF4();
  343. // Then the camera target
  344. camera->mLookAt.x = stream->GetF4() - camera->mPosition.x;
  345. camera->mLookAt.y = stream->GetF4() - camera->mPosition.y;
  346. camera->mLookAt.z = stream->GetF4() - camera->mPosition.z;
  347. ai_real len = camera->mLookAt.Length();
  348. if (len < 1e-5) {
  349. // There are some files with lookat == position. Don't know why or whether it's ok or not.
  350. ASSIMP_LOG_ERROR("3DS: Unable to read proper camera look-at vector");
  351. camera->mLookAt = aiVector3D(0.0, 1.0, 0.0);
  352. } else
  353. camera->mLookAt /= len;
  354. // And finally - the camera rotation angle, in counter clockwise direction
  355. const ai_real angle = AI_DEG_TO_RAD(stream->GetF4());
  356. aiQuaternion quat(camera->mLookAt, angle);
  357. camera->mUp = quat.GetMatrix() * aiVector3D(0.0, 1.0, 0.0);
  358. // Read the lense angle
  359. camera->mHorizontalFOV = AI_DEG_TO_RAD(stream->GetF4());
  360. if (camera->mHorizontalFOV < 0.001f) {
  361. camera->mHorizontalFOV = float(AI_DEG_TO_RAD(45.f));
  362. }
  363. // Now check for further subchunks
  364. if (!bIsPrj) /* fixme */ {
  365. ParseCameraChunk();
  366. }
  367. } break;
  368. };
  369. ASSIMP_3DS_END_CHUNK();
  370. }
  371. // ------------------------------------------------------------------------------------------------
  372. void Discreet3DSImporter::ParseLightChunk() {
  373. ASSIMP_3DS_BEGIN_CHUNK();
  374. aiLight *light = mScene->mLights.back();
  375. // get chunk type
  376. switch (chunk.Flag) {
  377. case Discreet3DS::CHUNK_DL_SPOTLIGHT:
  378. // Now we can be sure that the light is a spot light
  379. light->mType = aiLightSource_SPOT;
  380. // We wouldn't need to normalize here, but we do it
  381. light->mDirection.x = stream->GetF4() - light->mPosition.x;
  382. light->mDirection.y = stream->GetF4() - light->mPosition.y;
  383. light->mDirection.z = stream->GetF4() - light->mPosition.z;
  384. light->mDirection.Normalize();
  385. // Now the hotspot and falloff angles - in degrees
  386. light->mAngleInnerCone = AI_DEG_TO_RAD(stream->GetF4());
  387. // FIX: the falloff angle is just an offset
  388. light->mAngleOuterCone = light->mAngleInnerCone + AI_DEG_TO_RAD(stream->GetF4());
  389. break;
  390. // intensity multiplier
  391. case Discreet3DS::CHUNK_DL_MULTIPLIER:
  392. light->mColorDiffuse = light->mColorDiffuse * stream->GetF4();
  393. break;
  394. // light color
  395. case Discreet3DS::CHUNK_RGBF:
  396. case Discreet3DS::CHUNK_LINRGBF:
  397. light->mColorDiffuse.r *= stream->GetF4();
  398. light->mColorDiffuse.g *= stream->GetF4();
  399. light->mColorDiffuse.b *= stream->GetF4();
  400. break;
  401. // light attenuation
  402. case Discreet3DS::CHUNK_DL_ATTENUATE:
  403. light->mAttenuationLinear = stream->GetF4();
  404. break;
  405. };
  406. ASSIMP_3DS_END_CHUNK();
  407. }
  408. // ------------------------------------------------------------------------------------------------
  409. void Discreet3DSImporter::ParseCameraChunk() {
  410. ASSIMP_3DS_BEGIN_CHUNK();
  411. aiCamera *camera = mScene->mCameras.back();
  412. // get chunk type
  413. switch (chunk.Flag) {
  414. // near and far clip plane
  415. case Discreet3DS::CHUNK_CAM_RANGES:
  416. camera->mClipPlaneNear = stream->GetF4();
  417. camera->mClipPlaneFar = stream->GetF4();
  418. break;
  419. }
  420. ASSIMP_3DS_END_CHUNK();
  421. }
  422. // ------------------------------------------------------------------------------------------------
  423. void Discreet3DSImporter::ParseKeyframeChunk() {
  424. ASSIMP_3DS_BEGIN_CHUNK();
  425. // get chunk type
  426. switch (chunk.Flag) {
  427. case Discreet3DS::CHUNK_TRACKCAMTGT:
  428. case Discreet3DS::CHUNK_TRACKSPOTL:
  429. case Discreet3DS::CHUNK_TRACKCAMERA:
  430. case Discreet3DS::CHUNK_TRACKINFO:
  431. case Discreet3DS::CHUNK_TRACKLIGHT:
  432. case Discreet3DS::CHUNK_TRACKLIGTGT:
  433. // this starts a new mesh hierarchy chunk
  434. ParseHierarchyChunk(chunk.Flag);
  435. break;
  436. };
  437. ASSIMP_3DS_END_CHUNK();
  438. }
  439. // ------------------------------------------------------------------------------------------------
  440. // Little helper function for ParseHierarchyChunk
  441. void Discreet3DSImporter::InverseNodeSearch(D3DS::Node *pcNode, D3DS::Node *pcCurrent) {
  442. if (!pcCurrent) {
  443. mRootNode->push_back(pcNode);
  444. return;
  445. }
  446. if (pcCurrent->mHierarchyPos == pcNode->mHierarchyPos) {
  447. if (pcCurrent->mParent) {
  448. pcCurrent->mParent->push_back(pcNode);
  449. } else
  450. pcCurrent->push_back(pcNode);
  451. return;
  452. }
  453. return InverseNodeSearch(pcNode, pcCurrent->mParent);
  454. }
  455. // ------------------------------------------------------------------------------------------------
  456. // Find a node with a specific name in the import hierarchy
  457. D3DS::Node *FindNode(D3DS::Node *root, const std::string &name) {
  458. if (root->mName == name) {
  459. return root;
  460. }
  461. for (std::vector<D3DS::Node *>::iterator it = root->mChildren.begin(); it != root->mChildren.end(); ++it) {
  462. D3DS::Node *nd = FindNode(*it, name);
  463. if (nullptr != nd) {
  464. return nd;
  465. }
  466. }
  467. return nullptr;
  468. }
  469. // ------------------------------------------------------------------------------------------------
  470. // Binary predicate for std::unique()
  471. template <class T>
  472. bool KeyUniqueCompare(const T &first, const T &second) {
  473. return first.mTime == second.mTime;
  474. }
  475. // ------------------------------------------------------------------------------------------------
  476. // Skip some additional import data.
  477. void Discreet3DSImporter::SkipTCBInfo() {
  478. unsigned int flags = stream->GetI2();
  479. if (!flags) {
  480. // Currently we can't do anything with these values. They occur
  481. // quite rare, so it wouldn't be worth the effort implementing
  482. // them. 3DS is not really suitable for complex animations,
  483. // so full support is not required.
  484. ASSIMP_LOG_WARN("3DS: Skipping TCB animation info");
  485. }
  486. if (flags & Discreet3DS::KEY_USE_TENS) {
  487. stream->IncPtr(4);
  488. }
  489. if (flags & Discreet3DS::KEY_USE_BIAS) {
  490. stream->IncPtr(4);
  491. }
  492. if (flags & Discreet3DS::KEY_USE_CONT) {
  493. stream->IncPtr(4);
  494. }
  495. if (flags & Discreet3DS::KEY_USE_EASE_FROM) {
  496. stream->IncPtr(4);
  497. }
  498. if (flags & Discreet3DS::KEY_USE_EASE_TO) {
  499. stream->IncPtr(4);
  500. }
  501. }
  502. // ------------------------------------------------------------------------------------------------
  503. // Read hierarchy and keyframe info
  504. void Discreet3DSImporter::ParseHierarchyChunk(uint16_t parent) {
  505. ASSIMP_3DS_BEGIN_CHUNK();
  506. // get chunk type
  507. switch (chunk.Flag) {
  508. case Discreet3DS::CHUNK_TRACKOBJNAME:
  509. // This is the name of the object to which the track applies. The chunk also
  510. // defines the position of this object in the hierarchy.
  511. {
  512. // First of all: get the name of the object
  513. unsigned int cnt = 0;
  514. const char *sz = (const char *)stream->GetPtr();
  515. while (stream->GetI1())
  516. ++cnt;
  517. std::string name = std::string(sz, cnt);
  518. // Now find out whether we have this node already (target animation channels
  519. // are stored with a separate object ID)
  520. D3DS::Node *pcNode = FindNode(mRootNode, name);
  521. int instanceNumber = 1;
  522. if (pcNode) {
  523. // if the source is not a CHUNK_TRACKINFO block it won't be an object instance
  524. if (parent != Discreet3DS::CHUNK_TRACKINFO) {
  525. mCurrentNode = pcNode;
  526. break;
  527. }
  528. pcNode->mInstanceCount++;
  529. instanceNumber = pcNode->mInstanceCount;
  530. }
  531. pcNode = new D3DS::Node(name);
  532. pcNode->mInstanceNumber = instanceNumber;
  533. // There are two unknown values which we can safely ignore
  534. stream->IncPtr(4);
  535. // Now read the hierarchy position of the object
  536. uint16_t hierarchy = stream->GetI2() + 1;
  537. pcNode->mHierarchyPos = hierarchy;
  538. pcNode->mHierarchyIndex = mLastNodeIndex;
  539. // And find a proper position in the graph for it
  540. if (mCurrentNode && mCurrentNode->mHierarchyPos == hierarchy) {
  541. // add to the parent of the last touched node
  542. mCurrentNode->mParent->push_back(pcNode);
  543. mLastNodeIndex++;
  544. } else if (hierarchy >= mLastNodeIndex) {
  545. // place it at the current position in the hierarchy
  546. mCurrentNode->push_back(pcNode);
  547. mLastNodeIndex = hierarchy;
  548. } else {
  549. // need to go back to the specified position in the hierarchy.
  550. InverseNodeSearch(pcNode, mCurrentNode);
  551. mLastNodeIndex++;
  552. }
  553. // Make this node the current node
  554. mCurrentNode = pcNode;
  555. }
  556. break;
  557. case Discreet3DS::CHUNK_TRACKDUMMYOBJNAME:
  558. // This is the "real" name of a $$$DUMMY object
  559. {
  560. const char *sz = (const char *)stream->GetPtr();
  561. while (stream->GetI1())
  562. ;
  563. // If object name is DUMMY, take this one instead
  564. if (mCurrentNode->mName == "$$$DUMMY") {
  565. mCurrentNode->mName = std::string(sz);
  566. break;
  567. }
  568. }
  569. break;
  570. case Discreet3DS::CHUNK_TRACKPIVOT:
  571. if (Discreet3DS::CHUNK_TRACKINFO != parent) {
  572. ASSIMP_LOG_WARN("3DS: Skipping pivot subchunk for non usual object");
  573. break;
  574. }
  575. // Pivot = origin of rotation and scaling
  576. mCurrentNode->vPivot.x = stream->GetF4();
  577. mCurrentNode->vPivot.y = stream->GetF4();
  578. mCurrentNode->vPivot.z = stream->GetF4();
  579. break;
  580. // ////////////////////////////////////////////////////////////////////
  581. // POSITION KEYFRAME
  582. case Discreet3DS::CHUNK_TRACKPOS: {
  583. stream->IncPtr(10);
  584. const unsigned int numFrames = stream->GetI4();
  585. bool sortKeys = false;
  586. // This could also be meant as the target position for
  587. // (targeted) lights and cameras
  588. std::vector<aiVectorKey> *l;
  589. if (Discreet3DS::CHUNK_TRACKCAMTGT == parent || Discreet3DS::CHUNK_TRACKLIGTGT == parent) {
  590. l = &mCurrentNode->aTargetPositionKeys;
  591. } else
  592. l = &mCurrentNode->aPositionKeys;
  593. l->reserve(numFrames);
  594. for (unsigned int i = 0; i < numFrames; ++i) {
  595. const unsigned int fidx = stream->GetI4();
  596. // Setup a new position key
  597. aiVectorKey v;
  598. v.mTime = (double)fidx;
  599. SkipTCBInfo();
  600. v.mValue.x = stream->GetF4();
  601. v.mValue.y = stream->GetF4();
  602. v.mValue.z = stream->GetF4();
  603. // check whether we'll need to sort the keys
  604. if (!l->empty() && v.mTime <= l->back().mTime)
  605. sortKeys = true;
  606. // Add the new keyframe to the list
  607. l->push_back(v);
  608. }
  609. // Sort all keys with ascending time values and remove duplicates?
  610. if (sortKeys) {
  611. std::stable_sort(l->begin(), l->end());
  612. l->erase(std::unique(l->begin(), l->end(), &KeyUniqueCompare<aiVectorKey>), l->end());
  613. }
  614. }
  615. break;
  616. // ////////////////////////////////////////////////////////////////////
  617. // CAMERA ROLL KEYFRAME
  618. case Discreet3DS::CHUNK_TRACKROLL: {
  619. // roll keys are accepted for cameras only
  620. if (parent != Discreet3DS::CHUNK_TRACKCAMERA) {
  621. ASSIMP_LOG_WARN("3DS: Ignoring roll track for non-camera object");
  622. break;
  623. }
  624. bool sortKeys = false;
  625. std::vector<aiFloatKey> *l = &mCurrentNode->aCameraRollKeys;
  626. stream->IncPtr(10);
  627. const unsigned int numFrames = stream->GetI4();
  628. l->reserve(numFrames);
  629. for (unsigned int i = 0; i < numFrames; ++i) {
  630. const unsigned int fidx = stream->GetI4();
  631. // Setup a new position key
  632. aiFloatKey v;
  633. v.mTime = (double)fidx;
  634. // This is just a single float
  635. SkipTCBInfo();
  636. v.mValue = stream->GetF4();
  637. // Check whether we'll need to sort the keys
  638. if (!l->empty() && v.mTime <= l->back().mTime)
  639. sortKeys = true;
  640. // Add the new keyframe to the list
  641. l->push_back(v);
  642. }
  643. // Sort all keys with ascending time values and remove duplicates?
  644. if (sortKeys) {
  645. std::stable_sort(l->begin(), l->end());
  646. l->erase(std::unique(l->begin(), l->end(), &KeyUniqueCompare<aiFloatKey>), l->end());
  647. }
  648. } break;
  649. // ////////////////////////////////////////////////////////////////////
  650. // CAMERA FOV KEYFRAME
  651. case Discreet3DS::CHUNK_TRACKFOV: {
  652. ASSIMP_LOG_ERROR("3DS: Skipping FOV animation track. "
  653. "This is not supported");
  654. } break;
  655. // ////////////////////////////////////////////////////////////////////
  656. // ROTATION KEYFRAME
  657. case Discreet3DS::CHUNK_TRACKROTATE: {
  658. stream->IncPtr(10);
  659. const unsigned int numFrames = stream->GetI4();
  660. bool sortKeys = false;
  661. std::vector<aiQuatKey> *l = &mCurrentNode->aRotationKeys;
  662. l->reserve(numFrames);
  663. for (unsigned int i = 0; i < numFrames; ++i) {
  664. const unsigned int fidx = stream->GetI4();
  665. SkipTCBInfo();
  666. aiQuatKey v;
  667. v.mTime = (double)fidx;
  668. // The rotation keyframe is given as an axis-angle pair
  669. const float rad = stream->GetF4();
  670. aiVector3D axis;
  671. axis.x = stream->GetF4();
  672. axis.y = stream->GetF4();
  673. axis.z = stream->GetF4();
  674. if (!axis.x && !axis.y && !axis.z)
  675. axis.y = 1.f;
  676. // Construct a rotation quaternion from the axis-angle pair
  677. v.mValue = aiQuaternion(axis, rad);
  678. // Check whether we'll need to sort the keys
  679. if (!l->empty() && v.mTime <= l->back().mTime)
  680. sortKeys = true;
  681. // add the new keyframe to the list
  682. l->push_back(v);
  683. }
  684. // Sort all keys with ascending time values and remove duplicates?
  685. if (sortKeys) {
  686. std::stable_sort(l->begin(), l->end());
  687. l->erase(std::unique(l->begin(), l->end(), &KeyUniqueCompare<aiQuatKey>), l->end());
  688. }
  689. } break;
  690. // ////////////////////////////////////////////////////////////////////
  691. // SCALING KEYFRAME
  692. case Discreet3DS::CHUNK_TRACKSCALE: {
  693. stream->IncPtr(10);
  694. const unsigned int numFrames = stream->GetI2();
  695. stream->IncPtr(2);
  696. bool sortKeys = false;
  697. std::vector<aiVectorKey> *l = &mCurrentNode->aScalingKeys;
  698. l->reserve(numFrames);
  699. for (unsigned int i = 0; i < numFrames; ++i) {
  700. const unsigned int fidx = stream->GetI4();
  701. SkipTCBInfo();
  702. // Setup a new key
  703. aiVectorKey v;
  704. v.mTime = (double)fidx;
  705. // ... and read its value
  706. v.mValue.x = stream->GetF4();
  707. v.mValue.y = stream->GetF4();
  708. v.mValue.z = stream->GetF4();
  709. // check whether we'll need to sort the keys
  710. if (!l->empty() && v.mTime <= l->back().mTime)
  711. sortKeys = true;
  712. // Remove zero-scalings on singular axes - they've been reported to be there erroneously in some strange files
  713. if (!v.mValue.x) v.mValue.x = 1.f;
  714. if (!v.mValue.y) v.mValue.y = 1.f;
  715. if (!v.mValue.z) v.mValue.z = 1.f;
  716. l->push_back(v);
  717. }
  718. // Sort all keys with ascending time values and remove duplicates?
  719. if (sortKeys) {
  720. std::stable_sort(l->begin(), l->end());
  721. l->erase(std::unique(l->begin(), l->end(), &KeyUniqueCompare<aiVectorKey>), l->end());
  722. }
  723. } break;
  724. };
  725. ASSIMP_3DS_END_CHUNK();
  726. }
  727. // ------------------------------------------------------------------------------------------------
  728. // Read a face chunk - it contains smoothing groups and material assignments
  729. void Discreet3DSImporter::ParseFaceChunk() {
  730. ASSIMP_3DS_BEGIN_CHUNK();
  731. // Get the mesh we're currently working on
  732. D3DS::Mesh &mMesh = mScene->mMeshes.back();
  733. // Get chunk type
  734. switch (chunk.Flag) {
  735. case Discreet3DS::CHUNK_SMOOLIST: {
  736. // This is the list of smoothing groups - a bitfield for every face.
  737. // Up to 32 smoothing groups assigned to a single face.
  738. unsigned int num = chunkSize / 4, m = 0;
  739. if (num > mMesh.mFaces.size()) {
  740. throw DeadlyImportError("3DS: More smoothing groups than faces");
  741. }
  742. for (std::vector<D3DS::Face>::iterator i = mMesh.mFaces.begin(); m != num; ++i, ++m) {
  743. // nth bit is set for nth smoothing group
  744. (*i).iSmoothGroup = stream->GetI4();
  745. }
  746. } break;
  747. case Discreet3DS::CHUNK_FACEMAT: {
  748. // at fist an asciiz with the material name
  749. const char *sz = (const char *)stream->GetPtr();
  750. while (stream->GetI1())
  751. ;
  752. // find the index of the material
  753. unsigned int idx = 0xcdcdcdcd, cnt = 0;
  754. for (std::vector<D3DS::Material>::const_iterator i = mScene->mMaterials.begin(); i != mScene->mMaterials.end(); ++i, ++cnt) {
  755. // use case independent comparisons. hopefully it will work.
  756. if ((*i).mName.length() && !ASSIMP_stricmp(sz, (*i).mName.c_str())) {
  757. idx = cnt;
  758. break;
  759. }
  760. }
  761. if (0xcdcdcdcd == idx) {
  762. ASSIMP_LOG_ERROR("3DS: Unknown material: ", sz);
  763. }
  764. // Now continue and read all material indices
  765. cnt = (uint16_t)stream->GetI2();
  766. for (unsigned int i = 0; i < cnt; ++i) {
  767. unsigned int fidx = (uint16_t)stream->GetI2();
  768. // check range
  769. if (fidx >= mMesh.mFaceMaterials.size()) {
  770. ASSIMP_LOG_ERROR("3DS: Invalid face index in face material list");
  771. } else
  772. mMesh.mFaceMaterials[fidx] = idx;
  773. }
  774. } break;
  775. };
  776. ASSIMP_3DS_END_CHUNK();
  777. }
  778. // ------------------------------------------------------------------------------------------------
  779. // Read a mesh chunk. Here's the actual mesh data
  780. void Discreet3DSImporter::ParseMeshChunk() {
  781. ASSIMP_3DS_BEGIN_CHUNK();
  782. // Get the mesh we're currently working on
  783. D3DS::Mesh &mMesh = mScene->mMeshes.back();
  784. // get chunk type
  785. switch (chunk.Flag) {
  786. case Discreet3DS::CHUNK_VERTLIST: {
  787. // This is the list of all vertices in the current mesh
  788. int num = (int)(uint16_t)stream->GetI2();
  789. mMesh.mPositions.reserve(num);
  790. while (num-- > 0) {
  791. aiVector3D v;
  792. v.x = stream->GetF4();
  793. v.y = stream->GetF4();
  794. v.z = stream->GetF4();
  795. mMesh.mPositions.push_back(v);
  796. }
  797. } break;
  798. case Discreet3DS::CHUNK_TRMATRIX: {
  799. // This is the RLEATIVE transformation matrix of the current mesh. Vertices are
  800. // pretransformed by this matrix wonder.
  801. mMesh.mMat.a1 = stream->GetF4();
  802. mMesh.mMat.b1 = stream->GetF4();
  803. mMesh.mMat.c1 = stream->GetF4();
  804. mMesh.mMat.a2 = stream->GetF4();
  805. mMesh.mMat.b2 = stream->GetF4();
  806. mMesh.mMat.c2 = stream->GetF4();
  807. mMesh.mMat.a3 = stream->GetF4();
  808. mMesh.mMat.b3 = stream->GetF4();
  809. mMesh.mMat.c3 = stream->GetF4();
  810. mMesh.mMat.a4 = stream->GetF4();
  811. mMesh.mMat.b4 = stream->GetF4();
  812. mMesh.mMat.c4 = stream->GetF4();
  813. } break;
  814. case Discreet3DS::CHUNK_MAPLIST: {
  815. // This is the list of all UV coords in the current mesh
  816. int num = (int)(uint16_t)stream->GetI2();
  817. mMesh.mTexCoords.reserve(num);
  818. while (num-- > 0) {
  819. aiVector3D v;
  820. v.x = stream->GetF4();
  821. v.y = stream->GetF4();
  822. mMesh.mTexCoords.push_back(v);
  823. }
  824. } break;
  825. case Discreet3DS::CHUNK_FACELIST: {
  826. // This is the list of all faces in the current mesh
  827. int num = (int)(uint16_t)stream->GetI2();
  828. mMesh.mFaces.reserve(num);
  829. while (num-- > 0) {
  830. // 3DS faces are ALWAYS triangles
  831. mMesh.mFaces.push_back(D3DS::Face());
  832. D3DS::Face &sFace = mMesh.mFaces.back();
  833. sFace.mIndices[0] = (uint16_t)stream->GetI2();
  834. sFace.mIndices[1] = (uint16_t)stream->GetI2();
  835. sFace.mIndices[2] = (uint16_t)stream->GetI2();
  836. stream->IncPtr(2); // skip edge visibility flag
  837. }
  838. // Resize the material array (0xcdcdcdcd marks the default material; so if a face is
  839. // not referenced by a material, $$DEFAULT will be assigned to it)
  840. mMesh.mFaceMaterials.resize(mMesh.mFaces.size(), 0xcdcdcdcd);
  841. // Larger 3DS files could have multiple FACE chunks here
  842. chunkSize = (int)stream->GetRemainingSizeToLimit();
  843. if (chunkSize > (int)sizeof(Discreet3DS::Chunk))
  844. ParseFaceChunk();
  845. } break;
  846. };
  847. ASSIMP_3DS_END_CHUNK();
  848. }
  849. // ------------------------------------------------------------------------------------------------
  850. // Read a 3DS material chunk
  851. void Discreet3DSImporter::ParseMaterialChunk() {
  852. ASSIMP_3DS_BEGIN_CHUNK();
  853. switch (chunk.Flag) {
  854. case Discreet3DS::CHUNK_MAT_MATNAME:
  855. {
  856. // The material name string is already zero-terminated, but we need to be sure ...
  857. const char *sz = (const char *)stream->GetPtr();
  858. unsigned int cnt = 0;
  859. while (stream->GetI1())
  860. ++cnt;
  861. if (!cnt) {
  862. // This may not be, we use the default name instead
  863. ASSIMP_LOG_ERROR("3DS: Empty material name");
  864. } else
  865. mScene->mMaterials.back().mName = std::string(sz, cnt);
  866. } break;
  867. case Discreet3DS::CHUNK_MAT_DIFFUSE: {
  868. // This is the diffuse material color
  869. aiColor3D *pc = &mScene->mMaterials.back().mDiffuse;
  870. ParseColorChunk(pc);
  871. if (is_qnan(pc->r)) {
  872. // color chunk is invalid. Simply ignore it
  873. ASSIMP_LOG_ERROR("3DS: Unable to read DIFFUSE chunk");
  874. pc->r = pc->g = pc->b = 1.0f;
  875. }
  876. } break;
  877. case Discreet3DS::CHUNK_MAT_SPECULAR: {
  878. // This is the specular material color
  879. aiColor3D *pc = &mScene->mMaterials.back().mSpecular;
  880. ParseColorChunk(pc);
  881. if (is_qnan(pc->r)) {
  882. // color chunk is invalid. Simply ignore it
  883. ASSIMP_LOG_ERROR("3DS: Unable to read SPECULAR chunk");
  884. pc->r = pc->g = pc->b = 1.0f;
  885. }
  886. } break;
  887. case Discreet3DS::CHUNK_MAT_AMBIENT: {
  888. // This is the ambient material color
  889. aiColor3D *pc = &mScene->mMaterials.back().mAmbient;
  890. ParseColorChunk(pc);
  891. if (is_qnan(pc->r)) {
  892. // color chunk is invalid. Simply ignore it
  893. ASSIMP_LOG_ERROR("3DS: Unable to read AMBIENT chunk");
  894. pc->r = pc->g = pc->b = 0.0f;
  895. }
  896. } break;
  897. case Discreet3DS::CHUNK_MAT_SELF_ILLUM: {
  898. // This is the emissive material color
  899. aiColor3D *pc = &mScene->mMaterials.back().mEmissive;
  900. ParseColorChunk(pc);
  901. if (is_qnan(pc->r)) {
  902. // color chunk is invalid. Simply ignore it
  903. ASSIMP_LOG_ERROR("3DS: Unable to read EMISSIVE chunk");
  904. pc->r = pc->g = pc->b = 0.0f;
  905. }
  906. } break;
  907. case Discreet3DS::CHUNK_MAT_TRANSPARENCY: {
  908. // This is the material's transparency
  909. ai_real *pcf = &mScene->mMaterials.back().mTransparency;
  910. *pcf = ParsePercentageChunk();
  911. // NOTE: transparency, not opacity
  912. if (is_qnan(*pcf))
  913. *pcf = ai_real(1.0);
  914. else
  915. *pcf = ai_real(1.0) - *pcf * (ai_real)0xFFFF / ai_real(100.0);
  916. } break;
  917. case Discreet3DS::CHUNK_MAT_SHADING:
  918. // This is the material shading mode
  919. mScene->mMaterials.back().mShading = (D3DS::Discreet3DS::shadetype3ds)stream->GetI2();
  920. break;
  921. case Discreet3DS::CHUNK_MAT_TWO_SIDE:
  922. // This is the two-sided flag
  923. mScene->mMaterials.back().mTwoSided = true;
  924. break;
  925. case Discreet3DS::CHUNK_MAT_SHININESS: { // This is the shininess of the material
  926. ai_real *pcf = &mScene->mMaterials.back().mSpecularExponent;
  927. *pcf = ParsePercentageChunk();
  928. if (is_qnan(*pcf))
  929. *pcf = 0.0;
  930. else
  931. *pcf *= (ai_real)0xFFFF;
  932. } break;
  933. case Discreet3DS::CHUNK_MAT_SHININESS_PERCENT: { // This is the shininess strength of the material
  934. ai_real *pcf = &mScene->mMaterials.back().mShininessStrength;
  935. *pcf = ParsePercentageChunk();
  936. if (is_qnan(*pcf))
  937. *pcf = ai_real(0.0);
  938. else
  939. *pcf *= (ai_real)0xffff / ai_real(100.0);
  940. } break;
  941. case Discreet3DS::CHUNK_MAT_SELF_ILPCT: { // This is the self illumination strength of the material
  942. ai_real f = ParsePercentageChunk();
  943. if (is_qnan(f))
  944. f = ai_real(0.0);
  945. else
  946. f *= (ai_real)0xFFFF / ai_real(100.0);
  947. mScene->mMaterials.back().mEmissive = aiColor3D(f, f, f);
  948. } break;
  949. // Parse texture chunks
  950. case Discreet3DS::CHUNK_MAT_TEXTURE:
  951. // Diffuse texture
  952. ParseTextureChunk(&mScene->mMaterials.back().sTexDiffuse);
  953. break;
  954. case Discreet3DS::CHUNK_MAT_BUMPMAP:
  955. // Height map
  956. ParseTextureChunk(&mScene->mMaterials.back().sTexBump);
  957. break;
  958. case Discreet3DS::CHUNK_MAT_OPACMAP:
  959. // Opacity texture
  960. ParseTextureChunk(&mScene->mMaterials.back().sTexOpacity);
  961. break;
  962. case Discreet3DS::CHUNK_MAT_MAT_SHINMAP:
  963. // Shininess map
  964. ParseTextureChunk(&mScene->mMaterials.back().sTexShininess);
  965. break;
  966. case Discreet3DS::CHUNK_MAT_SPECMAP:
  967. // Specular map
  968. ParseTextureChunk(&mScene->mMaterials.back().sTexSpecular);
  969. break;
  970. case Discreet3DS::CHUNK_MAT_SELFIMAP:
  971. // Self-illumination (emissive) map
  972. ParseTextureChunk(&mScene->mMaterials.back().sTexEmissive);
  973. break;
  974. case Discreet3DS::CHUNK_MAT_REFLMAP:
  975. // Reflection map
  976. ParseTextureChunk(&mScene->mMaterials.back().sTexReflective);
  977. break;
  978. };
  979. ASSIMP_3DS_END_CHUNK();
  980. }
  981. // ------------------------------------------------------------------------------------------------
  982. void Discreet3DSImporter::ParseTextureChunk(D3DS::Texture *pcOut) {
  983. ASSIMP_3DS_BEGIN_CHUNK();
  984. // get chunk type
  985. switch (chunk.Flag) {
  986. case Discreet3DS::CHUNK_MAPFILE: {
  987. // The material name string is already zero-terminated, but we need to be sure ...
  988. const char *sz = (const char *)stream->GetPtr();
  989. unsigned int cnt = 0;
  990. while (stream->GetI1())
  991. ++cnt;
  992. pcOut->mMapName = std::string(sz, cnt);
  993. } break;
  994. case Discreet3DS::CHUNK_PERCENTD:
  995. // Manually parse the blend factor
  996. pcOut->mTextureBlend = ai_real(stream->GetF8());
  997. break;
  998. case Discreet3DS::CHUNK_PERCENTF:
  999. // Manually parse the blend factor
  1000. pcOut->mTextureBlend = stream->GetF4();
  1001. break;
  1002. case Discreet3DS::CHUNK_PERCENTW:
  1003. // Manually parse the blend factor
  1004. pcOut->mTextureBlend = (ai_real)((uint16_t)stream->GetI2()) / ai_real(100.0);
  1005. break;
  1006. case Discreet3DS::CHUNK_MAT_MAP_USCALE:
  1007. // Texture coordinate scaling in the U direction
  1008. pcOut->mScaleU = stream->GetF4();
  1009. if (0.0f == pcOut->mScaleU) {
  1010. ASSIMP_LOG_WARN("Texture coordinate scaling in the x direction is zero. Assuming 1.");
  1011. pcOut->mScaleU = 1.0f;
  1012. }
  1013. break;
  1014. case Discreet3DS::CHUNK_MAT_MAP_VSCALE:
  1015. // Texture coordinate scaling in the V direction
  1016. pcOut->mScaleV = stream->GetF4();
  1017. if (0.0f == pcOut->mScaleV) {
  1018. ASSIMP_LOG_WARN("Texture coordinate scaling in the y direction is zero. Assuming 1.");
  1019. pcOut->mScaleV = 1.0f;
  1020. }
  1021. break;
  1022. case Discreet3DS::CHUNK_MAT_MAP_UOFFSET:
  1023. // Texture coordinate offset in the U direction
  1024. pcOut->mOffsetU = -stream->GetF4();
  1025. break;
  1026. case Discreet3DS::CHUNK_MAT_MAP_VOFFSET:
  1027. // Texture coordinate offset in the V direction
  1028. pcOut->mOffsetV = stream->GetF4();
  1029. break;
  1030. case Discreet3DS::CHUNK_MAT_MAP_ANG:
  1031. // Texture coordinate rotation, CCW in DEGREES
  1032. pcOut->mRotation = -AI_DEG_TO_RAD(stream->GetF4());
  1033. break;
  1034. case Discreet3DS::CHUNK_MAT_MAP_TILING: {
  1035. const uint16_t iFlags = stream->GetI2();
  1036. // Get the mapping mode (for both axes)
  1037. if (iFlags & 0x2u)
  1038. pcOut->mMapMode = aiTextureMapMode_Mirror;
  1039. else if (iFlags & 0x10u)
  1040. pcOut->mMapMode = aiTextureMapMode_Decal;
  1041. // wrapping in all remaining cases
  1042. else
  1043. pcOut->mMapMode = aiTextureMapMode_Wrap;
  1044. } break;
  1045. };
  1046. ASSIMP_3DS_END_CHUNK();
  1047. }
  1048. // ------------------------------------------------------------------------------------------------
  1049. // Read a percentage chunk
  1050. ai_real Discreet3DSImporter::ParsePercentageChunk() {
  1051. Discreet3DS::Chunk chunk;
  1052. ReadChunk(&chunk);
  1053. if (Discreet3DS::CHUNK_PERCENTF == chunk.Flag) {
  1054. return stream->GetF4() * ai_real(100) / ai_real(0xFFFF);
  1055. } else if (Discreet3DS::CHUNK_PERCENTW == chunk.Flag) {
  1056. return (ai_real)((uint16_t)stream->GetI2()) / (ai_real)0xFFFF;
  1057. }
  1058. return get_qnan();
  1059. }
  1060. // ------------------------------------------------------------------------------------------------
  1061. // Read a color chunk. If a percentage chunk is found instead it is read as a grayscale color
  1062. void Discreet3DSImporter::ParseColorChunk(aiColor3D *out, bool acceptPercent) {
  1063. ai_assert(out != nullptr);
  1064. // error return value
  1065. const ai_real qnan = get_qnan();
  1066. static const aiColor3D clrError = aiColor3D(qnan, qnan, qnan);
  1067. Discreet3DS::Chunk chunk;
  1068. ReadChunk(&chunk);
  1069. const unsigned int diff = chunk.Size - sizeof(Discreet3DS::Chunk);
  1070. bool bGamma = false;
  1071. // Get the type of the chunk
  1072. switch (chunk.Flag) {
  1073. case Discreet3DS::CHUNK_LINRGBF:
  1074. bGamma = true;
  1075. case Discreet3DS::CHUNK_RGBF:
  1076. if (sizeof(float) * 3 > diff) {
  1077. *out = clrError;
  1078. return;
  1079. }
  1080. out->r = stream->GetF4();
  1081. out->g = stream->GetF4();
  1082. out->b = stream->GetF4();
  1083. break;
  1084. case Discreet3DS::CHUNK_LINRGBB:
  1085. bGamma = true;
  1086. case Discreet3DS::CHUNK_RGBB: {
  1087. if (sizeof(char) * 3 > diff) {
  1088. *out = clrError;
  1089. return;
  1090. }
  1091. const ai_real invVal = ai_real(1.0) / ai_real(255.0);
  1092. out->r = (ai_real)(uint8_t)stream->GetI1() * invVal;
  1093. out->g = (ai_real)(uint8_t)stream->GetI1() * invVal;
  1094. out->b = (ai_real)(uint8_t)stream->GetI1() * invVal;
  1095. } break;
  1096. // Percentage chunks are accepted, too.
  1097. case Discreet3DS::CHUNK_PERCENTF:
  1098. if (acceptPercent && 4 <= diff) {
  1099. out->g = out->b = out->r = stream->GetF4();
  1100. break;
  1101. }
  1102. *out = clrError;
  1103. return;
  1104. case Discreet3DS::CHUNK_PERCENTW:
  1105. if (acceptPercent && 1 <= diff) {
  1106. out->g = out->b = out->r = (ai_real)(uint8_t)stream->GetI1() / ai_real(255.0);
  1107. break;
  1108. }
  1109. *out = clrError;
  1110. return;
  1111. default:
  1112. stream->IncPtr(diff);
  1113. // Skip unknown chunks, hope this won't cause any problems.
  1114. return ParseColorChunk(out, acceptPercent);
  1115. };
  1116. (void)bGamma;
  1117. }
  1118. #endif // !! ASSIMP_BUILD_NO_3DS_IMPORTER