3DSLoader.cpp 41 KB

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