MD3Loader.cpp 42 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094
  1. /*
  2. ---------------------------------------------------------------------------
  3. Open Asset Import Library (assimp)
  4. ---------------------------------------------------------------------------
  5. Copyright (c) 2006-2016, 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 MD3Loader.cpp
  35. * @brief Implementation of the MD3 importer class
  36. *
  37. * Sources:
  38. * http://www.gamers.org/dEngine/quake3/UQ3S
  39. * http://linux.ucla.edu/~phaethon/q3/formats/md3format.html
  40. * http://www.heppler.com/shader/shader/
  41. */
  42. #ifndef ASSIMP_BUILD_NO_MD3_IMPORTER
  43. #include "MD3Loader.h"
  44. #include "SceneCombiner.h"
  45. #include "GenericProperty.h"
  46. #include "RemoveComments.h"
  47. #include "ParsingUtils.h"
  48. #include "Importer.h"
  49. #include <assimp/DefaultLogger.hpp>
  50. #include <memory>
  51. #include <assimp/IOSystem.hpp>
  52. #include <assimp/material.h>
  53. #include <assimp/scene.h>
  54. #include <cctype>
  55. using namespace Assimp;
  56. static const aiImporterDesc desc = {
  57. "Quake III Mesh Importer",
  58. "",
  59. "",
  60. "",
  61. aiImporterFlags_SupportBinaryFlavour,
  62. 0,
  63. 0,
  64. 0,
  65. 0,
  66. "md3"
  67. };
  68. // ------------------------------------------------------------------------------------------------
  69. // Convert a Q3 shader blend function to the appropriate enum value
  70. Q3Shader::BlendFunc StringToBlendFunc(const std::string& m)
  71. {
  72. if (m == "GL_ONE") {
  73. return Q3Shader::BLEND_GL_ONE;
  74. }
  75. if (m == "GL_ZERO") {
  76. return Q3Shader::BLEND_GL_ZERO;
  77. }
  78. if (m == "GL_SRC_ALPHA") {
  79. return Q3Shader::BLEND_GL_SRC_ALPHA;
  80. }
  81. if (m == "GL_ONE_MINUS_SRC_ALPHA") {
  82. return Q3Shader::BLEND_GL_ONE_MINUS_SRC_ALPHA;
  83. }
  84. if (m == "GL_ONE_MINUS_DST_COLOR") {
  85. return Q3Shader::BLEND_GL_ONE_MINUS_DST_COLOR;
  86. }
  87. DefaultLogger::get()->error("Q3Shader: Unknown blend function: " + m);
  88. return Q3Shader::BLEND_NONE;
  89. }
  90. // ------------------------------------------------------------------------------------------------
  91. // Load a Quake 3 shader
  92. bool Q3Shader::LoadShader(ShaderData& fill, const std::string& pFile,IOSystem* io)
  93. {
  94. std::unique_ptr<IOStream> file( io->Open( pFile, "rt"));
  95. if (!file.get())
  96. return false; // if we can't access the file, don't worry and return
  97. DefaultLogger::get()->info("Loading Quake3 shader file " + pFile);
  98. // read file in memory
  99. const size_t s = file->FileSize();
  100. std::vector<char> _buff(s+1);
  101. file->Read(&_buff[0],s,1);
  102. _buff[s] = 0;
  103. // remove comments from it (C++ style)
  104. CommentRemover::RemoveLineComments("//",&_buff[0]);
  105. const char* buff = &_buff[0];
  106. Q3Shader::ShaderDataBlock* curData = NULL;
  107. Q3Shader::ShaderMapBlock* curMap = NULL;
  108. // read line per line
  109. for (;SkipSpacesAndLineEnd(&buff);SkipLine(&buff)) {
  110. if (*buff == '{') {
  111. ++buff;
  112. // append to last section, if any
  113. if (!curData) {
  114. DefaultLogger::get()->error("Q3Shader: Unexpected shader section token \'{\'");
  115. return true; // still no failure, the file is there
  116. }
  117. // read this data section
  118. for (;SkipSpacesAndLineEnd(&buff);SkipLine(&buff)) {
  119. if (*buff == '{') {
  120. ++buff;
  121. // add new map section
  122. curData->maps.push_back(Q3Shader::ShaderMapBlock());
  123. curMap = &curData->maps.back();
  124. for (;SkipSpacesAndLineEnd(&buff);SkipLine(&buff)) {
  125. // 'map' - Specifies texture file name
  126. if (TokenMatchI(buff,"map",3) || TokenMatchI(buff,"clampmap",8)) {
  127. curMap->name = GetNextToken(buff);
  128. }
  129. // 'blendfunc' - Alpha blending mode
  130. else if (TokenMatchI(buff,"blendfunc",9)) {
  131. const std::string blend_src = GetNextToken(buff);
  132. if (blend_src == "add") {
  133. curMap->blend_src = Q3Shader::BLEND_GL_ONE;
  134. curMap->blend_dest = Q3Shader::BLEND_GL_ONE;
  135. }
  136. else if (blend_src == "filter") {
  137. curMap->blend_src = Q3Shader::BLEND_GL_DST_COLOR;
  138. curMap->blend_dest = Q3Shader::BLEND_GL_ZERO;
  139. }
  140. else if (blend_src == "blend") {
  141. curMap->blend_src = Q3Shader::BLEND_GL_SRC_ALPHA;
  142. curMap->blend_dest = Q3Shader::BLEND_GL_ONE_MINUS_SRC_ALPHA;
  143. }
  144. else {
  145. curMap->blend_src = StringToBlendFunc(blend_src);
  146. curMap->blend_dest = StringToBlendFunc(GetNextToken(buff));
  147. }
  148. }
  149. // 'alphafunc' - Alpha testing mode
  150. else if (TokenMatchI(buff,"alphafunc",9)) {
  151. const std::string at = GetNextToken(buff);
  152. if (at == "GT0") {
  153. curMap->alpha_test = Q3Shader::AT_GT0;
  154. }
  155. else if (at == "LT128") {
  156. curMap->alpha_test = Q3Shader::AT_LT128;
  157. }
  158. else if (at == "GE128") {
  159. curMap->alpha_test = Q3Shader::AT_GE128;
  160. }
  161. }
  162. else if (*buff == '}') {
  163. ++buff;
  164. // close this map section
  165. curMap = NULL;
  166. break;
  167. }
  168. }
  169. }
  170. else if (*buff == '}') {
  171. ++buff;
  172. curData = NULL;
  173. break;
  174. }
  175. // 'cull' specifies culling behaviour for the model
  176. else if (TokenMatchI(buff,"cull",4)) {
  177. SkipSpaces(&buff);
  178. if (!ASSIMP_strincmp(buff,"back",4)) {
  179. curData->cull = Q3Shader::CULL_CCW;
  180. }
  181. else if (!ASSIMP_strincmp(buff,"front",5)) {
  182. curData->cull = Q3Shader::CULL_CW;
  183. }
  184. else if (!ASSIMP_strincmp(buff,"none",4) || !ASSIMP_strincmp(buff,"disable",7)) {
  185. curData->cull = Q3Shader::CULL_NONE;
  186. }
  187. else DefaultLogger::get()->error("Q3Shader: Unrecognized cull mode");
  188. }
  189. }
  190. }
  191. else {
  192. // add new section
  193. fill.blocks.push_back(Q3Shader::ShaderDataBlock());
  194. curData = &fill.blocks.back();
  195. // get the name of this section
  196. curData->name = GetNextToken(buff);
  197. }
  198. }
  199. return true;
  200. }
  201. // ------------------------------------------------------------------------------------------------
  202. // Load a Quake 3 skin
  203. bool Q3Shader::LoadSkin(SkinData& fill, const std::string& pFile,IOSystem* io)
  204. {
  205. std::unique_ptr<IOStream> file( io->Open( pFile, "rt"));
  206. if (!file.get())
  207. return false; // if we can't access the file, don't worry and return
  208. DefaultLogger::get()->info("Loading Quake3 skin file " + pFile);
  209. // read file in memory
  210. const size_t s = file->FileSize();
  211. std::vector<char> _buff(s+1);const char* buff = &_buff[0];
  212. file->Read(&_buff[0],s,1);
  213. _buff[s] = 0;
  214. // remove commas
  215. std::replace(_buff.begin(),_buff.end(),',',' ');
  216. // read token by token and fill output table
  217. for (;*buff;) {
  218. SkipSpacesAndLineEnd(&buff);
  219. // get first identifier
  220. std::string ss = GetNextToken(buff);
  221. // ignore tokens starting with tag_
  222. if (!::strncmp(&ss[0],"tag_",std::min((size_t)4, ss.length())))
  223. continue;
  224. fill.textures.push_back(SkinData::TextureEntry());
  225. SkinData::TextureEntry& s = fill.textures.back();
  226. s.first = ss;
  227. s.second = GetNextToken(buff);
  228. }
  229. return true;
  230. }
  231. // ------------------------------------------------------------------------------------------------
  232. // Convert Q3Shader to material
  233. void Q3Shader::ConvertShaderToMaterial(aiMaterial* out, const ShaderDataBlock& shader)
  234. {
  235. ai_assert(NULL != out);
  236. /* IMPORTANT: This is not a real conversion. Actually we're just guessing and
  237. * hacking around to build an aiMaterial that looks nearly equal to the
  238. * original Quake 3 shader. We're missing some important features like
  239. * animatable material properties in our material system, but at least
  240. * multiple textures should be handled correctly.
  241. */
  242. // Two-sided material?
  243. if (shader.cull == Q3Shader::CULL_NONE) {
  244. const int twosided = 1;
  245. out->AddProperty(&twosided,1,AI_MATKEY_TWOSIDED);
  246. }
  247. unsigned int cur_emissive = 0, cur_diffuse = 0, cur_lm =0;
  248. // Iterate through all textures
  249. for (std::list< Q3Shader::ShaderMapBlock >::const_iterator it = shader.maps.begin(); it != shader.maps.end();++it) {
  250. // CONVERSION BEHAVIOUR:
  251. //
  252. //
  253. // If the texture is additive
  254. // - if it is the first texture, assume additive blending for the whole material
  255. // - otherwise register it as emissive texture.
  256. //
  257. // If the texture is using standard blend (or if the blend mode is unknown)
  258. // - if first texture: assume default blending for material
  259. // - in any case: set it as diffuse texture
  260. //
  261. // If the texture is using 'filter' blending
  262. // - take as lightmap
  263. //
  264. // Textures with alpha funcs
  265. // - aiTextureFlags_UseAlpha is set (otherwise aiTextureFlags_NoAlpha is explicitly set)
  266. aiString s((*it).name);
  267. aiTextureType type; unsigned int index;
  268. if ((*it).blend_src == Q3Shader::BLEND_GL_ONE && (*it).blend_dest == Q3Shader::BLEND_GL_ONE) {
  269. if (it == shader.maps.begin()) {
  270. const int additive = aiBlendMode_Additive;
  271. out->AddProperty(&additive,1,AI_MATKEY_BLEND_FUNC);
  272. index = cur_diffuse++;
  273. type = aiTextureType_DIFFUSE;
  274. }
  275. else {
  276. index = cur_emissive++;
  277. type = aiTextureType_EMISSIVE;
  278. }
  279. }
  280. else if ((*it).blend_src == Q3Shader::BLEND_GL_DST_COLOR && (*it).blend_dest == Q3Shader::BLEND_GL_ZERO) {
  281. index = cur_lm++;
  282. type = aiTextureType_LIGHTMAP;
  283. }
  284. else {
  285. const int blend = aiBlendMode_Default;
  286. out->AddProperty(&blend,1,AI_MATKEY_BLEND_FUNC);
  287. index = cur_diffuse++;
  288. type = aiTextureType_DIFFUSE;
  289. }
  290. // setup texture
  291. out->AddProperty(&s,AI_MATKEY_TEXTURE(type,index));
  292. // setup texture flags
  293. const int use_alpha = ((*it).alpha_test != Q3Shader::AT_NONE ? aiTextureFlags_UseAlpha : aiTextureFlags_IgnoreAlpha);
  294. out->AddProperty(&use_alpha,1,AI_MATKEY_TEXFLAGS(type,index));
  295. }
  296. // If at least one emissive texture was set, set the emissive base color to 1 to ensure
  297. // the texture is actually displayed.
  298. if (0 != cur_emissive) {
  299. aiColor3D one(1.f,1.f,1.f);
  300. out->AddProperty(&one,1,AI_MATKEY_COLOR_EMISSIVE);
  301. }
  302. }
  303. // ------------------------------------------------------------------------------------------------
  304. // Constructor to be privately used by Importer
  305. MD3Importer::MD3Importer()
  306. : configFrameID (0)
  307. , configHandleMP (true)
  308. , configSpeedFlag()
  309. , pcHeader()
  310. , mBuffer()
  311. , fileSize()
  312. , mScene()
  313. , mIOHandler()
  314. {}
  315. // ------------------------------------------------------------------------------------------------
  316. // Destructor, private as well
  317. MD3Importer::~MD3Importer()
  318. {}
  319. // ------------------------------------------------------------------------------------------------
  320. // Returns whether the class can handle the format of the given file.
  321. bool MD3Importer::CanRead( const std::string& pFile, IOSystem* pIOHandler, bool checkSig) const
  322. {
  323. const std::string extension = GetExtension(pFile);
  324. if (extension == "md3")
  325. return true;
  326. // if check for extension is not enough, check for the magic tokens
  327. if (!extension.length() || checkSig) {
  328. uint32_t tokens[1];
  329. tokens[0] = AI_MD3_MAGIC_NUMBER_LE;
  330. return CheckMagicToken(pIOHandler,pFile,tokens,1);
  331. }
  332. return false;
  333. }
  334. // ------------------------------------------------------------------------------------------------
  335. void MD3Importer::ValidateHeaderOffsets()
  336. {
  337. // Check magic number
  338. if (pcHeader->IDENT != AI_MD3_MAGIC_NUMBER_BE &&
  339. pcHeader->IDENT != AI_MD3_MAGIC_NUMBER_LE)
  340. throw DeadlyImportError( "Invalid MD3 file: Magic bytes not found");
  341. // Check file format version
  342. if (pcHeader->VERSION > 15)
  343. DefaultLogger::get()->warn( "Unsupported MD3 file version. Continuing happily ...");
  344. // Check some offset values whether they are valid
  345. if (!pcHeader->NUM_SURFACES)
  346. throw DeadlyImportError( "Invalid md3 file: NUM_SURFACES is 0");
  347. if (pcHeader->OFS_FRAMES >= fileSize || pcHeader->OFS_SURFACES >= fileSize ||
  348. pcHeader->OFS_EOF > fileSize) {
  349. throw DeadlyImportError("Invalid MD3 header: some offsets are outside the file");
  350. }
  351. if (pcHeader->NUM_SURFACES > AI_MAX_ALLOC(MD3::Surface)) {
  352. throw DeadlyImportError("Invalid MD3 header: too many surfaces, would overflow");
  353. }
  354. if (pcHeader->OFS_SURFACES + pcHeader->NUM_SURFACES * sizeof(MD3::Surface) >= fileSize) {
  355. throw DeadlyImportError("Invalid MD3 header: some surfaces are outside the file");
  356. }
  357. if (pcHeader->NUM_FRAMES <= configFrameID )
  358. throw DeadlyImportError("The requested frame is not existing the file");
  359. }
  360. // ------------------------------------------------------------------------------------------------
  361. void MD3Importer::ValidateSurfaceHeaderOffsets(const MD3::Surface* pcSurf)
  362. {
  363. // Calculate the relative offset of the surface
  364. const int32_t ofs = int32_t((const unsigned char*)pcSurf-this->mBuffer);
  365. // Check whether all data chunks are inside the valid range
  366. if (pcSurf->OFS_TRIANGLES + ofs + pcSurf->NUM_TRIANGLES * sizeof(MD3::Triangle) > fileSize ||
  367. pcSurf->OFS_SHADERS + ofs + pcSurf->NUM_SHADER * sizeof(MD3::Shader) > fileSize ||
  368. pcSurf->OFS_ST + ofs + pcSurf->NUM_VERTICES * sizeof(MD3::TexCoord) > fileSize ||
  369. pcSurf->OFS_XYZNORMAL + ofs + pcSurf->NUM_VERTICES * sizeof(MD3::Vertex) > fileSize) {
  370. throw DeadlyImportError("Invalid MD3 surface header: some offsets are outside the file");
  371. }
  372. // Check whether all requirements for Q3 files are met. We don't
  373. // care, but probably someone does.
  374. if (pcSurf->NUM_TRIANGLES > AI_MD3_MAX_TRIANGLES) {
  375. DefaultLogger::get()->warn("MD3: Quake III triangle limit exceeded");
  376. }
  377. if (pcSurf->NUM_SHADER > AI_MD3_MAX_SHADERS) {
  378. DefaultLogger::get()->warn("MD3: Quake III shader limit exceeded");
  379. }
  380. if (pcSurf->NUM_VERTICES > AI_MD3_MAX_VERTS) {
  381. DefaultLogger::get()->warn("MD3: Quake III vertex limit exceeded");
  382. }
  383. if (pcSurf->NUM_FRAMES > AI_MD3_MAX_FRAMES) {
  384. DefaultLogger::get()->warn("MD3: Quake III frame limit exceeded");
  385. }
  386. }
  387. // ------------------------------------------------------------------------------------------------
  388. const aiImporterDesc* MD3Importer::GetInfo () const
  389. {
  390. return &desc;
  391. }
  392. // ------------------------------------------------------------------------------------------------
  393. // Setup configuration properties
  394. void MD3Importer::SetupProperties(const Importer* pImp)
  395. {
  396. // The
  397. // AI_CONFIG_IMPORT_MD3_KEYFRAME option overrides the
  398. // AI_CONFIG_IMPORT_GLOBAL_KEYFRAME option.
  399. configFrameID = pImp->GetPropertyInteger(AI_CONFIG_IMPORT_MD3_KEYFRAME,-1);
  400. if(static_cast<unsigned int>(-1) == configFrameID) {
  401. configFrameID = pImp->GetPropertyInteger(AI_CONFIG_IMPORT_GLOBAL_KEYFRAME,0);
  402. }
  403. // AI_CONFIG_IMPORT_MD3_HANDLE_MULTIPART
  404. configHandleMP = (0 != pImp->GetPropertyInteger(AI_CONFIG_IMPORT_MD3_HANDLE_MULTIPART,1));
  405. // AI_CONFIG_IMPORT_MD3_SKIN_NAME
  406. configSkinFile = (pImp->GetPropertyString(AI_CONFIG_IMPORT_MD3_SKIN_NAME,"default"));
  407. // AI_CONFIG_IMPORT_MD3_SHADER_SRC
  408. configShaderFile = (pImp->GetPropertyString(AI_CONFIG_IMPORT_MD3_SHADER_SRC,""));
  409. // AI_CONFIG_FAVOUR_SPEED
  410. configSpeedFlag = (0 != pImp->GetPropertyInteger(AI_CONFIG_FAVOUR_SPEED,0));
  411. }
  412. // ------------------------------------------------------------------------------------------------
  413. // Try to read the skin for a MD3 file
  414. void MD3Importer::ReadSkin(Q3Shader::SkinData& fill) const
  415. {
  416. // skip any postfixes (e.g. lower_1.md3)
  417. std::string::size_type s = filename.find_last_of('_');
  418. if (s == std::string::npos) {
  419. s = filename.find_last_of('.');
  420. if (s == std::string::npos) {
  421. s = filename.size();
  422. }
  423. }
  424. ai_assert(s != std::string::npos);
  425. const std::string skin_file = path + filename.substr(0,s) + "_" + configSkinFile + ".skin";
  426. Q3Shader::LoadSkin(fill,skin_file,mIOHandler);
  427. }
  428. // ------------------------------------------------------------------------------------------------
  429. // Try to read the shader for a MD3 file
  430. void MD3Importer::ReadShader(Q3Shader::ShaderData& fill) const
  431. {
  432. // Determine Q3 model name from given path
  433. const std::string::size_type s = path.find_last_of("\\/",path.length()-2);
  434. const std::string model_file = path.substr(s+1,path.length()-(s+2));
  435. // If no specific dir or file is given, use our default search behaviour
  436. if (!configShaderFile.length()) {
  437. if(!Q3Shader::LoadShader(fill,path + "..\\..\\..\\scripts\\" + model_file + ".shader",mIOHandler)) {
  438. Q3Shader::LoadShader(fill,path + "..\\..\\..\\scripts\\" + filename + ".shader",mIOHandler);
  439. }
  440. }
  441. else {
  442. // If the given string specifies a file, load this file.
  443. // Otherwise it's a directory.
  444. const std::string::size_type st = configShaderFile.find_last_of('.');
  445. if (st == std::string::npos) {
  446. if(!Q3Shader::LoadShader(fill,configShaderFile + model_file + ".shader",mIOHandler)) {
  447. Q3Shader::LoadShader(fill,configShaderFile + filename + ".shader",mIOHandler);
  448. }
  449. }
  450. else {
  451. Q3Shader::LoadShader(fill,configShaderFile,mIOHandler);
  452. }
  453. }
  454. }
  455. // ------------------------------------------------------------------------------------------------
  456. // Tiny helper to remove a single node from its parent' list
  457. void RemoveSingleNodeFromList(aiNode* nd)
  458. {
  459. if (!nd || nd->mNumChildren || !nd->mParent)return;
  460. aiNode* par = nd->mParent;
  461. for (unsigned int i = 0; i < par->mNumChildren;++i) {
  462. if (par->mChildren[i] == nd) {
  463. --par->mNumChildren;
  464. for (;i < par->mNumChildren;++i) {
  465. par->mChildren[i] = par->mChildren[i+1];
  466. }
  467. delete nd;
  468. break;
  469. }
  470. }
  471. }
  472. // ------------------------------------------------------------------------------------------------
  473. // Read a multi-part Q3 player model
  474. bool MD3Importer::ReadMultipartFile()
  475. {
  476. // check whether the file name contains a common postfix, e.g lower_2.md3
  477. std::string::size_type s = filename.find_last_of('_'), t = filename.find_last_of('.');
  478. if (t == std::string::npos)
  479. t = filename.size();
  480. if (s == std::string::npos)
  481. s = t;
  482. const std::string mod_filename = filename.substr(0,s);
  483. const std::string suffix = filename.substr(s,t-s);
  484. if (mod_filename == "lower" || mod_filename == "upper" || mod_filename == "head"){
  485. const std::string lower = path + "lower" + suffix + ".md3";
  486. const std::string upper = path + "upper" + suffix + ".md3";
  487. const std::string head = path + "head" + suffix + ".md3";
  488. aiScene* scene_upper = NULL;
  489. aiScene* scene_lower = NULL;
  490. aiScene* scene_head = NULL;
  491. std::string failure;
  492. aiNode* tag_torso, *tag_head;
  493. std::vector<AttachmentInfo> attach;
  494. DefaultLogger::get()->info("Multi part MD3 player model: lower, upper and head parts are joined");
  495. // ensure we won't try to load ourselves recursively
  496. BatchLoader::PropertyMap props;
  497. SetGenericProperty( props.ints, AI_CONFIG_IMPORT_MD3_HANDLE_MULTIPART, 0);
  498. // now read these three files
  499. BatchLoader batch(mIOHandler);
  500. const unsigned int _lower = batch.AddLoadRequest(lower,0,&props);
  501. const unsigned int _upper = batch.AddLoadRequest(upper,0,&props);
  502. const unsigned int _head = batch.AddLoadRequest(head,0,&props);
  503. batch.LoadAll();
  504. // now construct a dummy scene to place these three parts in
  505. aiScene* master = new aiScene();
  506. aiNode* nd = master->mRootNode = new aiNode();
  507. nd->mName.Set("<MD3_Player>");
  508. // ... and get them. We need all of them.
  509. scene_lower = batch.GetImport(_lower);
  510. if (!scene_lower) {
  511. DefaultLogger::get()->error("M3D: Failed to read multi part model, lower.md3 fails to load");
  512. failure = "lower";
  513. goto error_cleanup;
  514. }
  515. scene_upper = batch.GetImport(_upper);
  516. if (!scene_upper) {
  517. DefaultLogger::get()->error("M3D: Failed to read multi part model, upper.md3 fails to load");
  518. failure = "upper";
  519. goto error_cleanup;
  520. }
  521. scene_head = batch.GetImport(_head);
  522. if (!scene_head) {
  523. DefaultLogger::get()->error("M3D: Failed to read multi part model, head.md3 fails to load");
  524. failure = "head";
  525. goto error_cleanup;
  526. }
  527. // build attachment infos. search for typical Q3 tags
  528. // original root
  529. scene_lower->mRootNode->mName.Set("lower");
  530. attach.push_back(AttachmentInfo(scene_lower, nd));
  531. // tag_torso
  532. tag_torso = scene_lower->mRootNode->FindNode("tag_torso");
  533. if (!tag_torso) {
  534. DefaultLogger::get()->error("M3D: Failed to find attachment tag for multi part model: tag_torso expected");
  535. goto error_cleanup;
  536. }
  537. scene_upper->mRootNode->mName.Set("upper");
  538. attach.push_back(AttachmentInfo(scene_upper,tag_torso));
  539. // tag_head
  540. tag_head = scene_upper->mRootNode->FindNode("tag_head");
  541. if (!tag_head) {
  542. DefaultLogger::get()->error("M3D: Failed to find attachment tag for multi part model: tag_head expected");
  543. goto error_cleanup;
  544. }
  545. scene_head->mRootNode->mName.Set("head");
  546. attach.push_back(AttachmentInfo(scene_head,tag_head));
  547. // Remove tag_head and tag_torso from all other model parts ...
  548. // this ensures (together with AI_INT_MERGE_SCENE_GEN_UNIQUE_NAMES_IF_NECESSARY)
  549. // that tag_torso/tag_head is also the name of the (unique) output node
  550. RemoveSingleNodeFromList (scene_upper->mRootNode->FindNode("tag_torso"));
  551. RemoveSingleNodeFromList (scene_head-> mRootNode->FindNode("tag_head" ));
  552. // Undo the rotations which we applied to the coordinate systems. We're
  553. // working in global Quake space here
  554. scene_head->mRootNode->mTransformation = aiMatrix4x4();
  555. scene_lower->mRootNode->mTransformation = aiMatrix4x4();
  556. scene_upper->mRootNode->mTransformation = aiMatrix4x4();
  557. // and merge the scenes
  558. SceneCombiner::MergeScenes(&mScene,master, attach,
  559. AI_INT_MERGE_SCENE_GEN_UNIQUE_NAMES |
  560. AI_INT_MERGE_SCENE_GEN_UNIQUE_MATNAMES |
  561. AI_INT_MERGE_SCENE_RESOLVE_CROSS_ATTACHMENTS |
  562. (!configSpeedFlag ? AI_INT_MERGE_SCENE_GEN_UNIQUE_NAMES_IF_NECESSARY : 0));
  563. // Now rotate the whole scene 90 degrees around the x axis to convert to internal coordinate system
  564. mScene->mRootNode->mTransformation = aiMatrix4x4(1.f,0.f,0.f,0.f,
  565. 0.f,0.f,1.f,0.f,0.f,-1.f,0.f,0.f,0.f,0.f,0.f,1.f);
  566. return true;
  567. error_cleanup:
  568. delete scene_upper;
  569. delete scene_lower;
  570. delete scene_head;
  571. delete master;
  572. if (failure == mod_filename) {
  573. throw DeadlyImportError("MD3: failure to read multipart host file");
  574. }
  575. }
  576. return false;
  577. }
  578. // ------------------------------------------------------------------------------------------------
  579. // Convert a MD3 path to a proper value
  580. void MD3Importer::ConvertPath(const char* texture_name, const char* header_name, std::string& out) const
  581. {
  582. // If the MD3's internal path itself and the given path are using
  583. // the same directory, remove it completely to get right output paths.
  584. const char* end1 = ::strrchr(header_name,'\\');
  585. if (!end1)end1 = ::strrchr(header_name,'/');
  586. const char* end2 = ::strrchr(texture_name,'\\');
  587. if (!end2)end2 = ::strrchr(texture_name,'/');
  588. // HACK: If the paths starts with "models", ignore the
  589. // next two hierarchy levels, it specifies just the model name.
  590. // Ignored by Q3, it might be not equal to the real model location.
  591. if (end2) {
  592. size_t len2;
  593. const size_t len1 = (size_t)(end1 - header_name);
  594. if (!ASSIMP_strincmp(texture_name,"models",6) && (texture_name[6] == '/' || texture_name[6] == '\\')) {
  595. len2 = 6; // ignore the seventh - could be slash or backslash
  596. if (!header_name[0]) {
  597. // Use the file name only
  598. out = end2+1;
  599. return;
  600. }
  601. }
  602. else len2 = std::min (len1, (size_t)(end2 - texture_name ));
  603. if (!ASSIMP_strincmp(texture_name,header_name,static_cast<unsigned int>(len2))) {
  604. // Use the file name only
  605. out = end2+1;
  606. return;
  607. }
  608. }
  609. // Use the full path
  610. out = texture_name;
  611. }
  612. // ------------------------------------------------------------------------------------------------
  613. // Imports the given file into the given scene structure.
  614. void MD3Importer::InternReadFile( const std::string& pFile,
  615. aiScene* pScene, IOSystem* pIOHandler)
  616. {
  617. mFile = pFile;
  618. mScene = pScene;
  619. mIOHandler = pIOHandler;
  620. // get base path and file name
  621. // todo ... move to PathConverter
  622. std::string::size_type s = mFile.find_last_of("/\\");
  623. if (s == std::string::npos) {
  624. s = 0;
  625. }
  626. else ++s;
  627. filename = mFile.substr(s), path = mFile.substr(0,s);
  628. for( std::string::iterator it = filename .begin(); it != filename.end(); ++it)
  629. *it = tolower( *it);
  630. // Load multi-part model file, if necessary
  631. if (configHandleMP) {
  632. if (ReadMultipartFile())
  633. return;
  634. }
  635. std::unique_ptr<IOStream> file( pIOHandler->Open( pFile));
  636. // Check whether we can read from the file
  637. if( file.get() == NULL)
  638. throw DeadlyImportError( "Failed to open MD3 file " + pFile + ".");
  639. // Check whether the md3 file is large enough to contain the header
  640. fileSize = (unsigned int)file->FileSize();
  641. if( fileSize < sizeof(MD3::Header))
  642. throw DeadlyImportError( "MD3 File is too small.");
  643. // Allocate storage and copy the contents of the file to a memory buffer
  644. std::vector<unsigned char> mBuffer2 (fileSize);
  645. file->Read( &mBuffer2[0], 1, fileSize);
  646. mBuffer = &mBuffer2[0];
  647. pcHeader = (BE_NCONST MD3::Header*)mBuffer;
  648. // Ensure correct endianness
  649. #ifdef AI_BUILD_BIG_ENDIAN
  650. AI_SWAP4(pcHeader->VERSION);
  651. AI_SWAP4(pcHeader->FLAGS);
  652. AI_SWAP4(pcHeader->IDENT);
  653. AI_SWAP4(pcHeader->NUM_FRAMES);
  654. AI_SWAP4(pcHeader->NUM_SKINS);
  655. AI_SWAP4(pcHeader->NUM_SURFACES);
  656. AI_SWAP4(pcHeader->NUM_TAGS);
  657. AI_SWAP4(pcHeader->OFS_EOF);
  658. AI_SWAP4(pcHeader->OFS_FRAMES);
  659. AI_SWAP4(pcHeader->OFS_SURFACES);
  660. AI_SWAP4(pcHeader->OFS_TAGS);
  661. #endif
  662. // Validate the file header
  663. ValidateHeaderOffsets();
  664. // Navigate to the list of surfaces
  665. BE_NCONST MD3::Surface* pcSurfaces = (BE_NCONST MD3::Surface*)(mBuffer + pcHeader->OFS_SURFACES);
  666. // Navigate to the list of tags
  667. BE_NCONST MD3::Tag* pcTags = (BE_NCONST MD3::Tag*)(mBuffer + pcHeader->OFS_TAGS);
  668. // Allocate output storage
  669. pScene->mNumMeshes = pcHeader->NUM_SURFACES;
  670. if (pcHeader->NUM_SURFACES == 0) {
  671. throw DeadlyImportError("MD3: No surfaces");
  672. } else if (pcHeader->NUM_SURFACES > AI_MAX_ALLOC(aiMesh)) {
  673. // We allocate pointers but check against the size of aiMesh
  674. // since those pointers will eventually have to point to real objects
  675. throw DeadlyImportError("MD3: Too many surfaces, would run out of memory");
  676. }
  677. pScene->mMeshes = new aiMesh*[pScene->mNumMeshes];
  678. pScene->mNumMaterials = pcHeader->NUM_SURFACES;
  679. pScene->mMaterials = new aiMaterial*[pScene->mNumMeshes];
  680. // Set arrays to zero to ensue proper destruction if an exception is raised
  681. ::memset(pScene->mMeshes,0,pScene->mNumMeshes*sizeof(aiMesh*));
  682. ::memset(pScene->mMaterials,0,pScene->mNumMaterials*sizeof(aiMaterial*));
  683. // Now read possible skins from .skin file
  684. Q3Shader::SkinData skins;
  685. ReadSkin(skins);
  686. // And check whether we can locate a shader file for this model
  687. Q3Shader::ShaderData shaders;
  688. ReadShader(shaders);
  689. // Adjust all texture paths in the shader
  690. const char* header_name = pcHeader->NAME;
  691. if (!shaders.blocks.empty()) {
  692. for (std::list< Q3Shader::ShaderDataBlock >::iterator dit = shaders.blocks.begin(); dit != shaders.blocks.end(); ++dit) {
  693. ConvertPath((*dit).name.c_str(),header_name,(*dit).name);
  694. for (std::list< Q3Shader::ShaderMapBlock >::iterator mit = (*dit).maps.begin(); mit != (*dit).maps.end(); ++mit) {
  695. ConvertPath((*mit).name.c_str(),header_name,(*mit).name);
  696. }
  697. }
  698. }
  699. // Read all surfaces from the file
  700. unsigned int iNum = pcHeader->NUM_SURFACES;
  701. unsigned int iNumMaterials = 0;
  702. while (iNum-- > 0) {
  703. // Ensure correct endianness
  704. #ifdef AI_BUILD_BIG_ENDIAN
  705. AI_SWAP4(pcSurfaces->FLAGS);
  706. AI_SWAP4(pcSurfaces->IDENT);
  707. AI_SWAP4(pcSurfaces->NUM_FRAMES);
  708. AI_SWAP4(pcSurfaces->NUM_SHADER);
  709. AI_SWAP4(pcSurfaces->NUM_TRIANGLES);
  710. AI_SWAP4(pcSurfaces->NUM_VERTICES);
  711. AI_SWAP4(pcSurfaces->OFS_END);
  712. AI_SWAP4(pcSurfaces->OFS_SHADERS);
  713. AI_SWAP4(pcSurfaces->OFS_ST);
  714. AI_SWAP4(pcSurfaces->OFS_TRIANGLES);
  715. AI_SWAP4(pcSurfaces->OFS_XYZNORMAL);
  716. #endif
  717. // Validate the surface header
  718. ValidateSurfaceHeaderOffsets(pcSurfaces);
  719. // Navigate to the vertex list of the surface
  720. BE_NCONST MD3::Vertex* pcVertices = (BE_NCONST MD3::Vertex*)
  721. (((uint8_t*)pcSurfaces) + pcSurfaces->OFS_XYZNORMAL);
  722. // Navigate to the triangle list of the surface
  723. BE_NCONST MD3::Triangle* pcTriangles = (BE_NCONST MD3::Triangle*)
  724. (((uint8_t*)pcSurfaces) + pcSurfaces->OFS_TRIANGLES);
  725. // Navigate to the texture coordinate list of the surface
  726. BE_NCONST MD3::TexCoord* pcUVs = (BE_NCONST MD3::TexCoord*)
  727. (((uint8_t*)pcSurfaces) + pcSurfaces->OFS_ST);
  728. // Navigate to the shader list of the surface
  729. BE_NCONST MD3::Shader* pcShaders = (BE_NCONST MD3::Shader*)
  730. (((uint8_t*)pcSurfaces) + pcSurfaces->OFS_SHADERS);
  731. // If the submesh is empty ignore it
  732. if (0 == pcSurfaces->NUM_VERTICES || 0 == pcSurfaces->NUM_TRIANGLES)
  733. {
  734. pcSurfaces = (BE_NCONST MD3::Surface*)(((uint8_t*)pcSurfaces) + pcSurfaces->OFS_END);
  735. pScene->mNumMeshes--;
  736. continue;
  737. }
  738. // Allocate output mesh
  739. pScene->mMeshes[iNum] = new aiMesh();
  740. aiMesh* pcMesh = pScene->mMeshes[iNum];
  741. std::string _texture_name;
  742. const char* texture_name = NULL;
  743. // Check whether we have a texture record for this surface in the .skin file
  744. std::list< Q3Shader::SkinData::TextureEntry >::iterator it = std::find(
  745. skins.textures.begin(), skins.textures.end(), pcSurfaces->NAME );
  746. if (it != skins.textures.end()) {
  747. texture_name = &*( _texture_name = (*it).second).begin();
  748. DefaultLogger::get()->debug("MD3: Assigning skin texture " + (*it).second + " to surface " + pcSurfaces->NAME);
  749. (*it).resolved = true; // mark entry as resolved
  750. }
  751. // Get the first shader (= texture?) assigned to the surface
  752. if (!texture_name && pcSurfaces->NUM_SHADER) {
  753. texture_name = pcShaders->NAME;
  754. }
  755. std::string convertedPath;
  756. if (texture_name) {
  757. ConvertPath(texture_name,header_name,convertedPath);
  758. }
  759. const Q3Shader::ShaderDataBlock* shader = NULL;
  760. // Now search the current shader for a record with this name (
  761. // excluding texture file extension)
  762. if (!shaders.blocks.empty()) {
  763. std::string::size_type s = convertedPath.find_last_of('.');
  764. if (s == std::string::npos)
  765. s = convertedPath.length();
  766. const std::string without_ext = convertedPath.substr(0,s);
  767. std::list< Q3Shader::ShaderDataBlock >::const_iterator dit = std::find(shaders.blocks.begin(),shaders.blocks.end(),without_ext);
  768. if (dit != shaders.blocks.end()) {
  769. // Hurra, wir haben einen. Tolle Sache.
  770. shader = &*dit;
  771. DefaultLogger::get()->info("Found shader record for " +without_ext );
  772. }
  773. else DefaultLogger::get()->warn("Unable to find shader record for " +without_ext );
  774. }
  775. aiMaterial* pcHelper = new aiMaterial();
  776. const int iMode = (int)aiShadingMode_Gouraud;
  777. pcHelper->AddProperty<int>(&iMode, 1, AI_MATKEY_SHADING_MODEL);
  778. // Add a small ambient color value - Quake 3 seems to have one
  779. aiColor3D clr;
  780. clr.b = clr.g = clr.r = 0.05f;
  781. pcHelper->AddProperty<aiColor3D>(&clr, 1,AI_MATKEY_COLOR_AMBIENT);
  782. clr.b = clr.g = clr.r = 1.0f;
  783. pcHelper->AddProperty<aiColor3D>(&clr, 1,AI_MATKEY_COLOR_DIFFUSE);
  784. pcHelper->AddProperty<aiColor3D>(&clr, 1,AI_MATKEY_COLOR_SPECULAR);
  785. // use surface name + skin_name as material name
  786. aiString name;
  787. name.Set("MD3_[" + configSkinFile + "][" + pcSurfaces->NAME + "]");
  788. pcHelper->AddProperty(&name,AI_MATKEY_NAME);
  789. if (!shader) {
  790. // Setup dummy texture file name to ensure UV coordinates are kept during postprocessing
  791. aiString szString;
  792. if (convertedPath.length()) {
  793. szString.Set(convertedPath);
  794. }
  795. else {
  796. DefaultLogger::get()->warn("Texture file name has zero length. Using default name");
  797. szString.Set("dummy_texture.bmp");
  798. }
  799. pcHelper->AddProperty(&szString,AI_MATKEY_TEXTURE_DIFFUSE(0));
  800. // prevent transparency by default
  801. int no_alpha = aiTextureFlags_IgnoreAlpha;
  802. pcHelper->AddProperty(&no_alpha,1,AI_MATKEY_TEXFLAGS_DIFFUSE(0));
  803. }
  804. else {
  805. Q3Shader::ConvertShaderToMaterial(pcHelper,*shader);
  806. }
  807. pScene->mMaterials[iNumMaterials] = (aiMaterial*)pcHelper;
  808. pcMesh->mMaterialIndex = iNumMaterials++;
  809. // Ensure correct endianness
  810. #ifdef AI_BUILD_BIG_ENDIAN
  811. for (uint32_t i = 0; i < pcSurfaces->NUM_VERTICES;++i) {
  812. AI_SWAP2( pcVertices[i].NORMAL );
  813. AI_SWAP2( pcVertices[i].X );
  814. AI_SWAP2( pcVertices[i].Y );
  815. AI_SWAP2( pcVertices[i].Z );
  816. AI_SWAP4( pcUVs[i].U );
  817. AI_SWAP4( pcUVs[i].U );
  818. }
  819. for (uint32_t i = 0; i < pcSurfaces->NUM_TRIANGLES;++i) {
  820. AI_SWAP4(pcTriangles[i].INDEXES[0]);
  821. AI_SWAP4(pcTriangles[i].INDEXES[1]);
  822. AI_SWAP4(pcTriangles[i].INDEXES[2]);
  823. }
  824. #endif
  825. // Fill mesh information
  826. pcMesh->mPrimitiveTypes = aiPrimitiveType_TRIANGLE;
  827. pcMesh->mNumVertices = pcSurfaces->NUM_TRIANGLES*3;
  828. pcMesh->mNumFaces = pcSurfaces->NUM_TRIANGLES;
  829. pcMesh->mFaces = new aiFace[pcSurfaces->NUM_TRIANGLES];
  830. pcMesh->mNormals = new aiVector3D[pcMesh->mNumVertices];
  831. pcMesh->mVertices = new aiVector3D[pcMesh->mNumVertices];
  832. pcMesh->mTextureCoords[0] = new aiVector3D[pcMesh->mNumVertices];
  833. pcMesh->mNumUVComponents[0] = 2;
  834. // Fill in all triangles
  835. unsigned int iCurrent = 0;
  836. for (unsigned int i = 0; i < (unsigned int)pcSurfaces->NUM_TRIANGLES;++i) {
  837. pcMesh->mFaces[i].mIndices = new unsigned int[3];
  838. pcMesh->mFaces[i].mNumIndices = 3;
  839. //unsigned int iTemp = iCurrent;
  840. for (unsigned int c = 0; c < 3;++c,++iCurrent) {
  841. pcMesh->mFaces[i].mIndices[c] = iCurrent;
  842. // Read vertices
  843. aiVector3D& vec = pcMesh->mVertices[iCurrent];
  844. uint32_t index = pcTriangles->INDEXES[c];
  845. if (index >= pcSurfaces->NUM_VERTICES) {
  846. throw DeadlyImportError( "MD3: Invalid vertex index");
  847. }
  848. vec.x = pcVertices[index].X*AI_MD3_XYZ_SCALE;
  849. vec.y = pcVertices[index].Y*AI_MD3_XYZ_SCALE;
  850. vec.z = pcVertices[index].Z*AI_MD3_XYZ_SCALE;
  851. // Convert the normal vector to uncompressed float3 format
  852. aiVector3D& nor = pcMesh->mNormals[iCurrent];
  853. LatLngNormalToVec3(pcVertices[pcTriangles->INDEXES[c]].NORMAL,(ai_real*)&nor);
  854. // Read texture coordinates
  855. pcMesh->mTextureCoords[0][iCurrent].x = pcUVs[ pcTriangles->INDEXES[c]].U;
  856. pcMesh->mTextureCoords[0][iCurrent].y = 1.0f-pcUVs[ pcTriangles->INDEXES[c]].V;
  857. }
  858. // Flip face order if necessary
  859. if (!shader || shader->cull == Q3Shader::CULL_CW) {
  860. std::swap(pcMesh->mFaces[i].mIndices[2],pcMesh->mFaces[i].mIndices[1]);
  861. }
  862. pcTriangles++;
  863. }
  864. // Go to the next surface
  865. pcSurfaces = (BE_NCONST MD3::Surface*)(((unsigned char*)pcSurfaces) + pcSurfaces->OFS_END);
  866. }
  867. // For debugging purposes: check whether we found matches for all entries in the skins file
  868. if (!DefaultLogger::isNullLogger()) {
  869. for (std::list< Q3Shader::SkinData::TextureEntry>::const_iterator it = skins.textures.begin();it != skins.textures.end(); ++it) {
  870. if (!(*it).resolved) {
  871. DefaultLogger::get()->error("MD3: Failed to match skin " + (*it).first + " to surface " + (*it).second);
  872. }
  873. }
  874. }
  875. if (!pScene->mNumMeshes)
  876. throw DeadlyImportError( "MD3: File contains no valid mesh");
  877. pScene->mNumMaterials = iNumMaterials;
  878. // Now we need to generate an empty node graph
  879. pScene->mRootNode = new aiNode("<MD3Root>");
  880. pScene->mRootNode->mNumMeshes = pScene->mNumMeshes;
  881. pScene->mRootNode->mMeshes = new unsigned int[pScene->mNumMeshes];
  882. // Attach tiny children for all tags
  883. if (pcHeader->NUM_TAGS) {
  884. pScene->mRootNode->mNumChildren = pcHeader->NUM_TAGS;
  885. pScene->mRootNode->mChildren = new aiNode*[pcHeader->NUM_TAGS];
  886. for (unsigned int i = 0; i < pcHeader->NUM_TAGS; ++i, ++pcTags) {
  887. aiNode* nd = pScene->mRootNode->mChildren[i] = new aiNode();
  888. nd->mName.Set((const char*)pcTags->NAME);
  889. nd->mParent = pScene->mRootNode;
  890. AI_SWAP4(pcTags->origin.x);
  891. AI_SWAP4(pcTags->origin.y);
  892. AI_SWAP4(pcTags->origin.z);
  893. // Copy local origin, again flip z,y
  894. nd->mTransformation.a4 = pcTags->origin.x;
  895. nd->mTransformation.b4 = pcTags->origin.y;
  896. nd->mTransformation.c4 = pcTags->origin.z;
  897. // Copy rest of transformation (need to transpose to match row-order matrix)
  898. for (unsigned int a = 0; a < 3;++a) {
  899. for (unsigned int m = 0; m < 3;++m) {
  900. nd->mTransformation[m][a] = pcTags->orientation[a][m];
  901. AI_SWAP4(nd->mTransformation[m][a]);
  902. }
  903. }
  904. }
  905. }
  906. for (unsigned int i = 0; i < pScene->mNumMeshes;++i)
  907. pScene->mRootNode->mMeshes[i] = i;
  908. // Now rotate the whole scene 90 degrees around the x axis to convert to internal coordinate system
  909. pScene->mRootNode->mTransformation = aiMatrix4x4(1.f,0.f,0.f,0.f,
  910. 0.f,0.f,1.f,0.f,0.f,-1.f,0.f,0.f,0.f,0.f,0.f,1.f);
  911. }
  912. #endif // !! ASSIMP_BUILD_NO_MD3_IMPORTER