MDLLoader.cpp 87 KB

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