3DSLoader.cpp 42 KB

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