ColladaLoader.cpp 81 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822
  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 Implementation of the Collada loader */
  35. #ifndef ASSIMP_BUILD_NO_COLLADA_IMPORTER
  36. #include "ColladaLoader.h"
  37. #include "ColladaParser.h"
  38. #include <assimp/ColladaMetaData.h>
  39. #include <assimp/CreateAnimMesh.h>
  40. #include <assimp/ParsingUtils.h>
  41. #include <assimp/SkeletonMeshBuilder.h>
  42. #include <assimp/ZipArchiveIOSystem.h>
  43. #include <assimp/anim.h>
  44. #include <assimp/fast_atof.h>
  45. #include <assimp/importerdesc.h>
  46. #include <assimp/scene.h>
  47. #include <assimp/DefaultLogger.hpp>
  48. #include <assimp/Importer.hpp>
  49. #include <numeric>
  50. namespace Assimp {
  51. using namespace Assimp::Formatter;
  52. using namespace Assimp::Collada;
  53. static constexpr aiImporterDesc desc = {
  54. "Collada Importer",
  55. "",
  56. "",
  57. "http://collada.org",
  58. aiImporterFlags_SupportTextFlavour | aiImporterFlags_SupportCompressedFlavour,
  59. 1,
  60. 3,
  61. 1,
  62. 5,
  63. "dae xml zae"
  64. };
  65. static const float kMillisecondsFromSeconds = 1000.f;
  66. // Add an item of metadata to a node
  67. // Assumes the key is not already in the list
  68. template <typename T>
  69. inline void AddNodeMetaData(aiNode *node, const std::string &key, const T &value) {
  70. if (nullptr == node->mMetaData) {
  71. node->mMetaData = new aiMetadata();
  72. }
  73. node->mMetaData->Add(key, value);
  74. }
  75. // ------------------------------------------------------------------------------------------------
  76. // Constructor to be privately used by Importer
  77. ColladaLoader::ColladaLoader() :
  78. noSkeletonMesh(false),
  79. removeEmptyBones(false),
  80. ignoreUpDirection(false),
  81. ignoreUnitSize(false),
  82. useColladaName(false),
  83. mNodeNameCounter(0) {
  84. // empty
  85. }
  86. // ------------------------------------------------------------------------------------------------
  87. // Returns whether the class can handle the format of the given file.
  88. bool ColladaLoader::CanRead(const std::string &pFile, IOSystem *pIOHandler, bool /*checkSig*/) const {
  89. // Look for a DAE file inside, but don't extract it
  90. ZipArchiveIOSystem zip_archive(pIOHandler, pFile);
  91. if (zip_archive.isOpen()) {
  92. return !ColladaParser::ReadZaeManifest(zip_archive).empty();
  93. }
  94. static const char *tokens[] = { "<collada" };
  95. return SearchFileHeaderForToken(pIOHandler, pFile, tokens, AI_COUNT_OF(tokens));
  96. }
  97. // ------------------------------------------------------------------------------------------------
  98. void ColladaLoader::SetupProperties(const Importer *pImp) {
  99. noSkeletonMesh = pImp->GetPropertyInteger(AI_CONFIG_IMPORT_NO_SKELETON_MESHES, 0) != 0;
  100. removeEmptyBones = pImp->GetPropertyInteger(AI_CONFIG_IMPORT_REMOVE_EMPTY_BONES, true) != 0;
  101. ignoreUpDirection = pImp->GetPropertyInteger(AI_CONFIG_IMPORT_COLLADA_IGNORE_UP_DIRECTION, 0) != 0;
  102. ignoreUnitSize = pImp->GetPropertyInteger(AI_CONFIG_IMPORT_COLLADA_IGNORE_UNIT_SIZE, 0) != 0;
  103. useColladaName = pImp->GetPropertyInteger(AI_CONFIG_IMPORT_COLLADA_USE_COLLADA_NAMES, 0) != 0;
  104. }
  105. // ------------------------------------------------------------------------------------------------
  106. // Get file extension list
  107. const aiImporterDesc *ColladaLoader::GetInfo() const {
  108. return &desc;
  109. }
  110. // ------------------------------------------------------------------------------------------------
  111. // Imports the given file into the given scene structure.
  112. void ColladaLoader::InternReadFile(const std::string &pFile, aiScene *pScene, IOSystem *pIOHandler) {
  113. mFileName = pFile;
  114. // clean all member arrays - just for safety, it should work even if we did not
  115. mMeshIndexByID.clear();
  116. mMaterialIndexByName.clear();
  117. mMeshes.clear();
  118. mTargetMeshes.clear();
  119. newMats.clear();
  120. mLights.clear();
  121. mCameras.clear();
  122. mTextures.clear();
  123. mAnims.clear();
  124. // parse the input file
  125. ColladaParser parser(pIOHandler, pFile);
  126. if (!parser.mRootNode) {
  127. throw DeadlyImportError("Collada: File came out empty. Something is wrong here.");
  128. }
  129. // reserve some storage to avoid unnecessary reallocs
  130. newMats.reserve(parser.mMaterialLibrary.size() * 2u);
  131. mMeshes.reserve(parser.mMeshLibrary.size() * 2u);
  132. mCameras.reserve(parser.mCameraLibrary.size());
  133. mLights.reserve(parser.mLightLibrary.size());
  134. // create the materials first, for the meshes to find
  135. BuildMaterials(parser, pScene);
  136. // build the node hierarchy from it
  137. pScene->mRootNode = BuildHierarchy(parser, parser.mRootNode);
  138. // ... then fill the materials with the now adjusted settings
  139. FillMaterials(parser, pScene);
  140. if (!ignoreUnitSize) {
  141. // Apply unit-size scale calculation
  142. pScene->mRootNode->mTransformation *= aiMatrix4x4(
  143. parser.mUnitSize, 0, 0, 0,
  144. 0, parser.mUnitSize, 0, 0,
  145. 0, 0, parser.mUnitSize, 0,
  146. 0, 0, 0, 1);
  147. }
  148. if (!ignoreUpDirection) {
  149. // Convert to Y_UP, if different orientation
  150. if (parser.mUpDirection == ColladaParser::UP_X) {
  151. pScene->mRootNode->mTransformation *= aiMatrix4x4(
  152. 0, -1, 0, 0,
  153. 1, 0, 0, 0,
  154. 0, 0, 1, 0,
  155. 0, 0, 0, 1);
  156. } else if (parser.mUpDirection == ColladaParser::UP_Z) {
  157. pScene->mRootNode->mTransformation *= aiMatrix4x4(
  158. 1, 0, 0, 0,
  159. 0, 0, 1, 0,
  160. 0, -1, 0, 0,
  161. 0, 0, 0, 1);
  162. }
  163. }
  164. // Store scene metadata
  165. if (!parser.mAssetMetaData.empty()) {
  166. const size_t numMeta(parser.mAssetMetaData.size());
  167. pScene->mMetaData = aiMetadata::Alloc(static_cast<unsigned int>(numMeta));
  168. size_t i = 0;
  169. for (auto it = parser.mAssetMetaData.cbegin(); it != parser.mAssetMetaData.cend(); ++it, ++i) {
  170. pScene->mMetaData->Set(static_cast<unsigned int>(i), (*it).first, (*it).second);
  171. }
  172. }
  173. StoreSceneMeshes(pScene);
  174. StoreSceneMaterials(pScene);
  175. StoreSceneTextures(pScene);
  176. StoreSceneLights(pScene);
  177. StoreSceneCameras(pScene);
  178. StoreAnimations(pScene, parser);
  179. // If no meshes have been loaded, it's probably just an animated skeleton.
  180. if (0u == pScene->mNumMeshes) {
  181. if (!noSkeletonMesh) {
  182. SkeletonMeshBuilder hero(pScene);
  183. }
  184. pScene->mFlags |= AI_SCENE_FLAGS_INCOMPLETE;
  185. }
  186. }
  187. // ------------------------------------------------------------------------------------------------
  188. // Recursively constructs a scene node for the given parser node and returns it.
  189. aiNode *ColladaLoader::BuildHierarchy(const ColladaParser &pParser, const Collada::Node *pNode) {
  190. // create a node for it
  191. aiNode *node = new aiNode();
  192. // find a name for the new node. It's more complicated than you might think
  193. node->mName.Set(FindNameForNode(pNode));
  194. // if we're not using the unique IDs, hold onto them for reference and export
  195. if (useColladaName) {
  196. if (!pNode->mID.empty()) {
  197. AddNodeMetaData(node, AI_METADATA_COLLADA_ID, aiString(pNode->mID));
  198. }
  199. if (!pNode->mSID.empty()) {
  200. AddNodeMetaData(node, AI_METADATA_COLLADA_SID, aiString(pNode->mSID));
  201. }
  202. }
  203. // calculate the transformation matrix for it
  204. node->mTransformation = pParser.CalculateResultTransform(pNode->mTransforms);
  205. // now resolve node instances
  206. std::vector<const Node*> instances;
  207. ResolveNodeInstances(pParser, pNode, instances);
  208. // add children. first the *real* ones
  209. node->mNumChildren = static_cast<unsigned int>(pNode->mChildren.size() + instances.size());
  210. if (node->mNumChildren != 0) {
  211. node->mChildren = new aiNode * [node->mNumChildren];
  212. }
  213. for (size_t a = 0; a < pNode->mChildren.size(); ++a) {
  214. node->mChildren[a] = BuildHierarchy(pParser, pNode->mChildren[a]);
  215. node->mChildren[a]->mParent = node;
  216. }
  217. // ... and finally the resolved node instances
  218. for (size_t a = 0; a < instances.size(); ++a) {
  219. node->mChildren[pNode->mChildren.size() + a] = BuildHierarchy(pParser, instances[a]);
  220. node->mChildren[pNode->mChildren.size() + a]->mParent = node;
  221. }
  222. BuildMeshesForNode(pParser, pNode, node);
  223. BuildCamerasForNode(pParser, pNode, node);
  224. BuildLightsForNode(pParser, pNode, node);
  225. return node;
  226. }
  227. // ------------------------------------------------------------------------------------------------
  228. // Resolve node instances
  229. void ColladaLoader::ResolveNodeInstances(const ColladaParser &pParser, const Node *pNode,
  230. std::vector<const Node*> &resolved) {
  231. // reserve enough storage
  232. resolved.reserve(pNode->mNodeInstances.size());
  233. // ... and iterate through all nodes to be instanced as children of pNode
  234. for (const auto &nodeInst : pNode->mNodeInstances) {
  235. // find the corresponding node in the library
  236. const ColladaParser::NodeLibrary::const_iterator itt = pParser.mNodeLibrary.find(nodeInst.mNode);
  237. const Node *nd = itt == pParser.mNodeLibrary.end() ? nullptr : (*itt).second;
  238. // FIX for http://sourceforge.net/tracker/?func=detail&aid=3054873&group_id=226462&atid=1067632
  239. // need to check for both name and ID to catch all. To avoid breaking valid files,
  240. // the workaround is only enabled when the first attempt to resolve the node has failed.
  241. if (nullptr == nd) {
  242. nd = FindNode(pParser.mRootNode, nodeInst.mNode);
  243. }
  244. if (nullptr == nd) {
  245. ASSIMP_LOG_ERROR("Collada: Unable to resolve reference to instanced node ", nodeInst.mNode);
  246. } else {
  247. // attach this node to the list of children
  248. resolved.push_back(nd);
  249. }
  250. }
  251. }
  252. // ------------------------------------------------------------------------------------------------
  253. // Resolve UV channels
  254. void ColladaLoader::ApplyVertexToEffectSemanticMapping(Sampler &sampler, const SemanticMappingTable &table) {
  255. SemanticMappingTable::InputSemanticMap::const_iterator it = table.mMap.find(sampler.mUVChannel);
  256. if (it == table.mMap.end()) {
  257. return;
  258. }
  259. if (it->second.mType != IT_Texcoord) {
  260. ASSIMP_LOG_ERROR("Collada: Unexpected effect input mapping");
  261. }
  262. sampler.mUVId = it->second.mSet;
  263. }
  264. // ------------------------------------------------------------------------------------------------
  265. // Builds lights for the given node and references them
  266. void ColladaLoader::BuildLightsForNode(const ColladaParser &pParser, const Node *pNode, aiNode *pTarget) {
  267. for (const LightInstance &lid : pNode->mLights) {
  268. // find the referred light
  269. ColladaParser::LightLibrary::const_iterator srcLightIt = pParser.mLightLibrary.find(lid.mLight);
  270. if (srcLightIt == pParser.mLightLibrary.end()) {
  271. ASSIMP_LOG_WARN("Collada: Unable to find light for ID \"", lid.mLight, "\". Skipping.");
  272. continue;
  273. }
  274. const Collada::Light *srcLight = &srcLightIt->second;
  275. // now fill our ai data structure
  276. aiLight *out = new aiLight();
  277. out->mName = pTarget->mName;
  278. out->mType = (aiLightSourceType)srcLight->mType;
  279. // collada lights point in -Z by default, rest is specified in node transform
  280. out->mDirection = aiVector3D(0.f, 0.f, -1.f);
  281. out->mAttenuationConstant = srcLight->mAttConstant;
  282. out->mAttenuationLinear = srcLight->mAttLinear;
  283. out->mAttenuationQuadratic = srcLight->mAttQuadratic;
  284. out->mColorDiffuse = out->mColorSpecular = out->mColorAmbient = srcLight->mColor * srcLight->mIntensity;
  285. if (out->mType == aiLightSource_AMBIENT) {
  286. out->mColorDiffuse = out->mColorSpecular = aiColor3D(0, 0, 0);
  287. out->mColorAmbient = srcLight->mColor * srcLight->mIntensity;
  288. } else {
  289. // collada doesn't differentiate between these color types
  290. out->mColorDiffuse = out->mColorSpecular = srcLight->mColor * srcLight->mIntensity;
  291. out->mColorAmbient = aiColor3D(0, 0, 0);
  292. }
  293. // convert falloff angle and falloff exponent in our representation, if given
  294. if (out->mType == aiLightSource_SPOT) {
  295. out->mAngleInnerCone = AI_DEG_TO_RAD(srcLight->mFalloffAngle);
  296. // ... some extension magic.
  297. if (srcLight->mOuterAngle >= ASSIMP_COLLADA_LIGHT_ANGLE_NOT_SET * (1 - ai_epsilon)) {
  298. // ... some deprecation magic.
  299. if (srcLight->mPenumbraAngle >= ASSIMP_COLLADA_LIGHT_ANGLE_NOT_SET * (1 - ai_epsilon)) {
  300. // Need to rely on falloff_exponent. I don't know how to interpret it, so I need to guess ....
  301. // epsilon chosen to be 0.1
  302. float f = 1.0f;
  303. if ( 0.0f != srcLight->mFalloffExponent ) {
  304. f = 1.f / srcLight->mFalloffExponent;
  305. }
  306. out->mAngleOuterCone = std::acos(std::pow(0.1f, f)) +
  307. out->mAngleInnerCone;
  308. } else {
  309. out->mAngleOuterCone = out->mAngleInnerCone + AI_DEG_TO_RAD(srcLight->mPenumbraAngle);
  310. if (out->mAngleOuterCone < out->mAngleInnerCone)
  311. std::swap(out->mAngleInnerCone, out->mAngleOuterCone);
  312. }
  313. } else {
  314. out->mAngleOuterCone = AI_DEG_TO_RAD(srcLight->mOuterAngle);
  315. }
  316. }
  317. // add to light list
  318. mLights.push_back(out);
  319. }
  320. }
  321. // ------------------------------------------------------------------------------------------------
  322. // Builds cameras for the given node and references them
  323. void ColladaLoader::BuildCamerasForNode(const ColladaParser &pParser, const Node *pNode, aiNode *pTarget) {
  324. for (const CameraInstance &cid : pNode->mCameras) {
  325. // find the referred light
  326. ColladaParser::CameraLibrary::const_iterator srcCameraIt = pParser.mCameraLibrary.find(cid.mCamera);
  327. if (srcCameraIt == pParser.mCameraLibrary.end()) {
  328. ASSIMP_LOG_WARN("Collada: Unable to find camera for ID \"", cid.mCamera, "\". Skipping.");
  329. continue;
  330. }
  331. const Collada::Camera *srcCamera = &srcCameraIt->second;
  332. // orthographic cameras not yet supported in Assimp
  333. if (srcCamera->mOrtho) {
  334. ASSIMP_LOG_WARN("Collada: Orthographic cameras are not supported.");
  335. }
  336. // now fill our ai data structure
  337. aiCamera *out = new aiCamera();
  338. out->mName = pTarget->mName;
  339. // collada cameras point in -Z by default, rest is specified in node transform
  340. out->mLookAt = aiVector3D(0.f, 0.f, -1.f);
  341. // near/far z is already ok
  342. out->mClipPlaneFar = srcCamera->mZFar;
  343. out->mClipPlaneNear = srcCamera->mZNear;
  344. // ... but for the rest some values are optional
  345. // and we need to compute the others in any combination.
  346. if (srcCamera->mAspect != 10e10f) {
  347. out->mAspect = srcCamera->mAspect;
  348. }
  349. if (srcCamera->mHorFov != 10e10f) {
  350. out->mHorizontalFOV = srcCamera->mHorFov;
  351. if (srcCamera->mVerFov != 10e10f && srcCamera->mAspect == 10e10f) {
  352. out->mAspect = std::tan(AI_DEG_TO_RAD(srcCamera->mHorFov)) /
  353. std::tan(AI_DEG_TO_RAD(srcCamera->mVerFov));
  354. }
  355. } else if (srcCamera->mAspect != 10e10f && srcCamera->mVerFov != 10e10f) {
  356. out->mHorizontalFOV = 2.0f * AI_RAD_TO_DEG(std::atan(srcCamera->mAspect *
  357. std::tan(AI_DEG_TO_RAD(srcCamera->mVerFov) * 0.5f)));
  358. }
  359. // Collada uses degrees, we use radians
  360. out->mHorizontalFOV = AI_DEG_TO_RAD(out->mHorizontalFOV);
  361. // add to camera list
  362. mCameras.push_back(out);
  363. }
  364. }
  365. // ------------------------------------------------------------------------------------------------
  366. // Builds meshes for the given node and references them
  367. void ColladaLoader::BuildMeshesForNode(const ColladaParser &pParser, const Node *pNode, aiNode *pTarget) {
  368. // accumulated mesh references by this node
  369. std::vector<size_t> newMeshRefs;
  370. newMeshRefs.reserve(pNode->mMeshes.size());
  371. // add a mesh for each subgroup in each collada mesh
  372. for (const MeshInstance &mid : pNode->mMeshes) {
  373. const Mesh *srcMesh = nullptr;
  374. const Controller *srcController = nullptr;
  375. // find the referred mesh
  376. ColladaParser::MeshLibrary::const_iterator srcMeshIt = pParser.mMeshLibrary.find(mid.mMeshOrController);
  377. if (srcMeshIt == pParser.mMeshLibrary.end()) {
  378. // if not found in the mesh-library, it might also be a controller referring to a mesh
  379. ColladaParser::ControllerLibrary::const_iterator srcContrIt = pParser.mControllerLibrary.find(mid.mMeshOrController);
  380. if (srcContrIt != pParser.mControllerLibrary.end()) {
  381. srcController = &srcContrIt->second;
  382. srcMeshIt = pParser.mMeshLibrary.find(srcController->mMeshId);
  383. if (srcMeshIt != pParser.mMeshLibrary.end()) {
  384. srcMesh = srcMeshIt->second;
  385. }
  386. }
  387. if (nullptr == srcMesh) {
  388. ASSIMP_LOG_WARN("Collada: Unable to find geometry for ID \"", mid.mMeshOrController, "\". Skipping.");
  389. continue;
  390. }
  391. } else {
  392. // ID found in the mesh library -> direct reference to an unskinned mesh
  393. srcMesh = srcMeshIt->second;
  394. }
  395. // build a mesh for each of its subgroups
  396. size_t vertexStart = 0, faceStart = 0;
  397. for (size_t sm = 0; sm < srcMesh->mSubMeshes.size(); ++sm) {
  398. const Collada::SubMesh &submesh = srcMesh->mSubMeshes[sm];
  399. if (submesh.mNumFaces == 0) {
  400. continue;
  401. }
  402. // find material assigned to this submesh
  403. std::string meshMaterial;
  404. std::map<std::string, SemanticMappingTable>::const_iterator meshMatIt = mid.mMaterials.find(submesh.mMaterial);
  405. const Collada::SemanticMappingTable *table = nullptr;
  406. if (meshMatIt != mid.mMaterials.end()) {
  407. table = &meshMatIt->second;
  408. meshMaterial = table->mMatName;
  409. } else {
  410. ASSIMP_LOG_WARN("Collada: No material specified for subgroup <", submesh.mMaterial, "> in geometry <",
  411. mid.mMeshOrController, ">.");
  412. if (!mid.mMaterials.empty()) {
  413. meshMaterial = mid.mMaterials.begin()->second.mMatName;
  414. }
  415. }
  416. // OK ... here the *real* fun starts ... we have the vertex-input-to-effect-semantic-table
  417. // given. The only mapping stuff which we do actually support is the UV channel.
  418. std::map<std::string, size_t>::const_iterator matIt = mMaterialIndexByName.find(meshMaterial);
  419. unsigned int matIdx = 0;
  420. if (matIt != mMaterialIndexByName.end()) {
  421. matIdx = static_cast<unsigned int>(matIt->second);
  422. }
  423. if (table && !table->mMap.empty()) {
  424. std::pair<Collada::Effect *, aiMaterial *> &mat = newMats[matIdx];
  425. // Iterate through all texture channels assigned to the effect and
  426. // check whether we have mapping information for it.
  427. ApplyVertexToEffectSemanticMapping(mat.first->mTexDiffuse, *table);
  428. ApplyVertexToEffectSemanticMapping(mat.first->mTexAmbient, *table);
  429. ApplyVertexToEffectSemanticMapping(mat.first->mTexSpecular, *table);
  430. ApplyVertexToEffectSemanticMapping(mat.first->mTexEmissive, *table);
  431. ApplyVertexToEffectSemanticMapping(mat.first->mTexTransparent, *table);
  432. ApplyVertexToEffectSemanticMapping(mat.first->mTexBump, *table);
  433. }
  434. // built lookup index of the Mesh-Submesh-Material combination
  435. ColladaMeshIndex index(mid.mMeshOrController, sm, meshMaterial);
  436. // if we already have the mesh at the library, just add its index to the node's array
  437. std::map<ColladaMeshIndex, size_t>::const_iterator dstMeshIt = mMeshIndexByID.find(index);
  438. if (dstMeshIt != mMeshIndexByID.end()) {
  439. newMeshRefs.push_back(dstMeshIt->second);
  440. } else {
  441. // else we have to add the mesh to the collection and store its newly assigned index at the node
  442. aiMesh *dstMesh = CreateMesh(pParser, srcMesh, submesh, srcController, vertexStart, faceStart);
  443. // store the mesh, and store its new index in the node
  444. newMeshRefs.push_back(mMeshes.size());
  445. mMeshIndexByID[index] = mMeshes.size();
  446. mMeshes.push_back(dstMesh);
  447. vertexStart += dstMesh->mNumVertices;
  448. faceStart += submesh.mNumFaces;
  449. // assign the material index
  450. std::map<std::string, size_t>::const_iterator subMatIt = mMaterialIndexByName.find(submesh.mMaterial);
  451. if (subMatIt != mMaterialIndexByName.end()) {
  452. dstMesh->mMaterialIndex = static_cast<unsigned int>(subMatIt->second);
  453. } else {
  454. dstMesh->mMaterialIndex = matIdx;
  455. }
  456. if (dstMesh->mName.length == 0) {
  457. dstMesh->mName = mid.mMeshOrController;
  458. }
  459. }
  460. }
  461. }
  462. // now place all mesh references we gathered in the target node
  463. pTarget->mNumMeshes = static_cast<unsigned int>(newMeshRefs.size());
  464. if (!newMeshRefs.empty()) {
  465. struct UIntTypeConverter {
  466. unsigned int operator()(const size_t &v) const {
  467. return static_cast<unsigned int>(v);
  468. }
  469. };
  470. pTarget->mMeshes = new unsigned int[pTarget->mNumMeshes];
  471. std::transform(newMeshRefs.begin(), newMeshRefs.end(), pTarget->mMeshes, UIntTypeConverter());
  472. }
  473. }
  474. // ------------------------------------------------------------------------------------------------
  475. // Find mesh from either meshes or morph target meshes
  476. aiMesh *ColladaLoader::findMesh(const std::string &meshid) {
  477. if (meshid.empty()) {
  478. return nullptr;
  479. }
  480. for (auto & mMeshe : mMeshes) {
  481. if (std::string(mMeshe->mName.data) == meshid) {
  482. return mMeshe;
  483. }
  484. }
  485. for (auto & mTargetMeshe : mTargetMeshes) {
  486. if (std::string(mTargetMeshe->mName.data) == meshid) {
  487. return mTargetMeshe;
  488. }
  489. }
  490. return nullptr;
  491. }
  492. // ------------------------------------------------------------------------------------------------
  493. // Creates a mesh for the given ColladaMesh face subset and returns the newly created mesh
  494. aiMesh *ColladaLoader::CreateMesh(const ColladaParser &pParser, const Mesh *pSrcMesh, const SubMesh &pSubMesh,
  495. const Controller *pSrcController, size_t pStartVertex, size_t pStartFace) {
  496. std::unique_ptr<aiMesh> dstMesh(new aiMesh);
  497. if (useColladaName) {
  498. dstMesh->mName = pSrcMesh->mName;
  499. } else {
  500. dstMesh->mName = pSrcMesh->mId;
  501. }
  502. if (pSrcMesh->mPositions.empty()) {
  503. return dstMesh.release();
  504. }
  505. // count the vertices addressed by its faces
  506. const size_t numVertices = std::accumulate(pSrcMesh->mFaceSize.begin() + pStartFace,
  507. pSrcMesh->mFaceSize.begin() + pStartFace + pSubMesh.mNumFaces, size_t(0));
  508. // copy positions
  509. dstMesh->mNumVertices = static_cast<unsigned int>(numVertices);
  510. dstMesh->mVertices = new aiVector3D[numVertices];
  511. std::copy(pSrcMesh->mPositions.begin() + pStartVertex, pSrcMesh->mPositions.begin() + pStartVertex + numVertices, dstMesh->mVertices);
  512. // normals, if given. HACK: (thom) Due to the glorious Collada spec we never
  513. // know if we have the same number of normals as there are positions. So we
  514. // also ignore any vertex attribute if it has a different count
  515. if (pSrcMesh->mNormals.size() >= pStartVertex + numVertices) {
  516. dstMesh->mNormals = new aiVector3D[numVertices];
  517. std::copy(pSrcMesh->mNormals.begin() + pStartVertex, pSrcMesh->mNormals.begin() + pStartVertex + numVertices, dstMesh->mNormals);
  518. }
  519. // tangents, if given.
  520. if (pSrcMesh->mTangents.size() >= pStartVertex + numVertices) {
  521. dstMesh->mTangents = new aiVector3D[numVertices];
  522. std::copy(pSrcMesh->mTangents.begin() + pStartVertex, pSrcMesh->mTangents.begin() + pStartVertex + numVertices, dstMesh->mTangents);
  523. }
  524. // bitangents, if given.
  525. if (pSrcMesh->mBitangents.size() >= pStartVertex + numVertices) {
  526. dstMesh->mBitangents = new aiVector3D[numVertices];
  527. std::copy(pSrcMesh->mBitangents.begin() + pStartVertex, pSrcMesh->mBitangents.begin() + pStartVertex + numVertices, dstMesh->mBitangents);
  528. }
  529. // same for texture coords, as many as we have
  530. for (size_t a = 0; a < AI_MAX_NUMBER_OF_TEXTURECOORDS; ++a) {
  531. if (pSrcMesh->mTexCoords[a].size() >= pStartVertex + numVertices) {
  532. dstMesh->mTextureCoords[a] = new aiVector3D[numVertices];
  533. for (size_t b = 0; b < numVertices; ++b) {
  534. dstMesh->mTextureCoords[a][b] = pSrcMesh->mTexCoords[a][pStartVertex + b];
  535. }
  536. dstMesh->mNumUVComponents[a] = pSrcMesh->mNumUVComponents[a];
  537. }
  538. }
  539. // same for vertex colors, as many as we have. again the same packing to avoid empty slots
  540. for (size_t a = 0, real = 0; a < AI_MAX_NUMBER_OF_COLOR_SETS; ++a) {
  541. if (pSrcMesh->mColors[a].size() >= pStartVertex + numVertices) {
  542. dstMesh->mColors[real] = new aiColor4D[numVertices];
  543. std::copy(pSrcMesh->mColors[a].begin() + pStartVertex, pSrcMesh->mColors[a].begin() + pStartVertex + numVertices, dstMesh->mColors[real]);
  544. ++real;
  545. }
  546. }
  547. // create faces. Due to the fact that each face uses unique vertices, we can simply count up on each vertex
  548. size_t vertex = 0;
  549. dstMesh->mNumFaces = static_cast<unsigned int>(pSubMesh.mNumFaces);
  550. dstMesh->mFaces = new aiFace[dstMesh->mNumFaces];
  551. for (size_t a = 0; a < dstMesh->mNumFaces; ++a) {
  552. size_t s = pSrcMesh->mFaceSize[pStartFace + a];
  553. aiFace &face = dstMesh->mFaces[a];
  554. face.mNumIndices = static_cast<unsigned int>(s);
  555. face.mIndices = new unsigned int[s];
  556. for (size_t b = 0; b < s; ++b) {
  557. face.mIndices[b] = static_cast<unsigned int>(vertex++);
  558. }
  559. }
  560. // create morph target meshes if any
  561. std::vector<aiMesh *> targetMeshes;
  562. std::vector<float> targetWeights;
  563. Collada::MorphMethod method = Normalized;
  564. for (std::map<std::string, Controller>::const_iterator it = pParser.mControllerLibrary.begin();
  565. it != pParser.mControllerLibrary.end(); ++it) {
  566. const Controller &c = it->second;
  567. const Collada::Mesh *baseMesh = pParser.ResolveLibraryReference(pParser.mMeshLibrary, c.mMeshId);
  568. if (c.mType == Collada::Morph && baseMesh->mName == pSrcMesh->mName) {
  569. const Collada::Accessor &targetAccessor = pParser.ResolveLibraryReference(pParser.mAccessorLibrary, c.mMorphTarget);
  570. const Collada::Accessor &weightAccessor = pParser.ResolveLibraryReference(pParser.mAccessorLibrary, c.mMorphWeight);
  571. const Collada::Data &targetData = pParser.ResolveLibraryReference(pParser.mDataLibrary, targetAccessor.mSource);
  572. const Collada::Data &weightData = pParser.ResolveLibraryReference(pParser.mDataLibrary, weightAccessor.mSource);
  573. // take method
  574. method = c.mMethod;
  575. if (!targetData.mIsStringArray) {
  576. throw DeadlyImportError("target data must contain id. ");
  577. }
  578. if (weightData.mIsStringArray) {
  579. throw DeadlyImportError("target weight data must not be textual ");
  580. }
  581. for (const auto & mString : targetData.mStrings) {
  582. const Mesh *targetMesh = pParser.ResolveLibraryReference(pParser.mMeshLibrary, mString);
  583. aiMesh *aimesh = findMesh(useColladaName ? targetMesh->mName : targetMesh->mId);
  584. if (!aimesh) {
  585. if (targetMesh->mSubMeshes.size() > 1) {
  586. throw DeadlyImportError("Morphing target mesh must be a single");
  587. }
  588. aimesh = CreateMesh(pParser, targetMesh, targetMesh->mSubMeshes.at(0), nullptr, 0, 0);
  589. mTargetMeshes.push_back(aimesh);
  590. }
  591. targetMeshes.push_back(aimesh);
  592. }
  593. for (float mValue : weightData.mValues) {
  594. targetWeights.push_back(mValue);
  595. }
  596. }
  597. }
  598. if (!targetMeshes.empty() && targetWeights.size() == targetMeshes.size()) {
  599. std::vector<aiAnimMesh *> animMeshes;
  600. for (unsigned int i = 0; i < targetMeshes.size(); ++i) {
  601. aiMesh *targetMesh = targetMeshes.at(i);
  602. aiAnimMesh *animMesh = aiCreateAnimMesh(targetMesh);
  603. float weight = targetWeights[i];
  604. animMesh->mWeight = weight == 0 ? 1.0f : weight;
  605. animMesh->mName = targetMesh->mName;
  606. animMeshes.push_back(animMesh);
  607. }
  608. dstMesh->mMethod = (method == Relative) ? aiMorphingMethod_MORPH_RELATIVE : aiMorphingMethod_MORPH_NORMALIZED;
  609. dstMesh->mAnimMeshes = new aiAnimMesh *[animMeshes.size()];
  610. dstMesh->mNumAnimMeshes = static_cast<unsigned int>(animMeshes.size());
  611. for (unsigned int i = 0; i < animMeshes.size(); ++i) {
  612. dstMesh->mAnimMeshes[i] = animMeshes.at(i);
  613. }
  614. }
  615. // create bones if given
  616. if (pSrcController && pSrcController->mType == Collada::Skin) {
  617. // resolve references - joint names
  618. const Collada::Accessor &jointNamesAcc = pParser.ResolveLibraryReference(pParser.mAccessorLibrary, pSrcController->mJointNameSource);
  619. const Collada::Data &jointNames = pParser.ResolveLibraryReference(pParser.mDataLibrary, jointNamesAcc.mSource);
  620. // joint offset matrices
  621. const Collada::Accessor &jointMatrixAcc = pParser.ResolveLibraryReference(pParser.mAccessorLibrary, pSrcController->mJointOffsetMatrixSource);
  622. const Collada::Data &jointMatrices = pParser.ResolveLibraryReference(pParser.mDataLibrary, jointMatrixAcc.mSource);
  623. // joint vertex_weight name list - should refer to the same list as the joint names above. If not, report and reconsider
  624. const Collada::Accessor &weightNamesAcc = pParser.ResolveLibraryReference(pParser.mAccessorLibrary, pSrcController->mWeightInputJoints.mAccessor);
  625. if (&weightNamesAcc != &jointNamesAcc)
  626. throw DeadlyImportError("Temporary implementational laziness. If you read this, please report to the author.");
  627. // vertex weights
  628. const Collada::Accessor &weightsAcc = pParser.ResolveLibraryReference(pParser.mAccessorLibrary, pSrcController->mWeightInputWeights.mAccessor);
  629. const Collada::Data &weights = pParser.ResolveLibraryReference(pParser.mDataLibrary, weightsAcc.mSource);
  630. if (!jointNames.mIsStringArray || jointMatrices.mIsStringArray || weights.mIsStringArray) {
  631. throw DeadlyImportError("Data type mismatch while resolving mesh joints");
  632. }
  633. // sanity check: we rely on the vertex weights always coming as pairs of BoneIndex-WeightIndex
  634. if (pSrcController->mWeightInputJoints.mOffset != 0 || pSrcController->mWeightInputWeights.mOffset != 1) {
  635. throw DeadlyImportError("Unsupported vertex_weight addressing scheme. ");
  636. }
  637. // create containers to collect the weights for each bone
  638. size_t numBones = jointNames.mStrings.size();
  639. std::vector<std::vector<aiVertexWeight>> dstBones(numBones);
  640. // build a temporary array of pointers to the start of each vertex's weights
  641. using IndexPairVector = std::vector<std::pair<size_t, size_t>>;
  642. std::vector<IndexPairVector::const_iterator> weightStartPerVertex;
  643. weightStartPerVertex.resize(pSrcController->mWeightCounts.size(), pSrcController->mWeights.end());
  644. IndexPairVector::const_iterator pit = pSrcController->mWeights.begin();
  645. for (size_t a = 0; a < pSrcController->mWeightCounts.size(); ++a) {
  646. weightStartPerVertex[a] = pit;
  647. pit += pSrcController->mWeightCounts[a];
  648. }
  649. // now for each vertex put the corresponding vertex weights into each bone's weight collection
  650. for (size_t a = pStartVertex; a < pStartVertex + numVertices; ++a) {
  651. // which position index was responsible for this vertex? that's also the index by which
  652. // the controller assigns the vertex weights
  653. size_t orgIndex = pSrcMesh->mFacePosIndices[a];
  654. // find the vertex weights for this vertex
  655. IndexPairVector::const_iterator iit = weightStartPerVertex[orgIndex];
  656. size_t pairCount = pSrcController->mWeightCounts[orgIndex];
  657. for (size_t b = 0; b < pairCount; ++b, ++iit) {
  658. const size_t jointIndex = iit->first;
  659. const size_t vertexIndex = iit->second;
  660. ai_real weight = 1.0f;
  661. if (!weights.mValues.empty()) {
  662. weight = ReadFloat(weightsAcc, weights, vertexIndex, 0);
  663. }
  664. // one day I gonna kill that XSI Collada exporter
  665. if (weight > 0.0f) {
  666. aiVertexWeight w;
  667. w.mVertexId = static_cast<unsigned int>(a - pStartVertex);
  668. w.mWeight = weight;
  669. dstBones[jointIndex].push_back(w);
  670. }
  671. }
  672. }
  673. // count the number of bones which influence vertices of the current submesh
  674. size_t numRemainingBones = 0;
  675. for (const auto & dstBone : dstBones) {
  676. if (dstBone.empty() && removeEmptyBones) {
  677. continue;
  678. }
  679. ++numRemainingBones;
  680. }
  681. // create bone array and copy bone weights one by one
  682. dstMesh->mNumBones = static_cast<unsigned int>(numRemainingBones);
  683. dstMesh->mBones = new aiBone *[numRemainingBones];
  684. size_t boneCount = 0;
  685. for (size_t a = 0; a < numBones; ++a) {
  686. // omit bones without weights
  687. if (dstBones[a].empty() && removeEmptyBones) {
  688. continue;
  689. }
  690. // create bone with its weights
  691. aiBone *bone = new aiBone;
  692. bone->mName = ReadString(jointNamesAcc, jointNames, a);
  693. bone->mOffsetMatrix.a1 = ReadFloat(jointMatrixAcc, jointMatrices, a, 0);
  694. bone->mOffsetMatrix.a2 = ReadFloat(jointMatrixAcc, jointMatrices, a, 1);
  695. bone->mOffsetMatrix.a3 = ReadFloat(jointMatrixAcc, jointMatrices, a, 2);
  696. bone->mOffsetMatrix.a4 = ReadFloat(jointMatrixAcc, jointMatrices, a, 3);
  697. bone->mOffsetMatrix.b1 = ReadFloat(jointMatrixAcc, jointMatrices, a, 4);
  698. bone->mOffsetMatrix.b2 = ReadFloat(jointMatrixAcc, jointMatrices, a, 5);
  699. bone->mOffsetMatrix.b3 = ReadFloat(jointMatrixAcc, jointMatrices, a, 6);
  700. bone->mOffsetMatrix.b4 = ReadFloat(jointMatrixAcc, jointMatrices, a, 7);
  701. bone->mOffsetMatrix.c1 = ReadFloat(jointMatrixAcc, jointMatrices, a, 8);
  702. bone->mOffsetMatrix.c2 = ReadFloat(jointMatrixAcc, jointMatrices, a, 9);
  703. bone->mOffsetMatrix.c3 = ReadFloat(jointMatrixAcc, jointMatrices, a, 10);
  704. bone->mOffsetMatrix.c4 = ReadFloat(jointMatrixAcc, jointMatrices, a, 11);
  705. bone->mNumWeights = static_cast<unsigned int>(dstBones[a].size());
  706. bone->mWeights = new aiVertexWeight[bone->mNumWeights];
  707. std::copy(dstBones[a].begin(), dstBones[a].end(), bone->mWeights);
  708. // apply bind shape matrix to offset matrix
  709. aiMatrix4x4 bindShapeMatrix;
  710. bindShapeMatrix.a1 = pSrcController->mBindShapeMatrix[0];
  711. bindShapeMatrix.a2 = pSrcController->mBindShapeMatrix[1];
  712. bindShapeMatrix.a3 = pSrcController->mBindShapeMatrix[2];
  713. bindShapeMatrix.a4 = pSrcController->mBindShapeMatrix[3];
  714. bindShapeMatrix.b1 = pSrcController->mBindShapeMatrix[4];
  715. bindShapeMatrix.b2 = pSrcController->mBindShapeMatrix[5];
  716. bindShapeMatrix.b3 = pSrcController->mBindShapeMatrix[6];
  717. bindShapeMatrix.b4 = pSrcController->mBindShapeMatrix[7];
  718. bindShapeMatrix.c1 = pSrcController->mBindShapeMatrix[8];
  719. bindShapeMatrix.c2 = pSrcController->mBindShapeMatrix[9];
  720. bindShapeMatrix.c3 = pSrcController->mBindShapeMatrix[10];
  721. bindShapeMatrix.c4 = pSrcController->mBindShapeMatrix[11];
  722. bindShapeMatrix.d1 = pSrcController->mBindShapeMatrix[12];
  723. bindShapeMatrix.d2 = pSrcController->mBindShapeMatrix[13];
  724. bindShapeMatrix.d3 = pSrcController->mBindShapeMatrix[14];
  725. bindShapeMatrix.d4 = pSrcController->mBindShapeMatrix[15];
  726. bone->mOffsetMatrix *= bindShapeMatrix;
  727. // HACK: (thom) Some exporters address the bone nodes by SID, others address them by ID or even name.
  728. // Therefore I added a little name replacement here: I search for the bone's node by either name, ID or SID,
  729. // and replace the bone's name by the node's name so that the user can use the standard
  730. // find-by-name method to associate nodes with bones.
  731. const Collada::Node *bnode = FindNode(pParser.mRootNode, bone->mName.data);
  732. if (nullptr == bnode) {
  733. bnode = FindNodeBySID(pParser.mRootNode, bone->mName.data);
  734. }
  735. // assign the name that we would have assigned for the source node
  736. if (nullptr != bnode) {
  737. bone->mName.Set(FindNameForNode(bnode));
  738. } else {
  739. ASSIMP_LOG_WARN("ColladaLoader::CreateMesh(): could not find corresponding node for joint \"", bone->mName.data, "\".");
  740. }
  741. // and insert bone
  742. dstMesh->mBones[boneCount++] = bone;
  743. }
  744. }
  745. return dstMesh.release();
  746. }
  747. // ------------------------------------------------------------------------------------------------
  748. // Stores all meshes in the given scene
  749. void ColladaLoader::StoreSceneMeshes(aiScene *pScene) {
  750. pScene->mNumMeshes = static_cast<unsigned int>(mMeshes.size());
  751. if (mMeshes.empty()) {
  752. return;
  753. }
  754. pScene->mMeshes = new aiMesh *[mMeshes.size()];
  755. std::copy(mMeshes.begin(), mMeshes.end(), pScene->mMeshes);
  756. mMeshes.clear();
  757. }
  758. // ------------------------------------------------------------------------------------------------
  759. // Stores all cameras in the given scene
  760. void ColladaLoader::StoreSceneCameras(aiScene *pScene) {
  761. pScene->mNumCameras = static_cast<unsigned int>(mCameras.size());
  762. if (mCameras.empty()) {
  763. return;
  764. }
  765. pScene->mCameras = new aiCamera *[mCameras.size()];
  766. std::copy(mCameras.begin(), mCameras.end(), pScene->mCameras);
  767. mCameras.clear();
  768. }
  769. // ------------------------------------------------------------------------------------------------
  770. // Stores all lights in the given scene
  771. void ColladaLoader::StoreSceneLights(aiScene *pScene) {
  772. pScene->mNumLights = static_cast<unsigned int>(mLights.size());
  773. if (mLights.empty()) {
  774. return;
  775. }
  776. pScene->mLights = new aiLight *[mLights.size()];
  777. std::copy(mLights.begin(), mLights.end(), pScene->mLights);
  778. mLights.clear();
  779. }
  780. // ------------------------------------------------------------------------------------------------
  781. // Stores all textures in the given scene
  782. void ColladaLoader::StoreSceneTextures(aiScene *pScene) {
  783. pScene->mNumTextures = static_cast<unsigned int>(mTextures.size());
  784. if (mTextures.empty()) {
  785. return;
  786. }
  787. pScene->mTextures = new aiTexture *[mTextures.size()];
  788. std::copy(mTextures.begin(), mTextures.end(), pScene->mTextures);
  789. mTextures.clear();
  790. }
  791. // ------------------------------------------------------------------------------------------------
  792. // Stores all materials in the given scene
  793. void ColladaLoader::StoreSceneMaterials(aiScene *pScene) {
  794. pScene->mNumMaterials = static_cast<unsigned int>(newMats.size());
  795. if (newMats.empty()) {
  796. return;
  797. }
  798. pScene->mMaterials = new aiMaterial *[newMats.size()];
  799. for (unsigned int i = 0; i < newMats.size(); ++i) {
  800. pScene->mMaterials[i] = newMats[i].second;
  801. }
  802. newMats.clear();
  803. }
  804. // ------------------------------------------------------------------------------------------------
  805. // Stores all animations
  806. void ColladaLoader::StoreAnimations(aiScene *pScene, const ColladaParser &pParser) {
  807. // recursively collect all animations from the collada scene
  808. StoreAnimations(pScene, pParser, &pParser.mAnims, "");
  809. // catch special case: many animations with the same length, each affecting only a single node.
  810. // we need to unite all those single-node-anims to a proper combined animation
  811. for (size_t a = 0; a < mAnims.size(); ++a) {
  812. aiAnimation *templateAnim = mAnims[a];
  813. if (templateAnim->mNumChannels == 1) {
  814. // search for other single-channel-anims with the same duration
  815. std::vector<size_t> collectedAnimIndices;
  816. for (size_t b = a + 1; b < mAnims.size(); ++b) {
  817. aiAnimation *other = mAnims[b];
  818. if (other->mNumChannels == 1 && other->mDuration == templateAnim->mDuration &&
  819. other->mTicksPerSecond == templateAnim->mTicksPerSecond)
  820. collectedAnimIndices.push_back(b);
  821. }
  822. // We only want to combine the animations if they have different channels
  823. std::set<std::string> animTargets;
  824. animTargets.insert(templateAnim->mChannels[0]->mNodeName.C_Str());
  825. bool collectedAnimationsHaveDifferentChannels = true;
  826. for (unsigned long long collectedAnimIndice : collectedAnimIndices) {
  827. aiAnimation *srcAnimation = mAnims[(int)collectedAnimIndice];
  828. std::string channelName = std::string(srcAnimation->mChannels[0]->mNodeName.C_Str());
  829. if (animTargets.find(channelName) == animTargets.end()) {
  830. animTargets.insert(channelName);
  831. } else {
  832. collectedAnimationsHaveDifferentChannels = false;
  833. break;
  834. }
  835. }
  836. if (!collectedAnimationsHaveDifferentChannels) {
  837. continue;
  838. }
  839. // if there are other animations which fit the template anim, combine all channels into a single anim
  840. if (!collectedAnimIndices.empty()) {
  841. aiAnimation *combinedAnim = new aiAnimation();
  842. combinedAnim->mName = aiString(std::string("combinedAnim_") + char('0' + a));
  843. combinedAnim->mDuration = templateAnim->mDuration;
  844. combinedAnim->mTicksPerSecond = templateAnim->mTicksPerSecond;
  845. combinedAnim->mNumChannels = static_cast<unsigned int>(collectedAnimIndices.size() + 1);
  846. combinedAnim->mChannels = new aiNodeAnim *[combinedAnim->mNumChannels];
  847. // add the template anim as first channel by moving its aiNodeAnim to the combined animation
  848. combinedAnim->mChannels[0] = templateAnim->mChannels[0];
  849. templateAnim->mChannels[0] = nullptr;
  850. delete templateAnim;
  851. // combined animation replaces template animation in the anim array
  852. mAnims[a] = combinedAnim;
  853. // move the memory of all other anims to the combined anim and erase them from the source anims
  854. for (size_t b = 0; b < collectedAnimIndices.size(); ++b) {
  855. aiAnimation *srcAnimation = mAnims[collectedAnimIndices[b]];
  856. combinedAnim->mChannels[1 + b] = srcAnimation->mChannels[0];
  857. srcAnimation->mChannels[0] = nullptr;
  858. delete srcAnimation;
  859. }
  860. // in a second go, delete all the single-channel-anims that we've stripped from their channels
  861. // back to front to preserve indices - you know, removing an element from a vector moves all elements behind the removed one
  862. while (!collectedAnimIndices.empty()) {
  863. mAnims.erase(mAnims.begin() + collectedAnimIndices.back());
  864. collectedAnimIndices.pop_back();
  865. }
  866. }
  867. }
  868. }
  869. // now store all anims in the scene
  870. if (!mAnims.empty()) {
  871. pScene->mNumAnimations = static_cast<unsigned int>(mAnims.size());
  872. pScene->mAnimations = new aiAnimation *[mAnims.size()];
  873. std::copy(mAnims.begin(), mAnims.end(), pScene->mAnimations);
  874. }
  875. mAnims.clear();
  876. }
  877. // ------------------------------------------------------------------------------------------------
  878. // Constructs the animations for the given source anim
  879. void ColladaLoader::StoreAnimations(aiScene *pScene, const ColladaParser &pParser, const Animation *pSrcAnim, const std::string &pPrefix) {
  880. std::string animName = pPrefix.empty() ? pSrcAnim->mName : pPrefix + "_" + pSrcAnim->mName;
  881. // create nested animations, if given
  882. for (auto mSubAnim : pSrcAnim->mSubAnims) {
  883. StoreAnimations(pScene, pParser, mSubAnim, animName);
  884. }
  885. // create animation channels, if any
  886. if (!pSrcAnim->mChannels.empty()) {
  887. CreateAnimation(pScene, pParser, pSrcAnim, animName);
  888. }
  889. }
  890. struct MorphTimeValues {
  891. float mTime;
  892. struct key {
  893. float mWeight;
  894. unsigned int mValue;
  895. };
  896. std::vector<key> mKeys;
  897. };
  898. void insertMorphTimeValue(std::vector<MorphTimeValues> &values, float time, float weight, unsigned int value) {
  899. MorphTimeValues::key k;
  900. k.mValue = value;
  901. k.mWeight = weight;
  902. if (values.empty() || time < values[0].mTime) {
  903. MorphTimeValues val;
  904. val.mTime = time;
  905. val.mKeys.push_back(k);
  906. values.insert(values.begin(), val);
  907. return;
  908. }
  909. if (time > values.back().mTime) {
  910. MorphTimeValues val;
  911. val.mTime = time;
  912. val.mKeys.push_back(k);
  913. values.insert(values.end(), val);
  914. return;
  915. }
  916. for (unsigned int i = 0; i < values.size(); i++) {
  917. if (std::abs(time - values[i].mTime) < ai_epsilon) {
  918. values[i].mKeys.push_back(k);
  919. return;
  920. } else if (time > values[i].mTime && time < values[i + 1].mTime) {
  921. MorphTimeValues val;
  922. val.mTime = time;
  923. val.mKeys.push_back(k);
  924. values.insert(values.begin() + i, val);
  925. return;
  926. }
  927. }
  928. }
  929. static float getWeightAtKey(const std::vector<MorphTimeValues> &values, int key, unsigned int value) {
  930. for (auto mKey : values[key].mKeys) {
  931. if (mKey.mValue == value) {
  932. return mKey.mWeight;
  933. }
  934. }
  935. // no value at key found, try to interpolate if present at other keys. if not, return zero
  936. // TODO: interpolation
  937. return 0.0f;
  938. }
  939. // ------------------------------------------------------------------------------------------------
  940. // Constructs the animation for the given source anim
  941. void ColladaLoader::CreateAnimation(aiScene *pScene, const ColladaParser &pParser, const Animation *pSrcAnim, const std::string &pName) {
  942. // collect a list of animatable nodes
  943. std::vector<const aiNode *> nodes;
  944. CollectNodes(pScene->mRootNode, nodes);
  945. std::vector<aiNodeAnim *> anims;
  946. std::vector<aiMeshMorphAnim *> morphAnims;
  947. for (auto node : nodes) {
  948. // find all the collada anim channels which refer to the current node
  949. std::vector<ChannelEntry> entries;
  950. std::string nodeName = node->mName.data;
  951. // find the collada node corresponding to the aiNode
  952. const Node *srcNode = FindNode(pParser.mRootNode, nodeName);
  953. if (!srcNode) {
  954. continue;
  955. }
  956. // now check all channels if they affect the current node
  957. std::string targetID, subElement;
  958. for (std::vector<AnimationChannel>::const_iterator cit = pSrcAnim->mChannels.begin();
  959. cit != pSrcAnim->mChannels.end(); ++cit) {
  960. const AnimationChannel &srcChannel = *cit;
  961. ChannelEntry entry;
  962. // we expect the animation target to be of type "nodeName/transformID.subElement". Ignore all others
  963. // find the slash that separates the node name - there should be only one
  964. std::string::size_type slashPos = srcChannel.mTarget.find('/');
  965. if (slashPos == std::string::npos) {
  966. std::string::size_type targetPos = srcChannel.mTarget.find(srcNode->mID);
  967. if (targetPos == std::string::npos) {
  968. continue;
  969. }
  970. // not node transform, but something else. store as unknown animation channel for now
  971. entry.mChannel = &(*cit);
  972. entry.mTargetId = srcChannel.mTarget.substr(targetPos + pSrcAnim->mName.length(),
  973. srcChannel.mTarget.length() - targetPos - pSrcAnim->mName.length());
  974. if (entry.mTargetId.front() == '-') {
  975. entry.mTargetId = entry.mTargetId.substr(1);
  976. }
  977. entries.push_back(entry);
  978. continue;
  979. }
  980. if (srcChannel.mTarget.find('/', slashPos + 1) != std::string::npos) {
  981. continue;
  982. }
  983. targetID.clear();
  984. targetID = srcChannel.mTarget.substr(0, slashPos);
  985. if (targetID != srcNode->mID) {
  986. continue;
  987. }
  988. // find the dot that separates the transformID - there should be only one or zero
  989. std::string::size_type dotPos = srcChannel.mTarget.find('.');
  990. if (dotPos != std::string::npos) {
  991. if (srcChannel.mTarget.find('.', dotPos + 1) != std::string::npos) {
  992. continue;
  993. }
  994. entry.mTransformId = srcChannel.mTarget.substr(slashPos + 1, dotPos - slashPos - 1);
  995. subElement.clear();
  996. subElement = srcChannel.mTarget.substr(dotPos + 1);
  997. if (subElement == "ANGLE")
  998. entry.mSubElement = 3; // last number in an Axis-Angle-Transform is the angle
  999. else if (subElement == "X")
  1000. entry.mSubElement = 0;
  1001. else if (subElement == "Y")
  1002. entry.mSubElement = 1;
  1003. else if (subElement == "Z")
  1004. entry.mSubElement = 2;
  1005. else
  1006. ASSIMP_LOG_WARN("Unknown anim subelement <", subElement, ">. Ignoring");
  1007. } else {
  1008. // no sub-element following, transformId is remaining string
  1009. entry.mTransformId = srcChannel.mTarget.substr(slashPos + 1);
  1010. }
  1011. std::string::size_type bracketPos = srcChannel.mTarget.find('(');
  1012. if (bracketPos != std::string::npos) {
  1013. entry.mTransformId = srcChannel.mTarget.substr(slashPos + 1, bracketPos - slashPos - 1);
  1014. subElement.clear();
  1015. subElement = srcChannel.mTarget.substr(bracketPos);
  1016. if (subElement == "(0)(0)")
  1017. entry.mSubElement = 0;
  1018. else if (subElement == "(1)(0)")
  1019. entry.mSubElement = 1;
  1020. else if (subElement == "(2)(0)")
  1021. entry.mSubElement = 2;
  1022. else if (subElement == "(3)(0)")
  1023. entry.mSubElement = 3;
  1024. else if (subElement == "(0)(1)")
  1025. entry.mSubElement = 4;
  1026. else if (subElement == "(1)(1)")
  1027. entry.mSubElement = 5;
  1028. else if (subElement == "(2)(1)")
  1029. entry.mSubElement = 6;
  1030. else if (subElement == "(3)(1)")
  1031. entry.mSubElement = 7;
  1032. else if (subElement == "(0)(2)")
  1033. entry.mSubElement = 8;
  1034. else if (subElement == "(1)(2)")
  1035. entry.mSubElement = 9;
  1036. else if (subElement == "(2)(2)")
  1037. entry.mSubElement = 10;
  1038. else if (subElement == "(3)(2)")
  1039. entry.mSubElement = 11;
  1040. else if (subElement == "(0)(3)")
  1041. entry.mSubElement = 12;
  1042. else if (subElement == "(1)(3)")
  1043. entry.mSubElement = 13;
  1044. else if (subElement == "(2)(3)")
  1045. entry.mSubElement = 14;
  1046. else if (subElement == "(3)(3)")
  1047. entry.mSubElement = 15;
  1048. }
  1049. // determine which transform step is affected by this channel
  1050. entry.mTransformIndex = SIZE_MAX;
  1051. for (size_t a = 0; a < srcNode->mTransforms.size(); ++a)
  1052. if (srcNode->mTransforms[a].mID == entry.mTransformId)
  1053. entry.mTransformIndex = a;
  1054. if (entry.mTransformIndex == SIZE_MAX) {
  1055. if (entry.mTransformId.find("morph-weights") == std::string::npos) {
  1056. continue;
  1057. }
  1058. entry.mTargetId = entry.mTransformId;
  1059. entry.mTransformId = std::string();
  1060. }
  1061. entry.mChannel = &(*cit);
  1062. entries.push_back(entry);
  1063. }
  1064. // if there's no channel affecting the current node, we skip it
  1065. if (entries.empty()) {
  1066. continue;
  1067. }
  1068. // resolve the data pointers for all anim channels. Find the minimum time while we're at it
  1069. ai_real startTime = ai_real(1e20), endTime = ai_real(-1e20);
  1070. for (ChannelEntry & e : entries) {
  1071. e.mTimeAccessor = &pParser.ResolveLibraryReference(pParser.mAccessorLibrary, e.mChannel->mSourceTimes);
  1072. e.mTimeData = &pParser.ResolveLibraryReference(pParser.mDataLibrary, e.mTimeAccessor->mSource);
  1073. e.mValueAccessor = &pParser.ResolveLibraryReference(pParser.mAccessorLibrary, e.mChannel->mSourceValues);
  1074. e.mValueData = &pParser.ResolveLibraryReference(pParser.mDataLibrary, e.mValueAccessor->mSource);
  1075. // time count and value count must match
  1076. if (e.mTimeAccessor->mCount != e.mValueAccessor->mCount) {
  1077. throw DeadlyImportError("Time count / value count mismatch in animation channel \"", e.mChannel->mTarget, "\".");
  1078. }
  1079. if (e.mTimeAccessor->mCount > 0) {
  1080. // find bounding times
  1081. startTime = std::min(startTime, ReadFloat(*e.mTimeAccessor, *e.mTimeData, 0, 0));
  1082. endTime = std::max(endTime, ReadFloat(*e.mTimeAccessor, *e.mTimeData, e.mTimeAccessor->mCount - 1, 0));
  1083. }
  1084. }
  1085. std::vector<aiMatrix4x4> resultTrafos;
  1086. if (!entries.empty() && entries.front().mTimeAccessor->mCount > 0) {
  1087. // create a local transformation chain of the node's transforms
  1088. std::vector<Collada::Transform> transforms = srcNode->mTransforms;
  1089. // now for every unique point in time, find or interpolate the key values for that time
  1090. // and apply them to the transform chain. Then the node's present transformation can be calculated.
  1091. ai_real time = startTime;
  1092. while (true) {
  1093. for (ChannelEntry & e : entries) {
  1094. // find the keyframe behind the current point in time
  1095. size_t pos = 0;
  1096. ai_real postTime = 0.0;
  1097. while (true) {
  1098. if (pos >= e.mTimeAccessor->mCount) {
  1099. break;
  1100. }
  1101. postTime = ReadFloat(*e.mTimeAccessor, *e.mTimeData, pos, 0);
  1102. if (postTime >= time) {
  1103. break;
  1104. }
  1105. ++pos;
  1106. }
  1107. pos = std::min(pos, e.mTimeAccessor->mCount - 1);
  1108. // read values from there
  1109. ai_real temp[16];
  1110. for (size_t c = 0; c < e.mValueAccessor->mSize; ++c) {
  1111. temp[c] = ReadFloat(*e.mValueAccessor, *e.mValueData, pos, c);
  1112. }
  1113. // if not exactly at the key time, interpolate with previous value set
  1114. if (postTime > time && pos > 0) {
  1115. ai_real preTime = ReadFloat(*e.mTimeAccessor, *e.mTimeData, pos - 1, 0);
  1116. ai_real factor = (time - postTime) / (preTime - postTime);
  1117. for (size_t c = 0; c < e.mValueAccessor->mSize; ++c) {
  1118. ai_real v = ReadFloat(*e.mValueAccessor, *e.mValueData, pos - 1, c);
  1119. temp[c] += (v - temp[c]) * factor;
  1120. }
  1121. }
  1122. // Apply values to current transformation
  1123. std::copy(temp, temp + e.mValueAccessor->mSize, transforms[e.mTransformIndex].f + e.mSubElement);
  1124. }
  1125. // Calculate resulting transformation
  1126. aiMatrix4x4 mat = pParser.CalculateResultTransform(transforms);
  1127. // out of laziness: we store the time in matrix.d4
  1128. mat.d4 = time;
  1129. resultTrafos.push_back(mat);
  1130. // find next point in time to evaluate. That's the closest frame larger than the current in any channel
  1131. ai_real nextTime = ai_real(1e20);
  1132. for (ChannelEntry & channelElement : entries) {
  1133. // find the next time value larger than the current
  1134. size_t pos = 0;
  1135. while (pos < channelElement.mTimeAccessor->mCount) {
  1136. const ai_real t = ReadFloat(*channelElement.mTimeAccessor, *channelElement.mTimeData, pos, 0);
  1137. if (t > time) {
  1138. nextTime = std::min(nextTime, t);
  1139. break;
  1140. }
  1141. ++pos;
  1142. }
  1143. // https://github.com/assimp/assimp/issues/458
  1144. // Sub-sample axis-angle channels if the delta between two consecutive
  1145. // key-frame angles is >= 180 degrees.
  1146. if (transforms[channelElement.mTransformIndex].mType == TF_ROTATE && channelElement.mSubElement == 3 && pos > 0 && pos < channelElement.mTimeAccessor->mCount) {
  1147. const ai_real cur_key_angle = ReadFloat(*channelElement.mValueAccessor, *channelElement.mValueData, pos, 0);
  1148. const ai_real last_key_angle = ReadFloat(*channelElement.mValueAccessor, *channelElement.mValueData, pos - 1, 0);
  1149. const ai_real cur_key_time = ReadFloat(*channelElement.mTimeAccessor, *channelElement.mTimeData, pos, 0);
  1150. const ai_real last_key_time = ReadFloat(*channelElement.mTimeAccessor, *channelElement.mTimeData, pos - 1, 0);
  1151. const ai_real last_eval_angle = last_key_angle + (cur_key_angle - last_key_angle) * (time - last_key_time) / (cur_key_time - last_key_time);
  1152. const ai_real delta = std::abs(cur_key_angle - last_eval_angle);
  1153. if (delta >= 180.0) {
  1154. const int subSampleCount = static_cast<int>(std::floor(delta / 90.0));
  1155. if (cur_key_time != time) {
  1156. const ai_real nextSampleTime = time + (cur_key_time - time) / subSampleCount;
  1157. nextTime = std::min(nextTime, nextSampleTime);
  1158. }
  1159. }
  1160. }
  1161. }
  1162. // no more keys on any channel after the current time -> we're done
  1163. if (nextTime > 1e19) {
  1164. break;
  1165. }
  1166. // else construct next key-frame at this following time point
  1167. time = nextTime;
  1168. }
  1169. }
  1170. // build an animation channel for the given node out of these trafo keys
  1171. if (!resultTrafos.empty()) {
  1172. aiNodeAnim *dstAnim = new aiNodeAnim;
  1173. dstAnim->mNodeName = nodeName;
  1174. dstAnim->mNumPositionKeys = static_cast<unsigned int>(resultTrafos.size());
  1175. dstAnim->mNumRotationKeys = static_cast<unsigned int>(resultTrafos.size());
  1176. dstAnim->mNumScalingKeys = static_cast<unsigned int>(resultTrafos.size());
  1177. dstAnim->mPositionKeys = new aiVectorKey[resultTrafos.size()];
  1178. dstAnim->mRotationKeys = new aiQuatKey[resultTrafos.size()];
  1179. dstAnim->mScalingKeys = new aiVectorKey[resultTrafos.size()];
  1180. for (size_t a = 0; a < resultTrafos.size(); ++a) {
  1181. aiMatrix4x4 mat = resultTrafos[a];
  1182. double time = double(mat.d4); // remember? time is stored in mat.d4
  1183. mat.d4 = 1.0f;
  1184. dstAnim->mPositionKeys[a].mTime = time * kMillisecondsFromSeconds;
  1185. dstAnim->mRotationKeys[a].mTime = time * kMillisecondsFromSeconds;
  1186. dstAnim->mScalingKeys[a].mTime = time * kMillisecondsFromSeconds;
  1187. mat.Decompose(dstAnim->mScalingKeys[a].mValue, dstAnim->mRotationKeys[a].mValue, dstAnim->mPositionKeys[a].mValue);
  1188. }
  1189. anims.push_back(dstAnim);
  1190. } else {
  1191. ASSIMP_LOG_WARN("Collada loader: found empty animation channel, ignored. Please check your exporter.");
  1192. }
  1193. if (!entries.empty() && entries.front().mTimeAccessor->mCount > 0) {
  1194. std::vector<ChannelEntry> morphChannels;
  1195. for (ChannelEntry & e : entries) {
  1196. // skip non-transform types
  1197. if (e.mTargetId.empty()) {
  1198. continue;
  1199. }
  1200. if (e.mTargetId.find("morph-weights") != std::string::npos) {
  1201. morphChannels.push_back(e);
  1202. }
  1203. }
  1204. if (!morphChannels.empty()) {
  1205. // either 1) morph weight animation count should contain morph target count channels
  1206. // or 2) one channel with morph target count arrays
  1207. // assume first
  1208. aiMeshMorphAnim *morphAnim = new aiMeshMorphAnim;
  1209. morphAnim->mName.Set(nodeName);
  1210. std::vector<MorphTimeValues> morphTimeValues;
  1211. int morphAnimChannelIndex = 0;
  1212. for (ChannelEntry & e : morphChannels) {
  1213. std::string::size_type apos = e.mTargetId.find('(');
  1214. std::string::size_type bpos = e.mTargetId.find(')');
  1215. // If unknown way to specify weight -> ignore this animation
  1216. if (apos == std::string::npos || bpos == std::string::npos) {
  1217. continue;
  1218. }
  1219. // weight target can be in format Weight_M_N, Weight_N, WeightN, or some other way
  1220. // we ignore the name and just assume the channels are in the right order
  1221. for (unsigned int i = 0; i < e.mTimeData->mValues.size(); i++) {
  1222. insertMorphTimeValue(morphTimeValues, e.mTimeData->mValues[i], e.mValueData->mValues[i], morphAnimChannelIndex);
  1223. }
  1224. ++morphAnimChannelIndex;
  1225. }
  1226. morphAnim->mNumKeys = static_cast<unsigned int>(morphTimeValues.size());
  1227. morphAnim->mKeys = new aiMeshMorphKey[morphAnim->mNumKeys];
  1228. for (unsigned int key = 0; key < morphAnim->mNumKeys; key++) {
  1229. morphAnim->mKeys[key].mNumValuesAndWeights = static_cast<unsigned int>(morphChannels.size());
  1230. morphAnim->mKeys[key].mValues = new unsigned int[morphChannels.size()];
  1231. morphAnim->mKeys[key].mWeights = new double[morphChannels.size()];
  1232. morphAnim->mKeys[key].mTime = morphTimeValues[key].mTime * kMillisecondsFromSeconds;
  1233. for (unsigned int valueIndex = 0; valueIndex < morphChannels.size(); ++valueIndex) {
  1234. morphAnim->mKeys[key].mValues[valueIndex] = valueIndex;
  1235. morphAnim->mKeys[key].mWeights[valueIndex] = getWeightAtKey(morphTimeValues, key, valueIndex);
  1236. }
  1237. }
  1238. morphAnims.push_back(morphAnim);
  1239. }
  1240. }
  1241. }
  1242. if (!anims.empty() || !morphAnims.empty()) {
  1243. aiAnimation *anim = new aiAnimation;
  1244. anim->mName.Set(pName);
  1245. anim->mNumChannels = static_cast<unsigned int>(anims.size());
  1246. if (anim->mNumChannels > 0) {
  1247. anim->mChannels = new aiNodeAnim *[anims.size()];
  1248. std::copy(anims.begin(), anims.end(), anim->mChannels);
  1249. }
  1250. anim->mNumMorphMeshChannels = static_cast<unsigned int>(morphAnims.size());
  1251. if (anim->mNumMorphMeshChannels > 0) {
  1252. anim->mMorphMeshChannels = new aiMeshMorphAnim *[anim->mNumMorphMeshChannels];
  1253. std::copy(morphAnims.begin(), morphAnims.end(), anim->mMorphMeshChannels);
  1254. }
  1255. anim->mDuration = 0.0f;
  1256. for (auto & a : anims) {
  1257. anim->mDuration = std::max(anim->mDuration, a->mPositionKeys[a->mNumPositionKeys - 1].mTime);
  1258. anim->mDuration = std::max(anim->mDuration, a->mRotationKeys[a->mNumRotationKeys - 1].mTime);
  1259. anim->mDuration = std::max(anim->mDuration, a->mScalingKeys[a->mNumScalingKeys - 1].mTime);
  1260. }
  1261. for (auto & morphAnim : morphAnims) {
  1262. anim->mDuration = std::max(anim->mDuration, morphAnim->mKeys[morphAnim->mNumKeys - 1].mTime);
  1263. }
  1264. anim->mTicksPerSecond = 1000.0;
  1265. mAnims.push_back(anim);
  1266. }
  1267. }
  1268. // ------------------------------------------------------------------------------------------------
  1269. // Add a texture to a material structure
  1270. void ColladaLoader::AddTexture(aiMaterial &mat,
  1271. const ColladaParser &pParser,
  1272. const Effect &effect,
  1273. const Sampler &sampler,
  1274. aiTextureType type,
  1275. unsigned int idx) {
  1276. // first of all, basic file name
  1277. const aiString name = FindFilenameForEffectTexture(pParser, effect, sampler.mName);
  1278. mat.AddProperty(&name, _AI_MATKEY_TEXTURE_BASE, type, idx);
  1279. // mapping mode
  1280. int map = aiTextureMapMode_Clamp;
  1281. if (sampler.mWrapU) {
  1282. map = aiTextureMapMode_Wrap;
  1283. }
  1284. if (sampler.mWrapU && sampler.mMirrorU) {
  1285. map = aiTextureMapMode_Mirror;
  1286. }
  1287. mat.AddProperty(&map, 1, _AI_MATKEY_MAPPINGMODE_U_BASE, type, idx);
  1288. map = aiTextureMapMode_Clamp;
  1289. if (sampler.mWrapV) {
  1290. map = aiTextureMapMode_Wrap;
  1291. }
  1292. if (sampler.mWrapV && sampler.mMirrorV) {
  1293. map = aiTextureMapMode_Mirror;
  1294. }
  1295. mat.AddProperty(&map, 1, _AI_MATKEY_MAPPINGMODE_V_BASE, type, idx);
  1296. // UV transformation
  1297. mat.AddProperty(&sampler.mTransform, 1,
  1298. _AI_MATKEY_UVTRANSFORM_BASE, type, idx);
  1299. // Blend mode
  1300. mat.AddProperty((int *)&sampler.mOp, 1,
  1301. _AI_MATKEY_TEXBLEND_BASE, type, idx);
  1302. // Blend factor
  1303. mat.AddProperty((ai_real *)&sampler.mWeighting, 1,
  1304. _AI_MATKEY_TEXBLEND_BASE, type, idx);
  1305. // UV source index ... if we didn't resolve the mapping, it is actually just
  1306. // a guess but it works in most cases. We search for the frst occurrence of a
  1307. // number in the channel name. We assume it is the zero-based index into the
  1308. // UV channel array of all corresponding meshes. It could also be one-based
  1309. // for some exporters, but we won't care of it unless someone complains about.
  1310. if (sampler.mUVId != UINT_MAX) {
  1311. map = sampler.mUVId;
  1312. } else {
  1313. map = -1;
  1314. for (std::string::const_iterator it = sampler.mUVChannel.begin(); it != sampler.mUVChannel.end(); ++it) {
  1315. if (IsNumeric(*it)) {
  1316. map = strtoul10(&(*it));
  1317. break;
  1318. }
  1319. }
  1320. if (-1 == map) {
  1321. ASSIMP_LOG_WARN("Collada: unable to determine UV channel for texture");
  1322. map = 0;
  1323. }
  1324. }
  1325. mat.AddProperty(&map, 1, _AI_MATKEY_UVWSRC_BASE, type, idx);
  1326. }
  1327. // ------------------------------------------------------------------------------------------------
  1328. // Fills materials from the collada material definitions
  1329. void ColladaLoader::FillMaterials(const ColladaParser &pParser, aiScene * /*pScene*/) {
  1330. for (auto &elem : newMats) {
  1331. aiMaterial &mat = (aiMaterial &)*elem.second;
  1332. Collada::Effect &effect = *elem.first;
  1333. // resolve shading mode
  1334. int shadeMode;
  1335. if (effect.mFaceted) {
  1336. shadeMode = aiShadingMode_Flat;
  1337. } else {
  1338. switch (effect.mShadeType) {
  1339. case Collada::Shade_Constant:
  1340. shadeMode = aiShadingMode_NoShading;
  1341. break;
  1342. case Collada::Shade_Lambert:
  1343. shadeMode = aiShadingMode_Gouraud;
  1344. break;
  1345. case Collada::Shade_Blinn:
  1346. shadeMode = aiShadingMode_Blinn;
  1347. break;
  1348. case Collada::Shade_Phong:
  1349. shadeMode = aiShadingMode_Phong;
  1350. break;
  1351. default:
  1352. ASSIMP_LOG_WARN("Collada: Unrecognized shading mode, using gouraud shading");
  1353. shadeMode = aiShadingMode_Gouraud;
  1354. break;
  1355. }
  1356. }
  1357. mat.AddProperty<int>(&shadeMode, 1, AI_MATKEY_SHADING_MODEL);
  1358. // double-sided?
  1359. shadeMode = effect.mDoubleSided;
  1360. mat.AddProperty<int>(&shadeMode, 1, AI_MATKEY_TWOSIDED);
  1361. // wire-frame?
  1362. shadeMode = effect.mWireframe;
  1363. mat.AddProperty<int>(&shadeMode, 1, AI_MATKEY_ENABLE_WIREFRAME);
  1364. // add material colors
  1365. mat.AddProperty(&effect.mAmbient, 1, AI_MATKEY_COLOR_AMBIENT);
  1366. mat.AddProperty(&effect.mDiffuse, 1, AI_MATKEY_COLOR_DIFFUSE);
  1367. mat.AddProperty(&effect.mSpecular, 1, AI_MATKEY_COLOR_SPECULAR);
  1368. mat.AddProperty(&effect.mEmissive, 1, AI_MATKEY_COLOR_EMISSIVE);
  1369. mat.AddProperty(&effect.mReflective, 1, AI_MATKEY_COLOR_REFLECTIVE);
  1370. // scalar properties
  1371. mat.AddProperty(&effect.mShininess, 1, AI_MATKEY_SHININESS);
  1372. mat.AddProperty(&effect.mReflectivity, 1, AI_MATKEY_REFLECTIVITY);
  1373. mat.AddProperty(&effect.mRefractIndex, 1, AI_MATKEY_REFRACTI);
  1374. // transparency, a very hard one. seemingly not all files are following the
  1375. // specification here (1.0 transparency => completely opaque)...
  1376. // therefore, we let the opportunity for the user to manually invert
  1377. // the transparency if necessary and we add preliminary support for RGB_ZERO mode
  1378. if (effect.mTransparency >= 0.f && effect.mTransparency <= 1.f) {
  1379. // handle RGB transparency completely, cf Collada specs 1.5.0 pages 249 and 304
  1380. if (effect.mRGBTransparency) {
  1381. // use luminance as defined by ISO/CIE color standards (see ITU-R Recommendation BT.709-4)
  1382. effect.mTransparency *= (0.212671f * effect.mTransparent.r +
  1383. 0.715160f * effect.mTransparent.g +
  1384. 0.072169f * effect.mTransparent.b);
  1385. effect.mTransparent.a = 1.f;
  1386. mat.AddProperty(&effect.mTransparent, 1, AI_MATKEY_COLOR_TRANSPARENT);
  1387. } else {
  1388. effect.mTransparency *= effect.mTransparent.a;
  1389. }
  1390. if (effect.mInvertTransparency) {
  1391. effect.mTransparency = 1.f - effect.mTransparency;
  1392. }
  1393. // Is the material finally transparent ?
  1394. if (effect.mHasTransparency || effect.mTransparency < 1.f) {
  1395. mat.AddProperty(&effect.mTransparency, 1, AI_MATKEY_OPACITY);
  1396. }
  1397. }
  1398. // add textures, if given
  1399. if (!effect.mTexAmbient.mName.empty()) {
  1400. // It is merely a light-map
  1401. AddTexture(mat, pParser, effect, effect.mTexAmbient, aiTextureType_LIGHTMAP);
  1402. }
  1403. if (!effect.mTexEmissive.mName.empty())
  1404. AddTexture(mat, pParser, effect, effect.mTexEmissive, aiTextureType_EMISSIVE);
  1405. if (!effect.mTexSpecular.mName.empty())
  1406. AddTexture(mat, pParser, effect, effect.mTexSpecular, aiTextureType_SPECULAR);
  1407. if (!effect.mTexDiffuse.mName.empty())
  1408. AddTexture(mat, pParser, effect, effect.mTexDiffuse, aiTextureType_DIFFUSE);
  1409. if (!effect.mTexBump.mName.empty())
  1410. AddTexture(mat, pParser, effect, effect.mTexBump, aiTextureType_NORMALS);
  1411. if (!effect.mTexTransparent.mName.empty())
  1412. AddTexture(mat, pParser, effect, effect.mTexTransparent, aiTextureType_OPACITY);
  1413. if (!effect.mTexReflective.mName.empty())
  1414. AddTexture(mat, pParser, effect, effect.mTexReflective, aiTextureType_REFLECTION);
  1415. }
  1416. }
  1417. // ------------------------------------------------------------------------------------------------
  1418. // Constructs materials from the collada material definitions
  1419. void ColladaLoader::BuildMaterials(ColladaParser &pParser, aiScene * /*pScene*/) {
  1420. newMats.reserve(pParser.mMaterialLibrary.size());
  1421. for (ColladaParser::MaterialLibrary::const_iterator matIt = pParser.mMaterialLibrary.begin();
  1422. matIt != pParser.mMaterialLibrary.end(); ++matIt) {
  1423. const Material &material = matIt->second;
  1424. // a material is only a reference to an effect
  1425. ColladaParser::EffectLibrary::iterator effIt = pParser.mEffectLibrary.find(material.mEffect);
  1426. if (effIt == pParser.mEffectLibrary.end())
  1427. continue;
  1428. Effect &effect = effIt->second;
  1429. // create material
  1430. aiMaterial *mat = new aiMaterial;
  1431. aiString name(material.mName.empty() ? matIt->first : material.mName);
  1432. mat->AddProperty(&name, AI_MATKEY_NAME);
  1433. // store the material
  1434. mMaterialIndexByName[matIt->first] = newMats.size();
  1435. newMats.emplace_back(&effect, mat);
  1436. }
  1437. // ScenePreprocessor generates a default material automatically if none is there.
  1438. // All further code here in this loader works well without a valid material so
  1439. // we can safely let it to ScenePreprocessor.
  1440. }
  1441. // ------------------------------------------------------------------------------------------------
  1442. // Resolves the texture name for the given effect texture entry and loads the texture data
  1443. aiString ColladaLoader::FindFilenameForEffectTexture(const ColladaParser &pParser,
  1444. const Effect &pEffect, const std::string &pName) {
  1445. aiString result;
  1446. // recurse through the param references until we end up at an image
  1447. std::string name = pName;
  1448. while (true) {
  1449. // the given string is a param entry. Find it
  1450. Effect::ParamLibrary::const_iterator it = pEffect.mParams.find(name);
  1451. // if not found, we're at the end of the recursion. The resulting string should be the image ID
  1452. if (it == pEffect.mParams.end())
  1453. break;
  1454. // else recurse on
  1455. name = it->second.mReference;
  1456. }
  1457. // find the image referred by this name in the image library of the scene
  1458. ColladaParser::ImageLibrary::const_iterator imIt = pParser.mImageLibrary.find(name);
  1459. if (imIt == pParser.mImageLibrary.end()) {
  1460. ASSIMP_LOG_WARN("Collada: Unable to resolve effect texture entry \"", pName, "\", ended up at ID \"", name, "\".");
  1461. //set default texture file name
  1462. result.Set(name + ".jpg");
  1463. ColladaParser::UriDecodePath(result);
  1464. return result;
  1465. }
  1466. // if this is an embedded texture image setup an aiTexture for it
  1467. if (!imIt->second.mImageData.empty()) {
  1468. aiTexture *tex = new aiTexture();
  1469. // Store embedded texture name reference
  1470. tex->mFilename.Set(imIt->second.mFileName.c_str());
  1471. result.Set(imIt->second.mFileName);
  1472. // setup format hint
  1473. if (imIt->second.mEmbeddedFormat.length() >= HINTMAXTEXTURELEN) {
  1474. ASSIMP_LOG_WARN("Collada: texture format hint is too long, truncating to 3 characters");
  1475. }
  1476. strncpy(tex->achFormatHint, imIt->second.mEmbeddedFormat.c_str(), 3);
  1477. // and copy texture data
  1478. tex->mHeight = 0;
  1479. tex->mWidth = static_cast<unsigned int>(imIt->second.mImageData.size());
  1480. tex->pcData = (aiTexel *)new char[tex->mWidth];
  1481. memcpy(tex->pcData, &imIt->second.mImageData[0], tex->mWidth);
  1482. // and add this texture to the list
  1483. mTextures.push_back(tex);
  1484. return result;
  1485. }
  1486. if (imIt->second.mFileName.empty()) {
  1487. throw DeadlyImportError("Collada: Invalid texture, no data or file reference given");
  1488. }
  1489. result.Set(imIt->second.mFileName);
  1490. return result;
  1491. }
  1492. // ------------------------------------------------------------------------------------------------
  1493. // Reads a float value from an accessor and its data array.
  1494. ai_real ColladaLoader::ReadFloat(const Accessor &pAccessor, const Data &pData, size_t pIndex, size_t pOffset) const {
  1495. size_t pos = pAccessor.mStride * pIndex + pAccessor.mOffset + pOffset;
  1496. ai_assert(pos < pData.mValues.size());
  1497. return pData.mValues[pos];
  1498. }
  1499. // ------------------------------------------------------------------------------------------------
  1500. // Reads a string value from an accessor and its data array.
  1501. const std::string &ColladaLoader::ReadString(const Accessor &pAccessor, const Data &pData, size_t pIndex) const {
  1502. size_t pos = pAccessor.mStride * pIndex + pAccessor.mOffset;
  1503. ai_assert(pos < pData.mStrings.size());
  1504. return pData.mStrings[pos];
  1505. }
  1506. // ------------------------------------------------------------------------------------------------
  1507. // Collects all nodes into the given array
  1508. void ColladaLoader::CollectNodes(const aiNode *pNode, std::vector<const aiNode *> &poNodes) const {
  1509. poNodes.push_back(pNode);
  1510. for (size_t a = 0; a < pNode->mNumChildren; ++a) {
  1511. CollectNodes(pNode->mChildren[a], poNodes);
  1512. }
  1513. }
  1514. // ------------------------------------------------------------------------------------------------
  1515. // Finds a node in the collada scene by the given name
  1516. const Node *ColladaLoader::FindNode(const Node *pNode, const std::string &pName) const {
  1517. if (pNode->mName == pName || pNode->mID == pName)
  1518. return pNode;
  1519. for (auto a : pNode->mChildren) {
  1520. const Collada::Node *node = FindNode(a, pName);
  1521. if (node) {
  1522. return node;
  1523. }
  1524. }
  1525. return nullptr;
  1526. }
  1527. // ------------------------------------------------------------------------------------------------
  1528. // Finds a node in the collada scene by the given SID
  1529. const Node *ColladaLoader::FindNodeBySID(const Node *pNode, const std::string &pSID) const {
  1530. if (nullptr == pNode) {
  1531. return nullptr;
  1532. }
  1533. if (pNode->mSID == pSID) {
  1534. return pNode;
  1535. }
  1536. for (auto a : pNode->mChildren) {
  1537. const Collada::Node *node = FindNodeBySID(a, pSID);
  1538. if (node) {
  1539. return node;
  1540. }
  1541. }
  1542. return nullptr;
  1543. }
  1544. // ------------------------------------------------------------------------------------------------
  1545. // Finds a proper unique name for a node derived from the collada-node's properties.
  1546. // The name must be unique for proper node-bone association.
  1547. std::string ColladaLoader::FindNameForNode(const Node *pNode) {
  1548. // If explicitly requested, just use the collada name.
  1549. if (useColladaName) {
  1550. if (!pNode->mName.empty()) {
  1551. return pNode->mName;
  1552. } else {
  1553. return format() << "$ColladaAutoName$_" << mNodeNameCounter++;
  1554. }
  1555. } else {
  1556. // Now setup the name of the assimp node. The collada name might not be
  1557. // unique, so we use the collada ID.
  1558. if (!pNode->mID.empty())
  1559. return pNode->mID;
  1560. else if (!pNode->mSID.empty())
  1561. return pNode->mSID;
  1562. else {
  1563. // No need to worry. Unnamed nodes are no problem at all, except
  1564. // if cameras or lights need to be assigned to them.
  1565. return format() << "$ColladaAutoName$_" << mNodeNameCounter++;
  1566. }
  1567. }
  1568. }
  1569. } // Namespace Assimp
  1570. #endif // !! ASSIMP_BUILD_NO_DAE_IMPORTER