3DSLoader.cpp 46 KB

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