SMDLoader.cpp 38 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082
  1. /*
  2. ---------------------------------------------------------------------------
  3. Open Asset Import Library (assimp)
  4. ---------------------------------------------------------------------------
  5. Copyright (c) 2006-2022, 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 SMDLoader.cpp
  35. * @brief Implementation of the SMD importer class
  36. */
  37. #ifndef ASSIMP_BUILD_NO_SMD_IMPORTER
  38. #include <assimp/fast_atof.h>
  39. #include <assimp/SkeletonMeshBuilder.h>
  40. #include <assimp/Importer.hpp>
  41. #include <assimp/IOSystem.hpp>
  42. #include <assimp/scene.h>
  43. #include <assimp/DefaultLogger.hpp>
  44. #include <assimp/importerdesc.h>
  45. #include <memory>
  46. #include <assimp/DefaultIOSystem.h>
  47. #include <tuple>
  48. // internal headers
  49. #include "SMDLoader.h"
  50. #ifndef _MSC_VER
  51. #define strtok_s strtok_r
  52. #endif
  53. namespace Assimp {
  54. static constexpr aiImporterDesc desc = {
  55. "Valve SMD Importer",
  56. "",
  57. "",
  58. "",
  59. aiImporterFlags_SupportTextFlavour,
  60. 0,
  61. 0,
  62. 0,
  63. 0,
  64. "smd vta"
  65. };
  66. // ------------------------------------------------------------------------------------------------
  67. // Constructor to be privately used by Importer
  68. SMDImporter::SMDImporter() :
  69. configFrameID(),
  70. pScene( nullptr ),
  71. iFileSize( 0 ),
  72. iSmallestFrame( INT_MAX ),
  73. dLengthOfAnim( 0.0 ),
  74. bHasUVs(false ),
  75. iLineNumber((unsigned int)-1) {
  76. // empty
  77. }
  78. // ------------------------------------------------------------------------------------------------
  79. // Destructor, private as well
  80. SMDImporter::~SMDImporter() = default;
  81. // ------------------------------------------------------------------------------------------------
  82. // Returns whether the class can handle the format of the given file.
  83. bool SMDImporter::CanRead( const std::string& filename, IOSystem* /*pIOHandler*/, bool) const {
  84. return SimpleExtensionCheck(filename, "smd", "vta");
  85. }
  86. // ------------------------------------------------------------------------------------------------
  87. // Get a list of all supported file extensions
  88. const aiImporterDesc* SMDImporter::GetInfo () const {
  89. return &desc;
  90. }
  91. // ------------------------------------------------------------------------------------------------
  92. // Setup configuration properties
  93. void SMDImporter::SetupProperties(const Importer* pImp) {
  94. // The
  95. // AI_CONFIG_IMPORT_SMD_KEYFRAME option overrides the
  96. // AI_CONFIG_IMPORT_GLOBAL_KEYFRAME option.
  97. configFrameID = pImp->GetPropertyInteger(AI_CONFIG_IMPORT_SMD_KEYFRAME,-1);
  98. if(static_cast<unsigned int>(-1) == configFrameID) {
  99. configFrameID = pImp->GetPropertyInteger(AI_CONFIG_IMPORT_GLOBAL_KEYFRAME,0);
  100. }
  101. bLoadAnimationList = pImp->GetPropertyBool(AI_CONFIG_IMPORT_SMD_LOAD_ANIMATION_LIST, true);
  102. noSkeletonMesh = pImp->GetPropertyBool(AI_CONFIG_IMPORT_NO_SKELETON_MESHES, false);
  103. }
  104. // ------------------------------------------------------------------------------------------------
  105. // Imports the given file into the given scene structure.
  106. void SMDImporter::InternReadFile( const std::string& pFile, aiScene* scene, IOSystem* pIOHandler) {
  107. this->pScene = scene;
  108. ReadSmd(pFile, pIOHandler);
  109. // If there are no triangles it seems to be an animation SMD,
  110. // containing only the animation skeleton.
  111. if (asTriangles.empty()) {
  112. if (asBones.empty()) {
  113. throw DeadlyImportError("SMD: No triangles and no bones have "
  114. "been found in the file. This file seems to be invalid.");
  115. }
  116. // Set the flag in the scene structure which indicates
  117. // that there is nothing than an animation skeleton
  118. pScene->mFlags |= AI_SCENE_FLAGS_INCOMPLETE;
  119. }
  120. if (!asBones.empty()) {
  121. // Check whether all bones have been initialized
  122. for (const auto &asBone : asBones) {
  123. if (!asBone.mName.length()) {
  124. ASSIMP_LOG_WARN("SMD: Not all bones have been initialized");
  125. break;
  126. }
  127. }
  128. // now fix invalid time values and make sure the animation starts at frame 0
  129. FixTimeValues();
  130. }
  131. // build output nodes (bones are added as empty dummy nodes)
  132. CreateOutputNodes();
  133. if (!(pScene->mFlags & AI_SCENE_FLAGS_INCOMPLETE)) {
  134. // create output meshes
  135. CreateOutputMeshes();
  136. // build an output material list
  137. CreateOutputMaterials();
  138. // use root node that renders all meshes
  139. pScene->mRootNode->mNumMeshes = pScene->mNumMeshes;
  140. pScene->mRootNode->mMeshes = new unsigned int[pScene->mNumMeshes];
  141. for (unsigned int i = 0; i < pScene->mNumMeshes; ++i) {
  142. pScene->mRootNode->mMeshes[i] = i;
  143. }
  144. }
  145. // build the output animation
  146. CreateOutputAnimations(pFile, pIOHandler);
  147. if ((pScene->mFlags & AI_SCENE_FLAGS_INCOMPLETE) && !noSkeletonMesh) {
  148. SkeletonMeshBuilder skeleton(pScene);
  149. }
  150. }
  151. // ------------------------------------------------------------------------------------------------
  152. // Write an error message with line number to the log file
  153. void SMDImporter::LogErrorNoThrow(const char* msg) {
  154. const size_t _BufferSize = 1024;
  155. char szTemp[_BufferSize];
  156. ai_snprintf(szTemp,_BufferSize,"Line %u: %s",iLineNumber,msg);
  157. DefaultLogger::get()->error(szTemp);
  158. }
  159. // ------------------------------------------------------------------------------------------------
  160. // Write a warning with line number to the log file
  161. void SMDImporter::LogWarning(const char* msg) {
  162. const size_t _BufferSize = 1024;
  163. char szTemp[_BufferSize];
  164. ai_assert(strlen(msg) < 1000);
  165. ai_snprintf(szTemp,_BufferSize,"Line %u: %s",iLineNumber,msg);
  166. ASSIMP_LOG_WARN(szTemp);
  167. }
  168. // ------------------------------------------------------------------------------------------------
  169. // Fix invalid time values in the file
  170. void SMDImporter::FixTimeValues() {
  171. double dDelta = (double)iSmallestFrame;
  172. double dMax = 0.0f;
  173. for (auto &asBone : asBones) {
  174. for (auto &asKey : asBone.sAnim.asKeys) {
  175. asKey.dTime -= dDelta;
  176. dMax = std::max(dMax, asKey.dTime);
  177. }
  178. }
  179. dLengthOfAnim = dMax;
  180. }
  181. // ------------------------------------------------------------------------------------------------
  182. // create output meshes
  183. void SMDImporter::CreateOutputMeshes() {
  184. if (aszTextures.empty()) {
  185. aszTextures.emplace_back();
  186. }
  187. // we need to sort all faces by their material index
  188. // in opposition to other loaders we can be sure that each
  189. // material is at least used once.
  190. pScene->mNumMeshes = (unsigned int) aszTextures.size();
  191. pScene->mMeshes = new aiMesh*[pScene->mNumMeshes];
  192. typedef std::vector<unsigned int> FaceList;
  193. std::unique_ptr<FaceList[]> aaiFaces(new FaceList[pScene->mNumMeshes]);
  194. // approximate the space that will be required
  195. unsigned int iNum = (unsigned int)asTriangles.size() / pScene->mNumMeshes;
  196. iNum += iNum >> 1;
  197. for (unsigned int i = 0; i < pScene->mNumMeshes;++i) {
  198. aaiFaces[i].reserve(iNum);
  199. }
  200. // collect all faces
  201. iNum = 0;
  202. for (const auto &asTriangle : asTriangles) {
  203. if (asTriangle.iTexture >= aszTextures.size()) {
  204. ASSIMP_LOG_INFO("[SMD/VTA] Material index overflow in face");
  205. aaiFaces[asTriangle.iTexture].push_back((unsigned int)aszTextures.size()-1);
  206. } else {
  207. aaiFaces[asTriangle.iTexture].push_back(iNum);
  208. }
  209. ++iNum;
  210. }
  211. // now create the output meshes
  212. for (unsigned int i = 0; i < pScene->mNumMeshes;++i) {
  213. aiMesh*& pcMesh = pScene->mMeshes[i] = new aiMesh();
  214. ai_assert(!aaiFaces[i].empty()); // should not be empty ...
  215. pcMesh->mPrimitiveTypes = aiPrimitiveType_TRIANGLE;
  216. pcMesh->mNumVertices = (unsigned int)aaiFaces[i].size()*3;
  217. pcMesh->mNumFaces = (unsigned int)aaiFaces[i].size();
  218. pcMesh->mMaterialIndex = i;
  219. // storage for bones
  220. typedef std::pair<unsigned int,float> TempWeightListEntry;
  221. typedef std::vector< TempWeightListEntry > TempBoneWeightList;
  222. std::unique_ptr<TempBoneWeightList[]> aaiBones(new TempBoneWeightList[asBones.size()]());
  223. // try to reserve enough memory without wasting too much
  224. for (unsigned int iBone = 0; iBone < asBones.size();++iBone) {
  225. aaiBones[iBone].reserve(pcMesh->mNumVertices/asBones.size());
  226. }
  227. // allocate storage
  228. pcMesh->mFaces = new aiFace[pcMesh->mNumFaces];
  229. aiVector3D* pcNormals = pcMesh->mNormals = new aiVector3D[pcMesh->mNumVertices];
  230. aiVector3D* pcVerts = pcMesh->mVertices = new aiVector3D[pcMesh->mNumVertices];
  231. aiVector3D* pcUVs = nullptr;
  232. if (bHasUVs) {
  233. pcUVs = pcMesh->mTextureCoords[0] = new aiVector3D[pcMesh->mNumVertices];
  234. pcMesh->mNumUVComponents[0] = 2;
  235. }
  236. iNum = 0;
  237. for (unsigned int iFace = 0; iFace < pcMesh->mNumFaces;++iFace) {
  238. pcMesh->mFaces[iFace].mIndices = new unsigned int[3];
  239. pcMesh->mFaces[iFace].mNumIndices = 3;
  240. // fill the vertices
  241. unsigned int iSrcFace = aaiFaces[i][iFace];
  242. SMD::Face& face = asTriangles[iSrcFace];
  243. *pcVerts++ = face.avVertices[0].pos;
  244. *pcVerts++ = face.avVertices[1].pos;
  245. *pcVerts++ = face.avVertices[2].pos;
  246. // fill the normals
  247. *pcNormals++ = face.avVertices[0].nor;
  248. *pcNormals++ = face.avVertices[1].nor;
  249. *pcNormals++ = face.avVertices[2].nor;
  250. // fill the texture coordinates
  251. if (pcUVs) {
  252. *pcUVs++ = face.avVertices[0].uv;
  253. *pcUVs++ = face.avVertices[1].uv;
  254. *pcUVs++ = face.avVertices[2].uv;
  255. }
  256. for (unsigned int iVert = 0; iVert < 3;++iVert) {
  257. float fSum = 0.0f;
  258. for (unsigned int iBone = 0;iBone < face.avVertices[iVert].aiBoneLinks.size();++iBone) {
  259. TempWeightListEntry& pairval = face.avVertices[iVert].aiBoneLinks[iBone];
  260. // FIX: The second check is here just to make sure we won't
  261. // assign more than one weight to a single vertex index
  262. if (pairval.first >= asBones.size() || pairval.first == face.avVertices[iVert].iParentNode) {
  263. ASSIMP_LOG_ERROR("[SMD/VTA] Bone index overflow. "
  264. "The bone index will be ignored, the weight will be assigned "
  265. "to the vertex' parent node");
  266. continue;
  267. }
  268. aaiBones[pairval.first].emplace_back(iNum,pairval.second);
  269. fSum += pairval.second;
  270. }
  271. // ******************************************************************
  272. // If the sum of all vertex weights is not 1.0 we must assign
  273. // the rest to the vertex' parent node. Well, at least the doc says
  274. // we should ...
  275. // FIX: We use 0.975 as limit, floating-point inaccuracies seem to
  276. // be very strong in some SMD exporters. Furthermore it is possible
  277. // that the parent of a vertex is 0xffffffff (if the corresponding
  278. // entry in the file was unreadable)
  279. // ******************************************************************
  280. if (fSum < 0.975f && face.avVertices[iVert].iParentNode != UINT_MAX) {
  281. if (face.avVertices[iVert].iParentNode >= asBones.size()) {
  282. ASSIMP_LOG_ERROR("[SMD/VTA] Bone index overflow. "
  283. "The index of the vertex parent bone is invalid. "
  284. "The remaining weights will be normalized to 1.0");
  285. if (fSum) {
  286. fSum = 1 / fSum;
  287. for (auto &pairval : face.avVertices[iVert].aiBoneLinks) {
  288. if (pairval.first >= asBones.size()) {
  289. continue;
  290. }
  291. aaiBones[pairval.first].back().second *= fSum;
  292. }
  293. }
  294. } else {
  295. aaiBones[face.avVertices[iVert].iParentNode].emplace_back(iNum,1.0f-fSum);
  296. }
  297. }
  298. pcMesh->mFaces[iFace].mIndices[iVert] = iNum++;
  299. }
  300. }
  301. // now build all bones of the mesh
  302. iNum = 0;
  303. for (unsigned int iBone = 0; iBone < asBones.size();++iBone) {
  304. if (!aaiBones[iBone].empty())++iNum;
  305. }
  306. if (iNum) {
  307. pcMesh->mNumBones = iNum;
  308. pcMesh->mBones = new aiBone*[pcMesh->mNumBones];
  309. iNum = 0;
  310. for (unsigned int iBone = 0; iBone < asBones.size();++iBone) {
  311. if (aaiBones[iBone].empty()) {
  312. continue;
  313. }
  314. aiBone*& bone = pcMesh->mBones[iNum] = new aiBone();
  315. bone->mNumWeights = (unsigned int)aaiBones[iBone].size();
  316. bone->mWeights = new aiVertexWeight[bone->mNumWeights];
  317. bone->mOffsetMatrix = asBones[iBone].mOffsetMatrix;
  318. bone->mName.Set( asBones[iBone].mName );
  319. asBones[iBone].bIsUsed = true;
  320. for (unsigned int iWeight = 0; iWeight < bone->mNumWeights;++iWeight) {
  321. bone->mWeights[iWeight].mVertexId = aaiBones[iBone][iWeight].first;
  322. bone->mWeights[iWeight].mWeight = aaiBones[iBone][iWeight].second;
  323. }
  324. ++iNum;
  325. }
  326. }
  327. }
  328. }
  329. // ------------------------------------------------------------------------------------------------
  330. // add bone child nodes
  331. void SMDImporter::AddBoneChildren(aiNode* pcNode, uint32_t iParent) {
  332. ai_assert( nullptr != pcNode );
  333. ai_assert( 0 == pcNode->mNumChildren );
  334. ai_assert( nullptr == pcNode->mChildren);
  335. // first count ...
  336. for (auto &bone : asBones) {
  337. if (bone.iParent == iParent) {
  338. ++pcNode->mNumChildren;
  339. }
  340. }
  341. // now allocate the output array
  342. pcNode->mChildren = new aiNode*[pcNode->mNumChildren];
  343. // and fill all subnodes
  344. unsigned int qq( 0 );
  345. for (unsigned int i = 0; i < asBones.size();++i) {
  346. SMD::Bone& bone = asBones[i];
  347. if (bone.iParent != iParent) {
  348. continue;
  349. }
  350. aiNode* pc = pcNode->mChildren[qq++] = new aiNode();
  351. pc->mName.Set(bone.mName);
  352. // store the local transformation matrix of the bind pose
  353. if (bone.sAnim.asKeys.size()) {
  354. pc->mTransformation = bone.sAnim.asKeys[0].matrix;
  355. }
  356. if (bone.iParent == static_cast<uint32_t>(-1)) {
  357. bone.mOffsetMatrix = pc->mTransformation;
  358. } else {
  359. bone.mOffsetMatrix = asBones[bone.iParent].mOffsetMatrix * pc->mTransformation;
  360. }
  361. pc->mParent = pcNode;
  362. // add children to this node, too
  363. AddBoneChildren(pc,i);
  364. }
  365. }
  366. // ------------------------------------------------------------------------------------------------
  367. // create output nodes
  368. void SMDImporter::CreateOutputNodes() {
  369. pScene->mRootNode = new aiNode();
  370. // now add all bones as dummy sub nodes to the graph
  371. AddBoneChildren(pScene->mRootNode,(uint32_t)-1);
  372. for (auto &bone : asBones) {
  373. bone.mOffsetMatrix.Inverse();
  374. }
  375. // if we have only one bone we can even remove the root node
  376. if (pScene->mFlags & AI_SCENE_FLAGS_INCOMPLETE && 1 == pScene->mRootNode->mNumChildren) {
  377. aiNode* pcOldRoot = pScene->mRootNode;
  378. pScene->mRootNode = pcOldRoot->mChildren[0];
  379. pcOldRoot->mChildren[0] = nullptr;
  380. delete pcOldRoot;
  381. pScene->mRootNode->mParent = nullptr;
  382. }
  383. else
  384. {
  385. ::strcpy(pScene->mRootNode->mName.data, "<SMD_root>");
  386. pScene->mRootNode->mName.length = 10;
  387. }
  388. }
  389. // ------------------------------------------------------------------------------------------------
  390. // create output animations
  391. void SMDImporter::CreateOutputAnimations(const std::string &pFile, IOSystem* pIOHandler) {
  392. std::vector<std::tuple<std::string, std::string>> animFileList;
  393. if (bLoadAnimationList) {
  394. GetAnimationFileList(pFile, pIOHandler, animFileList);
  395. }
  396. int animCount = static_cast<int>( animFileList.size() + 1u );
  397. pScene->mNumAnimations = 1;
  398. pScene->mAnimations = new aiAnimation*[animCount];
  399. memset(pScene->mAnimations, 0, sizeof(aiAnimation*)*animCount);
  400. CreateOutputAnimation(0, "");
  401. for (auto &animFile : animFileList) {
  402. ReadSmd(std::get<1>(animFile), pIOHandler);
  403. if (asBones.empty()) {
  404. continue;
  405. }
  406. FixTimeValues();
  407. CreateOutputAnimation(pScene->mNumAnimations++, std::get<0>(animFile));
  408. }
  409. }
  410. void SMDImporter::CreateOutputAnimation(int index, const std::string &name) {
  411. aiAnimation*& anim = pScene->mAnimations[index] = new aiAnimation();
  412. if (name.length()) {
  413. anim->mName.Set(name.c_str());
  414. }
  415. anim->mDuration = dLengthOfAnim;
  416. anim->mNumChannels = static_cast<unsigned int>( asBones.size() );
  417. anim->mTicksPerSecond = 25.0; // FIXME: is this correct?
  418. aiNodeAnim** pp = anim->mChannels = new aiNodeAnim*[anim->mNumChannels];
  419. // now build valid keys
  420. unsigned int a = 0;
  421. for (const auto &asBone : asBones) {
  422. aiNodeAnim* p = pp[a] = new aiNodeAnim();
  423. // copy the name of the bone
  424. p->mNodeName.Set(asBone.mName);
  425. p->mNumRotationKeys = (unsigned int)asBone.sAnim.asKeys.size();
  426. if (p->mNumRotationKeys){
  427. p->mNumPositionKeys = p->mNumRotationKeys;
  428. aiVectorKey* pVecKeys = p->mPositionKeys = new aiVectorKey[p->mNumRotationKeys];
  429. aiQuatKey* pRotKeys = p->mRotationKeys = new aiQuatKey[p->mNumRotationKeys];
  430. for (const auto &asKey : asBone.sAnim.asKeys) {
  431. pRotKeys->mTime = pVecKeys->mTime = asKey.dTime;
  432. // compute the rotation quaternion from the euler angles
  433. // aiQuaternion: The order of the parameters is yzx?
  434. pRotKeys->mValue = aiQuaternion(asKey.vRot.y, asKey.vRot.z, asKey.vRot.x);
  435. pVecKeys->mValue = asKey.vPos;
  436. ++pVecKeys; ++pRotKeys;
  437. }
  438. }
  439. ++a;
  440. // there are no scaling keys ...
  441. }
  442. }
  443. void SMDImporter::GetAnimationFileList(const std::string &pFile, IOSystem* pIOHandler, std::vector<std::tuple<std::string, std::string>>& outList) {
  444. auto base = DefaultIOSystem::absolutePath(pFile);
  445. auto name = DefaultIOSystem::completeBaseName(pFile);
  446. auto path = base + "/" + name + "_animation.txt";
  447. std::unique_ptr<IOStream> file(pIOHandler->Open(path.c_str(), "rb"));
  448. if (file == nullptr) {
  449. return;
  450. }
  451. // Allocate storage and copy the contents of the file to a memory buffer
  452. std::vector<char> buf;
  453. size_t fileSize = file->FileSize();
  454. buf.resize(fileSize + 1);
  455. TextFileToBuffer(file.get(), buf);
  456. /*
  457. *_animation.txt format:
  458. name path
  459. idle idle.smd
  460. jump anim/jump.smd
  461. walk.smd
  462. ...
  463. */
  464. std::string animName, animPath;
  465. char *tok1, *tok2;
  466. char *context1, *context2;
  467. tok1 = strtok_s(&buf[0], "\r\n", &context1);
  468. while (tok1 != nullptr) {
  469. tok2 = strtok_s(tok1, " \t", &context2);
  470. if (tok2) {
  471. char *p = tok2;
  472. tok2 = strtok_s(nullptr, " \t", &context2);
  473. if (tok2) {
  474. animPath = tok2;
  475. animName = p;
  476. } else {
  477. // No name
  478. animPath = p;
  479. animName = DefaultIOSystem::completeBaseName(animPath);
  480. }
  481. outList.emplace_back(animName, base + "/" + animPath);
  482. }
  483. tok1 = strtok_s(nullptr, "\r\n", &context1);
  484. }
  485. }
  486. // ------------------------------------------------------------------------------------------------
  487. // create output materials
  488. void SMDImporter::CreateOutputMaterials() {
  489. ai_assert( nullptr != pScene );
  490. pScene->mNumMaterials = (unsigned int)aszTextures.size();
  491. pScene->mMaterials = new aiMaterial*[std::max(1u, pScene->mNumMaterials)];
  492. for (unsigned int iMat = 0; iMat < pScene->mNumMaterials; ++iMat) {
  493. aiMaterial* pcMat = new aiMaterial();
  494. ai_assert( nullptr != pcMat );
  495. pScene->mMaterials[iMat] = pcMat;
  496. aiString szName;
  497. szName.length = static_cast<ai_uint32>(ai_snprintf(szName.data,MAXLEN,"Texture_%u",iMat));
  498. pcMat->AddProperty(&szName,AI_MATKEY_NAME);
  499. if (aszTextures[iMat].length())
  500. {
  501. ::strncpy(szName.data, aszTextures[iMat].c_str(),MAXLEN-1);
  502. szName.length = static_cast<ai_uint32>( aszTextures[iMat].length() );
  503. pcMat->AddProperty(&szName,AI_MATKEY_TEXTURE_DIFFUSE(0));
  504. }
  505. }
  506. // create a default material if necessary
  507. if (0 == pScene->mNumMaterials) {
  508. pScene->mNumMaterials = 1;
  509. aiMaterial* pcHelper = new aiMaterial();
  510. pScene->mMaterials[0] = pcHelper;
  511. int iMode = static_cast<int>(aiShadingMode_Gouraud);
  512. pcHelper->AddProperty<int>(&iMode, 1, AI_MATKEY_SHADING_MODEL);
  513. aiColor3D clr;
  514. clr.b = clr.g = clr.r = 0.7f;
  515. pcHelper->AddProperty<aiColor3D>(&clr, 1,AI_MATKEY_COLOR_DIFFUSE);
  516. pcHelper->AddProperty<aiColor3D>(&clr, 1,AI_MATKEY_COLOR_SPECULAR);
  517. clr.b = clr.g = clr.r = 0.05f;
  518. pcHelper->AddProperty<aiColor3D>(&clr, 1,AI_MATKEY_COLOR_AMBIENT);
  519. aiString szName;
  520. szName.Set(AI_DEFAULT_MATERIAL_NAME);
  521. pcHelper->AddProperty(&szName,AI_MATKEY_NAME);
  522. }
  523. }
  524. // ------------------------------------------------------------------------------------------------
  525. // Parse the file
  526. void SMDImporter::ParseFile() {
  527. const char* szCurrent = &mBuffer[0];
  528. // read line per line ...
  529. for ( ;; ) {
  530. if(!SkipSpacesAndLineEnd(szCurrent,&szCurrent)) {
  531. break;
  532. }
  533. // "version <n> \n", <n> should be 1 for hl and hl2 SMD files
  534. if (TokenMatch(szCurrent,"version",7)) {
  535. if(!SkipSpaces(szCurrent,&szCurrent)) break;
  536. if (1 != strtoul10(szCurrent,&szCurrent)) {
  537. ASSIMP_LOG_WARN("SMD.version is not 1. This "
  538. "file format is not known. Continuing happily ...");
  539. }
  540. continue;
  541. }
  542. // "nodes\n" - Starts the node section
  543. if (TokenMatch(szCurrent,"nodes",5)) {
  544. ParseNodesSection(szCurrent,&szCurrent);
  545. continue;
  546. }
  547. // "triangles\n" - Starts the triangle section
  548. if (TokenMatch(szCurrent,"triangles",9)) {
  549. ParseTrianglesSection(szCurrent,&szCurrent);
  550. continue;
  551. }
  552. // "vertexanimation\n" - Starts the vertex animation section
  553. if (TokenMatch(szCurrent,"vertexanimation",15)) {
  554. bHasUVs = false;
  555. ParseVASection(szCurrent,&szCurrent);
  556. continue;
  557. }
  558. // "skeleton\n" - Starts the skeleton section
  559. if (TokenMatch(szCurrent,"skeleton",8)) {
  560. ParseSkeletonSection(szCurrent,&szCurrent);
  561. continue;
  562. }
  563. SkipLine(szCurrent,&szCurrent);
  564. }
  565. }
  566. void SMDImporter::ReadSmd(const std::string &pFile, IOSystem* pIOHandler) {
  567. std::unique_ptr<IOStream> file(pIOHandler->Open(pFile, "rb"));
  568. // Check whether we can read from the file
  569. if (file == nullptr) {
  570. throw DeadlyImportError("Failed to open SMD/VTA file ", pFile, ".");
  571. }
  572. iFileSize = (unsigned int)file->FileSize();
  573. // Allocate storage and copy the contents of the file to a memory buffer
  574. mBuffer.resize(iFileSize + 1);
  575. TextFileToBuffer(file.get(), mBuffer);
  576. iSmallestFrame = INT_MAX;
  577. bHasUVs = true;
  578. iLineNumber = 1;
  579. // Reserve enough space for ... hm ... 10 textures
  580. aszTextures.reserve(10);
  581. // Reserve enough space for ... hm ... 1000 triangles
  582. asTriangles.reserve(1000);
  583. // Reserve enough space for ... hm ... 20 bones
  584. asBones.reserve(20);
  585. aszTextures.clear();
  586. asTriangles.clear();
  587. asBones.clear();
  588. // parse the file ...
  589. ParseFile();
  590. }
  591. // ------------------------------------------------------------------------------------------------
  592. unsigned int SMDImporter::GetTextureIndex(const std::string& filename) {
  593. unsigned int iIndex = 0;
  594. for (std::vector<std::string>::const_iterator
  595. i = aszTextures.begin();
  596. i != aszTextures.end();++i,++iIndex) {
  597. // case-insensitive ... it's a path
  598. if (0 == ASSIMP_stricmp ( filename.c_str(),(*i).c_str())) {
  599. return iIndex;
  600. }
  601. }
  602. iIndex = (unsigned int)aszTextures.size();
  603. aszTextures.push_back(filename);
  604. return iIndex;
  605. }
  606. // ------------------------------------------------------------------------------------------------
  607. // Parse the nodes section of the file
  608. void SMDImporter::ParseNodesSection(const char* szCurrent, const char** szCurrentOut) {
  609. for ( ;; ) {
  610. // "end\n" - Ends the nodes section
  611. if (0 == ASSIMP_strincmp(szCurrent,"end",3) && IsSpaceOrNewLine(*(szCurrent+3))) {
  612. szCurrent += 4;
  613. break;
  614. }
  615. ParseNodeInfo(szCurrent,&szCurrent);
  616. }
  617. SkipSpacesAndLineEnd(szCurrent,&szCurrent);
  618. *szCurrentOut = szCurrent;
  619. }
  620. // ------------------------------------------------------------------------------------------------
  621. // Parse the triangles section of the file
  622. void SMDImporter::ParseTrianglesSection(const char* szCurrent, const char** szCurrentOut) {
  623. // Parse a triangle, parse another triangle, parse the next triangle ...
  624. // and so on until we reach a token that looks quite similar to "end"
  625. for ( ;; ) {
  626. if(!SkipSpacesAndLineEnd(szCurrent,&szCurrent)) {
  627. break;
  628. }
  629. // "end\n" - Ends the triangles section
  630. if (TokenMatch(szCurrent,"end",3)) {
  631. break;
  632. }
  633. ParseTriangle(szCurrent,&szCurrent);
  634. }
  635. SkipSpacesAndLineEnd(szCurrent,&szCurrent);
  636. *szCurrentOut = szCurrent;
  637. }
  638. // ------------------------------------------------------------------------------------------------
  639. // Parse the vertex animation section of the file
  640. void SMDImporter::ParseVASection(const char* szCurrent, const char** szCurrentOut) {
  641. unsigned int iCurIndex = 0;
  642. for ( ;; ) {
  643. if (!SkipSpacesAndLineEnd(szCurrent,&szCurrent)) {
  644. break;
  645. }
  646. // "end\n" - Ends the "vertexanimation" section
  647. if (TokenMatch(szCurrent,"end",3)) {
  648. break;
  649. }
  650. // "time <n>\n"
  651. if (TokenMatch(szCurrent,"time",4)) {
  652. // NOTE: The doc says that time values COULD be negative ...
  653. // NOTE2: this is the shape key -> valve docs
  654. int iTime = 0;
  655. if(!ParseSignedInt(szCurrent,&szCurrent,iTime) || configFrameID != (unsigned int)iTime) {
  656. break;
  657. }
  658. SkipLine(szCurrent,&szCurrent);
  659. } else {
  660. if(0 == iCurIndex) {
  661. asTriangles.emplace_back();
  662. }
  663. if (++iCurIndex == 3) {
  664. iCurIndex = 0;
  665. }
  666. ParseVertex(szCurrent,&szCurrent,asTriangles.back().avVertices[iCurIndex],true);
  667. }
  668. }
  669. if (iCurIndex != 2 && !asTriangles.empty()) {
  670. // we want to no degenerates, so throw this triangle away
  671. asTriangles.pop_back();
  672. }
  673. SkipSpacesAndLineEnd(szCurrent,&szCurrent);
  674. *szCurrentOut = szCurrent;
  675. }
  676. // ------------------------------------------------------------------------------------------------
  677. // Parse the skeleton section of the file
  678. void SMDImporter::ParseSkeletonSection(const char* szCurrent, const char** szCurrentOut) {
  679. int iTime = 0;
  680. for ( ;; ) {
  681. if (!SkipSpacesAndLineEnd(szCurrent,&szCurrent)) {
  682. break;
  683. }
  684. // "end\n" - Ends the skeleton section
  685. if (TokenMatch(szCurrent,"end",3)) {
  686. break;
  687. } else if (TokenMatch(szCurrent,"time",4)) {
  688. // "time <n>\n" - Specifies the current animation frame
  689. if(!ParseSignedInt(szCurrent,&szCurrent,iTime)) {
  690. break;
  691. }
  692. iSmallestFrame = std::min(iSmallestFrame,iTime);
  693. SkipLine(szCurrent,&szCurrent);
  694. } else {
  695. ParseSkeletonElement(szCurrent,&szCurrent,iTime);
  696. }
  697. }
  698. *szCurrentOut = szCurrent;
  699. }
  700. // ------------------------------------------------------------------------------------------------
  701. #define SMDI_PARSE_RETURN { \
  702. SkipLine(szCurrent,&szCurrent); \
  703. *szCurrentOut = szCurrent; \
  704. return; \
  705. }
  706. // ------------------------------------------------------------------------------------------------
  707. // Parse a node line
  708. void SMDImporter::ParseNodeInfo(const char* szCurrent, const char** szCurrentOut) {
  709. unsigned int iBone = 0;
  710. SkipSpacesAndLineEnd(szCurrent,&szCurrent);
  711. if ( !ParseUnsignedInt(szCurrent,&szCurrent,iBone) || !SkipSpaces(szCurrent,&szCurrent)) {
  712. throw DeadlyImportError("Unexpected EOF/EOL while parsing bone index");
  713. }
  714. if (iBone == UINT_MAX) {
  715. LogErrorNoThrow("Invalid bone number while parsing bone index");
  716. SMDI_PARSE_RETURN;
  717. }
  718. // add our bone to the list
  719. if (iBone >= asBones.size()) {
  720. asBones.resize(iBone+1);
  721. }
  722. SMD::Bone& bone = asBones[iBone];
  723. bool bQuota = true;
  724. if ('\"' != *szCurrent) {
  725. LogWarning("Bone name is expected to be enclosed in "
  726. "double quotation marks. ");
  727. bQuota = false;
  728. } else {
  729. ++szCurrent;
  730. }
  731. const char* szEnd = szCurrent;
  732. for ( ;; ) {
  733. if (bQuota && '\"' == *szEnd) {
  734. iBone = (unsigned int)(szEnd - szCurrent);
  735. ++szEnd;
  736. break;
  737. } else if (!bQuota && IsSpaceOrNewLine(*szEnd)) {
  738. iBone = (unsigned int)(szEnd - szCurrent);
  739. break;
  740. } else if (!(*szEnd)) {
  741. LogErrorNoThrow("Unexpected EOF/EOL while parsing bone name");
  742. SMDI_PARSE_RETURN;
  743. }
  744. ++szEnd;
  745. }
  746. bone.mName = std::string(szCurrent,iBone);
  747. szCurrent = szEnd;
  748. // the only negative bone parent index that could occur is -1 AFAIK
  749. if(!ParseSignedInt(szCurrent,&szCurrent,(int&)bone.iParent)) {
  750. LogErrorNoThrow("Unexpected EOF/EOL while parsing bone parent index. Assuming -1");
  751. SMDI_PARSE_RETURN;
  752. }
  753. // go to the beginning of the next line
  754. SMDI_PARSE_RETURN;
  755. }
  756. // ------------------------------------------------------------------------------------------------
  757. // Parse a skeleton element
  758. void SMDImporter::ParseSkeletonElement(const char* szCurrent, const char** szCurrentOut,int iTime) {
  759. aiVector3D vPos;
  760. aiVector3D vRot;
  761. unsigned int iBone = 0;
  762. if(!ParseUnsignedInt(szCurrent,&szCurrent,iBone)) {
  763. ASSIMP_LOG_ERROR("Unexpected EOF/EOL while parsing bone index");
  764. SMDI_PARSE_RETURN;
  765. }
  766. if (iBone >= asBones.size()) {
  767. LogErrorNoThrow("Bone index in skeleton section is out of range");
  768. SMDI_PARSE_RETURN;
  769. }
  770. SMD::Bone& bone = asBones[iBone];
  771. bone.sAnim.asKeys.emplace_back();
  772. SMD::Bone::Animation::MatrixKey& key = bone.sAnim.asKeys.back();
  773. key.dTime = (double)iTime;
  774. if(!ParseFloat(szCurrent,&szCurrent,(float&)vPos.x)) {
  775. LogErrorNoThrow("Unexpected EOF/EOL while parsing bone.pos.x");
  776. SMDI_PARSE_RETURN;
  777. }
  778. if(!ParseFloat(szCurrent,&szCurrent,(float&)vPos.y)) {
  779. LogErrorNoThrow("Unexpected EOF/EOL while parsing bone.pos.y");
  780. SMDI_PARSE_RETURN;
  781. }
  782. if(!ParseFloat(szCurrent,&szCurrent,(float&)vPos.z)) {
  783. LogErrorNoThrow("Unexpected EOF/EOL while parsing bone.pos.z");
  784. SMDI_PARSE_RETURN;
  785. }
  786. if(!ParseFloat(szCurrent,&szCurrent,(float&)vRot.x)) {
  787. LogErrorNoThrow("Unexpected EOF/EOL while parsing bone.rot.x");
  788. SMDI_PARSE_RETURN;
  789. }
  790. if(!ParseFloat(szCurrent,&szCurrent,(float&)vRot.y)) {
  791. LogErrorNoThrow("Unexpected EOF/EOL while parsing bone.rot.y");
  792. SMDI_PARSE_RETURN;
  793. }
  794. if(!ParseFloat(szCurrent,&szCurrent,(float&)vRot.z)) {
  795. LogErrorNoThrow("Unexpected EOF/EOL while parsing bone.rot.z");
  796. SMDI_PARSE_RETURN;
  797. }
  798. // build the transformation matrix of the key
  799. key.matrix.FromEulerAnglesXYZ(vRot.x,vRot.y,vRot.z); {
  800. aiMatrix4x4 mTemp;
  801. mTemp.a4 = vPos.x;
  802. mTemp.b4 = vPos.y;
  803. mTemp.c4 = vPos.z;
  804. key.matrix = mTemp * key.matrix;
  805. }
  806. key.vPos = vPos;
  807. key.vRot = vRot;
  808. // go to the beginning of the next line
  809. SMDI_PARSE_RETURN;
  810. }
  811. // ------------------------------------------------------------------------------------------------
  812. // Parse a triangle
  813. void SMDImporter::ParseTriangle(const char* szCurrent, const char** szCurrentOut) {
  814. asTriangles.emplace_back();
  815. SMD::Face& face = asTriangles.back();
  816. if(!SkipSpaces(szCurrent,&szCurrent)) {
  817. LogErrorNoThrow("Unexpected EOF/EOL while parsing a triangle");
  818. return;
  819. }
  820. // read the texture file name
  821. const char* szLast = szCurrent;
  822. while (!IsSpaceOrNewLine(*++szCurrent));
  823. // ... and get the index that belongs to this file name
  824. face.iTexture = GetTextureIndex(std::string(szLast,(uintptr_t)szCurrent-(uintptr_t)szLast));
  825. SkipSpacesAndLineEnd(szCurrent,&szCurrent);
  826. // load three vertices
  827. for (auto &avVertex : face.avVertices) {
  828. ParseVertex(szCurrent,&szCurrent, avVertex);
  829. }
  830. *szCurrentOut = szCurrent;
  831. }
  832. // ------------------------------------------------------------------------------------------------
  833. // Parse a float
  834. bool SMDImporter::ParseFloat(const char* szCurrent, const char** szCurrentOut, float& out) {
  835. if(!SkipSpaces(&szCurrent)) {
  836. return false;
  837. }
  838. *szCurrentOut = fast_atoreal_move<float>(szCurrent,out);
  839. return true;
  840. }
  841. // ------------------------------------------------------------------------------------------------
  842. // Parse an unsigned int
  843. bool SMDImporter::ParseUnsignedInt(const char* szCurrent, const char** szCurrentOut, unsigned int& out) {
  844. if(!SkipSpaces(&szCurrent)) {
  845. return false;
  846. }
  847. out = strtoul10(szCurrent,szCurrentOut);
  848. return true;
  849. }
  850. // ------------------------------------------------------------------------------------------------
  851. // Parse a signed int
  852. bool SMDImporter::ParseSignedInt(const char* szCurrent, const char** szCurrentOut, int& out) {
  853. if(!SkipSpaces(&szCurrent)) {
  854. return false;
  855. }
  856. out = strtol10(szCurrent,szCurrentOut);
  857. return true;
  858. }
  859. // ------------------------------------------------------------------------------------------------
  860. // Parse a vertex
  861. void SMDImporter::ParseVertex(const char* szCurrent,
  862. const char** szCurrentOut, SMD::Vertex& vertex,
  863. bool bVASection /*= false*/) {
  864. if (SkipSpaces(&szCurrent) && IsLineEnd(*szCurrent)) {
  865. SkipSpacesAndLineEnd(szCurrent,&szCurrent);
  866. return ParseVertex(szCurrent,szCurrentOut,vertex,bVASection);
  867. }
  868. if(!ParseSignedInt(szCurrent,&szCurrent,(int&)vertex.iParentNode)) {
  869. LogErrorNoThrow("Unexpected EOF/EOL while parsing vertex.parent");
  870. SMDI_PARSE_RETURN;
  871. }
  872. if(!ParseFloat(szCurrent,&szCurrent,(float&)vertex.pos.x)) {
  873. LogErrorNoThrow("Unexpected EOF/EOL while parsing vertex.pos.x");
  874. SMDI_PARSE_RETURN;
  875. }
  876. if(!ParseFloat(szCurrent,&szCurrent,(float&)vertex.pos.y)) {
  877. LogErrorNoThrow("Unexpected EOF/EOL while parsing vertex.pos.y");
  878. SMDI_PARSE_RETURN;
  879. }
  880. if(!ParseFloat(szCurrent,&szCurrent,(float&)vertex.pos.z)) {
  881. LogErrorNoThrow("Unexpected EOF/EOL while parsing vertex.pos.z");
  882. SMDI_PARSE_RETURN;
  883. }
  884. if(!ParseFloat(szCurrent,&szCurrent,(float&)vertex.nor.x)) {
  885. LogErrorNoThrow("Unexpected EOF/EOL while parsing vertex.nor.x");
  886. SMDI_PARSE_RETURN;
  887. }
  888. if(!ParseFloat(szCurrent,&szCurrent,(float&)vertex.nor.y)) {
  889. LogErrorNoThrow("Unexpected EOF/EOL while parsing vertex.nor.y");
  890. SMDI_PARSE_RETURN;
  891. }
  892. if(!ParseFloat(szCurrent,&szCurrent,(float&)vertex.nor.z)) {
  893. LogErrorNoThrow("Unexpected EOF/EOL while parsing vertex.nor.z");
  894. SMDI_PARSE_RETURN;
  895. }
  896. if (bVASection) {
  897. SMDI_PARSE_RETURN;
  898. }
  899. if(!ParseFloat(szCurrent,&szCurrent,(float&)vertex.uv.x)) {
  900. LogErrorNoThrow("Unexpected EOF/EOL while parsing vertex.uv.x");
  901. SMDI_PARSE_RETURN;
  902. }
  903. if(!ParseFloat(szCurrent,&szCurrent,(float&)vertex.uv.y)) {
  904. LogErrorNoThrow("Unexpected EOF/EOL while parsing vertex.uv.y");
  905. SMDI_PARSE_RETURN;
  906. }
  907. // now read the number of bones affecting this vertex
  908. // all elements from now are fully optional, we don't need them
  909. unsigned int iSize = 0;
  910. if(!ParseUnsignedInt(szCurrent,&szCurrent,iSize)) {
  911. SMDI_PARSE_RETURN;
  912. }
  913. vertex.aiBoneLinks.resize(iSize,std::pair<unsigned int, float>(0,0.0f));
  914. for (auto &aiBoneLink : vertex.aiBoneLinks) {
  915. if(!ParseUnsignedInt(szCurrent,&szCurrent,aiBoneLink.first)) {
  916. SMDI_PARSE_RETURN;
  917. }
  918. if(!ParseFloat(szCurrent,&szCurrent,aiBoneLink.second)) {
  919. SMDI_PARSE_RETURN;
  920. }
  921. }
  922. // go to the beginning of the next line
  923. SMDI_PARSE_RETURN;
  924. }
  925. }
  926. #endif // !! ASSIMP_BUILD_NO_SMD_IMPORTER