ColladaLoader.cpp 84 KB

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