ColladaLoader.cpp 82 KB

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