MDLLoader.cpp 87 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005
  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 "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. // the header of MDL 3/4/5 is nearly identical to the original Quake1 header
  518. BE_NCONST MDL::Header *pcHeader = (BE_NCONST MDL::Header *)this->mBuffer;
  519. #ifdef AI_BUILD_BIG_ENDIAN
  520. FlipQuakeHeader(pcHeader);
  521. #endif
  522. ValidateHeader_Quake1(pcHeader);
  523. // current cursor position in the file
  524. const unsigned char *szCurrent = (const unsigned char *)(pcHeader + 1);
  525. const unsigned char *szEnd = mBuffer + iFileSize;
  526. // need to read all textures
  527. for (unsigned int i = 0; i < (unsigned int)pcHeader->num_skins; ++i) {
  528. if (szCurrent + sizeof(uint32_t) > szEnd) {
  529. throw DeadlyImportError("Texture data past end of file.");
  530. }
  531. BE_NCONST MDL::Skin *pcSkin;
  532. pcSkin = (BE_NCONST MDL::Skin *)szCurrent;
  533. AI_SWAP4(pcSkin->group);
  534. // create one output image
  535. unsigned int iSkip = i ? UINT_MAX : 0;
  536. if (5 <= iGSFileVersion) {
  537. // MDL5 format could contain MIPmaps
  538. CreateTexture_3DGS_MDL5((unsigned char *)pcSkin + sizeof(uint32_t),
  539. pcSkin->group, &iSkip);
  540. } else {
  541. CreateTexture_3DGS_MDL4((unsigned char *)pcSkin + sizeof(uint32_t),
  542. pcSkin->group, &iSkip);
  543. }
  544. // need to skip one image
  545. szCurrent += iSkip + sizeof(uint32_t);
  546. }
  547. // get a pointer to the texture coordinates
  548. BE_NCONST MDL::TexCoord_MDL3 *pcTexCoords = (BE_NCONST MDL::TexCoord_MDL3 *)szCurrent;
  549. szCurrent += sizeof(MDL::TexCoord_MDL3) * pcHeader->synctype;
  550. // NOTE: for MDLn formats "synctype" corresponds to the number of UV coords
  551. // get a pointer to the triangles
  552. BE_NCONST MDL::Triangle_MDL3 *pcTriangles = (BE_NCONST MDL::Triangle_MDL3 *)szCurrent;
  553. szCurrent += sizeof(MDL::Triangle_MDL3) * pcHeader->num_tris;
  554. #ifdef AI_BUILD_BIG_ENDIAN
  555. for (int i = 0; i < pcHeader->synctype; ++i) {
  556. AI_SWAP2(pcTexCoords[i].u);
  557. AI_SWAP2(pcTexCoords[i].v);
  558. }
  559. for (int i = 0; i < pcHeader->num_tris; ++i) {
  560. AI_SWAP2(pcTriangles[i].index_xyz[0]);
  561. AI_SWAP2(pcTriangles[i].index_xyz[1]);
  562. AI_SWAP2(pcTriangles[i].index_xyz[2]);
  563. AI_SWAP2(pcTriangles[i].index_uv[0]);
  564. AI_SWAP2(pcTriangles[i].index_uv[1]);
  565. AI_SWAP2(pcTriangles[i].index_uv[2]);
  566. }
  567. #endif
  568. VALIDATE_FILE_SIZE(szCurrent);
  569. // setup materials
  570. SetupMaterialProperties_3DGS_MDL5_Quake1();
  571. // allocate enough storage to hold all vertices and triangles
  572. aiMesh *pcMesh = new aiMesh();
  573. pcMesh->mPrimitiveTypes = aiPrimitiveType_TRIANGLE;
  574. pcMesh->mNumVertices = pcHeader->num_tris * 3;
  575. pcMesh->mNumFaces = pcHeader->num_tris;
  576. pcMesh->mFaces = new aiFace[pcMesh->mNumFaces];
  577. // there won't be more than one mesh inside the file
  578. pScene->mRootNode = new aiNode();
  579. pScene->mRootNode->mNumMeshes = 1;
  580. pScene->mRootNode->mMeshes = new unsigned int[1];
  581. pScene->mRootNode->mMeshes[0] = 0;
  582. pScene->mNumMeshes = 1;
  583. pScene->mMeshes = new aiMesh *[1];
  584. pScene->mMeshes[0] = pcMesh;
  585. // allocate output storage
  586. pcMesh->mNumVertices = (unsigned int)pcHeader->num_tris * 3;
  587. pcMesh->mVertices = new aiVector3D[pcMesh->mNumVertices];
  588. pcMesh->mNormals = new aiVector3D[pcMesh->mNumVertices];
  589. if (pcHeader->synctype) {
  590. pcMesh->mTextureCoords[0] = new aiVector3D[pcMesh->mNumVertices];
  591. pcMesh->mNumUVComponents[0] = 2;
  592. }
  593. // now get a pointer to the first frame in the file
  594. BE_NCONST MDL::Frame *pcFrames = (BE_NCONST MDL::Frame *)szCurrent;
  595. AI_SWAP4(pcFrames->type);
  596. // byte packed vertices
  597. // FIXME: these two snippets below are almost identical ... join them?
  598. /////////////////////////////////////////////////////////////////////////////////////
  599. if (0 == pcFrames->type || 3 >= this->iGSFileVersion) {
  600. const MDL::SimpleFrame *pcFirstFrame = (const MDL::SimpleFrame *)(szCurrent + sizeof(uint32_t));
  601. const MDL::Vertex *pcVertices = (const MDL::Vertex *)((pcFirstFrame->name) + sizeof(pcFirstFrame->name));
  602. VALIDATE_FILE_SIZE(pcVertices + pcHeader->num_verts);
  603. // now iterate through all triangles
  604. unsigned int iCurrent = 0;
  605. for (unsigned int i = 0; i < (unsigned int)pcHeader->num_tris; ++i) {
  606. pcMesh->mFaces[i].mIndices = new unsigned int[3];
  607. pcMesh->mFaces[i].mNumIndices = 3;
  608. unsigned int iTemp = iCurrent;
  609. for (unsigned int c = 0; c < 3; ++c, ++iCurrent) {
  610. // read vertices
  611. unsigned int iIndex = pcTriangles->index_xyz[c];
  612. if (iIndex >= (unsigned int)pcHeader->num_verts) {
  613. iIndex = pcHeader->num_verts - 1;
  614. ASSIMP_LOG_WARN("Index overflow in MDLn vertex list");
  615. }
  616. aiVector3D &vec = pcMesh->mVertices[iCurrent];
  617. vec.x = (float)pcVertices[iIndex].v[0] * pcHeader->scale[0];
  618. vec.x += pcHeader->translate[0];
  619. vec.y = (float)pcVertices[iIndex].v[1] * pcHeader->scale[1];
  620. vec.y += pcHeader->translate[1];
  621. // vec.y *= -1.0f;
  622. vec.z = (float)pcVertices[iIndex].v[2] * pcHeader->scale[2];
  623. vec.z += pcHeader->translate[2];
  624. // read the normal vector from the precalculated normal table
  625. MD2::LookupNormalIndex(pcVertices[iIndex].normalIndex, pcMesh->mNormals[iCurrent]);
  626. // pcMesh->mNormals[iCurrent].y *= -1.0f;
  627. // read texture coordinates
  628. if (pcHeader->synctype) {
  629. ImportUVCoordinate_3DGS_MDL345(pcMesh->mTextureCoords[0][iCurrent],
  630. pcTexCoords, pcTriangles->index_uv[c]);
  631. }
  632. }
  633. pcMesh->mFaces[i].mIndices[0] = iTemp + 2;
  634. pcMesh->mFaces[i].mIndices[1] = iTemp + 1;
  635. pcMesh->mFaces[i].mIndices[2] = iTemp + 0;
  636. pcTriangles++;
  637. }
  638. }
  639. // short packed vertices
  640. /////////////////////////////////////////////////////////////////////////////////////
  641. else {
  642. // now get a pointer to the first frame in the file
  643. const MDL::SimpleFrame_MDLn_SP *pcFirstFrame = (const MDL::SimpleFrame_MDLn_SP *)(szCurrent + sizeof(uint32_t));
  644. // get a pointer to the vertices
  645. const MDL::Vertex_MDL4 *pcVertices = (const MDL::Vertex_MDL4 *)((pcFirstFrame->name) +
  646. sizeof(pcFirstFrame->name));
  647. VALIDATE_FILE_SIZE(pcVertices + pcHeader->num_verts);
  648. // now iterate through all triangles
  649. unsigned int iCurrent = 0;
  650. for (unsigned int i = 0; i < (unsigned int)pcHeader->num_tris; ++i) {
  651. pcMesh->mFaces[i].mIndices = new unsigned int[3];
  652. pcMesh->mFaces[i].mNumIndices = 3;
  653. unsigned int iTemp = iCurrent;
  654. for (unsigned int c = 0; c < 3; ++c, ++iCurrent) {
  655. // read vertices
  656. unsigned int iIndex = pcTriangles->index_xyz[c];
  657. if (iIndex >= (unsigned int)pcHeader->num_verts) {
  658. iIndex = pcHeader->num_verts - 1;
  659. ASSIMP_LOG_WARN("Index overflow in MDLn vertex list");
  660. }
  661. aiVector3D &vec = pcMesh->mVertices[iCurrent];
  662. vec.x = (float)pcVertices[iIndex].v[0] * pcHeader->scale[0];
  663. vec.x += pcHeader->translate[0];
  664. vec.y = (float)pcVertices[iIndex].v[1] * pcHeader->scale[1];
  665. vec.y += pcHeader->translate[1];
  666. // vec.y *= -1.0f;
  667. vec.z = (float)pcVertices[iIndex].v[2] * pcHeader->scale[2];
  668. vec.z += pcHeader->translate[2];
  669. // read the normal vector from the precalculated normal table
  670. MD2::LookupNormalIndex(pcVertices[iIndex].normalIndex, pcMesh->mNormals[iCurrent]);
  671. // pcMesh->mNormals[iCurrent].y *= -1.0f;
  672. // read texture coordinates
  673. if (pcHeader->synctype) {
  674. ImportUVCoordinate_3DGS_MDL345(pcMesh->mTextureCoords[0][iCurrent],
  675. pcTexCoords, pcTriangles->index_uv[c]);
  676. }
  677. }
  678. pcMesh->mFaces[i].mIndices[0] = iTemp + 2;
  679. pcMesh->mFaces[i].mIndices[1] = iTemp + 1;
  680. pcMesh->mFaces[i].mIndices[2] = iTemp + 0;
  681. pcTriangles++;
  682. }
  683. }
  684. // For MDL5 we will need to build valid texture coordinates
  685. // basing upon the file loaded (only support one file as skin)
  686. if (0x5 == iGSFileVersion)
  687. CalculateUVCoordinates_MDL5();
  688. return;
  689. }
  690. // ------------------------------------------------------------------------------------------------
  691. // Get a single UV coordinate for Quake and older GameStudio files
  692. void MDLImporter::ImportUVCoordinate_3DGS_MDL345(
  693. aiVector3D &vOut,
  694. const MDL::TexCoord_MDL3 *pcSrc,
  695. unsigned int iIndex) {
  696. ai_assert(nullptr != pcSrc);
  697. const MDL::Header *const pcHeader = (const MDL::Header *)this->mBuffer;
  698. // validate UV indices
  699. if (iIndex >= (unsigned int)pcHeader->synctype) {
  700. iIndex = pcHeader->synctype - 1;
  701. ASSIMP_LOG_WARN("Index overflow in MDLn UV coord list");
  702. }
  703. float s = (float)pcSrc[iIndex].u;
  704. float t = (float)pcSrc[iIndex].v;
  705. // Scale s and t to range from 0.0 to 1.0
  706. if (0x5 != iGSFileVersion) {
  707. s = (s + 0.5f) / pcHeader->skinwidth;
  708. t = 1.0f - (t + 0.5f) / pcHeader->skinheight;
  709. }
  710. vOut.x = s;
  711. vOut.y = t;
  712. vOut.z = 0.0f;
  713. }
  714. // ------------------------------------------------------------------------------------------------
  715. // Compute UV coordinates for a MDL5 file
  716. void MDLImporter::CalculateUVCoordinates_MDL5() {
  717. const MDL::Header *const pcHeader = (const MDL::Header *)this->mBuffer;
  718. if (pcHeader->num_skins && this->pScene->mNumTextures) {
  719. const aiTexture *pcTex = this->pScene->mTextures[0];
  720. // if the file is loaded in DDS format: get the size of the
  721. // texture from the header of the DDS file
  722. // skip three DWORDs and read first height, then the width
  723. unsigned int iWidth, iHeight;
  724. if (!pcTex->mHeight) {
  725. const uint32_t *piPtr = (uint32_t *)pcTex->pcData;
  726. piPtr += 3;
  727. iHeight = (unsigned int)*piPtr++;
  728. iWidth = (unsigned int)*piPtr;
  729. if (!iHeight || !iWidth) {
  730. ASSIMP_LOG_WARN("Either the width or the height of the "
  731. "embedded DDS texture is zero. Unable to compute final texture "
  732. "coordinates. The texture coordinates remain in their original "
  733. "0-x/0-y (x,y = texture size) range.");
  734. iWidth = 1;
  735. iHeight = 1;
  736. }
  737. } else {
  738. iWidth = pcTex->mWidth;
  739. iHeight = pcTex->mHeight;
  740. }
  741. if (1 != iWidth || 1 != iHeight) {
  742. const float fWidth = (float)iWidth;
  743. const float fHeight = (float)iHeight;
  744. aiMesh *pcMesh = this->pScene->mMeshes[0];
  745. for (unsigned int i = 0; i < pcMesh->mNumVertices; ++i) {
  746. if (!pcMesh->HasTextureCoords(0)) {
  747. continue;
  748. }
  749. pcMesh->mTextureCoords[0][i].x /= fWidth;
  750. pcMesh->mTextureCoords[0][i].y /= fHeight;
  751. pcMesh->mTextureCoords[0][i].y = 1.0f - pcMesh->mTextureCoords[0][i].y; // DX to OGL
  752. }
  753. }
  754. }
  755. }
  756. // ------------------------------------------------------------------------------------------------
  757. // Validate the header of a MDL7 file
  758. void MDLImporter::ValidateHeader_3DGS_MDL7(const MDL::Header_MDL7 *pcHeader) {
  759. ai_assert(nullptr != pcHeader);
  760. // There are some fixed sizes ...
  761. if (sizeof(MDL::ColorValue_MDL7) != pcHeader->colorvalue_stc_size) {
  762. throw DeadlyImportError(
  763. "[3DGS MDL7] sizeof(MDL::ColorValue_MDL7) != pcHeader->colorvalue_stc_size");
  764. }
  765. if (sizeof(MDL::TexCoord_MDL7) != pcHeader->skinpoint_stc_size) {
  766. throw DeadlyImportError(
  767. "[3DGS MDL7] sizeof(MDL::TexCoord_MDL7) != pcHeader->skinpoint_stc_size");
  768. }
  769. if (sizeof(MDL::Skin_MDL7) != pcHeader->skin_stc_size) {
  770. throw DeadlyImportError(
  771. "sizeof(MDL::Skin_MDL7) != pcHeader->skin_stc_size");
  772. }
  773. // if there are no groups ... how should we load such a file?
  774. if (!pcHeader->groups_num) {
  775. throw DeadlyImportError("[3DGS MDL7] No frames found");
  776. }
  777. }
  778. // ------------------------------------------------------------------------------------------------
  779. // resolve bone animation matrices
  780. void MDLImporter::CalcAbsBoneMatrices_3DGS_MDL7(MDL::IntBone_MDL7 **apcOutBones) {
  781. const MDL::Header_MDL7 *pcHeader = (const MDL::Header_MDL7 *)this->mBuffer;
  782. const MDL::Bone_MDL7 *pcBones = (const MDL::Bone_MDL7 *)(pcHeader + 1);
  783. ai_assert(nullptr != apcOutBones);
  784. // first find the bone that has NO parent, calculate the
  785. // animation matrix for it, then go on and search for the next parent
  786. // index (0) and so on until we can't find a new node.
  787. uint16_t iParent = 0xffff;
  788. uint32_t iIterations = 0;
  789. while (iIterations++ < pcHeader->bones_num) {
  790. for (uint32_t iBone = 0; iBone < pcHeader->bones_num; ++iBone) {
  791. BE_NCONST MDL::Bone_MDL7 *pcBone = _AI_MDL7_ACCESS_PTR(pcBones, iBone,
  792. pcHeader->bone_stc_size, MDL::Bone_MDL7);
  793. AI_SWAP2(pcBone->parent_index);
  794. AI_SWAP4(pcBone->x);
  795. AI_SWAP4(pcBone->y);
  796. AI_SWAP4(pcBone->z);
  797. if (iParent == pcBone->parent_index) {
  798. // MDL7 readme
  799. ////////////////////////////////////////////////////////////////
  800. /*
  801. The animation matrix is then calculated the following way:
  802. vector3 bPos = <absolute bone position>
  803. matrix44 laM; // local animation matrix
  804. sphrvector key_rotate = <bone rotation>
  805. matrix44 m1,m2;
  806. create_trans_matrix(m1, -bPos.x, -bPos.y, -bPos.z);
  807. create_trans_matrix(m2, -bPos.x, -bPos.y, -bPos.z);
  808. create_rotation_matrix(laM,key_rotate);
  809. laM = sm1 * laM;
  810. laM = laM * sm2;
  811. */
  812. /////////////////////////////////////////////////////////////////
  813. MDL::IntBone_MDL7 *const pcOutBone = apcOutBones[iBone];
  814. // store the parent index of the bone
  815. pcOutBone->iParent = pcBone->parent_index;
  816. if (0xffff != iParent) {
  817. const MDL::IntBone_MDL7 *pcParentBone = apcOutBones[iParent];
  818. pcOutBone->mOffsetMatrix.a4 = -pcParentBone->vPosition.x;
  819. pcOutBone->mOffsetMatrix.b4 = -pcParentBone->vPosition.y;
  820. pcOutBone->mOffsetMatrix.c4 = -pcParentBone->vPosition.z;
  821. }
  822. pcOutBone->vPosition.x = pcBone->x;
  823. pcOutBone->vPosition.y = pcBone->y;
  824. pcOutBone->vPosition.z = pcBone->z;
  825. pcOutBone->mOffsetMatrix.a4 -= pcBone->x;
  826. pcOutBone->mOffsetMatrix.b4 -= pcBone->y;
  827. pcOutBone->mOffsetMatrix.c4 -= pcBone->z;
  828. if (AI_MDL7_BONE_STRUCT_SIZE__NAME_IS_NOT_THERE == pcHeader->bone_stc_size) {
  829. // no real name for our poor bone is specified :-(
  830. pcOutBone->mName.length = ai_snprintf(pcOutBone->mName.data, AI_MAXLEN,
  831. "UnnamedBone_%i", iBone);
  832. } else {
  833. // Make sure we won't run over the buffer's end if there is no
  834. // terminal 0 character (however the documentation says there
  835. // should be one)
  836. uint32_t iMaxLen = pcHeader->bone_stc_size - 16;
  837. for (uint32_t qq = 0; qq < iMaxLen; ++qq) {
  838. if (!pcBone->name[qq]) {
  839. iMaxLen = qq;
  840. break;
  841. }
  842. }
  843. // store the name of the bone
  844. pcOutBone->mName.length = static_cast<ai_uint32>(iMaxLen);
  845. ::memcpy(pcOutBone->mName.data, pcBone->name, pcOutBone->mName.length);
  846. pcOutBone->mName.data[pcOutBone->mName.length] = '\0';
  847. }
  848. }
  849. }
  850. ++iParent;
  851. }
  852. }
  853. // ------------------------------------------------------------------------------------------------
  854. // read bones from a MDL7 file
  855. MDL::IntBone_MDL7 **MDLImporter::LoadBones_3DGS_MDL7() {
  856. const MDL::Header_MDL7 *pcHeader = (const MDL::Header_MDL7 *)this->mBuffer;
  857. if (pcHeader->bones_num) {
  858. // validate the size of the bone data structure in the file
  859. if (AI_MDL7_BONE_STRUCT_SIZE__NAME_IS_20_CHARS != pcHeader->bone_stc_size &&
  860. AI_MDL7_BONE_STRUCT_SIZE__NAME_IS_32_CHARS != pcHeader->bone_stc_size &&
  861. AI_MDL7_BONE_STRUCT_SIZE__NAME_IS_NOT_THERE != pcHeader->bone_stc_size) {
  862. ASSIMP_LOG_WARN("Unknown size of bone data structure");
  863. return nullptr;
  864. }
  865. MDL::IntBone_MDL7 **apcBonesOut = new MDL::IntBone_MDL7 *[pcHeader->bones_num];
  866. for (uint32_t crank = 0; crank < pcHeader->bones_num; ++crank)
  867. apcBonesOut[crank] = new MDL::IntBone_MDL7();
  868. // and calculate absolute bone offset matrices ...
  869. CalcAbsBoneMatrices_3DGS_MDL7(apcBonesOut);
  870. return apcBonesOut;
  871. }
  872. return nullptr;
  873. }
  874. // ------------------------------------------------------------------------------------------------
  875. // read faces from a MDL7 file
  876. void MDLImporter::ReadFaces_3DGS_MDL7(const MDL::IntGroupInfo_MDL7 &groupInfo,
  877. MDL::IntGroupData_MDL7 &groupData) {
  878. const MDL::Header_MDL7 *pcHeader = (const MDL::Header_MDL7 *)this->mBuffer;
  879. MDL::Triangle_MDL7 *pcGroupTris = groupInfo.pcGroupTris;
  880. // iterate through all triangles and build valid display lists
  881. unsigned int iOutIndex = 0;
  882. for (unsigned int iTriangle = 0; iTriangle < (unsigned int)groupInfo.pcGroup->numtris; ++iTriangle) {
  883. AI_SWAP2(pcGroupTris->v_index[0]);
  884. AI_SWAP2(pcGroupTris->v_index[1]);
  885. AI_SWAP2(pcGroupTris->v_index[2]);
  886. // iterate through all indices of the current triangle
  887. for (unsigned int c = 0; c < 3; ++c, ++iOutIndex) {
  888. // validate the vertex index
  889. unsigned int iIndex = pcGroupTris->v_index[c];
  890. if (iIndex > (unsigned int)groupInfo.pcGroup->numverts) {
  891. // (we might need to read this section a second time - to process frame vertices correctly)
  892. pcGroupTris->v_index[c] = (uint16_t)(iIndex = groupInfo.pcGroup->numverts - 1);
  893. ASSIMP_LOG_WARN("Index overflow in MDL7 vertex list");
  894. }
  895. // write the output face index
  896. groupData.pcFaces[iTriangle].mIndices[2 - c] = iOutIndex;
  897. aiVector3D &vPosition = groupData.vPositions[iOutIndex];
  898. vPosition.x = _AI_MDL7_ACCESS_VERT(groupInfo.pcGroupVerts, iIndex, pcHeader->mainvertex_stc_size).x;
  899. vPosition.y = _AI_MDL7_ACCESS_VERT(groupInfo.pcGroupVerts, iIndex, pcHeader->mainvertex_stc_size).y;
  900. vPosition.z = _AI_MDL7_ACCESS_VERT(groupInfo.pcGroupVerts, iIndex, pcHeader->mainvertex_stc_size).z;
  901. // if we have bones, save the index
  902. if (!groupData.aiBones.empty()) {
  903. groupData.aiBones[iOutIndex] = _AI_MDL7_ACCESS_VERT(groupInfo.pcGroupVerts,
  904. iIndex, pcHeader->mainvertex_stc_size)
  905. .vertindex;
  906. }
  907. // now read the normal vector
  908. if (AI_MDL7_FRAMEVERTEX030305_STCSIZE <= pcHeader->mainvertex_stc_size) {
  909. // read the full normal vector
  910. aiVector3D &vNormal = groupData.vNormals[iOutIndex];
  911. vNormal.x = _AI_MDL7_ACCESS_VERT(groupInfo.pcGroupVerts, iIndex, pcHeader->mainvertex_stc_size).norm[0];
  912. AI_SWAP4(vNormal.x);
  913. vNormal.y = _AI_MDL7_ACCESS_VERT(groupInfo.pcGroupVerts, iIndex, pcHeader->mainvertex_stc_size).norm[1];
  914. AI_SWAP4(vNormal.y);
  915. vNormal.z = _AI_MDL7_ACCESS_VERT(groupInfo.pcGroupVerts, iIndex, pcHeader->mainvertex_stc_size).norm[2];
  916. AI_SWAP4(vNormal.z);
  917. } else if (AI_MDL7_FRAMEVERTEX120503_STCSIZE <= pcHeader->mainvertex_stc_size) {
  918. // read the normal vector from Quake2's smart table
  919. aiVector3D &vNormal = groupData.vNormals[iOutIndex];
  920. MD2::LookupNormalIndex(_AI_MDL7_ACCESS_VERT(groupInfo.pcGroupVerts, iIndex,
  921. pcHeader->mainvertex_stc_size)
  922. .norm162index,
  923. vNormal);
  924. }
  925. // validate and process the first uv coordinate set
  926. if (pcHeader->triangle_stc_size >= AI_MDL7_TRIANGLE_STD_SIZE_ONE_UV) {
  927. if (groupInfo.pcGroup->num_stpts) {
  928. AI_SWAP2(pcGroupTris->skinsets[0].st_index[0]);
  929. AI_SWAP2(pcGroupTris->skinsets[0].st_index[1]);
  930. AI_SWAP2(pcGroupTris->skinsets[0].st_index[2]);
  931. iIndex = pcGroupTris->skinsets[0].st_index[c];
  932. if (iIndex > (unsigned int)groupInfo.pcGroup->num_stpts) {
  933. iIndex = groupInfo.pcGroup->num_stpts - 1;
  934. ASSIMP_LOG_WARN("Index overflow in MDL7 UV coordinate list (#1)");
  935. }
  936. float u = groupInfo.pcGroupUVs[iIndex].u;
  937. float v = 1.0f - groupInfo.pcGroupUVs[iIndex].v; // DX to OGL
  938. groupData.vTextureCoords1[iOutIndex].x = u;
  939. groupData.vTextureCoords1[iOutIndex].y = v;
  940. }
  941. // assign the material index, but only if it is existing
  942. if (pcHeader->triangle_stc_size >= AI_MDL7_TRIANGLE_STD_SIZE_ONE_UV_WITH_MATINDEX) {
  943. AI_SWAP4(pcGroupTris->skinsets[0].material);
  944. groupData.pcFaces[iTriangle].iMatIndex[0] = pcGroupTris->skinsets[0].material;
  945. }
  946. }
  947. // validate and process the second uv coordinate set
  948. if (pcHeader->triangle_stc_size >= AI_MDL7_TRIANGLE_STD_SIZE_TWO_UV) {
  949. if (groupInfo.pcGroup->num_stpts) {
  950. AI_SWAP2(pcGroupTris->skinsets[1].st_index[0]);
  951. AI_SWAP2(pcGroupTris->skinsets[1].st_index[1]);
  952. AI_SWAP2(pcGroupTris->skinsets[1].st_index[2]);
  953. AI_SWAP4(pcGroupTris->skinsets[1].material);
  954. iIndex = pcGroupTris->skinsets[1].st_index[c];
  955. if (iIndex > (unsigned int)groupInfo.pcGroup->num_stpts) {
  956. iIndex = groupInfo.pcGroup->num_stpts - 1;
  957. ASSIMP_LOG_WARN("Index overflow in MDL7 UV coordinate list (#2)");
  958. }
  959. float u = groupInfo.pcGroupUVs[iIndex].u;
  960. float v = 1.0f - groupInfo.pcGroupUVs[iIndex].v;
  961. groupData.vTextureCoords2[iOutIndex].x = u;
  962. groupData.vTextureCoords2[iOutIndex].y = v; // DX to OGL
  963. // check whether we do really need the second texture
  964. // coordinate set ... wastes memory and loading time
  965. if (0 != iIndex && (u != groupData.vTextureCoords1[iOutIndex].x ||
  966. v != groupData.vTextureCoords1[iOutIndex].y))
  967. groupData.bNeed2UV = true;
  968. // if the material differs, we need a second skin, too
  969. if (pcGroupTris->skinsets[1].material != pcGroupTris->skinsets[0].material)
  970. groupData.bNeed2UV = true;
  971. }
  972. // assign the material index
  973. groupData.pcFaces[iTriangle].iMatIndex[1] = pcGroupTris->skinsets[1].material;
  974. }
  975. }
  976. // get the next triangle in the list
  977. pcGroupTris = (MDL::Triangle_MDL7 *)((const char *)pcGroupTris + pcHeader->triangle_stc_size);
  978. }
  979. }
  980. // ------------------------------------------------------------------------------------------------
  981. // handle frames in a MDL7 file
  982. bool MDLImporter::ProcessFrames_3DGS_MDL7(const MDL::IntGroupInfo_MDL7 &groupInfo,
  983. MDL::IntGroupData_MDL7 &groupData,
  984. MDL::IntSharedData_MDL7 &shared,
  985. const unsigned char *szCurrent,
  986. const unsigned char **szCurrentOut) {
  987. ai_assert(nullptr != szCurrent);
  988. ai_assert(nullptr != szCurrentOut);
  989. const MDL::Header_MDL7 *pcHeader = (const MDL::Header_MDL7 *)mBuffer;
  990. // if we have no bones we can simply skip all frames,
  991. // otherwise we'll need to process them.
  992. // FIX: If we need another frame than the first we must apply frame vertex replacements ...
  993. for (unsigned int iFrame = 0; iFrame < (unsigned int)groupInfo.pcGroup->numframes; ++iFrame) {
  994. MDL::IntFrameInfo_MDL7 frame((BE_NCONST MDL::Frame_MDL7 *)szCurrent, iFrame);
  995. AI_SWAP4(frame.pcFrame->vertices_count);
  996. AI_SWAP4(frame.pcFrame->transmatrix_count);
  997. const unsigned int iAdd = pcHeader->frame_stc_size +
  998. frame.pcFrame->vertices_count * pcHeader->framevertex_stc_size +
  999. frame.pcFrame->transmatrix_count * pcHeader->bonetrans_stc_size;
  1000. if (((const char *)szCurrent - (const char *)pcHeader) + iAdd > (unsigned int)pcHeader->data_size) {
  1001. ASSIMP_LOG_WARN("Index overflow in frame area. "
  1002. "Ignoring all frames and all further mesh groups, too.");
  1003. // don't parse more groups if we can't even read one
  1004. // FIXME: sometimes this seems to occur even for valid files ...
  1005. *szCurrentOut = szCurrent;
  1006. return false;
  1007. }
  1008. // our output frame?
  1009. if (configFrameID == iFrame) {
  1010. BE_NCONST MDL::Vertex_MDL7 *pcFrameVertices = (BE_NCONST MDL::Vertex_MDL7 *)(szCurrent + pcHeader->frame_stc_size);
  1011. for (unsigned int qq = 0; qq < frame.pcFrame->vertices_count; ++qq) {
  1012. // I assume this are simple replacements for normal vertices, the bone index serving
  1013. // as the index of the vertex to be replaced.
  1014. uint16_t iIndex = _AI_MDL7_ACCESS(pcFrameVertices, qq, pcHeader->framevertex_stc_size, MDL::Vertex_MDL7).vertindex;
  1015. AI_SWAP2(iIndex);
  1016. if (iIndex >= groupInfo.pcGroup->numverts) {
  1017. ASSIMP_LOG_WARN("Invalid vertex index in frame vertex section");
  1018. continue;
  1019. }
  1020. aiVector3D vPosition, vNormal;
  1021. vPosition.x = _AI_MDL7_ACCESS_VERT(pcFrameVertices, qq, pcHeader->framevertex_stc_size).x;
  1022. AI_SWAP4(vPosition.x);
  1023. vPosition.y = _AI_MDL7_ACCESS_VERT(pcFrameVertices, qq, pcHeader->framevertex_stc_size).y;
  1024. AI_SWAP4(vPosition.y);
  1025. vPosition.z = _AI_MDL7_ACCESS_VERT(pcFrameVertices, qq, pcHeader->framevertex_stc_size).z;
  1026. AI_SWAP4(vPosition.z);
  1027. // now read the normal vector
  1028. if (AI_MDL7_FRAMEVERTEX030305_STCSIZE <= pcHeader->mainvertex_stc_size) {
  1029. // read the full normal vector
  1030. vNormal.x = _AI_MDL7_ACCESS_VERT(pcFrameVertices, qq, pcHeader->framevertex_stc_size).norm[0];
  1031. AI_SWAP4(vNormal.x);
  1032. vNormal.y = _AI_MDL7_ACCESS_VERT(pcFrameVertices, qq, pcHeader->framevertex_stc_size).norm[1];
  1033. AI_SWAP4(vNormal.y);
  1034. vNormal.z = _AI_MDL7_ACCESS_VERT(pcFrameVertices, qq, pcHeader->framevertex_stc_size).norm[2];
  1035. AI_SWAP4(vNormal.z);
  1036. } else if (AI_MDL7_FRAMEVERTEX120503_STCSIZE <= pcHeader->mainvertex_stc_size) {
  1037. // read the normal vector from Quake2's smart table
  1038. MD2::LookupNormalIndex(_AI_MDL7_ACCESS_VERT(pcFrameVertices, qq,
  1039. pcHeader->framevertex_stc_size)
  1040. .norm162index,
  1041. vNormal);
  1042. }
  1043. // FIXME: O(n^2) at the moment ...
  1044. BE_NCONST MDL::Triangle_MDL7 *pcGroupTris = groupInfo.pcGroupTris;
  1045. unsigned int iOutIndex = 0;
  1046. for (unsigned int iTriangle = 0; iTriangle < (unsigned int)groupInfo.pcGroup->numtris; ++iTriangle) {
  1047. // iterate through all indices of the current triangle
  1048. for (unsigned int c = 0; c < 3; ++c, ++iOutIndex) {
  1049. // replace the vertex with the new data
  1050. const unsigned int iCurIndex = pcGroupTris->v_index[c];
  1051. if (iCurIndex == iIndex) {
  1052. groupData.vPositions[iOutIndex] = vPosition;
  1053. groupData.vNormals[iOutIndex] = vNormal;
  1054. }
  1055. }
  1056. // get the next triangle in the list
  1057. pcGroupTris = (BE_NCONST MDL::Triangle_MDL7 *)((const char *)
  1058. pcGroupTris +
  1059. pcHeader->triangle_stc_size);
  1060. }
  1061. }
  1062. }
  1063. // parse bone trafo matrix keys (only if there are bones ...)
  1064. if (shared.apcOutBones) {
  1065. ParseBoneTrafoKeys_3DGS_MDL7(groupInfo, frame, shared);
  1066. }
  1067. szCurrent += iAdd;
  1068. }
  1069. *szCurrentOut = szCurrent;
  1070. return true;
  1071. }
  1072. // ------------------------------------------------------------------------------------------------
  1073. // Sort faces by material, handle multiple UVs correctly
  1074. void MDLImporter::SortByMaterials_3DGS_MDL7(
  1075. const MDL::IntGroupInfo_MDL7 &groupInfo,
  1076. MDL::IntGroupData_MDL7 &groupData,
  1077. MDL::IntSplitGroupData_MDL7 &splitGroupData) {
  1078. const unsigned int iNumMaterials = (unsigned int)splitGroupData.shared.pcMats.size();
  1079. if (!groupData.bNeed2UV) {
  1080. // if we don't need a second set of texture coordinates there is no reason to keep it in memory ...
  1081. groupData.vTextureCoords2.clear();
  1082. // allocate the array
  1083. splitGroupData.aiSplit = new std::vector<unsigned int> *[iNumMaterials];
  1084. for (unsigned int m = 0; m < iNumMaterials; ++m)
  1085. splitGroupData.aiSplit[m] = new std::vector<unsigned int>();
  1086. // iterate through all faces and sort by material
  1087. for (unsigned int iFace = 0; iFace < (unsigned int)groupInfo.pcGroup->numtris; ++iFace) {
  1088. // check range
  1089. if (groupData.pcFaces[iFace].iMatIndex[0] >= iNumMaterials) {
  1090. // use the last material instead
  1091. splitGroupData.aiSplit[iNumMaterials - 1]->push_back(iFace);
  1092. // sometimes MED writes -1, but normally only if there is only
  1093. // one skin assigned. No warning in this case
  1094. if (0xFFFFFFFF != groupData.pcFaces[iFace].iMatIndex[0])
  1095. ASSIMP_LOG_WARN("Index overflow in MDL7 material list [#0]");
  1096. } else
  1097. splitGroupData.aiSplit[groupData.pcFaces[iFace].iMatIndex[0]]->push_back(iFace);
  1098. }
  1099. } else {
  1100. // we need to build combined materials for each combination of
  1101. std::vector<MDL::IntMaterial_MDL7> avMats;
  1102. avMats.reserve(iNumMaterials * 2);
  1103. // fixme: why on the heap?
  1104. std::vector<std::vector<unsigned int> *> aiTempSplit(iNumMaterials * 2);
  1105. for (unsigned int m = 0; m < iNumMaterials; ++m)
  1106. aiTempSplit[m] = new std::vector<unsigned int>();
  1107. // iterate through all faces and sort by material
  1108. for (unsigned int iFace = 0; iFace < (unsigned int)groupInfo.pcGroup->numtris; ++iFace) {
  1109. // check range
  1110. unsigned int iMatIndex = groupData.pcFaces[iFace].iMatIndex[0];
  1111. if (iMatIndex >= iNumMaterials) {
  1112. // sometimes MED writes -1, but normally only if there is only
  1113. // one skin assigned. No warning in this case
  1114. if (UINT_MAX != iMatIndex)
  1115. ASSIMP_LOG_WARN("Index overflow in MDL7 material list [#1]");
  1116. iMatIndex = iNumMaterials - 1;
  1117. }
  1118. unsigned int iMatIndex2 = groupData.pcFaces[iFace].iMatIndex[1];
  1119. unsigned int iNum = iMatIndex;
  1120. if (UINT_MAX != iMatIndex2 && iMatIndex != iMatIndex2) {
  1121. if (iMatIndex2 >= iNumMaterials) {
  1122. // sometimes MED writes -1, but normally only if there is only
  1123. // one skin assigned. No warning in this case
  1124. ASSIMP_LOG_WARN("Index overflow in MDL7 material list [#2]");
  1125. iMatIndex2 = iNumMaterials - 1;
  1126. }
  1127. // do a slow search in the list ...
  1128. iNum = 0;
  1129. bool bFound = false;
  1130. for (std::vector<MDL::IntMaterial_MDL7>::iterator i = avMats.begin(); i != avMats.end(); ++i, ++iNum) {
  1131. if ((*i).iOldMatIndices[0] == iMatIndex && (*i).iOldMatIndices[1] == iMatIndex2) {
  1132. // reuse this material
  1133. bFound = true;
  1134. break;
  1135. }
  1136. }
  1137. if (!bFound) {
  1138. // build a new material ...
  1139. MDL::IntMaterial_MDL7 sHelper;
  1140. sHelper.pcMat = new aiMaterial();
  1141. sHelper.iOldMatIndices[0] = iMatIndex;
  1142. sHelper.iOldMatIndices[1] = iMatIndex2;
  1143. JoinSkins_3DGS_MDL7(splitGroupData.shared.pcMats[iMatIndex],
  1144. splitGroupData.shared.pcMats[iMatIndex2], sHelper.pcMat);
  1145. // and add it to the list
  1146. avMats.push_back(sHelper);
  1147. iNum = (unsigned int)avMats.size() - 1;
  1148. }
  1149. // adjust the size of the file array
  1150. if (iNum == aiTempSplit.size()) {
  1151. aiTempSplit.push_back(new std::vector<unsigned int>());
  1152. }
  1153. }
  1154. aiTempSplit[iNum]->push_back(iFace);
  1155. }
  1156. // now add the newly created materials to the old list
  1157. if (0 == groupInfo.iIndex) {
  1158. splitGroupData.shared.pcMats.resize(avMats.size());
  1159. for (unsigned int o = 0; o < avMats.size(); ++o)
  1160. splitGroupData.shared.pcMats[o] = avMats[o].pcMat;
  1161. } else {
  1162. // This might result in redundant materials ...
  1163. splitGroupData.shared.pcMats.resize(iNumMaterials + avMats.size());
  1164. for (unsigned int o = iNumMaterials; o < avMats.size(); ++o)
  1165. splitGroupData.shared.pcMats[o] = avMats[o].pcMat;
  1166. }
  1167. // and build the final face-to-material array
  1168. splitGroupData.aiSplit = new std::vector<unsigned int> *[aiTempSplit.size()];
  1169. for (unsigned int m = 0; m < iNumMaterials; ++m)
  1170. splitGroupData.aiSplit[m] = aiTempSplit[m];
  1171. }
  1172. }
  1173. // ------------------------------------------------------------------------------------------------
  1174. // Read a MDL7 file
  1175. void MDLImporter::InternReadFile_3DGS_MDL7() {
  1176. ai_assert(nullptr != pScene);
  1177. MDL::IntSharedData_MDL7 sharedData;
  1178. // current cursor position in the file
  1179. BE_NCONST MDL::Header_MDL7 *pcHeader = (BE_NCONST MDL::Header_MDL7 *)this->mBuffer;
  1180. const unsigned char *szCurrent = (const unsigned char *)(pcHeader + 1);
  1181. AI_SWAP4(pcHeader->version);
  1182. AI_SWAP4(pcHeader->bones_num);
  1183. AI_SWAP4(pcHeader->groups_num);
  1184. AI_SWAP4(pcHeader->data_size);
  1185. AI_SWAP4(pcHeader->entlump_size);
  1186. AI_SWAP4(pcHeader->medlump_size);
  1187. AI_SWAP2(pcHeader->bone_stc_size);
  1188. AI_SWAP2(pcHeader->skin_stc_size);
  1189. AI_SWAP2(pcHeader->colorvalue_stc_size);
  1190. AI_SWAP2(pcHeader->material_stc_size);
  1191. AI_SWAP2(pcHeader->skinpoint_stc_size);
  1192. AI_SWAP2(pcHeader->triangle_stc_size);
  1193. AI_SWAP2(pcHeader->mainvertex_stc_size);
  1194. AI_SWAP2(pcHeader->framevertex_stc_size);
  1195. AI_SWAP2(pcHeader->bonetrans_stc_size);
  1196. AI_SWAP2(pcHeader->frame_stc_size);
  1197. // validate the header of the file. There are some structure
  1198. // sizes that are expected by the loader to be constant
  1199. this->ValidateHeader_3DGS_MDL7(pcHeader);
  1200. // load all bones (they are shared by all groups, so
  1201. // we'll need to add them to all groups/meshes later)
  1202. // apcBonesOut is a list of all bones or nullptr if they could not been loaded
  1203. szCurrent += pcHeader->bones_num * pcHeader->bone_stc_size;
  1204. sharedData.apcOutBones = this->LoadBones_3DGS_MDL7();
  1205. // vector to held all created meshes
  1206. MeshArray *avOutList;
  1207. // 3 meshes per group - that should be OK for most models
  1208. avOutList = new MeshArray[pcHeader->groups_num];
  1209. for (uint32_t i = 0; i < pcHeader->groups_num; ++i)
  1210. avOutList[i].reserve(3);
  1211. // buffer to held the names of all groups in the file
  1212. const size_t buffersize(AI_MDL7_MAX_GROUPNAMESIZE * pcHeader->groups_num);
  1213. char *aszGroupNameBuffer = new char[buffersize];
  1214. // read all groups
  1215. for (unsigned int iGroup = 0; iGroup < (unsigned int)pcHeader->groups_num; ++iGroup) {
  1216. MDL::IntGroupInfo_MDL7 groupInfo((BE_NCONST MDL::Group_MDL7 *)szCurrent, iGroup);
  1217. szCurrent = (const unsigned char *)(groupInfo.pcGroup + 1);
  1218. VALIDATE_FILE_SIZE(szCurrent);
  1219. AI_SWAP4(groupInfo.pcGroup->groupdata_size);
  1220. AI_SWAP4(groupInfo.pcGroup->numskins);
  1221. AI_SWAP4(groupInfo.pcGroup->num_stpts);
  1222. AI_SWAP4(groupInfo.pcGroup->numtris);
  1223. AI_SWAP4(groupInfo.pcGroup->numverts);
  1224. AI_SWAP4(groupInfo.pcGroup->numframes);
  1225. if (1 != groupInfo.pcGroup->typ) {
  1226. // Not a triangle-based mesh
  1227. ASSIMP_LOG_WARN("[3DGS MDL7] Not a triangle mesh group. Continuing happily");
  1228. }
  1229. // store the name of the group
  1230. const unsigned int ofs = iGroup * AI_MDL7_MAX_GROUPNAMESIZE;
  1231. ::memcpy(&aszGroupNameBuffer[ofs],
  1232. groupInfo.pcGroup->name, AI_MDL7_MAX_GROUPNAMESIZE);
  1233. // make sure '\0' is at the end
  1234. aszGroupNameBuffer[ofs + AI_MDL7_MAX_GROUPNAMESIZE - 1] = '\0';
  1235. // read all skins
  1236. sharedData.pcMats.reserve(sharedData.pcMats.size() + groupInfo.pcGroup->numskins);
  1237. sharedData.abNeedMaterials.resize(sharedData.abNeedMaterials.size() +
  1238. groupInfo.pcGroup->numskins,
  1239. false);
  1240. for (unsigned int iSkin = 0; iSkin < (unsigned int)groupInfo.pcGroup->numskins; ++iSkin) {
  1241. ParseSkinLump_3DGS_MDL7(szCurrent, &szCurrent, sharedData.pcMats);
  1242. }
  1243. // if we have absolutely no skin loaded we need to generate a default material
  1244. if (sharedData.pcMats.empty()) {
  1245. const int iMode = (int)aiShadingMode_Gouraud;
  1246. sharedData.pcMats.push_back(new aiMaterial());
  1247. aiMaterial *pcHelper = (aiMaterial *)sharedData.pcMats[0];
  1248. pcHelper->AddProperty<int>(&iMode, 1, AI_MATKEY_SHADING_MODEL);
  1249. aiColor3D clr;
  1250. clr.b = clr.g = clr.r = 0.6f;
  1251. pcHelper->AddProperty<aiColor3D>(&clr, 1, AI_MATKEY_COLOR_DIFFUSE);
  1252. pcHelper->AddProperty<aiColor3D>(&clr, 1, AI_MATKEY_COLOR_SPECULAR);
  1253. clr.b = clr.g = clr.r = 0.05f;
  1254. pcHelper->AddProperty<aiColor3D>(&clr, 1, AI_MATKEY_COLOR_AMBIENT);
  1255. aiString szName;
  1256. szName.Set(AI_DEFAULT_MATERIAL_NAME);
  1257. pcHelper->AddProperty(&szName, AI_MATKEY_NAME);
  1258. sharedData.abNeedMaterials.resize(1, false);
  1259. }
  1260. // now get a pointer to all texture coords in the group
  1261. groupInfo.pcGroupUVs = (BE_NCONST MDL::TexCoord_MDL7 *)szCurrent;
  1262. for (int i = 0; i < groupInfo.pcGroup->num_stpts; ++i) {
  1263. AI_SWAP4(groupInfo.pcGroupUVs[i].u);
  1264. AI_SWAP4(groupInfo.pcGroupUVs[i].v);
  1265. }
  1266. szCurrent += pcHeader->skinpoint_stc_size * groupInfo.pcGroup->num_stpts;
  1267. // now get a pointer to all triangle in the group
  1268. groupInfo.pcGroupTris = (Triangle_MDL7 *)szCurrent;
  1269. szCurrent += pcHeader->triangle_stc_size * groupInfo.pcGroup->numtris;
  1270. // now get a pointer to all vertices in the group
  1271. groupInfo.pcGroupVerts = (BE_NCONST MDL::Vertex_MDL7 *)szCurrent;
  1272. for (int i = 0; i < groupInfo.pcGroup->numverts; ++i) {
  1273. AI_SWAP4(groupInfo.pcGroupVerts[i].x);
  1274. AI_SWAP4(groupInfo.pcGroupVerts[i].y);
  1275. AI_SWAP4(groupInfo.pcGroupVerts[i].z);
  1276. AI_SWAP2(groupInfo.pcGroupVerts[i].vertindex);
  1277. //We can not swap the normal information now as we don't know which of the two kinds it is
  1278. }
  1279. szCurrent += pcHeader->mainvertex_stc_size * groupInfo.pcGroup->numverts;
  1280. VALIDATE_FILE_SIZE(szCurrent);
  1281. MDL::IntSplitGroupData_MDL7 splitGroupData(sharedData, avOutList[iGroup]);
  1282. MDL::IntGroupData_MDL7 groupData;
  1283. if (groupInfo.pcGroup->numtris && groupInfo.pcGroup->numverts) {
  1284. // build output vectors
  1285. const unsigned int iNumVertices = groupInfo.pcGroup->numtris * 3;
  1286. groupData.vPositions.resize(iNumVertices);
  1287. groupData.vNormals.resize(iNumVertices);
  1288. if (sharedData.apcOutBones) groupData.aiBones.resize(iNumVertices, UINT_MAX);
  1289. // it is also possible that there are 0 UV coordinate sets
  1290. if (groupInfo.pcGroup->num_stpts) {
  1291. groupData.vTextureCoords1.resize(iNumVertices, aiVector3D());
  1292. // check whether the triangle data structure is large enough
  1293. // to contain a second UV coordinate set
  1294. if (pcHeader->triangle_stc_size >= AI_MDL7_TRIANGLE_STD_SIZE_TWO_UV) {
  1295. groupData.vTextureCoords2.resize(iNumVertices, aiVector3D());
  1296. groupData.bNeed2UV = true;
  1297. }
  1298. }
  1299. groupData.pcFaces.resize(groupInfo.pcGroup->numtris);
  1300. // read all faces into the preallocated arrays
  1301. ReadFaces_3DGS_MDL7(groupInfo, groupData);
  1302. // sort by materials
  1303. SortByMaterials_3DGS_MDL7(groupInfo, groupData,
  1304. splitGroupData);
  1305. for (unsigned int qq = 0; qq < sharedData.pcMats.size(); ++qq) {
  1306. if (!splitGroupData.aiSplit[qq]->empty())
  1307. sharedData.abNeedMaterials[qq] = true;
  1308. }
  1309. } else
  1310. ASSIMP_LOG_WARN("[3DGS MDL7] Mesh group consists of 0 "
  1311. "vertices or faces. It will be skipped.");
  1312. // process all frames and generate output meshes
  1313. ProcessFrames_3DGS_MDL7(groupInfo, groupData, sharedData, szCurrent, &szCurrent);
  1314. GenerateOutputMeshes_3DGS_MDL7(groupData, splitGroupData);
  1315. }
  1316. // generate a nodegraph and subnodes for each group
  1317. pScene->mRootNode = new aiNode();
  1318. // now we need to build a final mesh list
  1319. for (uint32_t i = 0; i < pcHeader->groups_num; ++i)
  1320. pScene->mNumMeshes += (unsigned int)avOutList[i].size();
  1321. pScene->mMeshes = new aiMesh *[pScene->mNumMeshes];
  1322. {
  1323. unsigned int p = 0, q = 0;
  1324. for (uint32_t i = 0; i < pcHeader->groups_num; ++i) {
  1325. for (unsigned int a = 0; a < avOutList[i].size(); ++a) {
  1326. pScene->mMeshes[p++] = avOutList[i][a];
  1327. }
  1328. if (!avOutList[i].empty()) ++pScene->mRootNode->mNumChildren;
  1329. }
  1330. // we will later need an extra node to serve as parent for all bones
  1331. if (sharedData.apcOutBones) ++pScene->mRootNode->mNumChildren;
  1332. this->pScene->mRootNode->mChildren = new aiNode *[pScene->mRootNode->mNumChildren];
  1333. p = 0;
  1334. for (uint32_t i = 0; i < pcHeader->groups_num; ++i) {
  1335. if (avOutList[i].empty()) continue;
  1336. aiNode *const pcNode = pScene->mRootNode->mChildren[p] = new aiNode();
  1337. pcNode->mNumMeshes = (unsigned int)avOutList[i].size();
  1338. pcNode->mMeshes = new unsigned int[pcNode->mNumMeshes];
  1339. pcNode->mParent = this->pScene->mRootNode;
  1340. for (unsigned int a = 0; a < pcNode->mNumMeshes; ++a)
  1341. pcNode->mMeshes[a] = q + a;
  1342. q += (unsigned int)avOutList[i].size();
  1343. // setup the name of the node
  1344. char *const szBuffer = &aszGroupNameBuffer[i * AI_MDL7_MAX_GROUPNAMESIZE];
  1345. if ('\0' == *szBuffer) {
  1346. const size_t maxSize(buffersize - (i * AI_MDL7_MAX_GROUPNAMESIZE));
  1347. pcNode->mName.length = ai_snprintf(szBuffer, maxSize, "Group_%u", p);
  1348. } else {
  1349. pcNode->mName.length = (ai_uint32)::strlen(szBuffer);
  1350. }
  1351. ::strncpy(pcNode->mName.data, szBuffer, AI_MAXLEN - 1);
  1352. ++p;
  1353. }
  1354. }
  1355. // if there is only one root node with a single child we can optimize it a bit ...
  1356. if (1 == pScene->mRootNode->mNumChildren && !sharedData.apcOutBones) {
  1357. aiNode *pcOldRoot = this->pScene->mRootNode;
  1358. pScene->mRootNode = pcOldRoot->mChildren[0];
  1359. pcOldRoot->mChildren[0] = nullptr;
  1360. delete pcOldRoot;
  1361. pScene->mRootNode->mParent = nullptr;
  1362. } else
  1363. pScene->mRootNode->mName.Set("<mesh_root>");
  1364. delete[] avOutList;
  1365. delete[] aszGroupNameBuffer;
  1366. AI_DEBUG_INVALIDATE_PTR(avOutList);
  1367. AI_DEBUG_INVALIDATE_PTR(aszGroupNameBuffer);
  1368. // build a final material list.
  1369. CopyMaterials_3DGS_MDL7(sharedData);
  1370. HandleMaterialReferences_3DGS_MDL7();
  1371. // generate output bone animations and add all bones to the scenegraph
  1372. if (sharedData.apcOutBones) {
  1373. // this step adds empty dummy bones to the nodegraph
  1374. // insert another dummy node to avoid name conflicts
  1375. aiNode *const pc = pScene->mRootNode->mChildren[pScene->mRootNode->mNumChildren - 1] = new aiNode();
  1376. pc->mName.Set("<skeleton_root>");
  1377. // add bones to the nodegraph
  1378. AddBonesToNodeGraph_3DGS_MDL7((const Assimp::MDL::IntBone_MDL7 **)
  1379. sharedData.apcOutBones,
  1380. pc, 0xffff);
  1381. // this steps build a valid output animation
  1382. BuildOutputAnims_3DGS_MDL7((const Assimp::MDL::IntBone_MDL7 **)
  1383. sharedData.apcOutBones);
  1384. }
  1385. }
  1386. // ------------------------------------------------------------------------------------------------
  1387. // Copy materials
  1388. void MDLImporter::CopyMaterials_3DGS_MDL7(MDL::IntSharedData_MDL7 &shared) {
  1389. pScene->mNumMaterials = (unsigned int)shared.pcMats.size();
  1390. pScene->mMaterials = new aiMaterial *[pScene->mNumMaterials];
  1391. for (unsigned int i = 0; i < pScene->mNumMaterials; ++i)
  1392. pScene->mMaterials[i] = shared.pcMats[i];
  1393. }
  1394. // ------------------------------------------------------------------------------------------------
  1395. // Process material references
  1396. void MDLImporter::HandleMaterialReferences_3DGS_MDL7() {
  1397. // search for referrer materials
  1398. for (unsigned int i = 0; i < pScene->mNumMaterials; ++i) {
  1399. int iIndex = 0;
  1400. if (AI_SUCCESS == aiGetMaterialInteger(pScene->mMaterials[i], AI_MDL7_REFERRER_MATERIAL, &iIndex)) {
  1401. for (unsigned int a = 0; a < pScene->mNumMeshes; ++a) {
  1402. aiMesh *const pcMesh = pScene->mMeshes[a];
  1403. if (i == pcMesh->mMaterialIndex) {
  1404. pcMesh->mMaterialIndex = iIndex;
  1405. }
  1406. }
  1407. // collapse the rest of the array
  1408. delete pScene->mMaterials[i];
  1409. for (unsigned int pp = i; pp < pScene->mNumMaterials - 1; ++pp) {
  1410. pScene->mMaterials[pp] = pScene->mMaterials[pp + 1];
  1411. for (unsigned int a = 0; a < pScene->mNumMeshes; ++a) {
  1412. aiMesh *const pcMesh = pScene->mMeshes[a];
  1413. if (pcMesh->mMaterialIndex > i) --pcMesh->mMaterialIndex;
  1414. }
  1415. }
  1416. --pScene->mNumMaterials;
  1417. }
  1418. }
  1419. }
  1420. // ------------------------------------------------------------------------------------------------
  1421. // Read bone transformation keys
  1422. void MDLImporter::ParseBoneTrafoKeys_3DGS_MDL7(
  1423. const MDL::IntGroupInfo_MDL7 &groupInfo,
  1424. IntFrameInfo_MDL7 &frame,
  1425. MDL::IntSharedData_MDL7 &shared) {
  1426. const MDL::Header_MDL7 *const pcHeader = (const MDL::Header_MDL7 *)this->mBuffer;
  1427. // only the first group contains bone animation keys
  1428. if (frame.pcFrame->transmatrix_count) {
  1429. if (!groupInfo.iIndex) {
  1430. // skip all frames vertices. We can't support them
  1431. const MDL::BoneTransform_MDL7 *pcBoneTransforms = (const MDL::BoneTransform_MDL7 *)(((const char *)frame.pcFrame) + pcHeader->frame_stc_size +
  1432. frame.pcFrame->vertices_count * pcHeader->framevertex_stc_size);
  1433. // read all transformation matrices
  1434. for (unsigned int iTrafo = 0; iTrafo < frame.pcFrame->transmatrix_count; ++iTrafo) {
  1435. if (pcBoneTransforms->bone_index >= pcHeader->bones_num) {
  1436. ASSIMP_LOG_WARN("Index overflow in frame area. "
  1437. "Unable to parse this bone transformation");
  1438. } else {
  1439. AddAnimationBoneTrafoKey_3DGS_MDL7(frame.iIndex,
  1440. pcBoneTransforms, shared.apcOutBones);
  1441. }
  1442. pcBoneTransforms = (const MDL::BoneTransform_MDL7 *)((const char *)pcBoneTransforms + pcHeader->bonetrans_stc_size);
  1443. }
  1444. } else {
  1445. ASSIMP_LOG_WARN("Ignoring animation keyframes in groups != 0");
  1446. }
  1447. }
  1448. }
  1449. // ------------------------------------------------------------------------------------------------
  1450. // Attach bones to the output nodegraph
  1451. void MDLImporter::AddBonesToNodeGraph_3DGS_MDL7(const MDL::IntBone_MDL7 **apcBones,
  1452. aiNode *pcParent, uint16_t iParentIndex) {
  1453. ai_assert(nullptr != apcBones);
  1454. ai_assert(nullptr != pcParent);
  1455. // get a pointer to the header ...
  1456. const MDL::Header_MDL7 *const pcHeader = (const MDL::Header_MDL7 *)this->mBuffer;
  1457. const MDL::IntBone_MDL7 **apcBones2 = apcBones;
  1458. for (uint32_t i = 0; i < pcHeader->bones_num; ++i) {
  1459. const MDL::IntBone_MDL7 *const pcBone = *apcBones2++;
  1460. if (pcBone->iParent == iParentIndex) {
  1461. ++pcParent->mNumChildren;
  1462. }
  1463. }
  1464. pcParent->mChildren = new aiNode *[pcParent->mNumChildren];
  1465. unsigned int qq = 0;
  1466. for (uint32_t i = 0; i < pcHeader->bones_num; ++i) {
  1467. const MDL::IntBone_MDL7 *const pcBone = *apcBones++;
  1468. if (pcBone->iParent != iParentIndex) continue;
  1469. aiNode *pcNode = pcParent->mChildren[qq++] = new aiNode();
  1470. pcNode->mName = aiString(pcBone->mName);
  1471. AddBonesToNodeGraph_3DGS_MDL7(apcBones, pcNode, (uint16_t)i);
  1472. }
  1473. }
  1474. // ------------------------------------------------------------------------------------------------
  1475. // Build output animations
  1476. void MDLImporter::BuildOutputAnims_3DGS_MDL7(
  1477. const MDL::IntBone_MDL7 **apcBonesOut) {
  1478. ai_assert(nullptr != apcBonesOut);
  1479. const MDL::Header_MDL7 *const pcHeader = (const MDL::Header_MDL7 *)mBuffer;
  1480. // one animation ...
  1481. aiAnimation *pcAnim = new aiAnimation();
  1482. for (uint32_t i = 0; i < pcHeader->bones_num; ++i) {
  1483. if (!apcBonesOut[i]->pkeyPositions.empty()) {
  1484. // get the last frame ... (needn't be equal to pcHeader->frames_num)
  1485. for (size_t qq = 0; qq < apcBonesOut[i]->pkeyPositions.size(); ++qq) {
  1486. pcAnim->mDuration = std::max(pcAnim->mDuration, (double)
  1487. apcBonesOut[i]
  1488. ->pkeyPositions[qq]
  1489. .mTime);
  1490. }
  1491. ++pcAnim->mNumChannels;
  1492. }
  1493. }
  1494. if (pcAnim->mDuration) {
  1495. pcAnim->mChannels = new aiNodeAnim *[pcAnim->mNumChannels];
  1496. unsigned int iCnt = 0;
  1497. for (uint32_t i = 0; i < pcHeader->bones_num; ++i) {
  1498. if (!apcBonesOut[i]->pkeyPositions.empty()) {
  1499. const MDL::IntBone_MDL7 *const intBone = apcBonesOut[i];
  1500. aiNodeAnim *const pcNodeAnim = pcAnim->mChannels[iCnt++] = new aiNodeAnim();
  1501. pcNodeAnim->mNodeName = aiString(intBone->mName);
  1502. // allocate enough storage for all keys
  1503. pcNodeAnim->mNumPositionKeys = (unsigned int)intBone->pkeyPositions.size();
  1504. pcNodeAnim->mNumScalingKeys = (unsigned int)intBone->pkeyPositions.size();
  1505. pcNodeAnim->mNumRotationKeys = (unsigned int)intBone->pkeyPositions.size();
  1506. pcNodeAnim->mPositionKeys = new aiVectorKey[pcNodeAnim->mNumPositionKeys];
  1507. pcNodeAnim->mScalingKeys = new aiVectorKey[pcNodeAnim->mNumPositionKeys];
  1508. pcNodeAnim->mRotationKeys = new aiQuatKey[pcNodeAnim->mNumPositionKeys];
  1509. // copy all keys
  1510. for (unsigned int qq = 0; qq < pcNodeAnim->mNumPositionKeys; ++qq) {
  1511. pcNodeAnim->mPositionKeys[qq] = intBone->pkeyPositions[qq];
  1512. pcNodeAnim->mScalingKeys[qq] = intBone->pkeyScalings[qq];
  1513. pcNodeAnim->mRotationKeys[qq] = intBone->pkeyRotations[qq];
  1514. }
  1515. }
  1516. }
  1517. // store the output animation
  1518. pScene->mNumAnimations = 1;
  1519. pScene->mAnimations = new aiAnimation *[1];
  1520. pScene->mAnimations[0] = pcAnim;
  1521. } else
  1522. delete pcAnim;
  1523. }
  1524. // ------------------------------------------------------------------------------------------------
  1525. void MDLImporter::AddAnimationBoneTrafoKey_3DGS_MDL7(unsigned int iTrafo,
  1526. const MDL::BoneTransform_MDL7 *pcBoneTransforms,
  1527. MDL::IntBone_MDL7 **apcBonesOut) {
  1528. ai_assert(nullptr != pcBoneTransforms);
  1529. ai_assert(nullptr != apcBonesOut);
  1530. // first .. get the transformation matrix
  1531. aiMatrix4x4 mTransform;
  1532. mTransform.a1 = pcBoneTransforms->m[0];
  1533. mTransform.b1 = pcBoneTransforms->m[1];
  1534. mTransform.c1 = pcBoneTransforms->m[2];
  1535. mTransform.d1 = pcBoneTransforms->m[3];
  1536. mTransform.a2 = pcBoneTransforms->m[4];
  1537. mTransform.b2 = pcBoneTransforms->m[5];
  1538. mTransform.c2 = pcBoneTransforms->m[6];
  1539. mTransform.d2 = pcBoneTransforms->m[7];
  1540. mTransform.a3 = pcBoneTransforms->m[8];
  1541. mTransform.b3 = pcBoneTransforms->m[9];
  1542. mTransform.c3 = pcBoneTransforms->m[10];
  1543. mTransform.d3 = pcBoneTransforms->m[11];
  1544. // now decompose the transformation matrix into separate
  1545. // scaling, rotation and translation
  1546. aiVectorKey vScaling, vPosition;
  1547. aiQuatKey qRotation;
  1548. // FIXME: Decompose will assert in debug builds if the matrix is invalid ...
  1549. mTransform.Decompose(vScaling.mValue, qRotation.mValue, vPosition.mValue);
  1550. // now generate keys
  1551. vScaling.mTime = qRotation.mTime = vPosition.mTime = (double)iTrafo;
  1552. // add the keys to the bone
  1553. MDL::IntBone_MDL7 *const pcBoneOut = apcBonesOut[pcBoneTransforms->bone_index];
  1554. pcBoneOut->pkeyPositions.push_back(vPosition);
  1555. pcBoneOut->pkeyScalings.push_back(vScaling);
  1556. pcBoneOut->pkeyRotations.push_back(qRotation);
  1557. }
  1558. // ------------------------------------------------------------------------------------------------
  1559. // Construct output meshes
  1560. void MDLImporter::GenerateOutputMeshes_3DGS_MDL7(
  1561. MDL::IntGroupData_MDL7 &groupData,
  1562. MDL::IntSplitGroupData_MDL7 &splitGroupData) {
  1563. const MDL::IntSharedData_MDL7 &shared = splitGroupData.shared;
  1564. // get a pointer to the header ...
  1565. const MDL::Header_MDL7 *const pcHeader = (const MDL::Header_MDL7 *)this->mBuffer;
  1566. const unsigned int iNumOutBones = pcHeader->bones_num;
  1567. for (std::vector<aiMaterial *>::size_type i = 0; i < shared.pcMats.size(); ++i) {
  1568. if (!splitGroupData.aiSplit[i]->empty()) {
  1569. // allocate the output mesh
  1570. aiMesh *pcMesh = new aiMesh();
  1571. pcMesh->mPrimitiveTypes = aiPrimitiveType_TRIANGLE;
  1572. pcMesh->mMaterialIndex = (unsigned int)i;
  1573. // allocate output storage
  1574. pcMesh->mNumFaces = (unsigned int)splitGroupData.aiSplit[i]->size();
  1575. pcMesh->mFaces = new aiFace[pcMesh->mNumFaces];
  1576. pcMesh->mNumVertices = pcMesh->mNumFaces * 3;
  1577. pcMesh->mVertices = new aiVector3D[pcMesh->mNumVertices];
  1578. pcMesh->mNormals = new aiVector3D[pcMesh->mNumVertices];
  1579. if (!groupData.vTextureCoords1.empty()) {
  1580. pcMesh->mNumUVComponents[0] = 2;
  1581. pcMesh->mTextureCoords[0] = new aiVector3D[pcMesh->mNumVertices];
  1582. if (!groupData.vTextureCoords2.empty()) {
  1583. pcMesh->mNumUVComponents[1] = 2;
  1584. pcMesh->mTextureCoords[1] = new aiVector3D[pcMesh->mNumVertices];
  1585. }
  1586. }
  1587. // iterate through all faces and build an unique set of vertices
  1588. unsigned int iCurrent = 0;
  1589. for (unsigned int iFace = 0; iFace < pcMesh->mNumFaces; ++iFace) {
  1590. pcMesh->mFaces[iFace].mNumIndices = 3;
  1591. pcMesh->mFaces[iFace].mIndices = new unsigned int[3];
  1592. unsigned int iSrcFace = splitGroupData.aiSplit[i]->operator[](iFace);
  1593. const MDL::IntFace_MDL7 &oldFace = groupData.pcFaces[iSrcFace];
  1594. // iterate through all face indices
  1595. for (unsigned int c = 0; c < 3; ++c) {
  1596. const uint32_t iIndex = oldFace.mIndices[c];
  1597. pcMesh->mVertices[iCurrent] = groupData.vPositions[iIndex];
  1598. pcMesh->mNormals[iCurrent] = groupData.vNormals[iIndex];
  1599. if (!groupData.vTextureCoords1.empty()) {
  1600. pcMesh->mTextureCoords[0][iCurrent] = groupData.vTextureCoords1[iIndex];
  1601. if (!groupData.vTextureCoords2.empty()) {
  1602. pcMesh->mTextureCoords[1][iCurrent] = groupData.vTextureCoords2[iIndex];
  1603. }
  1604. }
  1605. pcMesh->mFaces[iFace].mIndices[c] = iCurrent++;
  1606. }
  1607. }
  1608. // if we have bones in the mesh we'll need to generate
  1609. // proper vertex weights for them
  1610. if (!groupData.aiBones.empty()) {
  1611. std::vector<std::vector<unsigned int>> aaiVWeightList;
  1612. aaiVWeightList.resize(iNumOutBones);
  1613. int iCurrentWeight = 0;
  1614. for (unsigned int iFace = 0; iFace < pcMesh->mNumFaces; ++iFace) {
  1615. unsigned int iSrcFace = splitGroupData.aiSplit[i]->operator[](iFace);
  1616. const MDL::IntFace_MDL7 &oldFace = groupData.pcFaces[iSrcFace];
  1617. // iterate through all face indices
  1618. for (unsigned int c = 0; c < 3; ++c) {
  1619. unsigned int iBone = groupData.aiBones[oldFace.mIndices[c]];
  1620. if (UINT_MAX != iBone) {
  1621. if (iBone >= iNumOutBones) {
  1622. ASSIMP_LOG_ERROR("Bone index overflow. "
  1623. "The bone index of a vertex exceeds the allowed range. ");
  1624. iBone = iNumOutBones - 1;
  1625. }
  1626. aaiVWeightList[iBone].push_back(iCurrentWeight);
  1627. }
  1628. ++iCurrentWeight;
  1629. }
  1630. }
  1631. // now check which bones are required ...
  1632. for (std::vector<std::vector<unsigned int>>::const_iterator k = aaiVWeightList.begin(); k != aaiVWeightList.end(); ++k) {
  1633. if (!(*k).empty()) {
  1634. ++pcMesh->mNumBones;
  1635. }
  1636. }
  1637. pcMesh->mBones = new aiBone *[pcMesh->mNumBones];
  1638. iCurrent = 0;
  1639. for (std::vector<std::vector<unsigned int>>::const_iterator k = aaiVWeightList.begin(); k != aaiVWeightList.end(); ++k, ++iCurrent) {
  1640. if ((*k).empty())
  1641. continue;
  1642. // seems we'll need this node
  1643. aiBone *pcBone = pcMesh->mBones[iCurrent] = new aiBone();
  1644. pcBone->mName = aiString(shared.apcOutBones[iCurrent]->mName);
  1645. pcBone->mOffsetMatrix = shared.apcOutBones[iCurrent]->mOffsetMatrix;
  1646. // setup vertex weights
  1647. pcBone->mNumWeights = (unsigned int)(*k).size();
  1648. pcBone->mWeights = new aiVertexWeight[pcBone->mNumWeights];
  1649. for (unsigned int weight = 0; weight < pcBone->mNumWeights; ++weight) {
  1650. pcBone->mWeights[weight].mVertexId = (*k)[weight];
  1651. pcBone->mWeights[weight].mWeight = 1.0f;
  1652. }
  1653. }
  1654. }
  1655. // add the mesh to the list of output meshes
  1656. splitGroupData.avOutList.push_back(pcMesh);
  1657. }
  1658. }
  1659. }
  1660. // ------------------------------------------------------------------------------------------------
  1661. // Join to materials
  1662. void MDLImporter::JoinSkins_3DGS_MDL7(
  1663. aiMaterial *pcMat1,
  1664. aiMaterial *pcMat2,
  1665. aiMaterial *pcMatOut) {
  1666. ai_assert(nullptr != pcMat1);
  1667. ai_assert(nullptr != pcMat2);
  1668. ai_assert(nullptr != pcMatOut);
  1669. // first create a full copy of the first skin property set
  1670. // and assign it to the output material
  1671. aiMaterial::CopyPropertyList(pcMatOut, pcMat1);
  1672. int iVal = 0;
  1673. pcMatOut->AddProperty<int>(&iVal, 1, AI_MATKEY_UVWSRC_DIFFUSE(0));
  1674. // then extract the diffuse texture from the second skin,
  1675. // setup 1 as UV source and we have it
  1676. aiString sString;
  1677. if (AI_SUCCESS == aiGetMaterialString(pcMat2, AI_MATKEY_TEXTURE_DIFFUSE(0), &sString)) {
  1678. iVal = 1;
  1679. pcMatOut->AddProperty<int>(&iVal, 1, AI_MATKEY_UVWSRC_DIFFUSE(1));
  1680. pcMatOut->AddProperty(&sString, AI_MATKEY_TEXTURE_DIFFUSE(1));
  1681. }
  1682. }
  1683. // ------------------------------------------------------------------------------------------------
  1684. // Read a Half-life 1 MDL
  1685. void MDLImporter::InternReadFile_HL1(const std::string &pFile, const uint32_t iMagicWord) {
  1686. // We can't correctly load an MDL from a MDL "sequence" file.
  1687. if (iMagicWord == AI_MDL_MAGIC_NUMBER_BE_HL2b || iMagicWord == AI_MDL_MAGIC_NUMBER_LE_HL2b)
  1688. throw DeadlyImportError("Impossible to properly load a model from an MDL sequence file.");
  1689. // Check if the buffer is large enough to hold the header
  1690. if (iFileSize < sizeof(HalfLife::Header_HL1)) {
  1691. throw DeadlyImportError("HL1 MDL file is too small to contain header.");
  1692. }
  1693. // Read the MDL file.
  1694. HalfLife::HL1MDLLoader loader(
  1695. pScene,
  1696. mIOHandler,
  1697. mBuffer,
  1698. pFile,
  1699. mHL1ImportSettings);
  1700. }
  1701. // ------------------------------------------------------------------------------------------------
  1702. // Read a half-life 2 MDL
  1703. void MDLImporter::InternReadFile_HL2() {
  1704. //const MDL::Header_HL2* pcHeader = (const MDL::Header_HL2*)this->mBuffer;
  1705. throw DeadlyImportError("HL2 MDLs are not implemented");
  1706. }
  1707. #endif // !! ASSIMP_BUILD_NO_MDL_IMPORTER