ColladaLoader.cpp 82 KB

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