3DSLoader.cpp 41 KB

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