3DSLoader.cpp 46 KB

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