MDLLoader.cpp 87 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015
  1. /*
  2. ---------------------------------------------------------------------------
  3. Open Asset Import Library (assimp)
  4. ---------------------------------------------------------------------------
  5. Copyright (c) 2006-2026, assimp team
  6. All rights reserved.
  7. Redistribution and use of this software in source and binary forms,
  8. with or without modification, are permitted provided that the following
  9. conditions are met:
  10. * Redistributions of source code must retain the above
  11. copyright notice, this list of conditions and the
  12. following disclaimer.
  13. * Redistributions in binary form must reproduce the above
  14. copyright notice, this list of conditions and the
  15. following disclaimer in the documentation and/or other
  16. materials provided with the distribution.
  17. * Neither the name of the assimp team, nor the names of its
  18. contributors may be used to endorse or promote products
  19. derived from this software without specific prior
  20. written permission of the assimp team.
  21. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  22. "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  23. LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  24. A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  25. OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  26. SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  27. LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  28. DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  29. THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  30. (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  31. OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  32. ---------------------------------------------------------------------------
  33. */
  34. /** @file MDLLoader.cpp
  35. * @brief Implementation of the main parts of the MDL importer class
  36. * *TODO* Cleanup and further testing of some parts necessary
  37. */
  38. // internal headers
  39. #ifndef ASSIMP_BUILD_NO_MDL_IMPORTER
  40. #include "MDLLoader.h"
  41. #include "AssetLib/MD2/MD2FileData.h"
  42. #include "HalfLife/HL1MDLLoader.h"
  43. #include "HalfLife/HL1FileData.h"
  44. #include "MDLDefaultColorMap.h"
  45. #include <assimp/StringUtils.h>
  46. #include <assimp/importerdesc.h>
  47. #include <assimp/qnan.h>
  48. #include <assimp/scene.h>
  49. #include <assimp/DefaultLogger.hpp>
  50. #include <assimp/IOSystem.hpp>
  51. #include <assimp/Importer.hpp>
  52. #include <memory>
  53. using namespace Assimp;
  54. static constexpr aiImporterDesc desc = {
  55. "Quake Mesh / 3D GameStudio Mesh Importer",
  56. "",
  57. "",
  58. "",
  59. aiImporterFlags_SupportBinaryFlavour,
  60. 0,
  61. 0,
  62. 7,
  63. 0,
  64. "mdl"
  65. };
  66. // ------------------------------------------------------------------------------------------------
  67. // Ugly stuff ... nevermind
  68. #define _AI_MDL7_ACCESS(_data, _index, _limit, _type) \
  69. (*((const _type *)(((const char *)_data) + _index * _limit)))
  70. #define _AI_MDL7_ACCESS_PTR(_data, _index, _limit, _type) \
  71. ((BE_NCONST _type *)(((const char *)_data) + _index * _limit))
  72. #define _AI_MDL7_ACCESS_VERT(_data, _index, _limit) \
  73. _AI_MDL7_ACCESS(_data, _index, _limit, MDL::Vertex_MDL7)
  74. // ------------------------------------------------------------------------------------------------
  75. // Constructor to be privately used by Importer
  76. MDLImporter::MDLImporter() :
  77. configFrameID(), mBuffer(), iGSFileVersion(), mIOHandler(nullptr), pScene(), iFileSize() {
  78. // empty
  79. }
  80. // ------------------------------------------------------------------------------------------------
  81. // Returns whether the class can handle the format of the given file.
  82. bool MDLImporter::CanRead(const std::string &pFile, IOSystem *pIOHandler, bool /*checkSig*/) const {
  83. static constexpr uint32_t tokens[] = {
  84. AI_MDL_MAGIC_NUMBER_LE_HL2a,
  85. AI_MDL_MAGIC_NUMBER_LE_HL2b,
  86. AI_MDL_MAGIC_NUMBER_LE_GS7,
  87. AI_MDL_MAGIC_NUMBER_LE_GS5b,
  88. AI_MDL_MAGIC_NUMBER_LE_GS5a,
  89. AI_MDL_MAGIC_NUMBER_LE_GS4,
  90. AI_MDL_MAGIC_NUMBER_LE_GS3,
  91. AI_MDL_MAGIC_NUMBER_LE
  92. };
  93. return CheckMagicToken(pIOHandler, pFile, tokens, AI_COUNT_OF(tokens));
  94. }
  95. // ------------------------------------------------------------------------------------------------
  96. // Setup configuration properties
  97. void MDLImporter::SetupProperties(const Importer *pImp) {
  98. configFrameID = pImp->GetPropertyInteger(AI_CONFIG_IMPORT_MDL_KEYFRAME, -1);
  99. // The
  100. // AI_CONFIG_IMPORT_MDL_KEYFRAME option overrides the
  101. // AI_CONFIG_IMPORT_GLOBAL_KEYFRAME option.
  102. if (static_cast<unsigned int>(-1) == configFrameID) {
  103. configFrameID = pImp->GetPropertyInteger(AI_CONFIG_IMPORT_GLOBAL_KEYFRAME, 0);
  104. }
  105. // AI_CONFIG_IMPORT_MDL_COLORMAP - palette file
  106. configPalette = pImp->GetPropertyString(AI_CONFIG_IMPORT_MDL_COLORMAP, "colormap.lmp");
  107. // Read configuration specific to MDL (Half-Life 1).
  108. mHL1ImportSettings.read_animations = pImp->GetPropertyBool(AI_CONFIG_IMPORT_MDL_HL1_READ_ANIMATIONS, true);
  109. if (mHL1ImportSettings.read_animations) {
  110. mHL1ImportSettings.read_animation_events = pImp->GetPropertyBool(AI_CONFIG_IMPORT_MDL_HL1_READ_ANIMATION_EVENTS, true);
  111. mHL1ImportSettings.read_blend_controllers = pImp->GetPropertyBool(AI_CONFIG_IMPORT_MDL_HL1_READ_BLEND_CONTROLLERS, true);
  112. mHL1ImportSettings.read_sequence_transitions = pImp->GetPropertyBool(AI_CONFIG_IMPORT_MDL_HL1_READ_SEQUENCE_TRANSITIONS, true);
  113. }
  114. mHL1ImportSettings.read_attachments = pImp->GetPropertyBool(AI_CONFIG_IMPORT_MDL_HL1_READ_ATTACHMENTS, true);
  115. mHL1ImportSettings.read_bone_controllers = pImp->GetPropertyBool(AI_CONFIG_IMPORT_MDL_HL1_READ_BONE_CONTROLLERS, true);
  116. mHL1ImportSettings.read_hitboxes = pImp->GetPropertyBool(AI_CONFIG_IMPORT_MDL_HL1_READ_HITBOXES, true);
  117. mHL1ImportSettings.read_misc_global_info = pImp->GetPropertyBool(AI_CONFIG_IMPORT_MDL_HL1_READ_MISC_GLOBAL_INFO, true);
  118. mHL1ImportSettings.transform_coord_system = pImp->GetPropertyBool(AI_CONFIG_IMPORT_MDL_HL1_TRANSFORM_COORD_SYSTEM);
  119. }
  120. // ------------------------------------------------------------------------------------------------
  121. // Get a list of all supported extensions
  122. const aiImporterDesc *MDLImporter::GetInfo() const {
  123. return &desc;
  124. }
  125. // ------------------------------------------------------------------------------------------------
  126. static void transformCoordinateSystem(const aiScene *pScene) {
  127. if (pScene == nullptr) {
  128. return;
  129. }
  130. pScene->mRootNode->mTransformation = aiMatrix4x4(
  131. 0.f, -1.f, 0.f, 0.f,
  132. 0.f, 0.f, 1.f, 0.f,
  133. -1.f, 0.f, 0.f, 0.f,
  134. 0.f, 0.f, 0.f, 1.f
  135. );
  136. }
  137. // ------------------------------------------------------------------------------------------------
  138. // Imports the given file into the given scene structure.
  139. void MDLImporter::InternReadFile(const std::string &pFile,
  140. aiScene *_pScene, IOSystem *pIOHandler) {
  141. pScene = _pScene;
  142. mIOHandler = pIOHandler;
  143. std::unique_ptr<IOStream> file(pIOHandler->Open(pFile));
  144. // Check whether we can read from the file
  145. if (file == nullptr) {
  146. throw DeadlyImportError("Failed to open MDL file ", pFile, ".");
  147. }
  148. // This should work for all other types of MDL files, too ...
  149. // the HL1 sequence group header is one of the smallest, afaik
  150. iFileSize = (unsigned int)file->FileSize();
  151. if (iFileSize < sizeof(MDL::HalfLife::SequenceHeader_HL1)) {
  152. throw DeadlyImportError("MDL File is too small.");
  153. }
  154. // delete the file buffer and cleanup.
  155. auto DeleteBufferAndCleanup = [&]() {
  156. if (mBuffer) {
  157. delete[] mBuffer;
  158. mBuffer = nullptr;
  159. }
  160. AI_DEBUG_INVALIDATE_PTR(mIOHandler);
  161. AI_DEBUG_INVALIDATE_PTR(pScene);
  162. };
  163. try {
  164. // Allocate storage and copy the contents of the file to a memory buffer
  165. mBuffer = new unsigned char[iFileSize + 1];
  166. file->Read((void *)mBuffer, 1, iFileSize);
  167. // Append a binary zero to the end of the buffer.
  168. // this is just for safety that string parsing routines
  169. // find the end of the buffer ...
  170. mBuffer[iFileSize] = '\0';
  171. const uint32_t iMagicWord = *((uint32_t *)mBuffer);
  172. // Determine the file subtype and call the appropriate member function
  173. bool is_half_life = false;
  174. // Original Quake1 format
  175. if (AI_MDL_MAGIC_NUMBER_BE == iMagicWord || AI_MDL_MAGIC_NUMBER_LE == iMagicWord) {
  176. ASSIMP_LOG_DEBUG("MDL subtype: Quake 1, magic word is IDPO");
  177. iGSFileVersion = 0;
  178. InternReadFile_Quake1();
  179. }
  180. // GameStudio A<old> MDL2 format - used by some test models that come with 3DGS
  181. else if (AI_MDL_MAGIC_NUMBER_BE_GS3 == iMagicWord || AI_MDL_MAGIC_NUMBER_LE_GS3 == iMagicWord) {
  182. ASSIMP_LOG_DEBUG("MDL subtype: 3D GameStudio A2, magic word is MDL2");
  183. iGSFileVersion = 2;
  184. InternReadFile_Quake1();
  185. }
  186. // GameStudio A4 MDL3 format
  187. else if (AI_MDL_MAGIC_NUMBER_BE_GS4 == iMagicWord || AI_MDL_MAGIC_NUMBER_LE_GS4 == iMagicWord) {
  188. ASSIMP_LOG_DEBUG("MDL subtype: 3D GameStudio A4, magic word is MDL3");
  189. iGSFileVersion = 3;
  190. InternReadFile_3DGS_MDL345();
  191. }
  192. // GameStudio A5+ MDL4 format
  193. else if (AI_MDL_MAGIC_NUMBER_BE_GS5a == iMagicWord || AI_MDL_MAGIC_NUMBER_LE_GS5a == iMagicWord) {
  194. ASSIMP_LOG_DEBUG("MDL subtype: 3D GameStudio A4, magic word is MDL4");
  195. iGSFileVersion = 4;
  196. InternReadFile_3DGS_MDL345();
  197. }
  198. // GameStudio A5+ MDL5 format
  199. else if (AI_MDL_MAGIC_NUMBER_BE_GS5b == iMagicWord || AI_MDL_MAGIC_NUMBER_LE_GS5b == iMagicWord) {
  200. ASSIMP_LOG_DEBUG("MDL subtype: 3D GameStudio A5, magic word is MDL5");
  201. iGSFileVersion = 5;
  202. InternReadFile_3DGS_MDL345();
  203. }
  204. // GameStudio A7 MDL7 format
  205. else if (AI_MDL_MAGIC_NUMBER_BE_GS7 == iMagicWord || AI_MDL_MAGIC_NUMBER_LE_GS7 == iMagicWord) {
  206. ASSIMP_LOG_DEBUG("MDL subtype: 3D GameStudio A7, magic word is MDL7");
  207. iGSFileVersion = 7;
  208. InternReadFile_3DGS_MDL7();
  209. }
  210. // IDST/IDSQ Format (CS:S/HL^2, etc ...)
  211. else if (AI_MDL_MAGIC_NUMBER_BE_HL2a == iMagicWord || AI_MDL_MAGIC_NUMBER_LE_HL2a == iMagicWord ||
  212. AI_MDL_MAGIC_NUMBER_BE_HL2b == iMagicWord || AI_MDL_MAGIC_NUMBER_LE_HL2b == iMagicWord) {
  213. iGSFileVersion = 0;
  214. is_half_life = true;
  215. HalfLife::HalfLifeMDLBaseHeader *pHeader = (HalfLife::HalfLifeMDLBaseHeader *)mBuffer;
  216. if (pHeader->version == AI_MDL_HL1_VERSION) {
  217. ASSIMP_LOG_DEBUG("MDL subtype: Half-Life 1/Goldsrc Engine, magic word is IDST/IDSQ");
  218. InternReadFile_HL1(pFile, iMagicWord);
  219. } else {
  220. ASSIMP_LOG_DEBUG("MDL subtype: Source(tm) Engine, magic word is IDST/IDSQ");
  221. InternReadFile_HL2();
  222. }
  223. } else {
  224. // print the magic word to the log file
  225. throw DeadlyImportError("Unknown MDL subformat ", pFile,
  226. ". Magic word (", ai_str_toprintable((const char *)&iMagicWord, sizeof(iMagicWord)), ") is not known");
  227. }
  228. if (is_half_life && mHL1ImportSettings.transform_coord_system) {
  229. // Now rotate the whole scene 90 degrees around the z and x axes to convert to internal coordinate system
  230. transformCoordinateSystem(pScene);
  231. } else {
  232. // Now rotate the whole scene 90 degrees around the x axis to convert to internal coordinate system
  233. pScene->mRootNode->mTransformation = aiMatrix4x4(
  234. 1.f, 0.f, 0.f, 0.f,
  235. 0.f, 0.f, 1.f, 0.f,
  236. 0.f, -1.f, 0.f, 0.f,
  237. 0.f, 0.f, 0.f, 1.f);
  238. }
  239. DeleteBufferAndCleanup();
  240. } catch (...) {
  241. DeleteBufferAndCleanup();
  242. throw;
  243. }
  244. }
  245. // ------------------------------------------------------------------------------------------------
  246. // Check whether we're still inside the valid file range
  247. bool MDLImporter::IsPosValid(const void *szPos) const {
  248. return szPos && (const unsigned char *)szPos <= this->mBuffer + this->iFileSize && szPos >= this->mBuffer;
  249. }
  250. // ------------------------------------------------------------------------------------------------
  251. // Check whether we're still inside the valid file range
  252. void MDLImporter::SizeCheck(const void *szPos) {
  253. if (!IsPosValid(szPos)) {
  254. throw DeadlyImportError("Invalid MDL file. The file is too small "
  255. "or contains invalid data.");
  256. }
  257. }
  258. // ------------------------------------------------------------------------------------------------
  259. // Just for debugging purposes
  260. void MDLImporter::SizeCheck(const void *szPos, const char *szFile, unsigned int iLine) {
  261. ai_assert(nullptr != szFile);
  262. if (!IsPosValid(szPos)) {
  263. // remove a directory if there is one
  264. const char *szFilePtr = ::strrchr(szFile, '\\');
  265. if (!szFilePtr) {
  266. szFilePtr = ::strrchr(szFile, '/');
  267. if (nullptr == szFilePtr) {
  268. szFilePtr = szFile;
  269. }
  270. }
  271. if (szFilePtr) {
  272. ++szFilePtr;
  273. }
  274. char szBuffer[1024];
  275. ::snprintf(szBuffer, sizeof(szBuffer), "Invalid MDL file. The file is too small "
  276. "or contains invalid data (File: %s Line: %u)",
  277. szFilePtr, iLine);
  278. throw DeadlyImportError(szBuffer);
  279. }
  280. }
  281. // ------------------------------------------------------------------------------------------------
  282. // Validate a quake file header
  283. void MDLImporter::ValidateHeader_Quake1(const MDL::Header *pcHeader) {
  284. // some values may not be nullptr
  285. if (pcHeader->num_frames <= 0)
  286. throw DeadlyImportError("[Quake 1 MDL] There are no frames in the file");
  287. if (pcHeader->num_verts <= 0)
  288. throw DeadlyImportError("[Quake 1 MDL] There are no vertices in the file");
  289. if (pcHeader->num_tris <= 0)
  290. throw DeadlyImportError("[Quake 1 MDL] There are no triangles in the file");
  291. // check whether the maxima are exceeded ...however, this applies for Quake 1 MDLs only
  292. if (!this->iGSFileVersion) {
  293. if (pcHeader->num_verts > AI_MDL_MAX_VERTS)
  294. ASSIMP_LOG_WARN("Quake 1 MDL model has more than AI_MDL_MAX_VERTS vertices");
  295. if (pcHeader->num_tris > AI_MDL_MAX_TRIANGLES)
  296. ASSIMP_LOG_WARN("Quake 1 MDL model has more than AI_MDL_MAX_TRIANGLES triangles");
  297. if (pcHeader->num_frames > AI_MDL_MAX_FRAMES)
  298. ASSIMP_LOG_WARN("Quake 1 MDL model has more than AI_MDL_MAX_FRAMES frames");
  299. // (this does not apply for 3DGS MDLs)
  300. if (!this->iGSFileVersion && pcHeader->version != AI_MDL_VERSION)
  301. ASSIMP_LOG_WARN("Quake 1 MDL model has an unknown version: AI_MDL_VERSION (=6) is "
  302. "the expected file format version");
  303. if (pcHeader->num_skins && (!pcHeader->skinwidth || !pcHeader->skinheight))
  304. ASSIMP_LOG_WARN("Skin width or height are 0");
  305. }
  306. }
  307. #ifdef AI_BUILD_BIG_ENDIAN
  308. // ------------------------------------------------------------------------------------------------
  309. void FlipQuakeHeader(BE_NCONST MDL::Header *pcHeader) {
  310. AI_SWAP4(pcHeader->ident);
  311. AI_SWAP4(pcHeader->version);
  312. AI_SWAP4(pcHeader->boundingradius);
  313. AI_SWAP4(pcHeader->flags);
  314. AI_SWAP4(pcHeader->num_frames);
  315. AI_SWAP4(pcHeader->num_skins);
  316. AI_SWAP4(pcHeader->num_tris);
  317. AI_SWAP4(pcHeader->num_verts);
  318. for (unsigned int i = 0; i < 3; ++i) {
  319. AI_SWAP4(pcHeader->scale[i]);
  320. AI_SWAP4(pcHeader->translate[i]);
  321. }
  322. AI_SWAP4(pcHeader->size);
  323. AI_SWAP4(pcHeader->skinheight);
  324. AI_SWAP4(pcHeader->skinwidth);
  325. AI_SWAP4(pcHeader->synctype);
  326. }
  327. #endif
  328. // ------------------------------------------------------------------------------------------------
  329. // Read a Quake 1 file
  330. void MDLImporter::InternReadFile_Quake1() {
  331. ai_assert(nullptr != pScene);
  332. BE_NCONST MDL::Header *pcHeader = (BE_NCONST MDL::Header *)this->mBuffer;
  333. #ifdef AI_BUILD_BIG_ENDIAN
  334. FlipQuakeHeader(pcHeader);
  335. #endif
  336. ValidateHeader_Quake1(pcHeader);
  337. // current cursor position in the file
  338. const unsigned char *szCurrent = (const unsigned char *)(pcHeader + 1);
  339. // need to read all textures
  340. for (unsigned int i = 0; i < (unsigned int)pcHeader->num_skins; ++i) {
  341. union {
  342. BE_NCONST MDL::Skin *pcSkin;
  343. BE_NCONST MDL::GroupSkin *pcGroupSkin;
  344. };
  345. if (szCurrent + sizeof(MDL::Skin) > this->mBuffer + this->iFileSize) {
  346. throw DeadlyImportError("[Quake 1 MDL] Unexpected EOF");
  347. }
  348. pcSkin = (BE_NCONST MDL::Skin *)szCurrent;
  349. AI_SWAP4(pcSkin->group);
  350. // Quake 1 group-skins
  351. if (1 == pcSkin->group) {
  352. AI_SWAP4(pcGroupSkin->nb);
  353. // need to skip multiple images
  354. const unsigned int iNumImages = (unsigned int)pcGroupSkin->nb;
  355. szCurrent += sizeof(uint32_t) * 2;
  356. if (0 != iNumImages) {
  357. if (!i) {
  358. // however, create only one output image (the first)
  359. this->CreateTextureARGB8_3DGS_MDL3(szCurrent + iNumImages * sizeof(float));
  360. }
  361. // go to the end of the skin section / the beginning of the next skin
  362. bool overflow = false;
  363. if (pcHeader->skinwidth != 0 && pcHeader->skinheight != 0) {
  364. if ((pcHeader->skinheight > INT_MAX / pcHeader->skinwidth) || (pcHeader->skinwidth > INT_MAX / pcHeader->skinheight)){
  365. overflow = true;
  366. }
  367. if (!overflow) {
  368. szCurrent += pcHeader->skinheight * pcHeader->skinwidth +sizeof(float) * iNumImages;
  369. }
  370. }
  371. }
  372. } else {
  373. szCurrent += sizeof(uint32_t);
  374. unsigned int iSkip = i ? UINT_MAX : 0;
  375. CreateTexture_3DGS_MDL4(szCurrent, pcSkin->group, &iSkip);
  376. szCurrent += iSkip;
  377. }
  378. }
  379. // get a pointer to the texture coordinates
  380. BE_NCONST MDL::TexCoord *pcTexCoords = (BE_NCONST MDL::TexCoord *)szCurrent;
  381. szCurrent += sizeof(MDL::TexCoord) * pcHeader->num_verts;
  382. // get a pointer to the triangles
  383. BE_NCONST MDL::Triangle *pcTriangles = (BE_NCONST MDL::Triangle *)szCurrent;
  384. szCurrent += sizeof(MDL::Triangle) * pcHeader->num_tris;
  385. VALIDATE_FILE_SIZE(szCurrent);
  386. // now get a pointer to the first frame in the file
  387. BE_NCONST MDL::Frame *pcFrames = (BE_NCONST MDL::Frame *)szCurrent;
  388. MDL::SimpleFrame *pcFirstFrame;
  389. if (0 == pcFrames->type) {
  390. // get address of single frame
  391. pcFirstFrame = (MDL::SimpleFrame *)&pcFrames->frame;
  392. } else {
  393. // get the first frame in the group
  394. BE_NCONST MDL::GroupFrame *pcFrames2 = (BE_NCONST MDL::GroupFrame *)szCurrent;
  395. pcFirstFrame = (MDL::SimpleFrame *)( szCurrent + sizeof(MDL::GroupFrame::type) + sizeof(MDL::GroupFrame::numframes)
  396. + sizeof(MDL::GroupFrame::min) + sizeof(MDL::GroupFrame::max) + sizeof(*MDL::GroupFrame::times) * pcFrames2->numframes );
  397. }
  398. BE_NCONST MDL::Vertex *pcVertices = (BE_NCONST MDL::Vertex *)((pcFirstFrame->name) + sizeof(pcFirstFrame->name));
  399. VALIDATE_FILE_SIZE((const unsigned char *)(pcVertices + pcHeader->num_verts));
  400. #ifdef AI_BUILD_BIG_ENDIAN
  401. for (int i = 0; i < pcHeader->num_verts; ++i) {
  402. AI_SWAP4(pcTexCoords[i].onseam);
  403. AI_SWAP4(pcTexCoords[i].s);
  404. AI_SWAP4(pcTexCoords[i].t);
  405. }
  406. for (int i = 0; i < pcHeader->num_tris; ++i) {
  407. AI_SWAP4(pcTriangles[i].facesfront);
  408. AI_SWAP4(pcTriangles[i].vertex[0]);
  409. AI_SWAP4(pcTriangles[i].vertex[1]);
  410. AI_SWAP4(pcTriangles[i].vertex[2]);
  411. }
  412. #endif
  413. // setup materials
  414. SetupMaterialProperties_3DGS_MDL5_Quake1();
  415. // allocate enough storage to hold all vertices and triangles
  416. aiMesh *pcMesh = new aiMesh();
  417. pcMesh->mPrimitiveTypes = aiPrimitiveType_TRIANGLE;
  418. pcMesh->mNumVertices = pcHeader->num_tris * 3;
  419. pcMesh->mNumFaces = pcHeader->num_tris;
  420. pcMesh->mVertices = new aiVector3D[pcMesh->mNumVertices];
  421. pcMesh->mTextureCoords[0] = new aiVector3D[pcMesh->mNumVertices];
  422. pcMesh->mFaces = new aiFace[pcMesh->mNumFaces];
  423. pcMesh->mNormals = new aiVector3D[pcMesh->mNumVertices];
  424. pcMesh->mNumUVComponents[0] = 2;
  425. // there won't be more than one mesh inside the file
  426. pScene->mRootNode = new aiNode();
  427. pScene->mRootNode->mNumMeshes = 1;
  428. pScene->mRootNode->mMeshes = new unsigned int[1];
  429. pScene->mRootNode->mMeshes[0] = 0;
  430. pScene->mNumMeshes = 1;
  431. pScene->mMeshes = new aiMesh *[1];
  432. pScene->mMeshes[0] = pcMesh;
  433. // now iterate through all triangles
  434. unsigned int iCurrent = 0;
  435. for (unsigned int i = 0; i < (unsigned int)pcHeader->num_tris; ++i) {
  436. pcMesh->mFaces[i].mIndices = new unsigned int[3];
  437. pcMesh->mFaces[i].mNumIndices = 3;
  438. unsigned int iTemp = iCurrent;
  439. for (unsigned int c = 0; c < 3; ++c, ++iCurrent) {
  440. pcMesh->mFaces[i].mIndices[c] = iCurrent;
  441. // read vertices
  442. unsigned int iIndex = pcTriangles->vertex[c];
  443. if (iIndex >= (unsigned int)pcHeader->num_verts) {
  444. iIndex = pcHeader->num_verts - 1;
  445. ASSIMP_LOG_WARN("Index overflow in Q1-MDL vertex list.");
  446. }
  447. aiVector3D &vec = pcMesh->mVertices[iCurrent];
  448. vec.x = (float)pcVertices[iIndex].v[0] * pcHeader->scale[0];
  449. vec.x += pcHeader->translate[0];
  450. vec.y = (float)pcVertices[iIndex].v[1] * pcHeader->scale[1];
  451. vec.y += pcHeader->translate[1];
  452. //vec.y *= -1.0f;
  453. vec.z = (float)pcVertices[iIndex].v[2] * pcHeader->scale[2];
  454. vec.z += pcHeader->translate[2];
  455. // read the normal vector from the precalculated normal table
  456. MD2::LookupNormalIndex(pcVertices[iIndex].normalIndex, pcMesh->mNormals[iCurrent]);
  457. //pcMesh->mNormals[iCurrent].y *= -1.0f;
  458. // read texture coordinates
  459. float s = (float)pcTexCoords[iIndex].s;
  460. float t = (float)pcTexCoords[iIndex].t;
  461. // translate texture coordinates
  462. if (0 == pcTriangles->facesfront && 0 != pcTexCoords[iIndex].onseam) {
  463. s += pcHeader->skinwidth * 0.5f;
  464. }
  465. // Scale s and t to range from 0.0 to 1.0
  466. pcMesh->mTextureCoords[0][iCurrent].x = (s + 0.5f) / pcHeader->skinwidth;
  467. pcMesh->mTextureCoords[0][iCurrent].y = 1.0f - (t + 0.5f) / pcHeader->skinheight;
  468. }
  469. pcMesh->mFaces[i].mIndices[0] = iTemp + 2;
  470. pcMesh->mFaces[i].mIndices[1] = iTemp + 1;
  471. pcMesh->mFaces[i].mIndices[2] = iTemp + 0;
  472. pcTriangles++;
  473. }
  474. return;
  475. }
  476. // ------------------------------------------------------------------------------------------------
  477. // Setup material properties for Quake and older GameStudio files
  478. void MDLImporter::SetupMaterialProperties_3DGS_MDL5_Quake1() {
  479. const MDL::Header *const pcHeader = (const MDL::Header *)this->mBuffer;
  480. // allocate ONE material
  481. pScene->mMaterials = new aiMaterial *[1];
  482. pScene->mMaterials[0] = new aiMaterial();
  483. pScene->mNumMaterials = 1;
  484. // setup the material's properties
  485. const int iMode = (int)aiShadingMode_Gouraud;
  486. aiMaterial *const pcHelper = (aiMaterial *)pScene->mMaterials[0];
  487. pcHelper->AddProperty<int>(&iMode, 1, AI_MATKEY_SHADING_MODEL);
  488. aiColor4D clr;
  489. if (0 != pcHeader->num_skins && pScene->mNumTextures) {
  490. // can we replace the texture with a single color?
  491. clr = this->ReplaceTextureWithColor(pScene->mTextures[0]);
  492. if (is_not_qnan(clr.r)) {
  493. delete pScene->mTextures[0];
  494. delete[] pScene->mTextures;
  495. pScene->mTextures = nullptr;
  496. pScene->mNumTextures = 0;
  497. } else {
  498. clr.b = clr.a = clr.g = clr.r = 1.0f;
  499. aiString szString;
  500. ::memcpy(szString.data, AI_MAKE_EMBEDDED_TEXNAME(0), 3);
  501. szString.length = 2;
  502. pcHelper->AddProperty(&szString, AI_MATKEY_TEXTURE_DIFFUSE(0));
  503. }
  504. }
  505. pcHelper->AddProperty<aiColor4D>(&clr, 1, AI_MATKEY_COLOR_DIFFUSE);
  506. pcHelper->AddProperty<aiColor4D>(&clr, 1, AI_MATKEY_COLOR_SPECULAR);
  507. clr.r *= 0.05f;
  508. clr.g *= 0.05f;
  509. clr.b *= 0.05f;
  510. clr.a = 1.0f;
  511. pcHelper->AddProperty<aiColor4D>(&clr, 1, AI_MATKEY_COLOR_AMBIENT);
  512. }
  513. // ------------------------------------------------------------------------------------------------
  514. // Read a MDL 3,4,5 file
  515. void MDLImporter::InternReadFile_3DGS_MDL345() {
  516. ai_assert(nullptr != pScene);
  517. if (pScene == nullptr) {
  518. throw DeadlyImportError("INvalid scene pointer detected.");
  519. }
  520. // the header of MDL 3/4/5 is nearly identical to the original Quake1 header
  521. BE_NCONST MDL::Header *pcHeader = (BE_NCONST MDL::Header *)this->mBuffer;
  522. #ifdef AI_BUILD_BIG_ENDIAN
  523. FlipQuakeHeader(pcHeader);
  524. #endif
  525. ValidateHeader_Quake1(pcHeader);
  526. if (pcHeader->synctype < 0) {
  527. throw DeadlyImportError("Invalid synctype value in MDL header; possible corrupt file.");
  528. }
  529. // current cursor position in the file
  530. const unsigned char *szCurrent = (const unsigned char *)(pcHeader + 1);
  531. const unsigned char *szEnd = mBuffer + iFileSize;
  532. // need to read all textures
  533. for (unsigned int i = 0; i < (unsigned int)pcHeader->num_skins; ++i) {
  534. if (szCurrent + sizeof(uint32_t) > szEnd) {
  535. throw DeadlyImportError("Texture data past end of file.");
  536. }
  537. BE_NCONST MDL::Skin *pcSkin = (BE_NCONST MDL::Skin *)szCurrent;
  538. AI_SWAP4(pcSkin->group);
  539. // create one output image
  540. unsigned int iSkip = i ? UINT_MAX : 0;
  541. if (5 <= iGSFileVersion) {
  542. // MDL5 format could contain MIPmaps
  543. CreateTexture_3DGS_MDL5((unsigned char *)pcSkin + sizeof(uint32_t),
  544. pcSkin->group, &iSkip);
  545. } else {
  546. CreateTexture_3DGS_MDL4((unsigned char *)pcSkin + sizeof(uint32_t),
  547. pcSkin->group, &iSkip);
  548. }
  549. // need to skip one image
  550. szCurrent += iSkip + sizeof(uint32_t);
  551. }
  552. // get a pointer to the texture coordinates
  553. BE_NCONST MDL::TexCoord_MDL3 *pcTexCoords = (BE_NCONST MDL::TexCoord_MDL3 *)szCurrent;
  554. szCurrent += sizeof(MDL::TexCoord_MDL3) * pcHeader->synctype;
  555. // NOTE: for MDLn formats "synctype" corresponds to the number of UV coords
  556. // get a pointer to the triangles
  557. BE_NCONST MDL::Triangle_MDL3 *pcTriangles = (BE_NCONST MDL::Triangle_MDL3 *)szCurrent;
  558. szCurrent += sizeof(MDL::Triangle_MDL3) * pcHeader->num_tris;
  559. #ifdef AI_BUILD_BIG_ENDIAN
  560. for (int i = 0; i < pcHeader->synctype; ++i) {
  561. AI_SWAP2(pcTexCoords[i].u);
  562. AI_SWAP2(pcTexCoords[i].v);
  563. }
  564. for (int i = 0; i < pcHeader->num_tris; ++i) {
  565. AI_SWAP2(pcTriangles[i].index_xyz[0]);
  566. AI_SWAP2(pcTriangles[i].index_xyz[1]);
  567. AI_SWAP2(pcTriangles[i].index_xyz[2]);
  568. AI_SWAP2(pcTriangles[i].index_uv[0]);
  569. AI_SWAP2(pcTriangles[i].index_uv[1]);
  570. AI_SWAP2(pcTriangles[i].index_uv[2]);
  571. }
  572. #endif
  573. VALIDATE_FILE_SIZE(szCurrent);
  574. // setup materials
  575. SetupMaterialProperties_3DGS_MDL5_Quake1();
  576. // allocate enough storage to hold all vertices and triangles
  577. aiMesh *pcMesh = new aiMesh();
  578. pcMesh->mPrimitiveTypes = aiPrimitiveType_TRIANGLE;
  579. pcMesh->mNumVertices = pcHeader->num_tris * 3;
  580. pcMesh->mNumFaces = pcHeader->num_tris;
  581. pcMesh->mFaces = new aiFace[pcMesh->mNumFaces];
  582. // there won't be more than one mesh inside the file
  583. pScene->mRootNode = new aiNode();
  584. pScene->mRootNode->mNumMeshes = 1;
  585. pScene->mRootNode->mMeshes = new unsigned int[1];
  586. pScene->mRootNode->mMeshes[0] = 0;
  587. pScene->mNumMeshes = 1;
  588. pScene->mMeshes = new aiMesh *[1];
  589. pScene->mMeshes[0] = pcMesh;
  590. // allocate output storage
  591. pcMesh->mNumVertices = (unsigned int)pcHeader->num_tris * 3;
  592. pcMesh->mVertices = new aiVector3D[pcMesh->mNumVertices];
  593. pcMesh->mNormals = new aiVector3D[pcMesh->mNumVertices];
  594. if (pcHeader->synctype) {
  595. pcMesh->mTextureCoords[0] = new aiVector3D[pcMesh->mNumVertices];
  596. pcMesh->mNumUVComponents[0] = 2;
  597. }
  598. // now get a pointer to the first frame in the file
  599. BE_NCONST MDL::Frame *pcFrames = (BE_NCONST MDL::Frame *)szCurrent;
  600. AI_SWAP4(pcFrames->type);
  601. // byte packed vertices
  602. // FIXME: these two snippets below are almost identical ... join them?
  603. /////////////////////////////////////////////////////////////////////////////////////
  604. if (0 == pcFrames->type || 3 >= this->iGSFileVersion) {
  605. const MDL::SimpleFrame *pcFirstFrame = (const MDL::SimpleFrame *)(szCurrent + sizeof(uint32_t));
  606. const MDL::Vertex *pcVertices = (const MDL::Vertex *)((pcFirstFrame->name) + sizeof(pcFirstFrame->name));
  607. VALIDATE_FILE_SIZE(pcVertices + pcHeader->num_verts);
  608. // now iterate through all triangles
  609. unsigned int iCurrent = 0;
  610. for (unsigned int i = 0; i < (unsigned int)pcHeader->num_tris; ++i) {
  611. pcMesh->mFaces[i].mIndices = new unsigned int[3];
  612. pcMesh->mFaces[i].mNumIndices = 3;
  613. unsigned int iTemp = iCurrent;
  614. for (unsigned int c = 0; c < 3; ++c, ++iCurrent) {
  615. // read vertices
  616. unsigned int iIndex = pcTriangles->index_xyz[c];
  617. if (iIndex >= (unsigned int)pcHeader->num_verts) {
  618. iIndex = pcHeader->num_verts - 1;
  619. ASSIMP_LOG_WARN("Index overflow in MDLn vertex list");
  620. }
  621. aiVector3D &vec = pcMesh->mVertices[iCurrent];
  622. vec.x = (float)pcVertices[iIndex].v[0] * pcHeader->scale[0];
  623. vec.x += pcHeader->translate[0];
  624. vec.y = (float)pcVertices[iIndex].v[1] * pcHeader->scale[1];
  625. vec.y += pcHeader->translate[1];
  626. // vec.y *= -1.0f;
  627. vec.z = (float)pcVertices[iIndex].v[2] * pcHeader->scale[2];
  628. vec.z += pcHeader->translate[2];
  629. // read the normal vector from the precalculated normal table
  630. MD2::LookupNormalIndex(pcVertices[iIndex].normalIndex, pcMesh->mNormals[iCurrent]);
  631. // pcMesh->mNormals[iCurrent].y *= -1.0f;
  632. // read texture coordinates
  633. if (pcHeader->synctype) {
  634. ImportUVCoordinate_3DGS_MDL345(pcMesh->mTextureCoords[0][iCurrent],
  635. pcTexCoords, pcTriangles->index_uv[c]);
  636. }
  637. }
  638. pcMesh->mFaces[i].mIndices[0] = iTemp + 2;
  639. pcMesh->mFaces[i].mIndices[1] = iTemp + 1;
  640. pcMesh->mFaces[i].mIndices[2] = iTemp + 0;
  641. pcTriangles++;
  642. }
  643. }
  644. // short packed vertices
  645. /////////////////////////////////////////////////////////////////////////////////////
  646. else {
  647. // now get a pointer to the first frame in the file
  648. const MDL::SimpleFrame_MDLn_SP *pcFirstFrame = (const MDL::SimpleFrame_MDLn_SP *)(szCurrent + sizeof(uint32_t));
  649. // get a pointer to the vertices
  650. const MDL::Vertex_MDL4 *pcVertices = (const MDL::Vertex_MDL4 *)((pcFirstFrame->name) +
  651. sizeof(pcFirstFrame->name));
  652. VALIDATE_FILE_SIZE(pcVertices + pcHeader->num_verts);
  653. // now iterate through all triangles
  654. unsigned int iCurrent = 0;
  655. for (unsigned int i = 0; i < (unsigned int)pcHeader->num_tris; ++i) {
  656. pcMesh->mFaces[i].mIndices = new unsigned int[3];
  657. pcMesh->mFaces[i].mNumIndices = 3;
  658. unsigned int iTemp = iCurrent;
  659. for (unsigned int c = 0; c < 3; ++c, ++iCurrent) {
  660. // read vertices
  661. unsigned int iIndex = pcTriangles->index_xyz[c];
  662. if (iIndex >= (unsigned int)pcHeader->num_verts) {
  663. iIndex = pcHeader->num_verts - 1;
  664. ASSIMP_LOG_WARN("Index overflow in MDLn vertex list");
  665. }
  666. aiVector3D &vec = pcMesh->mVertices[iCurrent];
  667. vec.x = (float)pcVertices[iIndex].v[0] * pcHeader->scale[0];
  668. vec.x += pcHeader->translate[0];
  669. vec.y = (float)pcVertices[iIndex].v[1] * pcHeader->scale[1];
  670. vec.y += pcHeader->translate[1];
  671. // vec.y *= -1.0f;
  672. vec.z = (float)pcVertices[iIndex].v[2] * pcHeader->scale[2];
  673. vec.z += pcHeader->translate[2];
  674. // read the normal vector from the precalculated normal table
  675. MD2::LookupNormalIndex(pcVertices[iIndex].normalIndex, pcMesh->mNormals[iCurrent]);
  676. // pcMesh->mNormals[iCurrent].y *= -1.0f;
  677. // read texture coordinates
  678. if (pcHeader->synctype) {
  679. ImportUVCoordinate_3DGS_MDL345(pcMesh->mTextureCoords[0][iCurrent],
  680. pcTexCoords, pcTriangles->index_uv[c]);
  681. }
  682. }
  683. pcMesh->mFaces[i].mIndices[0] = iTemp + 2;
  684. pcMesh->mFaces[i].mIndices[1] = iTemp + 1;
  685. pcMesh->mFaces[i].mIndices[2] = iTemp + 0;
  686. pcTriangles++;
  687. }
  688. }
  689. // For MDL5 we will need to build valid texture coordinates
  690. // basing upon the file loaded (only support one file as skin)
  691. if (0x5 == iGSFileVersion)
  692. CalculateUVCoordinates_MDL5();
  693. return;
  694. }
  695. // ------------------------------------------------------------------------------------------------
  696. // Get a single UV coordinate for Quake and older GameStudio files
  697. void MDLImporter::ImportUVCoordinate_3DGS_MDL345(
  698. aiVector3D &vOut,
  699. const MDL::TexCoord_MDL3 *pcSrc,
  700. unsigned int iIndex) {
  701. ai_assert(nullptr != pcSrc);
  702. const MDL::Header *const pcHeader = (const MDL::Header *)this->mBuffer;
  703. // validate UV indices
  704. if (iIndex >= (unsigned int)pcHeader->synctype) {
  705. iIndex = pcHeader->synctype - 1;
  706. ASSIMP_LOG_WARN("Index overflow in MDLn UV coord list");
  707. }
  708. float s = (float)pcSrc[iIndex].u;
  709. float t = (float)pcSrc[iIndex].v;
  710. // Scale s and t to range from 0.0 to 1.0
  711. if (0x5 != iGSFileVersion) {
  712. s = (s + 0.5f) / pcHeader->skinwidth;
  713. t = 1.0f - (t + 0.5f) / pcHeader->skinheight;
  714. }
  715. vOut.x = s;
  716. vOut.y = t;
  717. vOut.z = 0.0f;
  718. }
  719. // ------------------------------------------------------------------------------------------------
  720. // Compute UV coordinates for a MDL5 file
  721. void MDLImporter::CalculateUVCoordinates_MDL5() {
  722. const MDL::Header *const pcHeader = (const MDL::Header *)this->mBuffer;
  723. if (pcHeader->num_skins && this->pScene->mNumTextures) {
  724. const aiTexture *pcTex = this->pScene->mTextures[0];
  725. // if the file is loaded in DDS format: get the size of the
  726. // texture from the header of the DDS file
  727. // skip three DWORDs and read first height, then the width
  728. unsigned int iWidth, iHeight;
  729. if (!pcTex->mHeight) {
  730. const uint32_t *piPtr = (uint32_t *)pcTex->pcData;
  731. piPtr += 3;
  732. iHeight = (unsigned int)*piPtr++;
  733. iWidth = (unsigned int)*piPtr;
  734. if (!iHeight || !iWidth) {
  735. ASSIMP_LOG_WARN("Either the width or the height of the "
  736. "embedded DDS texture is zero. Unable to compute final texture "
  737. "coordinates. The texture coordinates remain in their original "
  738. "0-x/0-y (x,y = texture size) range.");
  739. iWidth = 1;
  740. iHeight = 1;
  741. }
  742. } else {
  743. iWidth = pcTex->mWidth;
  744. iHeight = pcTex->mHeight;
  745. }
  746. if (1 != iWidth || 1 != iHeight) {
  747. const float fWidth = (float)iWidth;
  748. const float fHeight = (float)iHeight;
  749. aiMesh *pcMesh = this->pScene->mMeshes[0];
  750. for (unsigned int i = 0; i < pcMesh->mNumVertices; ++i) {
  751. if (!pcMesh->HasTextureCoords(0)) {
  752. continue;
  753. }
  754. pcMesh->mTextureCoords[0][i].x /= fWidth;
  755. pcMesh->mTextureCoords[0][i].y /= fHeight;
  756. pcMesh->mTextureCoords[0][i].y = 1.0f - pcMesh->mTextureCoords[0][i].y; // DX to OGL
  757. }
  758. }
  759. }
  760. }
  761. // ------------------------------------------------------------------------------------------------
  762. // Validate the header of a MDL7 file
  763. void MDLImporter::ValidateHeader_3DGS_MDL7(const MDL::Header_MDL7 *pcHeader) {
  764. ai_assert(nullptr != pcHeader);
  765. // There are some fixed sizes ...
  766. if (sizeof(MDL::ColorValue_MDL7) != pcHeader->colorvalue_stc_size) {
  767. throw DeadlyImportError(
  768. "[3DGS MDL7] sizeof(MDL::ColorValue_MDL7) != pcHeader->colorvalue_stc_size");
  769. }
  770. if (sizeof(MDL::TexCoord_MDL7) != pcHeader->skinpoint_stc_size) {
  771. throw DeadlyImportError(
  772. "[3DGS MDL7] sizeof(MDL::TexCoord_MDL7) != pcHeader->skinpoint_stc_size");
  773. }
  774. if (sizeof(MDL::Skin_MDL7) != pcHeader->skin_stc_size) {
  775. throw DeadlyImportError(
  776. "sizeof(MDL::Skin_MDL7) != pcHeader->skin_stc_size");
  777. }
  778. // if there are no groups ... how should we load such a file?
  779. if (!pcHeader->groups_num) {
  780. throw DeadlyImportError("[3DGS MDL7] No frames found");
  781. }
  782. }
  783. // ------------------------------------------------------------------------------------------------
  784. // resolve bone animation matrices
  785. void MDLImporter::CalcAbsBoneMatrices_3DGS_MDL7(MDL::IntBone_MDL7 **apcOutBones) {
  786. const MDL::Header_MDL7 *pcHeader = (const MDL::Header_MDL7 *)this->mBuffer;
  787. const MDL::Bone_MDL7 *pcBones = (const MDL::Bone_MDL7 *)(pcHeader + 1);
  788. ai_assert(nullptr != apcOutBones);
  789. // first find the bone that has NO parent, calculate the
  790. // animation matrix for it, then go on and search for the next parent
  791. // index (0) and so on until we can't find a new node.
  792. uint16_t iParent = 0xffff;
  793. uint32_t iIterations = 0;
  794. while (iIterations++ < pcHeader->bones_num) {
  795. for (uint32_t iBone = 0; iBone < pcHeader->bones_num; ++iBone) {
  796. BE_NCONST MDL::Bone_MDL7 *pcBone = _AI_MDL7_ACCESS_PTR(pcBones, iBone,
  797. pcHeader->bone_stc_size, MDL::Bone_MDL7);
  798. AI_SWAP2(pcBone->parent_index);
  799. AI_SWAP4(pcBone->x);
  800. AI_SWAP4(pcBone->y);
  801. AI_SWAP4(pcBone->z);
  802. if (iParent == pcBone->parent_index) {
  803. // MDL7 readme
  804. ////////////////////////////////////////////////////////////////
  805. /*
  806. The animation matrix is then calculated the following way:
  807. vector3 bPos = <absolute bone position>
  808. matrix44 laM; // local animation matrix
  809. sphrvector key_rotate = <bone rotation>
  810. matrix44 m1,m2;
  811. create_trans_matrix(m1, -bPos.x, -bPos.y, -bPos.z);
  812. create_trans_matrix(m2, -bPos.x, -bPos.y, -bPos.z);
  813. create_rotation_matrix(laM,key_rotate);
  814. laM = sm1 * laM;
  815. laM = laM * sm2;
  816. */
  817. /////////////////////////////////////////////////////////////////
  818. MDL::IntBone_MDL7 *const pcOutBone = apcOutBones[iBone];
  819. // store the parent index of the bone
  820. pcOutBone->iParent = pcBone->parent_index;
  821. if (0xffff != iParent) {
  822. const MDL::IntBone_MDL7 *pcParentBone = apcOutBones[iParent];
  823. pcOutBone->mOffsetMatrix.a4 = -pcParentBone->vPosition.x;
  824. pcOutBone->mOffsetMatrix.b4 = -pcParentBone->vPosition.y;
  825. pcOutBone->mOffsetMatrix.c4 = -pcParentBone->vPosition.z;
  826. }
  827. pcOutBone->vPosition.x = pcBone->x;
  828. pcOutBone->vPosition.y = pcBone->y;
  829. pcOutBone->vPosition.z = pcBone->z;
  830. pcOutBone->mOffsetMatrix.a4 -= pcBone->x;
  831. pcOutBone->mOffsetMatrix.b4 -= pcBone->y;
  832. pcOutBone->mOffsetMatrix.c4 -= pcBone->z;
  833. if (AI_MDL7_BONE_STRUCT_SIZE__NAME_IS_NOT_THERE == pcHeader->bone_stc_size) {
  834. // no real name for our poor bone is specified :-(
  835. pcOutBone->mName.length = ai_snprintf(pcOutBone->mName.data, AI_MAXLEN,
  836. "UnnamedBone_%i", iBone);
  837. } else {
  838. // Make sure we won't run over the buffer's end if there is no
  839. // terminal 0 character (however the documentation says there
  840. // should be one)
  841. uint32_t iMaxLen = pcHeader->bone_stc_size - 16;
  842. for (uint32_t qq = 0; qq < iMaxLen; ++qq) {
  843. if (!pcBone->name[qq]) {
  844. iMaxLen = qq;
  845. break;
  846. }
  847. }
  848. // store the name of the bone
  849. pcOutBone->mName.length = static_cast<ai_uint32>(iMaxLen);
  850. ::memcpy(pcOutBone->mName.data, pcBone->name, pcOutBone->mName.length);
  851. pcOutBone->mName.data[pcOutBone->mName.length] = '\0';
  852. }
  853. }
  854. }
  855. ++iParent;
  856. }
  857. }
  858. // ------------------------------------------------------------------------------------------------
  859. // read bones from a MDL7 file
  860. MDL::IntBone_MDL7 **MDLImporter::LoadBones_3DGS_MDL7() {
  861. const MDL::Header_MDL7 *pcHeader = (const MDL::Header_MDL7 *)this->mBuffer;
  862. if (pcHeader->bones_num) {
  863. // validate the size of the bone data structure in the file
  864. if (AI_MDL7_BONE_STRUCT_SIZE__NAME_IS_20_CHARS != pcHeader->bone_stc_size &&
  865. AI_MDL7_BONE_STRUCT_SIZE__NAME_IS_32_CHARS != pcHeader->bone_stc_size &&
  866. AI_MDL7_BONE_STRUCT_SIZE__NAME_IS_NOT_THERE != pcHeader->bone_stc_size) {
  867. ASSIMP_LOG_WARN("Unknown size of bone data structure");
  868. return nullptr;
  869. }
  870. MDL::IntBone_MDL7 **apcBonesOut = new MDL::IntBone_MDL7 *[pcHeader->bones_num];
  871. for (uint32_t crank = 0; crank < pcHeader->bones_num; ++crank)
  872. apcBonesOut[crank] = new MDL::IntBone_MDL7();
  873. // and calculate absolute bone offset matrices ...
  874. CalcAbsBoneMatrices_3DGS_MDL7(apcBonesOut);
  875. return apcBonesOut;
  876. }
  877. return nullptr;
  878. }
  879. // ------------------------------------------------------------------------------------------------
  880. // read faces from a MDL7 file
  881. void MDLImporter::ReadFaces_3DGS_MDL7(const MDL::IntGroupInfo_MDL7 &groupInfo,
  882. MDL::IntGroupData_MDL7 &groupData) {
  883. const MDL::Header_MDL7 *pcHeader = (const MDL::Header_MDL7 *)this->mBuffer;
  884. MDL::Triangle_MDL7 *pcGroupTris = groupInfo.pcGroupTris;
  885. // iterate through all triangles and build valid display lists
  886. unsigned int iOutIndex = 0;
  887. for (unsigned int iTriangle = 0; iTriangle < (unsigned int)groupInfo.pcGroup->numtris; ++iTriangle) {
  888. AI_SWAP2(pcGroupTris->v_index[0]);
  889. AI_SWAP2(pcGroupTris->v_index[1]);
  890. AI_SWAP2(pcGroupTris->v_index[2]);
  891. // iterate through all indices of the current triangle
  892. for (unsigned int c = 0; c < 3; ++c, ++iOutIndex) {
  893. // validate the vertex index
  894. unsigned int iIndex = pcGroupTris->v_index[c];
  895. if (iIndex > (unsigned int)groupInfo.pcGroup->numverts) {
  896. // (we might need to read this section a second time - to process frame vertices correctly)
  897. pcGroupTris->v_index[c] = (uint16_t)(iIndex = groupInfo.pcGroup->numverts - 1);
  898. ASSIMP_LOG_WARN("Index overflow in MDL7 vertex list");
  899. }
  900. // write the output face index
  901. groupData.pcFaces[iTriangle].mIndices[2 - c] = iOutIndex;
  902. aiVector3D &vPosition = groupData.vPositions[iOutIndex];
  903. vPosition.x = _AI_MDL7_ACCESS_VERT(groupInfo.pcGroupVerts, iIndex, pcHeader->mainvertex_stc_size).x;
  904. vPosition.y = _AI_MDL7_ACCESS_VERT(groupInfo.pcGroupVerts, iIndex, pcHeader->mainvertex_stc_size).y;
  905. vPosition.z = _AI_MDL7_ACCESS_VERT(groupInfo.pcGroupVerts, iIndex, pcHeader->mainvertex_stc_size).z;
  906. // if we have bones, save the index
  907. if (!groupData.aiBones.empty()) {
  908. groupData.aiBones[iOutIndex] = _AI_MDL7_ACCESS_VERT(groupInfo.pcGroupVerts,
  909. iIndex, pcHeader->mainvertex_stc_size)
  910. .vertindex;
  911. }
  912. // now read the normal vector
  913. if (AI_MDL7_FRAMEVERTEX030305_STCSIZE <= pcHeader->mainvertex_stc_size) {
  914. // read the full normal vector
  915. aiVector3D &vNormal = groupData.vNormals[iOutIndex];
  916. vNormal.x = _AI_MDL7_ACCESS_VERT(groupInfo.pcGroupVerts, iIndex, pcHeader->mainvertex_stc_size).norm[0];
  917. AI_SWAP4(vNormal.x);
  918. vNormal.y = _AI_MDL7_ACCESS_VERT(groupInfo.pcGroupVerts, iIndex, pcHeader->mainvertex_stc_size).norm[1];
  919. AI_SWAP4(vNormal.y);
  920. vNormal.z = _AI_MDL7_ACCESS_VERT(groupInfo.pcGroupVerts, iIndex, pcHeader->mainvertex_stc_size).norm[2];
  921. AI_SWAP4(vNormal.z);
  922. } else if (AI_MDL7_FRAMEVERTEX120503_STCSIZE <= pcHeader->mainvertex_stc_size) {
  923. // read the normal vector from Quake2's smart table
  924. aiVector3D &vNormal = groupData.vNormals[iOutIndex];
  925. MD2::LookupNormalIndex(_AI_MDL7_ACCESS_VERT(groupInfo.pcGroupVerts, iIndex,
  926. pcHeader->mainvertex_stc_size)
  927. .norm162index,
  928. vNormal);
  929. }
  930. // validate and process the first uv coordinate set
  931. if (pcHeader->triangle_stc_size >= AI_MDL7_TRIANGLE_STD_SIZE_ONE_UV) {
  932. if (groupInfo.pcGroup->num_stpts) {
  933. AI_SWAP2(pcGroupTris->skinsets[0].st_index[0]);
  934. AI_SWAP2(pcGroupTris->skinsets[0].st_index[1]);
  935. AI_SWAP2(pcGroupTris->skinsets[0].st_index[2]);
  936. iIndex = pcGroupTris->skinsets[0].st_index[c];
  937. if (iIndex > (unsigned int)groupInfo.pcGroup->num_stpts) {
  938. iIndex = groupInfo.pcGroup->num_stpts - 1;
  939. ASSIMP_LOG_WARN("Index overflow in MDL7 UV coordinate list (#1)");
  940. }
  941. float u = groupInfo.pcGroupUVs[iIndex].u;
  942. float v = 1.0f - groupInfo.pcGroupUVs[iIndex].v; // DX to OGL
  943. groupData.vTextureCoords1[iOutIndex].x = u;
  944. groupData.vTextureCoords1[iOutIndex].y = v;
  945. }
  946. // assign the material index, but only if it is existing
  947. if (pcHeader->triangle_stc_size >= AI_MDL7_TRIANGLE_STD_SIZE_ONE_UV_WITH_MATINDEX) {
  948. AI_SWAP4(pcGroupTris->skinsets[0].material);
  949. groupData.pcFaces[iTriangle].iMatIndex[0] = pcGroupTris->skinsets[0].material;
  950. }
  951. }
  952. // validate and process the second uv coordinate set
  953. if (pcHeader->triangle_stc_size >= AI_MDL7_TRIANGLE_STD_SIZE_TWO_UV) {
  954. if (groupInfo.pcGroup->num_stpts) {
  955. AI_SWAP2(pcGroupTris->skinsets[1].st_index[0]);
  956. AI_SWAP2(pcGroupTris->skinsets[1].st_index[1]);
  957. AI_SWAP2(pcGroupTris->skinsets[1].st_index[2]);
  958. AI_SWAP4(pcGroupTris->skinsets[1].material);
  959. iIndex = pcGroupTris->skinsets[1].st_index[c];
  960. if (iIndex > (unsigned int)groupInfo.pcGroup->num_stpts) {
  961. iIndex = groupInfo.pcGroup->num_stpts - 1;
  962. ASSIMP_LOG_WARN("Index overflow in MDL7 UV coordinate list (#2)");
  963. }
  964. float u = groupInfo.pcGroupUVs[iIndex].u;
  965. float v = 1.0f - groupInfo.pcGroupUVs[iIndex].v;
  966. groupData.vTextureCoords2[iOutIndex].x = u;
  967. groupData.vTextureCoords2[iOutIndex].y = v; // DX to OGL
  968. // check whether we do really need the second texture
  969. // coordinate set ... wastes memory and loading time
  970. if (0 != iIndex && (u != groupData.vTextureCoords1[iOutIndex].x ||
  971. v != groupData.vTextureCoords1[iOutIndex].y))
  972. groupData.bNeed2UV = true;
  973. // if the material differs, we need a second skin, too
  974. if (pcGroupTris->skinsets[1].material != pcGroupTris->skinsets[0].material)
  975. groupData.bNeed2UV = true;
  976. }
  977. // assign the material index
  978. groupData.pcFaces[iTriangle].iMatIndex[1] = pcGroupTris->skinsets[1].material;
  979. }
  980. }
  981. // get the next triangle in the list
  982. pcGroupTris = (MDL::Triangle_MDL7 *)((const char *)pcGroupTris + pcHeader->triangle_stc_size);
  983. }
  984. }
  985. // ------------------------------------------------------------------------------------------------
  986. // handle frames in a MDL7 file
  987. bool MDLImporter::ProcessFrames_3DGS_MDL7(const MDL::IntGroupInfo_MDL7 &groupInfo,
  988. MDL::IntGroupData_MDL7 &groupData,
  989. MDL::IntSharedData_MDL7 &shared,
  990. const unsigned char *szCurrent,
  991. const unsigned char **szCurrentOut) {
  992. ai_assert(nullptr != szCurrent);
  993. ai_assert(nullptr != szCurrentOut);
  994. const MDL::Header_MDL7 *pcHeader = (const MDL::Header_MDL7 *)mBuffer;
  995. // if we have no bones we can simply skip all frames,
  996. // otherwise we'll need to process them.
  997. // FIX: If we need another frame than the first we must apply frame vertex replacements ...
  998. for (unsigned int iFrame = 0; iFrame < (unsigned int)groupInfo.pcGroup->numframes; ++iFrame) {
  999. MDL::IntFrameInfo_MDL7 frame((BE_NCONST MDL::Frame_MDL7 *)szCurrent, iFrame);
  1000. AI_SWAP4(frame.pcFrame->vertices_count);
  1001. AI_SWAP4(frame.pcFrame->transmatrix_count);
  1002. const unsigned int iAdd = pcHeader->frame_stc_size +
  1003. frame.pcFrame->vertices_count * pcHeader->framevertex_stc_size +
  1004. frame.pcFrame->transmatrix_count * pcHeader->bonetrans_stc_size;
  1005. if (((const char *)szCurrent - (const char *)pcHeader) + iAdd > (unsigned int)pcHeader->data_size) {
  1006. ASSIMP_LOG_WARN("Index overflow in frame area. "
  1007. "Ignoring all frames and all further mesh groups, too.");
  1008. // don't parse more groups if we can't even read one
  1009. // FIXME: sometimes this seems to occur even for valid files ...
  1010. *szCurrentOut = szCurrent;
  1011. return false;
  1012. }
  1013. // our output frame?
  1014. if (configFrameID == iFrame) {
  1015. BE_NCONST MDL::Vertex_MDL7 *pcFrameVertices = (BE_NCONST MDL::Vertex_MDL7 *)(szCurrent + pcHeader->frame_stc_size);
  1016. for (unsigned int qq = 0; qq < frame.pcFrame->vertices_count; ++qq) {
  1017. // I assume this are simple replacements for normal vertices, the bone index serving
  1018. // as the index of the vertex to be replaced.
  1019. uint16_t iIndex = _AI_MDL7_ACCESS(pcFrameVertices, qq, pcHeader->framevertex_stc_size, MDL::Vertex_MDL7).vertindex;
  1020. AI_SWAP2(iIndex);
  1021. if (iIndex >= groupInfo.pcGroup->numverts) {
  1022. ASSIMP_LOG_WARN("Invalid vertex index in frame vertex section");
  1023. continue;
  1024. }
  1025. aiVector3D vPosition, vNormal;
  1026. vPosition.x = _AI_MDL7_ACCESS_VERT(pcFrameVertices, qq, pcHeader->framevertex_stc_size).x;
  1027. AI_SWAP4(vPosition.x);
  1028. vPosition.y = _AI_MDL7_ACCESS_VERT(pcFrameVertices, qq, pcHeader->framevertex_stc_size).y;
  1029. AI_SWAP4(vPosition.y);
  1030. vPosition.z = _AI_MDL7_ACCESS_VERT(pcFrameVertices, qq, pcHeader->framevertex_stc_size).z;
  1031. AI_SWAP4(vPosition.z);
  1032. // now read the normal vector
  1033. if (AI_MDL7_FRAMEVERTEX030305_STCSIZE <= pcHeader->mainvertex_stc_size) {
  1034. // read the full normal vector
  1035. vNormal.x = _AI_MDL7_ACCESS_VERT(pcFrameVertices, qq, pcHeader->framevertex_stc_size).norm[0];
  1036. AI_SWAP4(vNormal.x);
  1037. vNormal.y = _AI_MDL7_ACCESS_VERT(pcFrameVertices, qq, pcHeader->framevertex_stc_size).norm[1];
  1038. AI_SWAP4(vNormal.y);
  1039. vNormal.z = _AI_MDL7_ACCESS_VERT(pcFrameVertices, qq, pcHeader->framevertex_stc_size).norm[2];
  1040. AI_SWAP4(vNormal.z);
  1041. } else if (AI_MDL7_FRAMEVERTEX120503_STCSIZE <= pcHeader->mainvertex_stc_size) {
  1042. // read the normal vector from Quake2's smart table
  1043. MD2::LookupNormalIndex(_AI_MDL7_ACCESS_VERT(pcFrameVertices, qq,
  1044. pcHeader->framevertex_stc_size)
  1045. .norm162index,
  1046. vNormal);
  1047. }
  1048. // FIXME: O(n^2) at the moment ...
  1049. BE_NCONST MDL::Triangle_MDL7 *pcGroupTris = groupInfo.pcGroupTris;
  1050. unsigned int iOutIndex = 0;
  1051. for (unsigned int iTriangle = 0; iTriangle < (unsigned int)groupInfo.pcGroup->numtris; ++iTriangle) {
  1052. // iterate through all indices of the current triangle
  1053. for (unsigned int c = 0; c < 3; ++c, ++iOutIndex) {
  1054. // replace the vertex with the new data
  1055. const unsigned int iCurIndex = pcGroupTris->v_index[c];
  1056. if (iCurIndex == iIndex) {
  1057. groupData.vPositions[iOutIndex] = vPosition;
  1058. groupData.vNormals[iOutIndex] = vNormal;
  1059. }
  1060. }
  1061. // get the next triangle in the list
  1062. pcGroupTris = (BE_NCONST MDL::Triangle_MDL7 *)((const char *)
  1063. pcGroupTris +
  1064. pcHeader->triangle_stc_size);
  1065. }
  1066. }
  1067. }
  1068. // parse bone trafo matrix keys (only if there are bones ...)
  1069. if (shared.apcOutBones) {
  1070. ParseBoneTrafoKeys_3DGS_MDL7(groupInfo, frame, shared);
  1071. }
  1072. szCurrent += iAdd;
  1073. }
  1074. *szCurrentOut = szCurrent;
  1075. return true;
  1076. }
  1077. // ------------------------------------------------------------------------------------------------
  1078. // Sort faces by material, handle multiple UVs correctly
  1079. void MDLImporter::SortByMaterials_3DGS_MDL7(
  1080. const MDL::IntGroupInfo_MDL7 &groupInfo,
  1081. MDL::IntGroupData_MDL7 &groupData,
  1082. MDL::IntSplitGroupData_MDL7 &splitGroupData) {
  1083. const unsigned int iNumMaterials = (unsigned int)splitGroupData.shared.pcMats.size();
  1084. if (!groupData.bNeed2UV) {
  1085. // if we don't need a second set of texture coordinates there is no reason to keep it in memory ...
  1086. groupData.vTextureCoords2.clear();
  1087. // allocate the array
  1088. splitGroupData.aiSplit = new std::vector<unsigned int> *[iNumMaterials];
  1089. for (unsigned int m = 0; m < iNumMaterials; ++m)
  1090. splitGroupData.aiSplit[m] = new std::vector<unsigned int>();
  1091. // iterate through all faces and sort by material
  1092. for (unsigned int iFace = 0; iFace < (unsigned int)groupInfo.pcGroup->numtris; ++iFace) {
  1093. // check range
  1094. if (groupData.pcFaces[iFace].iMatIndex[0] >= iNumMaterials) {
  1095. // use the last material instead
  1096. splitGroupData.aiSplit[iNumMaterials - 1]->push_back(iFace);
  1097. // sometimes MED writes -1, but normally only if there is only
  1098. // one skin assigned. No warning in this case
  1099. if (0xFFFFFFFF != groupData.pcFaces[iFace].iMatIndex[0])
  1100. ASSIMP_LOG_WARN("Index overflow in MDL7 material list [#0]");
  1101. } else
  1102. splitGroupData.aiSplit[groupData.pcFaces[iFace].iMatIndex[0]]->push_back(iFace);
  1103. }
  1104. } else {
  1105. // we need to build combined materials for each combination of
  1106. std::vector<MDL::IntMaterial_MDL7> avMats;
  1107. avMats.reserve(iNumMaterials * 2);
  1108. // fixme: why on the heap?
  1109. std::vector<std::vector<unsigned int> *> aiTempSplit(iNumMaterials * 2);
  1110. for (unsigned int m = 0; m < iNumMaterials; ++m)
  1111. aiTempSplit[m] = new std::vector<unsigned int>();
  1112. // iterate through all faces and sort by material
  1113. for (unsigned int iFace = 0; iFace < (unsigned int)groupInfo.pcGroup->numtris; ++iFace) {
  1114. // check range
  1115. unsigned int iMatIndex = groupData.pcFaces[iFace].iMatIndex[0];
  1116. if (iMatIndex >= iNumMaterials) {
  1117. // sometimes MED writes -1, but normally only if there is only
  1118. // one skin assigned. No warning in this case
  1119. if (UINT_MAX != iMatIndex)
  1120. ASSIMP_LOG_WARN("Index overflow in MDL7 material list [#1]");
  1121. iMatIndex = iNumMaterials - 1;
  1122. }
  1123. unsigned int iMatIndex2 = groupData.pcFaces[iFace].iMatIndex[1];
  1124. unsigned int iNum = iMatIndex;
  1125. if (UINT_MAX != iMatIndex2 && iMatIndex != iMatIndex2) {
  1126. if (iMatIndex2 >= iNumMaterials) {
  1127. // sometimes MED writes -1, but normally only if there is only
  1128. // one skin assigned. No warning in this case
  1129. ASSIMP_LOG_WARN("Index overflow in MDL7 material list [#2]");
  1130. iMatIndex2 = iNumMaterials - 1;
  1131. }
  1132. // do a slow search in the list ...
  1133. iNum = 0;
  1134. bool bFound = false;
  1135. for (std::vector<MDL::IntMaterial_MDL7>::iterator i = avMats.begin(); i != avMats.end(); ++i, ++iNum) {
  1136. if ((*i).iOldMatIndices[0] == iMatIndex && (*i).iOldMatIndices[1] == iMatIndex2) {
  1137. // reuse this material
  1138. bFound = true;
  1139. break;
  1140. }
  1141. }
  1142. if (!bFound) {
  1143. // build a new material ...
  1144. MDL::IntMaterial_MDL7 sHelper;
  1145. sHelper.pcMat = new aiMaterial();
  1146. sHelper.iOldMatIndices[0] = iMatIndex;
  1147. sHelper.iOldMatIndices[1] = iMatIndex2;
  1148. JoinSkins_3DGS_MDL7(splitGroupData.shared.pcMats[iMatIndex],
  1149. splitGroupData.shared.pcMats[iMatIndex2], sHelper.pcMat);
  1150. // and add it to the list
  1151. avMats.push_back(sHelper);
  1152. iNum = (unsigned int)avMats.size() - 1;
  1153. }
  1154. // adjust the size of the file array
  1155. if (iNum == aiTempSplit.size()) {
  1156. aiTempSplit.push_back(new std::vector<unsigned int>());
  1157. }
  1158. }
  1159. aiTempSplit[iNum]->push_back(iFace);
  1160. }
  1161. // now add the newly created materials to the old list
  1162. if (0 == groupInfo.iIndex) {
  1163. splitGroupData.shared.pcMats.resize(avMats.size());
  1164. for (unsigned int o = 0; o < avMats.size(); ++o)
  1165. splitGroupData.shared.pcMats[o] = avMats[o].pcMat;
  1166. } else {
  1167. // This might result in redundant materials ...
  1168. splitGroupData.shared.pcMats.resize(iNumMaterials + avMats.size());
  1169. for (unsigned int o = iNumMaterials; o < avMats.size(); ++o)
  1170. splitGroupData.shared.pcMats[o] = avMats[o].pcMat;
  1171. }
  1172. // and build the final face-to-material array
  1173. splitGroupData.aiSplit = new std::vector<unsigned int> *[aiTempSplit.size()];
  1174. for (unsigned int m = 0; m < iNumMaterials; ++m)
  1175. splitGroupData.aiSplit[m] = aiTempSplit[m];
  1176. }
  1177. }
  1178. // ------------------------------------------------------------------------------------------------
  1179. // Read a MDL7 file
  1180. void MDLImporter::InternReadFile_3DGS_MDL7() {
  1181. ai_assert(nullptr != pScene);
  1182. MDL::IntSharedData_MDL7 sharedData;
  1183. // current cursor position in the file
  1184. BE_NCONST MDL::Header_MDL7 *pcHeader = (BE_NCONST MDL::Header_MDL7 *)this->mBuffer;
  1185. const unsigned char *szCurrent = (const unsigned char *)(pcHeader + 1);
  1186. AI_SWAP4(pcHeader->version);
  1187. AI_SWAP4(pcHeader->bones_num);
  1188. AI_SWAP4(pcHeader->groups_num);
  1189. AI_SWAP4(pcHeader->data_size);
  1190. AI_SWAP4(pcHeader->entlump_size);
  1191. AI_SWAP4(pcHeader->medlump_size);
  1192. AI_SWAP2(pcHeader->bone_stc_size);
  1193. AI_SWAP2(pcHeader->skin_stc_size);
  1194. AI_SWAP2(pcHeader->colorvalue_stc_size);
  1195. AI_SWAP2(pcHeader->material_stc_size);
  1196. AI_SWAP2(pcHeader->skinpoint_stc_size);
  1197. AI_SWAP2(pcHeader->triangle_stc_size);
  1198. AI_SWAP2(pcHeader->mainvertex_stc_size);
  1199. AI_SWAP2(pcHeader->framevertex_stc_size);
  1200. AI_SWAP2(pcHeader->bonetrans_stc_size);
  1201. AI_SWAP2(pcHeader->frame_stc_size);
  1202. // validate the header of the file. There are some structure
  1203. // sizes that are expected by the loader to be constant
  1204. this->ValidateHeader_3DGS_MDL7(pcHeader);
  1205. // load all bones (they are shared by all groups, so
  1206. // we'll need to add them to all groups/meshes later)
  1207. // apcBonesOut is a list of all bones or nullptr if they could not been loaded
  1208. szCurrent += pcHeader->bones_num * pcHeader->bone_stc_size;
  1209. sharedData.apcOutBones = this->LoadBones_3DGS_MDL7();
  1210. // vector to held all created meshes
  1211. std::vector<aiMesh *> *avOutList;
  1212. // 3 meshes per group - that should be OK for most models
  1213. avOutList = new std::vector<aiMesh *>[pcHeader->groups_num];
  1214. for (uint32_t i = 0; i < pcHeader->groups_num; ++i)
  1215. avOutList[i].reserve(3);
  1216. // buffer to held the names of all groups in the file
  1217. const size_t buffersize(AI_MDL7_MAX_GROUPNAMESIZE * pcHeader->groups_num);
  1218. char *aszGroupNameBuffer = new char[buffersize];
  1219. // read all groups
  1220. for (unsigned int iGroup = 0; iGroup < (unsigned int)pcHeader->groups_num; ++iGroup) {
  1221. MDL::IntGroupInfo_MDL7 groupInfo((BE_NCONST MDL::Group_MDL7 *)szCurrent, iGroup);
  1222. szCurrent = (const unsigned char *)(groupInfo.pcGroup + 1);
  1223. VALIDATE_FILE_SIZE(szCurrent);
  1224. AI_SWAP4(groupInfo.pcGroup->groupdata_size);
  1225. AI_SWAP4(groupInfo.pcGroup->numskins);
  1226. AI_SWAP4(groupInfo.pcGroup->num_stpts);
  1227. AI_SWAP4(groupInfo.pcGroup->numtris);
  1228. AI_SWAP4(groupInfo.pcGroup->numverts);
  1229. AI_SWAP4(groupInfo.pcGroup->numframes);
  1230. if (1 != groupInfo.pcGroup->typ) {
  1231. // Not a triangle-based mesh
  1232. ASSIMP_LOG_WARN("[3DGS MDL7] Not a triangle mesh group. Continuing happily");
  1233. }
  1234. // store the name of the group
  1235. const unsigned int ofs = iGroup * AI_MDL7_MAX_GROUPNAMESIZE;
  1236. ::memcpy(&aszGroupNameBuffer[ofs],
  1237. groupInfo.pcGroup->name, AI_MDL7_MAX_GROUPNAMESIZE);
  1238. // make sure '\0' is at the end
  1239. aszGroupNameBuffer[ofs + AI_MDL7_MAX_GROUPNAMESIZE - 1] = '\0';
  1240. // read all skins
  1241. sharedData.pcMats.reserve(sharedData.pcMats.size() + groupInfo.pcGroup->numskins);
  1242. sharedData.abNeedMaterials.resize(sharedData.abNeedMaterials.size() +
  1243. groupInfo.pcGroup->numskins,
  1244. false);
  1245. for (unsigned int iSkin = 0; iSkin < (unsigned int)groupInfo.pcGroup->numskins; ++iSkin) {
  1246. ParseSkinLump_3DGS_MDL7(szCurrent, &szCurrent, sharedData.pcMats);
  1247. }
  1248. // if we have absolutely no skin loaded we need to generate a default material
  1249. if (sharedData.pcMats.empty()) {
  1250. const int iMode = (int)aiShadingMode_Gouraud;
  1251. sharedData.pcMats.push_back(new aiMaterial());
  1252. aiMaterial *pcHelper = (aiMaterial *)sharedData.pcMats[0];
  1253. pcHelper->AddProperty<int>(&iMode, 1, AI_MATKEY_SHADING_MODEL);
  1254. aiColor3D clr;
  1255. clr.b = clr.g = clr.r = 0.6f;
  1256. pcHelper->AddProperty<aiColor3D>(&clr, 1, AI_MATKEY_COLOR_DIFFUSE);
  1257. pcHelper->AddProperty<aiColor3D>(&clr, 1, AI_MATKEY_COLOR_SPECULAR);
  1258. clr.b = clr.g = clr.r = 0.05f;
  1259. pcHelper->AddProperty<aiColor3D>(&clr, 1, AI_MATKEY_COLOR_AMBIENT);
  1260. aiString szName;
  1261. szName.Set(AI_DEFAULT_MATERIAL_NAME);
  1262. pcHelper->AddProperty(&szName, AI_MATKEY_NAME);
  1263. sharedData.abNeedMaterials.resize(1, false);
  1264. }
  1265. // now get a pointer to all texture coords in the group
  1266. groupInfo.pcGroupUVs = (BE_NCONST MDL::TexCoord_MDL7 *)szCurrent;
  1267. for (int i = 0; i < groupInfo.pcGroup->num_stpts; ++i) {
  1268. AI_SWAP4(groupInfo.pcGroupUVs[i].u);
  1269. AI_SWAP4(groupInfo.pcGroupUVs[i].v);
  1270. }
  1271. szCurrent += pcHeader->skinpoint_stc_size * groupInfo.pcGroup->num_stpts;
  1272. // now get a pointer to all triangle in the group
  1273. groupInfo.pcGroupTris = (Triangle_MDL7 *)szCurrent;
  1274. szCurrent += pcHeader->triangle_stc_size * groupInfo.pcGroup->numtris;
  1275. // now get a pointer to all vertices in the group
  1276. groupInfo.pcGroupVerts = (BE_NCONST MDL::Vertex_MDL7 *)szCurrent;
  1277. for (int i = 0; i < groupInfo.pcGroup->numverts; ++i) {
  1278. AI_SWAP4(groupInfo.pcGroupVerts[i].x);
  1279. AI_SWAP4(groupInfo.pcGroupVerts[i].y);
  1280. AI_SWAP4(groupInfo.pcGroupVerts[i].z);
  1281. AI_SWAP2(groupInfo.pcGroupVerts[i].vertindex);
  1282. //We can not swap the normal information now as we don't know which of the two kinds it is
  1283. }
  1284. szCurrent += pcHeader->mainvertex_stc_size * groupInfo.pcGroup->numverts;
  1285. VALIDATE_FILE_SIZE(szCurrent);
  1286. MDL::IntSplitGroupData_MDL7 splitGroupData(sharedData, avOutList[iGroup]);
  1287. MDL::IntGroupData_MDL7 groupData;
  1288. if (groupInfo.pcGroup->numtris && groupInfo.pcGroup->numverts) {
  1289. // build output vectors
  1290. const unsigned int iNumVertices = groupInfo.pcGroup->numtris * 3;
  1291. groupData.vPositions.resize(iNumVertices);
  1292. groupData.vNormals.resize(iNumVertices);
  1293. if (sharedData.apcOutBones) groupData.aiBones.resize(iNumVertices, UINT_MAX);
  1294. // it is also possible that there are 0 UV coordinate sets
  1295. if (groupInfo.pcGroup->num_stpts) {
  1296. groupData.vTextureCoords1.resize(iNumVertices, aiVector3D());
  1297. // check whether the triangle data structure is large enough
  1298. // to contain a second UV coordinate set
  1299. if (pcHeader->triangle_stc_size >= AI_MDL7_TRIANGLE_STD_SIZE_TWO_UV) {
  1300. groupData.vTextureCoords2.resize(iNumVertices, aiVector3D());
  1301. groupData.bNeed2UV = true;
  1302. }
  1303. }
  1304. groupData.pcFaces.resize(groupInfo.pcGroup->numtris);
  1305. // read all faces into the preallocated arrays
  1306. ReadFaces_3DGS_MDL7(groupInfo, groupData);
  1307. // sort by materials
  1308. SortByMaterials_3DGS_MDL7(groupInfo, groupData,
  1309. splitGroupData);
  1310. for (unsigned int qq = 0; qq < sharedData.pcMats.size(); ++qq) {
  1311. if (!splitGroupData.aiSplit[qq]->empty())
  1312. sharedData.abNeedMaterials[qq] = true;
  1313. }
  1314. } else
  1315. ASSIMP_LOG_WARN("[3DGS MDL7] Mesh group consists of 0 "
  1316. "vertices or faces. It will be skipped.");
  1317. // process all frames and generate output meshes
  1318. ProcessFrames_3DGS_MDL7(groupInfo, groupData, sharedData, szCurrent, &szCurrent);
  1319. GenerateOutputMeshes_3DGS_MDL7(groupData, splitGroupData);
  1320. }
  1321. // generate a nodegraph and subnodes for each group
  1322. pScene->mRootNode = new aiNode();
  1323. // now we need to build a final mesh list
  1324. for (uint32_t i = 0; i < pcHeader->groups_num; ++i)
  1325. pScene->mNumMeshes += (unsigned int)avOutList[i].size();
  1326. pScene->mMeshes = new aiMesh *[pScene->mNumMeshes];
  1327. {
  1328. unsigned int p = 0, q = 0;
  1329. for (uint32_t i = 0; i < pcHeader->groups_num; ++i) {
  1330. for (unsigned int a = 0; a < avOutList[i].size(); ++a) {
  1331. pScene->mMeshes[p++] = avOutList[i][a];
  1332. }
  1333. if (!avOutList[i].empty()) ++pScene->mRootNode->mNumChildren;
  1334. }
  1335. // we will later need an extra node to serve as parent for all bones
  1336. if (sharedData.apcOutBones) ++pScene->mRootNode->mNumChildren;
  1337. this->pScene->mRootNode->mChildren = new aiNode *[pScene->mRootNode->mNumChildren];
  1338. p = 0;
  1339. for (uint32_t i = 0; i < pcHeader->groups_num; ++i) {
  1340. if (avOutList[i].empty()) continue;
  1341. aiNode *const pcNode = pScene->mRootNode->mChildren[p] = new aiNode();
  1342. pcNode->mNumMeshes = (unsigned int)avOutList[i].size();
  1343. pcNode->mMeshes = new unsigned int[pcNode->mNumMeshes];
  1344. pcNode->mParent = this->pScene->mRootNode;
  1345. for (unsigned int a = 0; a < pcNode->mNumMeshes; ++a)
  1346. pcNode->mMeshes[a] = q + a;
  1347. q += (unsigned int)avOutList[i].size();
  1348. // setup the name of the node
  1349. char *const szBuffer = &aszGroupNameBuffer[i * AI_MDL7_MAX_GROUPNAMESIZE];
  1350. if ('\0' == *szBuffer) {
  1351. const size_t maxSize(buffersize - (i * AI_MDL7_MAX_GROUPNAMESIZE));
  1352. pcNode->mName.length = ai_snprintf(szBuffer, maxSize, "Group_%u", p);
  1353. } else {
  1354. pcNode->mName.length = (ai_uint32)::strlen(szBuffer);
  1355. }
  1356. ::strncpy(pcNode->mName.data, szBuffer, AI_MAXLEN - 1);
  1357. ++p;
  1358. }
  1359. }
  1360. // if there is only one root node with a single child we can optimize it a bit ...
  1361. if (1 == pScene->mRootNode->mNumChildren && !sharedData.apcOutBones) {
  1362. aiNode *pcOldRoot = this->pScene->mRootNode;
  1363. pScene->mRootNode = pcOldRoot->mChildren[0];
  1364. pcOldRoot->mChildren[0] = nullptr;
  1365. delete pcOldRoot;
  1366. pScene->mRootNode->mParent = nullptr;
  1367. } else
  1368. pScene->mRootNode->mName.Set("<mesh_root>");
  1369. delete[] avOutList;
  1370. delete[] aszGroupNameBuffer;
  1371. AI_DEBUG_INVALIDATE_PTR(avOutList);
  1372. AI_DEBUG_INVALIDATE_PTR(aszGroupNameBuffer);
  1373. // build a final material list.
  1374. CopyMaterials_3DGS_MDL7(sharedData);
  1375. HandleMaterialReferences_3DGS_MDL7();
  1376. // generate output bone animations and add all bones to the scenegraph
  1377. if (sharedData.apcOutBones) {
  1378. // this step adds empty dummy bones to the nodegraph
  1379. // insert another dummy node to avoid name conflicts
  1380. aiNode *const pc = pScene->mRootNode->mChildren[pScene->mRootNode->mNumChildren - 1] = new aiNode();
  1381. pc->mName.Set("<skeleton_root>");
  1382. // add bones to the nodegraph
  1383. AddBonesToNodeGraph_3DGS_MDL7((const Assimp::MDL::IntBone_MDL7 **)
  1384. sharedData.apcOutBones,
  1385. pc, 0xffff);
  1386. // this steps build a valid output animation
  1387. BuildOutputAnims_3DGS_MDL7((const Assimp::MDL::IntBone_MDL7 **)
  1388. sharedData.apcOutBones);
  1389. }
  1390. }
  1391. // ------------------------------------------------------------------------------------------------
  1392. // Copy materials
  1393. void MDLImporter::CopyMaterials_3DGS_MDL7(MDL::IntSharedData_MDL7 &shared) {
  1394. pScene->mNumMaterials = (unsigned int)shared.pcMats.size();
  1395. pScene->mMaterials = new aiMaterial *[pScene->mNumMaterials];
  1396. for (unsigned int i = 0; i < pScene->mNumMaterials; ++i)
  1397. pScene->mMaterials[i] = shared.pcMats[i];
  1398. }
  1399. // ------------------------------------------------------------------------------------------------
  1400. // Process material references
  1401. void MDLImporter::HandleMaterialReferences_3DGS_MDL7() {
  1402. // search for referrer materials
  1403. for (unsigned int i = 0; i < pScene->mNumMaterials; ++i) {
  1404. int iIndex = 0;
  1405. if (AI_SUCCESS == aiGetMaterialInteger(pScene->mMaterials[i], AI_MDL7_REFERRER_MATERIAL, &iIndex)) {
  1406. for (unsigned int a = 0; a < pScene->mNumMeshes; ++a) {
  1407. aiMesh *const pcMesh = pScene->mMeshes[a];
  1408. if (i == pcMesh->mMaterialIndex) {
  1409. pcMesh->mMaterialIndex = iIndex;
  1410. }
  1411. }
  1412. // collapse the rest of the array
  1413. delete pScene->mMaterials[i];
  1414. for (unsigned int pp = i; pp < pScene->mNumMaterials - 1; ++pp) {
  1415. pScene->mMaterials[pp] = pScene->mMaterials[pp + 1];
  1416. for (unsigned int a = 0; a < pScene->mNumMeshes; ++a) {
  1417. aiMesh *const pcMesh = pScene->mMeshes[a];
  1418. if (pcMesh->mMaterialIndex > i) --pcMesh->mMaterialIndex;
  1419. }
  1420. }
  1421. --pScene->mNumMaterials;
  1422. }
  1423. }
  1424. }
  1425. // ------------------------------------------------------------------------------------------------
  1426. // Read bone transformation keys
  1427. void MDLImporter::ParseBoneTrafoKeys_3DGS_MDL7(
  1428. const MDL::IntGroupInfo_MDL7 &groupInfo,
  1429. IntFrameInfo_MDL7 &frame,
  1430. MDL::IntSharedData_MDL7 &shared) {
  1431. const MDL::Header_MDL7 *const pcHeader = (const MDL::Header_MDL7 *)this->mBuffer;
  1432. // only the first group contains bone animation keys
  1433. if (frame.pcFrame->transmatrix_count) {
  1434. if (!groupInfo.iIndex) {
  1435. // skip all frames vertices. We can't support them
  1436. const MDL::BoneTransform_MDL7 *pcBoneTransforms = (const MDL::BoneTransform_MDL7 *)(((const char *)frame.pcFrame) + pcHeader->frame_stc_size +
  1437. frame.pcFrame->vertices_count * pcHeader->framevertex_stc_size);
  1438. // read all transformation matrices
  1439. for (unsigned int iTrafo = 0; iTrafo < frame.pcFrame->transmatrix_count; ++iTrafo) {
  1440. if (pcBoneTransforms->bone_index >= pcHeader->bones_num) {
  1441. ASSIMP_LOG_WARN("Index overflow in frame area. "
  1442. "Unable to parse this bone transformation");
  1443. } else {
  1444. AddAnimationBoneTrafoKey_3DGS_MDL7(frame.iIndex,
  1445. pcBoneTransforms, shared.apcOutBones);
  1446. }
  1447. pcBoneTransforms = (const MDL::BoneTransform_MDL7 *)((const char *)pcBoneTransforms + pcHeader->bonetrans_stc_size);
  1448. }
  1449. } else {
  1450. ASSIMP_LOG_WARN("Ignoring animation keyframes in groups != 0");
  1451. }
  1452. }
  1453. }
  1454. // ------------------------------------------------------------------------------------------------
  1455. // Attach bones to the output nodegraph
  1456. void MDLImporter::AddBonesToNodeGraph_3DGS_MDL7(const MDL::IntBone_MDL7 **apcBones,
  1457. aiNode *pcParent, uint16_t iParentIndex) {
  1458. ai_assert(nullptr != apcBones);
  1459. ai_assert(nullptr != pcParent);
  1460. // get a pointer to the header ...
  1461. const MDL::Header_MDL7 *const pcHeader = (const MDL::Header_MDL7 *)this->mBuffer;
  1462. const MDL::IntBone_MDL7 **apcBones2 = apcBones;
  1463. for (uint32_t i = 0; i < pcHeader->bones_num; ++i) {
  1464. const MDL::IntBone_MDL7 *const pcBone = *apcBones2++;
  1465. if (pcBone->iParent == iParentIndex) {
  1466. ++pcParent->mNumChildren;
  1467. }
  1468. }
  1469. pcParent->mChildren = new aiNode *[pcParent->mNumChildren];
  1470. unsigned int qq = 0;
  1471. for (uint32_t i = 0; i < pcHeader->bones_num; ++i) {
  1472. const MDL::IntBone_MDL7 *const pcBone = *apcBones++;
  1473. if (pcBone->iParent != iParentIndex) continue;
  1474. aiNode *pcNode = pcParent->mChildren[qq++] = new aiNode();
  1475. pcNode->mName = aiString(pcBone->mName);
  1476. AddBonesToNodeGraph_3DGS_MDL7(apcBones, pcNode, (uint16_t)i);
  1477. }
  1478. }
  1479. // ------------------------------------------------------------------------------------------------
  1480. // Build output animations
  1481. void MDLImporter::BuildOutputAnims_3DGS_MDL7(
  1482. const MDL::IntBone_MDL7 **apcBonesOut) {
  1483. ai_assert(nullptr != apcBonesOut);
  1484. const MDL::Header_MDL7 *const pcHeader = (const MDL::Header_MDL7 *)mBuffer;
  1485. // one animation ...
  1486. aiAnimation *pcAnim = new aiAnimation();
  1487. for (uint32_t i = 0; i < pcHeader->bones_num; ++i) {
  1488. if (!apcBonesOut[i]->pkeyPositions.empty()) {
  1489. // get the last frame ... (needn't be equal to pcHeader->frames_num)
  1490. for (size_t qq = 0; qq < apcBonesOut[i]->pkeyPositions.size(); ++qq) {
  1491. pcAnim->mDuration = std::max(pcAnim->mDuration, (double)
  1492. apcBonesOut[i]
  1493. ->pkeyPositions[qq]
  1494. .mTime);
  1495. }
  1496. ++pcAnim->mNumChannels;
  1497. }
  1498. }
  1499. if (pcAnim->mDuration) {
  1500. pcAnim->mChannels = new aiNodeAnim *[pcAnim->mNumChannels];
  1501. unsigned int iCnt = 0;
  1502. for (uint32_t i = 0; i < pcHeader->bones_num; ++i) {
  1503. if (!apcBonesOut[i]->pkeyPositions.empty()) {
  1504. const MDL::IntBone_MDL7 *const intBone = apcBonesOut[i];
  1505. aiNodeAnim *const pcNodeAnim = pcAnim->mChannels[iCnt++] = new aiNodeAnim();
  1506. pcNodeAnim->mNodeName = aiString(intBone->mName);
  1507. // allocate enough storage for all keys
  1508. pcNodeAnim->mNumPositionKeys = (unsigned int)intBone->pkeyPositions.size();
  1509. pcNodeAnim->mNumScalingKeys = (unsigned int)intBone->pkeyPositions.size();
  1510. pcNodeAnim->mNumRotationKeys = (unsigned int)intBone->pkeyPositions.size();
  1511. pcNodeAnim->mPositionKeys = new aiVectorKey[pcNodeAnim->mNumPositionKeys];
  1512. pcNodeAnim->mScalingKeys = new aiVectorKey[pcNodeAnim->mNumPositionKeys];
  1513. pcNodeAnim->mRotationKeys = new aiQuatKey[pcNodeAnim->mNumPositionKeys];
  1514. // copy all keys
  1515. for (unsigned int qq = 0; qq < pcNodeAnim->mNumPositionKeys; ++qq) {
  1516. pcNodeAnim->mPositionKeys[qq] = intBone->pkeyPositions[qq];
  1517. pcNodeAnim->mScalingKeys[qq] = intBone->pkeyScalings[qq];
  1518. pcNodeAnim->mRotationKeys[qq] = intBone->pkeyRotations[qq];
  1519. }
  1520. }
  1521. }
  1522. // store the output animation
  1523. pScene->mNumAnimations = 1;
  1524. pScene->mAnimations = new aiAnimation *[1];
  1525. pScene->mAnimations[0] = pcAnim;
  1526. } else
  1527. delete pcAnim;
  1528. }
  1529. // ------------------------------------------------------------------------------------------------
  1530. void MDLImporter::AddAnimationBoneTrafoKey_3DGS_MDL7(unsigned int iTrafo,
  1531. const MDL::BoneTransform_MDL7 *pcBoneTransforms,
  1532. MDL::IntBone_MDL7 **apcBonesOut) {
  1533. ai_assert(nullptr != pcBoneTransforms);
  1534. ai_assert(nullptr != apcBonesOut);
  1535. // first .. get the transformation matrix
  1536. aiMatrix4x4 mTransform;
  1537. mTransform.a1 = pcBoneTransforms->m[0];
  1538. mTransform.b1 = pcBoneTransforms->m[1];
  1539. mTransform.c1 = pcBoneTransforms->m[2];
  1540. mTransform.d1 = pcBoneTransforms->m[3];
  1541. mTransform.a2 = pcBoneTransforms->m[4];
  1542. mTransform.b2 = pcBoneTransforms->m[5];
  1543. mTransform.c2 = pcBoneTransforms->m[6];
  1544. mTransform.d2 = pcBoneTransforms->m[7];
  1545. mTransform.a3 = pcBoneTransforms->m[8];
  1546. mTransform.b3 = pcBoneTransforms->m[9];
  1547. mTransform.c3 = pcBoneTransforms->m[10];
  1548. mTransform.d3 = pcBoneTransforms->m[11];
  1549. // now decompose the transformation matrix into separate
  1550. // scaling, rotation and translation
  1551. aiVectorKey vScaling, vPosition;
  1552. aiQuatKey qRotation;
  1553. // FIXME: Decompose will assert in debug builds if the matrix is invalid ...
  1554. mTransform.Decompose(vScaling.mValue, qRotation.mValue, vPosition.mValue);
  1555. // now generate keys
  1556. vScaling.mTime = qRotation.mTime = vPosition.mTime = (double)iTrafo;
  1557. // add the keys to the bone
  1558. MDL::IntBone_MDL7 *const pcBoneOut = apcBonesOut[pcBoneTransforms->bone_index];
  1559. pcBoneOut->pkeyPositions.push_back(vPosition);
  1560. pcBoneOut->pkeyScalings.push_back(vScaling);
  1561. pcBoneOut->pkeyRotations.push_back(qRotation);
  1562. }
  1563. // ------------------------------------------------------------------------------------------------
  1564. // Construct output meshes
  1565. void MDLImporter::GenerateOutputMeshes_3DGS_MDL7(
  1566. MDL::IntGroupData_MDL7 &groupData,
  1567. MDL::IntSplitGroupData_MDL7 &splitGroupData) {
  1568. const MDL::IntSharedData_MDL7 &shared = splitGroupData.shared;
  1569. // get a pointer to the header ...
  1570. const MDL::Header_MDL7 *const pcHeader = (const MDL::Header_MDL7 *)this->mBuffer;
  1571. const unsigned int iNumOutBones = pcHeader->bones_num;
  1572. for (std::vector<aiMaterial *>::size_type i = 0; i < shared.pcMats.size(); ++i) {
  1573. if (splitGroupData.aiSplit == nullptr) {
  1574. continue;
  1575. }
  1576. if (!splitGroupData.aiSplit[i]->empty()) {
  1577. // allocate the output mesh
  1578. aiMesh *pcMesh = new aiMesh();
  1579. pcMesh->mPrimitiveTypes = aiPrimitiveType_TRIANGLE;
  1580. pcMesh->mMaterialIndex = (unsigned int)i;
  1581. // allocate output storage
  1582. pcMesh->mNumFaces = (unsigned int)splitGroupData.aiSplit[i]->size();
  1583. pcMesh->mFaces = new aiFace[pcMesh->mNumFaces];
  1584. pcMesh->mNumVertices = pcMesh->mNumFaces * 3;
  1585. pcMesh->mVertices = new aiVector3D[pcMesh->mNumVertices];
  1586. pcMesh->mNormals = new aiVector3D[pcMesh->mNumVertices];
  1587. if (!groupData.vTextureCoords1.empty()) {
  1588. pcMesh->mNumUVComponents[0] = 2;
  1589. pcMesh->mTextureCoords[0] = new aiVector3D[pcMesh->mNumVertices];
  1590. if (!groupData.vTextureCoords2.empty()) {
  1591. pcMesh->mNumUVComponents[1] = 2;
  1592. pcMesh->mTextureCoords[1] = new aiVector3D[pcMesh->mNumVertices];
  1593. }
  1594. }
  1595. // iterate through all faces and build an unique set of vertices
  1596. unsigned int iCurrent = 0;
  1597. for (unsigned int iFace = 0; iFace < pcMesh->mNumFaces; ++iFace) {
  1598. pcMesh->mFaces[iFace].mNumIndices = 3;
  1599. pcMesh->mFaces[iFace].mIndices = new unsigned int[3];
  1600. unsigned int iSrcFace = splitGroupData.aiSplit[i]->operator[](iFace);
  1601. const MDL::IntFace_MDL7 &oldFace = groupData.pcFaces[iSrcFace];
  1602. // iterate through all face indices
  1603. for (unsigned int c = 0; c < 3; ++c) {
  1604. const uint32_t iIndex = oldFace.mIndices[c];
  1605. pcMesh->mVertices[iCurrent] = groupData.vPositions[iIndex];
  1606. pcMesh->mNormals[iCurrent] = groupData.vNormals[iIndex];
  1607. if (!groupData.vTextureCoords1.empty()) {
  1608. pcMesh->mTextureCoords[0][iCurrent] = groupData.vTextureCoords1[iIndex];
  1609. if (!groupData.vTextureCoords2.empty()) {
  1610. pcMesh->mTextureCoords[1][iCurrent] = groupData.vTextureCoords2[iIndex];
  1611. }
  1612. }
  1613. pcMesh->mFaces[iFace].mIndices[c] = iCurrent++;
  1614. }
  1615. }
  1616. // if we have bones in the mesh we'll need to generate
  1617. // proper vertex weights for them
  1618. if (!groupData.aiBones.empty()) {
  1619. std::vector<std::vector<unsigned int>> aaiVWeightList;
  1620. aaiVWeightList.resize(iNumOutBones);
  1621. int iCurrentWeight = 0;
  1622. for (unsigned int iFace = 0; iFace < pcMesh->mNumFaces; ++iFace) {
  1623. unsigned int iSrcFace = splitGroupData.aiSplit[i]->operator[](iFace);
  1624. const MDL::IntFace_MDL7 &oldFace = groupData.pcFaces[iSrcFace];
  1625. // iterate through all face indices
  1626. for (unsigned int c = 0; c < 3; ++c) {
  1627. unsigned int iBone = groupData.aiBones[oldFace.mIndices[c]];
  1628. if (UINT_MAX != iBone) {
  1629. if (iBone >= iNumOutBones) {
  1630. ASSIMP_LOG_ERROR("Bone index overflow. "
  1631. "The bone index of a vertex exceeds the allowed range. ");
  1632. iBone = iNumOutBones - 1;
  1633. }
  1634. aaiVWeightList[iBone].push_back(iCurrentWeight);
  1635. }
  1636. ++iCurrentWeight;
  1637. }
  1638. }
  1639. // now check which bones are required ...
  1640. for (std::vector<std::vector<unsigned int>>::const_iterator k = aaiVWeightList.begin(); k != aaiVWeightList.end(); ++k) {
  1641. if (!(*k).empty()) {
  1642. ++pcMesh->mNumBones;
  1643. }
  1644. }
  1645. pcMesh->mBones = new aiBone *[pcMesh->mNumBones];
  1646. iCurrent = 0;
  1647. for (std::vector<std::vector<unsigned int>>::const_iterator k = aaiVWeightList.begin(); k != aaiVWeightList.end(); ++k, ++iCurrent) {
  1648. if ((*k).empty())
  1649. continue;
  1650. // seems we'll need this node
  1651. aiBone *pcBone = pcMesh->mBones[iCurrent] = new aiBone();
  1652. pcBone->mName = aiString(shared.apcOutBones[iCurrent]->mName);
  1653. pcBone->mOffsetMatrix = shared.apcOutBones[iCurrent]->mOffsetMatrix;
  1654. // setup vertex weights
  1655. pcBone->mNumWeights = (unsigned int)(*k).size();
  1656. pcBone->mWeights = new aiVertexWeight[pcBone->mNumWeights];
  1657. for (unsigned int weight = 0; weight < pcBone->mNumWeights; ++weight) {
  1658. pcBone->mWeights[weight].mVertexId = (*k)[weight];
  1659. pcBone->mWeights[weight].mWeight = 1.0f;
  1660. }
  1661. }
  1662. }
  1663. // add the mesh to the list of output meshes
  1664. splitGroupData.avOutList.push_back(pcMesh);
  1665. }
  1666. }
  1667. }
  1668. // ------------------------------------------------------------------------------------------------
  1669. // Join to materials
  1670. void MDLImporter::JoinSkins_3DGS_MDL7(
  1671. aiMaterial *pcMat1,
  1672. aiMaterial *pcMat2,
  1673. aiMaterial *pcMatOut) {
  1674. ai_assert(nullptr != pcMat1);
  1675. ai_assert(nullptr != pcMat2);
  1676. ai_assert(nullptr != pcMatOut);
  1677. // first create a full copy of the first skin property set
  1678. // and assign it to the output material
  1679. aiMaterial::CopyPropertyList(pcMatOut, pcMat1);
  1680. int iVal = 0;
  1681. pcMatOut->AddProperty<int>(&iVal, 1, AI_MATKEY_UVWSRC_DIFFUSE(0));
  1682. // then extract the diffuse texture from the second skin,
  1683. // setup 1 as UV source and we have it
  1684. aiString sString;
  1685. if (AI_SUCCESS == aiGetMaterialString(pcMat2, AI_MATKEY_TEXTURE_DIFFUSE(0), &sString)) {
  1686. iVal = 1;
  1687. pcMatOut->AddProperty<int>(&iVal, 1, AI_MATKEY_UVWSRC_DIFFUSE(1));
  1688. pcMatOut->AddProperty(&sString, AI_MATKEY_TEXTURE_DIFFUSE(1));
  1689. }
  1690. }
  1691. // ------------------------------------------------------------------------------------------------
  1692. // Read a Half-life 1 MDL
  1693. void MDLImporter::InternReadFile_HL1(const std::string &pFile, const uint32_t iMagicWord) {
  1694. // We can't correctly load an MDL from a MDL "sequence" file.
  1695. if (iMagicWord == AI_MDL_MAGIC_NUMBER_BE_HL2b || iMagicWord == AI_MDL_MAGIC_NUMBER_LE_HL2b)
  1696. throw DeadlyImportError("Impossible to properly load a model from an MDL sequence file.");
  1697. // Check if the buffer is large enough to hold the header
  1698. if (iFileSize < sizeof(HalfLife::Header_HL1)) {
  1699. throw DeadlyImportError("HL1 MDL file is too small to contain header.");
  1700. }
  1701. // Read the MDL file.
  1702. HalfLife::HL1MDLLoader loader(
  1703. pScene,
  1704. mIOHandler,
  1705. mBuffer,
  1706. pFile,
  1707. mHL1ImportSettings);
  1708. }
  1709. // ------------------------------------------------------------------------------------------------
  1710. // Read a half-life 2 MDL
  1711. void MDLImporter::InternReadFile_HL2() {
  1712. //const MDL::Header_HL2* pcHeader = (const MDL::Header_HL2*)this->mBuffer;
  1713. throw DeadlyImportError("HL2 MDLs are not implemented");
  1714. }
  1715. #endif // !! ASSIMP_BUILD_NO_MDL_IMPORTER