ColladaLoader.cpp 53 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376
  1. /*
  2. ---------------------------------------------------------------------------
  3. Open Asset Import Library (ASSIMP)
  4. ---------------------------------------------------------------------------
  5. Copyright (c) 2006-2008, ASSIMP Development 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 Development 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. #include "AssimpPCH.h"
  36. #ifndef ASSIMP_BUILD_NO_DAE_IMPORTER
  37. #include "../include/aiAnim.h"
  38. #include "ColladaLoader.h"
  39. #include "ColladaParser.h"
  40. #include "fast_atof.h"
  41. #include "ParsingUtils.h"
  42. #include "SkeletonMeshBuilder.h"
  43. #include "time.h"
  44. using namespace Assimp;
  45. // ------------------------------------------------------------------------------------------------
  46. // Constructor to be privately used by Importer
  47. ColladaLoader::ColladaLoader()
  48. {}
  49. // ------------------------------------------------------------------------------------------------
  50. // Destructor, private as well
  51. ColladaLoader::~ColladaLoader()
  52. {}
  53. // ------------------------------------------------------------------------------------------------
  54. // Returns whether the class can handle the format of the given file.
  55. bool ColladaLoader::CanRead( const std::string& pFile, IOSystem* pIOHandler, bool checkSig) const
  56. {
  57. // check file extension
  58. std::string extension = GetExtension(pFile);
  59. if( extension == "dae")
  60. return true;
  61. // XML - too generic, we need to open the file and search for typical keywords
  62. if( extension == "xml" || !extension.length() || checkSig) {
  63. /* If CanRead() is called in order to check whether we
  64. * support a specific file extension in general pIOHandler
  65. * might be NULL and it's our duty to return true here.
  66. */
  67. if (!pIOHandler)return true;
  68. const char* tokens[] = {"collada"};
  69. return SearchFileHeaderForToken(pIOHandler,pFile,tokens,1);
  70. }
  71. return false;
  72. }
  73. // ------------------------------------------------------------------------------------------------
  74. // Get file extension list
  75. void ColladaLoader::GetExtensionList( std::string& append)
  76. {
  77. append.append("*.dae");
  78. }
  79. // ------------------------------------------------------------------------------------------------
  80. // Imports the given file into the given scene structure.
  81. void ColladaLoader::InternReadFile( const std::string& pFile, aiScene* pScene, IOSystem* pIOHandler)
  82. {
  83. mFileName = pFile;
  84. // clean all member arrays - just for safety, it should work even if we did not
  85. mMeshIndexByID.clear();
  86. mMaterialIndexByName.clear();
  87. mMeshes.clear();
  88. newMats.clear();
  89. mLights.clear();
  90. mCameras.clear();
  91. mTextures.clear();
  92. // parse the input file
  93. ColladaParser parser( pIOHandler, pFile);
  94. if( !parser.mRootNode)
  95. throw new ImportErrorException( "Collada: File came out empty. Something is wrong here.");
  96. // reserve some storage to avoid unnecessary reallocs
  97. newMats.reserve(parser.mMaterialLibrary.size()*2);
  98. mMeshes.reserve(parser.mMeshLibrary.size()*2);
  99. mCameras.reserve(parser.mCameraLibrary.size());
  100. mLights.reserve(parser.mLightLibrary.size());
  101. // create the materials first, for the meshes to find
  102. BuildMaterials( parser, pScene);
  103. // build the node hierarchy from it
  104. pScene->mRootNode = BuildHierarchy( parser, parser.mRootNode);
  105. // ... then fill the materials with the now adjusted settings
  106. FillMaterials(parser, pScene);
  107. // Convert to Y_UP, if different orientation
  108. if( parser.mUpDirection == ColladaParser::UP_X)
  109. pScene->mRootNode->mTransformation *= aiMatrix4x4(
  110. 0, -1, 0, 0,
  111. 1, 0, 0, 0,
  112. 0, 0, 1, 0,
  113. 0, 0, 0, 1);
  114. else if( parser.mUpDirection == ColladaParser::UP_Z)
  115. pScene->mRootNode->mTransformation *= aiMatrix4x4(
  116. 1, 0, 0, 0,
  117. 0, 0, 1, 0,
  118. 0, -1, 0, 0,
  119. 0, 0, 0, 1);
  120. // store all meshes
  121. StoreSceneMeshes( pScene);
  122. // store all materials
  123. StoreSceneMaterials( pScene);
  124. // store all lights
  125. StoreSceneLights( pScene);
  126. // store all cameras
  127. StoreSceneCameras( pScene);
  128. // store all animations
  129. StoreAnimations( pScene, parser);
  130. // If no meshes have been loaded, it's probably just an animated skeleton.
  131. if (!pScene->mNumMeshes) {
  132. SkeletonMeshBuilder hero(pScene);
  133. pScene->mFlags |= AI_SCENE_FLAGS_INCOMPLETE;
  134. }
  135. }
  136. // ------------------------------------------------------------------------------------------------
  137. // Recursively constructs a scene node for the given parser node and returns it.
  138. aiNode* ColladaLoader::BuildHierarchy( const ColladaParser& pParser, const Collada::Node* pNode)
  139. {
  140. // create a node for it
  141. aiNode* node = new aiNode();
  142. // now setup the name of the node. We take the name if not empty, otherwise the collada ID
  143. // FIX: Workaround for XSI calling the instanced visual scene 'untitled' by default.
  144. if (!pNode->mName.empty() && pNode->mName != "untitled")
  145. node->mName.Set(pNode->mName);
  146. else if (!pNode->mID.empty())
  147. node->mName.Set(pNode->mID);
  148. else
  149. {
  150. // No need to worry. Unnamed nodes are no problem at all, except
  151. // if cameras or lights need to be assigned to them.
  152. if (!pNode->mLights.empty() || !pNode->mCameras.empty()) {
  153. ::strcpy(node->mName.data,"$ColladaAutoName$_");
  154. node->mName.length = 17 + ASSIMP_itoa10(node->mName.data+18,MAXLEN-18,(uint32_t)clock());
  155. }
  156. }
  157. // calculate the transformation matrix for it
  158. node->mTransformation = pParser.CalculateResultTransform( pNode->mTransforms);
  159. // now resolve node instances
  160. std::vector<Collada::Node*> instances;
  161. ResolveNodeInstances(pParser,pNode,instances);
  162. // add children. first the *real* ones
  163. node->mNumChildren = pNode->mChildren.size()+instances.size();
  164. node->mChildren = new aiNode*[node->mNumChildren];
  165. unsigned int a = 0;
  166. for(; a < pNode->mChildren.size(); a++)
  167. {
  168. node->mChildren[a] = BuildHierarchy( pParser, pNode->mChildren[a]);
  169. node->mChildren[a]->mParent = node;
  170. }
  171. // ... and finally the resolved node instances
  172. for(; a < node->mNumChildren; a++)
  173. {
  174. node->mChildren[a] = BuildHierarchy( pParser, instances[a-pNode->mChildren.size()]);
  175. node->mChildren[a]->mParent = node;
  176. }
  177. // construct meshes
  178. BuildMeshesForNode( pParser, pNode, node);
  179. // construct cameras
  180. BuildCamerasForNode(pParser, pNode, node);
  181. // construct lights
  182. BuildLightsForNode(pParser, pNode, node);
  183. return node;
  184. }
  185. // ------------------------------------------------------------------------------------------------
  186. // Resolve node instances
  187. void ColladaLoader::ResolveNodeInstances( const ColladaParser& pParser, const Collada::Node* pNode,
  188. std::vector<Collada::Node*>& resolved)
  189. {
  190. // reserve enough storage
  191. resolved.reserve(pNode->mNodeInstances.size());
  192. // ... and iterate through all nodes to be instanced as children of pNode
  193. for (std::vector<Collada::NodeInstance>::const_iterator it = pNode->mNodeInstances.begin(),
  194. end = pNode->mNodeInstances.end(); it != end; ++it)
  195. {
  196. // find the corresponding node in the library
  197. ColladaParser::NodeLibrary::const_iterator fnd = pParser.mNodeLibrary.find((*it).mNode);
  198. if (fnd == pParser.mNodeLibrary.end())
  199. DefaultLogger::get()->error("Collada: Unable to resolve reference to instanced node " + (*it).mNode);
  200. else {
  201. // attach this node to the list of children
  202. resolved.push_back((*fnd).second);
  203. }
  204. }
  205. }
  206. // ------------------------------------------------------------------------------------------------
  207. // Resolve UV channels
  208. void ColladaLoader::ApplyVertexToEffectSemanticMapping(Collada::Sampler& sampler,
  209. const Collada::SemanticMappingTable& table)
  210. {
  211. std::map<std::string, Collada::InputSemanticMapEntry>::const_iterator it = table.mMap.find(sampler.mUVChannel);
  212. if (it != table.mMap.end()) {
  213. if (it->second.mType != Collada::IT_Texcoord)
  214. DefaultLogger::get()->error("Collada: Unexpected effect input mapping");
  215. sampler.mUVId = it->second.mSet;
  216. }
  217. }
  218. // ------------------------------------------------------------------------------------------------
  219. // Builds lights for the given node and references them
  220. void ColladaLoader::BuildLightsForNode( const ColladaParser& pParser, const Collada::Node* pNode, aiNode* pTarget)
  221. {
  222. BOOST_FOREACH( const Collada::LightInstance& lid, pNode->mLights)
  223. {
  224. // find the referred light
  225. ColladaParser::LightLibrary::const_iterator srcLightIt = pParser.mLightLibrary.find( lid.mLight);
  226. if( srcLightIt == pParser.mLightLibrary.end())
  227. {
  228. DefaultLogger::get()->warn("Collada: Unable to find light for ID \"" + lid.mLight + "\". Skipping.");
  229. continue;
  230. }
  231. const Collada::Light* srcLight = &srcLightIt->second;
  232. if (srcLight->mType == aiLightSource_AMBIENT) {
  233. DefaultLogger::get()->error("Collada: Skipping ambient light for the moment");
  234. continue;
  235. }
  236. // now fill our ai data structure
  237. aiLight* out = new aiLight();
  238. out->mName = pTarget->mName;
  239. out->mType = (aiLightSourceType)srcLight->mType;
  240. // collada lights point in -Z by default, rest is specified in node transform
  241. out->mDirection = aiVector3D(0.f,0.f,-1.f);
  242. out->mAttenuationConstant = srcLight->mAttConstant;
  243. out->mAttenuationLinear = srcLight->mAttLinear;
  244. out->mAttenuationQuadratic = srcLight->mAttQuadratic;
  245. // collada doesn't differenciate between these color types
  246. out->mColorDiffuse = out->mColorSpecular = out->mColorAmbient = srcLight->mColor*srcLight->mIntensity;
  247. // convert falloff angle and falloff exponent in our representation, if given
  248. if (out->mType == aiLightSource_SPOT) {
  249. out->mAngleInnerCone = AI_DEG_TO_RAD( srcLight->mFalloffAngle );
  250. // ... some extension magic. FUCKING COLLADA.
  251. if (srcLight->mOuterAngle == 10e10f)
  252. {
  253. // ... some deprecation magic. FUCKING FCOLLADA.
  254. if (srcLight->mPenumbraAngle == 10e10f)
  255. {
  256. // Need to rely on falloff_exponent. I don't know how to interpret it, so I need to guess ....
  257. // ci - inner cone angle
  258. // co - outer cone angle
  259. // fe - falloff exponent
  260. // ld - spot direction - normalized
  261. // rd - ray direction - normalized
  262. //
  263. // Formula is:
  264. // 1. (cos(acos (ld dot rd) - ci))^fe == epsilon
  265. // 2. (ld dot rd) == cos(acos(epsilon^(1/fe)) + ci)
  266. // 3. co == acos (ld dot rd)
  267. // 4. co == acos(epsilon^(1/fe)) + ci)
  268. // epsilon chosen to be 0.1
  269. out->mAngleOuterCone = AI_DEG_TO_RAD (acos(pow(0.1f,1.f/srcLight->mFalloffExponent))+
  270. srcLight->mFalloffAngle);
  271. }
  272. else {
  273. out->mAngleOuterCone = out->mAngleInnerCone + AI_DEG_TO_RAD( srcLight->mPenumbraAngle );
  274. if (out->mAngleOuterCone < out->mAngleInnerCone)
  275. std::swap(out->mAngleInnerCone,out->mAngleOuterCone);
  276. }
  277. }
  278. else out->mAngleOuterCone = AI_DEG_TO_RAD( srcLight->mOuterAngle );
  279. }
  280. // add to light list
  281. mLights.push_back(out);
  282. }
  283. }
  284. // ------------------------------------------------------------------------------------------------
  285. // Builds cameras for the given node and references them
  286. void ColladaLoader::BuildCamerasForNode( const ColladaParser& pParser, const Collada::Node* pNode, aiNode* pTarget)
  287. {
  288. BOOST_FOREACH( const Collada::CameraInstance& cid, pNode->mCameras)
  289. {
  290. // find the referred light
  291. ColladaParser::CameraLibrary::const_iterator srcCameraIt = pParser.mCameraLibrary.find( cid.mCamera);
  292. if( srcCameraIt == pParser.mCameraLibrary.end())
  293. {
  294. DefaultLogger::get()->warn("Collada: Unable to find camera for ID \"" + cid.mCamera + "\". Skipping.");
  295. continue;
  296. }
  297. const Collada::Camera* srcCamera = &srcCameraIt->second;
  298. // orthographic cameras not yet supported in Assimp
  299. if (srcCamera->mOrtho) {
  300. DefaultLogger::get()->warn("Collada: Orthographic cameras are not supported.");
  301. }
  302. // now fill our ai data structure
  303. aiCamera* out = new aiCamera();
  304. out->mName = pTarget->mName;
  305. // collada cameras point in -Z by default, rest is specified in node transform
  306. out->mLookAt = aiVector3D(0.f,0.f,-1.f);
  307. // near/far z is already ok
  308. out->mClipPlaneFar = srcCamera->mZFar;
  309. out->mClipPlaneNear = srcCamera->mZNear;
  310. // ... but for the rest some values are optional
  311. // and we need to compute the others in any combination. FUCKING COLLADA.
  312. if (srcCamera->mAspect != 10e10f)
  313. out->mAspect = srcCamera->mAspect;
  314. if (srcCamera->mHorFov != 10e10f) {
  315. out->mHorizontalFOV = srcCamera->mHorFov;
  316. if (srcCamera->mVerFov != 10e10f && srcCamera->mAspect != 10e10f) {
  317. out->mAspect = srcCamera->mHorFov/srcCamera->mVerFov;
  318. }
  319. }
  320. else if (srcCamera->mAspect != 10e10f && srcCamera->mVerFov != 10e10f) {
  321. out->mHorizontalFOV = srcCamera->mAspect*srcCamera->mVerFov;
  322. }
  323. // Collada uses degrees, we use radians
  324. out->mHorizontalFOV = AI_DEG_TO_RAD(out->mHorizontalFOV);
  325. // add to camera list
  326. mCameras.push_back(out);
  327. }
  328. }
  329. // ------------------------------------------------------------------------------------------------
  330. // Builds meshes for the given node and references them
  331. void ColladaLoader::BuildMeshesForNode( const ColladaParser& pParser, const Collada::Node* pNode, aiNode* pTarget)
  332. {
  333. // accumulated mesh references by this node
  334. std::vector<size_t> newMeshRefs;
  335. newMeshRefs.reserve(pNode->mMeshes.size());
  336. // add a mesh for each subgroup in each collada mesh
  337. BOOST_FOREACH( const Collada::MeshInstance& mid, pNode->mMeshes)
  338. {
  339. const Collada::Mesh* srcMesh = NULL;
  340. const Collada::Controller* srcController = NULL;
  341. // find the referred mesh
  342. ColladaParser::MeshLibrary::const_iterator srcMeshIt = pParser.mMeshLibrary.find( mid.mMeshOrController);
  343. if( srcMeshIt == pParser.mMeshLibrary.end())
  344. {
  345. // if not found in the mesh-library, it might also be a controller referring to a mesh
  346. ColladaParser::ControllerLibrary::const_iterator srcContrIt = pParser.mControllerLibrary.find( mid.mMeshOrController);
  347. if( srcContrIt != pParser.mControllerLibrary.end())
  348. {
  349. srcController = &srcContrIt->second;
  350. srcMeshIt = pParser.mMeshLibrary.find( srcController->mMeshId);
  351. if( srcMeshIt != pParser.mMeshLibrary.end())
  352. srcMesh = srcMeshIt->second;
  353. }
  354. if( !srcMesh)
  355. {
  356. DefaultLogger::get()->warn( boost::str( boost::format( "Collada: Unable to find geometry for ID \"%s\". Skipping.") % mid.mMeshOrController));
  357. continue;
  358. }
  359. } else
  360. {
  361. // ID found in the mesh library -> direct reference to an unskinned mesh
  362. srcMesh = srcMeshIt->second;
  363. }
  364. // build a mesh for each of its subgroups
  365. size_t vertexStart = 0, faceStart = 0;
  366. for( size_t sm = 0; sm < srcMesh->mSubMeshes.size(); ++sm)
  367. {
  368. const Collada::SubMesh& submesh = srcMesh->mSubMeshes[sm];
  369. if( submesh.mNumFaces == 0)
  370. continue;
  371. // find material assigned to this submesh
  372. std::map<std::string, Collada::SemanticMappingTable >::const_iterator meshMatIt = mid.mMaterials.find( submesh.mMaterial);
  373. const Collada::SemanticMappingTable* table;
  374. if( meshMatIt != mid.mMaterials.end())
  375. table = &meshMatIt->second;
  376. else {
  377. table = NULL;
  378. DefaultLogger::get()->warn( boost::str( boost::format( "Collada: No material specified for subgroup \"%s\" in geometry \"%s\".") % submesh.mMaterial % mid.mMeshOrController));
  379. }
  380. const std::string& meshMaterial = table ? table->mMatName : "";
  381. // OK ... here the *real* fun starts ... we have the vertex-input-to-effect-semantic-table
  382. // given. The only mapping stuff which we do actually support is the UV channel.
  383. std::map<std::string, size_t>::const_iterator matIt = mMaterialIndexByName.find( meshMaterial);
  384. unsigned int matIdx;
  385. if( matIt != mMaterialIndexByName.end())
  386. matIdx = matIt->second;
  387. else
  388. matIdx = 0;
  389. if (table && !table->mMap.empty() ) {
  390. std::pair<Collada::Effect*, aiMaterial*>& mat = newMats[matIdx];
  391. // Iterate through all texture channels assigned to the effect and
  392. // check whether we have mapping information for it.
  393. ApplyVertexToEffectSemanticMapping(mat.first->mTexDiffuse, *table);
  394. ApplyVertexToEffectSemanticMapping(mat.first->mTexAmbient, *table);
  395. ApplyVertexToEffectSemanticMapping(mat.first->mTexSpecular, *table);
  396. ApplyVertexToEffectSemanticMapping(mat.first->mTexEmissive, *table);
  397. ApplyVertexToEffectSemanticMapping(mat.first->mTexTransparent,*table);
  398. ApplyVertexToEffectSemanticMapping(mat.first->mTexBump, *table);
  399. }
  400. // built lookup index of the Mesh-Submesh-Material combination
  401. ColladaMeshIndex index( mid.mMeshOrController, sm, meshMaterial);
  402. // if we already have the mesh at the library, just add its index to the node's array
  403. std::map<ColladaMeshIndex, size_t>::const_iterator dstMeshIt = mMeshIndexByID.find( index);
  404. if( dstMeshIt != mMeshIndexByID.end())
  405. {
  406. newMeshRefs.push_back( dstMeshIt->second);
  407. } else
  408. {
  409. // else we have to add the mesh to the collection and store its newly assigned index at the node
  410. aiMesh* dstMesh = CreateMesh( pParser, srcMesh, submesh, srcController, vertexStart, faceStart);
  411. // store the mesh, and store its new index in the node
  412. newMeshRefs.push_back( mMeshes.size());
  413. mMeshIndexByID[index] = mMeshes.size();
  414. mMeshes.push_back( dstMesh);
  415. vertexStart += dstMesh->mNumVertices; faceStart += submesh.mNumFaces;
  416. // assign the material index
  417. dstMesh->mMaterialIndex = matIdx;
  418. }
  419. }
  420. }
  421. // now place all mesh references we gathered in the target node
  422. pTarget->mNumMeshes = newMeshRefs.size();
  423. if( newMeshRefs.size())
  424. {
  425. pTarget->mMeshes = new unsigned int[pTarget->mNumMeshes];
  426. std::copy( newMeshRefs.begin(), newMeshRefs.end(), pTarget->mMeshes);
  427. }
  428. }
  429. // ------------------------------------------------------------------------------------------------
  430. // Creates a mesh for the given ColladaMesh face subset and returns the newly created mesh
  431. aiMesh* ColladaLoader::CreateMesh( const ColladaParser& pParser, const Collada::Mesh* pSrcMesh, const Collada::SubMesh& pSubMesh,
  432. const Collada::Controller* pSrcController, size_t pStartVertex, size_t pStartFace)
  433. {
  434. aiMesh* dstMesh = new aiMesh;
  435. // count the vertices addressed by its faces
  436. const size_t numVertices = std::accumulate( pSrcMesh->mFaceSize.begin() + pStartFace,
  437. pSrcMesh->mFaceSize.begin() + pStartFace + pSubMesh.mNumFaces, 0);
  438. // copy positions
  439. dstMesh->mNumVertices = numVertices;
  440. dstMesh->mVertices = new aiVector3D[numVertices];
  441. std::copy( pSrcMesh->mPositions.begin() + pStartVertex, pSrcMesh->mPositions.begin() +
  442. pStartVertex + numVertices, dstMesh->mVertices);
  443. // normals, if given. HACK: (thom) Due to the fucking Collada spec we never
  444. // know if we have the same number of normals as there are positions. So we
  445. // also ignore any vertex attribute if it has a different count
  446. if( pSrcMesh->mNormals.size() == pSrcMesh->mPositions.size())
  447. {
  448. dstMesh->mNormals = new aiVector3D[numVertices];
  449. std::copy( pSrcMesh->mNormals.begin() + pStartVertex, pSrcMesh->mNormals.begin() +
  450. pStartVertex + numVertices, dstMesh->mNormals);
  451. }
  452. // tangents, if given.
  453. if( pSrcMesh->mTangents.size() == pSrcMesh->mPositions.size())
  454. {
  455. dstMesh->mTangents = new aiVector3D[numVertices];
  456. std::copy( pSrcMesh->mTangents.begin() + pStartVertex, pSrcMesh->mTangents.begin() +
  457. pStartVertex + numVertices, dstMesh->mTangents);
  458. }
  459. // bitangents, if given.
  460. if( pSrcMesh->mBitangents.size() == pSrcMesh->mPositions.size())
  461. {
  462. dstMesh->mBitangents = new aiVector3D[numVertices];
  463. std::copy( pSrcMesh->mBitangents.begin() + pStartVertex, pSrcMesh->mBitangents.begin() +
  464. pStartVertex + numVertices, dstMesh->mBitangents);
  465. }
  466. // same for texturecoords, as many as we have
  467. for( size_t a = 0; a < AI_MAX_NUMBER_OF_TEXTURECOORDS; a++)
  468. {
  469. if( pSrcMesh->mTexCoords[a].size() == pSrcMesh->mPositions.size())
  470. {
  471. dstMesh->mTextureCoords[a] = new aiVector3D[numVertices];
  472. for( size_t b = 0; b < numVertices; ++b)
  473. dstMesh->mTextureCoords[a][b] = pSrcMesh->mTexCoords[a][pStartVertex+b];
  474. dstMesh->mNumUVComponents[a] = pSrcMesh->mNumUVComponents[a];
  475. }
  476. }
  477. // same for vertex colors, as many as we have
  478. for( size_t a = 0; a < AI_MAX_NUMBER_OF_COLOR_SETS; a++)
  479. {
  480. if( pSrcMesh->mColors[a].size() == pSrcMesh->mPositions.size())
  481. {
  482. dstMesh->mColors[a] = new aiColor4D[numVertices];
  483. std::copy( pSrcMesh->mColors[a].begin() + pStartVertex, pSrcMesh->mColors[a].begin() + pStartVertex + numVertices, dstMesh->mColors[a]);
  484. }
  485. }
  486. // create faces. Due to the fact that each face uses unique vertices, we can simply count up on each vertex
  487. size_t vertex = 0;
  488. dstMesh->mNumFaces = pSubMesh.mNumFaces;
  489. dstMesh->mFaces = new aiFace[dstMesh->mNumFaces];
  490. for( size_t a = 0; a < dstMesh->mNumFaces; ++a)
  491. {
  492. size_t s = pSrcMesh->mFaceSize[ pStartFace + a];
  493. aiFace& face = dstMesh->mFaces[a];
  494. face.mNumIndices = s;
  495. face.mIndices = new unsigned int[s];
  496. for( size_t b = 0; b < s; ++b)
  497. face.mIndices[b] = vertex++;
  498. }
  499. // create bones if given
  500. if( pSrcController)
  501. {
  502. // refuse if the vertex count does not match
  503. // if( pSrcController->mWeightCounts.size() != dstMesh->mNumVertices)
  504. // throw new ImportErrorException( "Joint Controller vertex count does not match mesh vertex count");
  505. // resolve references - joint names
  506. const Collada::Accessor& jointNamesAcc = pParser.ResolveLibraryReference( pParser.mAccessorLibrary, pSrcController->mJointNameSource);
  507. const Collada::Data& jointNames = pParser.ResolveLibraryReference( pParser.mDataLibrary, jointNamesAcc.mSource);
  508. // joint offset matrices
  509. const Collada::Accessor& jointMatrixAcc = pParser.ResolveLibraryReference( pParser.mAccessorLibrary, pSrcController->mJointOffsetMatrixSource);
  510. const Collada::Data& jointMatrices = pParser.ResolveLibraryReference( pParser.mDataLibrary, jointMatrixAcc.mSource);
  511. // joint vertex_weight name list - should refer to the same list as the joint names above. If not, report and reconsider
  512. const Collada::Accessor& weightNamesAcc = pParser.ResolveLibraryReference( pParser.mAccessorLibrary, pSrcController->mWeightInputJoints.mAccessor);
  513. if( &weightNamesAcc != &jointNamesAcc)
  514. throw new ImportErrorException( "Temporary implementational lazyness. If you read this, please report to the author.");
  515. // vertex weights
  516. const Collada::Accessor& weightsAcc = pParser.ResolveLibraryReference( pParser.mAccessorLibrary, pSrcController->mWeightInputWeights.mAccessor);
  517. const Collada::Data& weights = pParser.ResolveLibraryReference( pParser.mDataLibrary, weightsAcc.mSource);
  518. if( !jointNames.mIsStringArray || jointMatrices.mIsStringArray || weights.mIsStringArray)
  519. throw new ImportErrorException( "Data type mismatch while resolving mesh joints");
  520. // sanity check: we rely on the vertex weights always coming as pairs of BoneIndex-WeightIndex
  521. if( pSrcController->mWeightInputJoints.mOffset != 0 || pSrcController->mWeightInputWeights.mOffset != 1)
  522. throw new ImportErrorException( "Unsupported vertex_weight adresssing scheme. Fucking collada spec.");
  523. // create containers to collect the weights for each bone
  524. size_t numBones = jointNames.mStrings.size();
  525. std::vector<std::vector<aiVertexWeight> > dstBones( numBones);
  526. // build a temporary array of pointers to the start of each vertex's weights
  527. typedef std::vector< std::pair<size_t, size_t> > IndexPairVector;
  528. std::vector<IndexPairVector::const_iterator> weightStartPerVertex( pSrcController->mWeightCounts.size());
  529. IndexPairVector::const_iterator pit = pSrcController->mWeights.begin();
  530. for( size_t a = 0; a < pSrcController->mWeightCounts.size(); ++a)
  531. {
  532. weightStartPerVertex[a] = pit;
  533. pit += pSrcController->mWeightCounts[a];
  534. }
  535. // now for each vertex put the corresponding vertex weights into each bone's weight collection
  536. for( size_t a = pStartVertex; a < pStartVertex + numVertices; ++a)
  537. {
  538. // which position index was responsible for this vertex? that's also the index by which
  539. // the controller assigns the vertex weights
  540. size_t orgIndex = pSrcMesh->mFacePosIndices[a];
  541. // find the vertex weights for this vertex
  542. IndexPairVector::const_iterator iit = weightStartPerVertex[orgIndex];
  543. size_t pairCount = pSrcController->mWeightCounts[orgIndex];
  544. for( size_t b = 0; b < pairCount; ++b, ++iit)
  545. {
  546. size_t jointIndex = iit->first;
  547. size_t vertexIndex = iit->second;
  548. float weight = ReadFloat( weightsAcc, weights, vertexIndex, 0);
  549. aiVertexWeight w;
  550. w.mVertexId = a - pStartVertex;
  551. w.mWeight = weight;
  552. dstBones[jointIndex].push_back( w);
  553. }
  554. }
  555. // count the number of bones which influence vertices of the current submesh
  556. size_t numRemainingBones = 0;
  557. for( std::vector<std::vector<aiVertexWeight> >::const_iterator it = dstBones.begin(); it != dstBones.end(); ++it)
  558. if( it->size() > 0)
  559. numRemainingBones++;
  560. // create bone array and copy bone weights one by one
  561. dstMesh->mNumBones = numRemainingBones;
  562. dstMesh->mBones = new aiBone*[numRemainingBones];
  563. size_t boneCount = 0;
  564. for( size_t a = 0; a < numBones; ++a)
  565. {
  566. // omit bones without weights
  567. if( dstBones[a].size() == 0)
  568. continue;
  569. // create bone with its weights
  570. aiBone* bone = new aiBone;
  571. bone->mName = ReadString( jointNamesAcc, jointNames, a);
  572. bone->mOffsetMatrix.a1 = ReadFloat( jointMatrixAcc, jointMatrices, a, 0);
  573. bone->mOffsetMatrix.a2 = ReadFloat( jointMatrixAcc, jointMatrices, a, 1);
  574. bone->mOffsetMatrix.a3 = ReadFloat( jointMatrixAcc, jointMatrices, a, 2);
  575. bone->mOffsetMatrix.a4 = ReadFloat( jointMatrixAcc, jointMatrices, a, 3);
  576. bone->mOffsetMatrix.b1 = ReadFloat( jointMatrixAcc, jointMatrices, a, 4);
  577. bone->mOffsetMatrix.b2 = ReadFloat( jointMatrixAcc, jointMatrices, a, 5);
  578. bone->mOffsetMatrix.b3 = ReadFloat( jointMatrixAcc, jointMatrices, a, 6);
  579. bone->mOffsetMatrix.b4 = ReadFloat( jointMatrixAcc, jointMatrices, a, 7);
  580. bone->mOffsetMatrix.c1 = ReadFloat( jointMatrixAcc, jointMatrices, a, 8);
  581. bone->mOffsetMatrix.c2 = ReadFloat( jointMatrixAcc, jointMatrices, a, 9);
  582. bone->mOffsetMatrix.c3 = ReadFloat( jointMatrixAcc, jointMatrices, a, 10);
  583. bone->mOffsetMatrix.c4 = ReadFloat( jointMatrixAcc, jointMatrices, a, 11);
  584. bone->mNumWeights = dstBones[a].size();
  585. bone->mWeights = new aiVertexWeight[bone->mNumWeights];
  586. std::copy( dstBones[a].begin(), dstBones[a].end(), bone->mWeights);
  587. // and insert bone
  588. dstMesh->mBones[boneCount++] = bone;
  589. }
  590. }
  591. return dstMesh;
  592. }
  593. // ------------------------------------------------------------------------------------------------
  594. // Stores all meshes in the given scene
  595. void ColladaLoader::StoreSceneMeshes( aiScene* pScene)
  596. {
  597. pScene->mNumMeshes = mMeshes.size();
  598. if( mMeshes.size() > 0)
  599. {
  600. pScene->mMeshes = new aiMesh*[mMeshes.size()];
  601. std::copy( mMeshes.begin(), mMeshes.end(), pScene->mMeshes);
  602. mMeshes.clear();
  603. }
  604. }
  605. // ------------------------------------------------------------------------------------------------
  606. // Stores all cameras in the given scene
  607. void ColladaLoader::StoreSceneCameras( aiScene* pScene)
  608. {
  609. pScene->mNumCameras = mCameras.size();
  610. if( mCameras.size() > 0)
  611. {
  612. pScene->mCameras = new aiCamera*[mCameras.size()];
  613. std::copy( mCameras.begin(), mCameras.end(), pScene->mCameras);
  614. mCameras.clear();
  615. }
  616. }
  617. // ------------------------------------------------------------------------------------------------
  618. // Stores all lights in the given scene
  619. void ColladaLoader::StoreSceneLights( aiScene* pScene)
  620. {
  621. pScene->mNumLights = mLights.size();
  622. if( mLights.size() > 0)
  623. {
  624. pScene->mLights = new aiLight*[mLights.size()];
  625. std::copy( mLights.begin(), mLights.end(), pScene->mLights);
  626. mLights.clear();
  627. }
  628. }
  629. // ------------------------------------------------------------------------------------------------
  630. // Stores all textures in the given scene
  631. void ColladaLoader::StoreSceneTextures( aiScene* pScene)
  632. {
  633. pScene->mNumTextures = mTextures.size();
  634. if( mTextures.size() > 0)
  635. {
  636. pScene->mTextures = new aiTexture*[mTextures.size()];
  637. std::copy( mTextures.begin(), mTextures.end(), pScene->mTextures);
  638. mTextures.clear();
  639. }
  640. }
  641. // ------------------------------------------------------------------------------------------------
  642. // Stores all materials in the given scene
  643. void ColladaLoader::StoreSceneMaterials( aiScene* pScene)
  644. {
  645. pScene->mNumMaterials = newMats.size();
  646. if (newMats.size() > 0) {
  647. pScene->mMaterials = new aiMaterial*[newMats.size()];
  648. for (unsigned int i = 0; i < newMats.size();++i)
  649. pScene->mMaterials[i] = newMats[i].second;
  650. newMats.clear();
  651. }
  652. }
  653. // ------------------------------------------------------------------------------------------------
  654. // Stores all animations
  655. void ColladaLoader::StoreAnimations( aiScene* pScene, const ColladaParser& pParser)
  656. {
  657. // recursivly collect all animations from the collada scene
  658. StoreAnimations( pScene, pParser, &pParser.mAnims, "");
  659. // now store all anims in the scene
  660. if( !mAnims.empty())
  661. {
  662. pScene->mNumAnimations = mAnims.size();
  663. pScene->mAnimations = new aiAnimation*[mAnims.size()];
  664. std::copy( mAnims.begin(), mAnims.end(), pScene->mAnimations);
  665. }
  666. }
  667. // ------------------------------------------------------------------------------------------------
  668. // Constructs the animations for the given source anim
  669. void ColladaLoader::StoreAnimations( aiScene* pScene, const ColladaParser& pParser, const Collada::Animation* pSrcAnim, const std::string pPrefix)
  670. {
  671. std::string animName = pPrefix.empty() ? pSrcAnim->mName : pPrefix + "_" + pSrcAnim->mName;
  672. // create nested animations, if given
  673. for( std::vector<Collada::Animation*>::const_iterator it = pSrcAnim->mSubAnims.begin(); it != pSrcAnim->mSubAnims.end(); ++it)
  674. StoreAnimations( pScene, pParser, *it, animName);
  675. // create animation channels, if any
  676. if( !pSrcAnim->mChannels.empty())
  677. CreateAnimation( pScene, pParser, pSrcAnim, animName);
  678. }
  679. /** Description of a collada animation channel which has been determined to affect the current node */
  680. struct ChannelEntry
  681. {
  682. const Collada::AnimationChannel* mChannel; ///> the source channel
  683. std::string mTransformId; // the ID of the transformation step of the node which is influenced
  684. size_t mTransformIndex; // Index into the node's transform chain to apply the channel to
  685. size_t mSubElement; // starting index inside the transform data
  686. // resolved data references
  687. const Collada::Accessor* mTimeAccessor; ///> Collada accessor to the time values
  688. const Collada::Data* mTimeData; ///> Source data array for the time values
  689. const Collada::Accessor* mValueAccessor; ///> Collada accessor to the key value values
  690. const Collada::Data* mValueData; ///> Source datat array for the key value values
  691. ChannelEntry() { mChannel = NULL; mSubElement = 0; }
  692. };
  693. // ------------------------------------------------------------------------------------------------
  694. // Constructs the animation for the given source anim
  695. void ColladaLoader::CreateAnimation( aiScene* pScene, const ColladaParser& pParser, const Collada::Animation* pSrcAnim, const std::string& pName)
  696. {
  697. // collect a list of animatable nodes
  698. std::vector<const aiNode*> nodes;
  699. CollectNodes( pScene->mRootNode, nodes);
  700. std::vector<aiNodeAnim*> anims;
  701. for( std::vector<const aiNode*>::const_iterator nit = nodes.begin(); nit != nodes.end(); ++nit)
  702. {
  703. // find all the collada anim channels which refer to the current node
  704. std::vector<ChannelEntry> entries;
  705. std::string nodeName = (*nit)->mName.data;
  706. // find the collada node corresponding to the aiNode
  707. const Collada::Node* srcNode = FindNode( pParser.mRootNode, nodeName);
  708. // ai_assert( srcNode != NULL);
  709. if( !srcNode)
  710. continue;
  711. // now check all channels if they affect the current node
  712. for( std::vector<Collada::AnimationChannel>::const_iterator cit = pSrcAnim->mChannels.begin();
  713. cit != pSrcAnim->mChannels.end(); ++cit)
  714. {
  715. const Collada::AnimationChannel& srcChannel = *cit;
  716. ChannelEntry entry;
  717. // we except the animation target to be of type "nodeName/transformID.subElement". Ignore all others
  718. // find the slash that separates the node name - there should be only one
  719. std::string::size_type slashPos = srcChannel.mTarget.find( '/');
  720. if( slashPos == std::string::npos)
  721. continue;
  722. if( srcChannel.mTarget.find( '/', slashPos+1) != std::string::npos)
  723. continue;
  724. std::string targetName = srcChannel.mTarget.substr( 0, slashPos);
  725. if( targetName != nodeName)
  726. continue;
  727. // find the dot that separates the transformID - there should be only one or zero
  728. std::string::size_type dotPos = srcChannel.mTarget.find( '.');
  729. if( dotPos != std::string::npos)
  730. {
  731. if( srcChannel.mTarget.find( '.', dotPos+1) != std::string::npos)
  732. continue;
  733. entry.mTransformId = srcChannel.mTarget.substr( slashPos+1, dotPos - slashPos - 1);
  734. std::string subElement = srcChannel.mTarget.substr( dotPos+1);
  735. if( subElement == "ANGLE")
  736. entry.mSubElement = 3; // last number in an Axis-Angle-Transform is the angle
  737. else
  738. DefaultLogger::get()->warn( boost::str( boost::format( "Unknown anim subelement \"%s\". Ignoring") % subElement));
  739. } else
  740. {
  741. // no subelement following, transformId is remaining string
  742. entry.mTransformId = srcChannel.mTarget.substr( slashPos+1);
  743. }
  744. // determine which transform step is affected by this channel
  745. entry.mTransformIndex = -1;
  746. for( size_t a = 0; a < srcNode->mTransforms.size(); ++a)
  747. if( srcNode->mTransforms[a].mID == entry.mTransformId)
  748. entry.mTransformIndex = a;
  749. if( entry.mTransformIndex == -1)
  750. continue;
  751. entry.mChannel = &(*cit);
  752. entries.push_back( entry);
  753. }
  754. // if there's no channel affecting the current node, we skip it
  755. if( entries.empty())
  756. continue;
  757. // resolve the data pointers for all anim channels. Find the minimum time while we're at it
  758. float startTime = 1e20, endTime = -1e20;
  759. for( std::vector<ChannelEntry>::iterator it = entries.begin(); it != entries.end(); ++it)
  760. {
  761. ChannelEntry& e = *it;
  762. e.mTimeAccessor = &pParser.ResolveLibraryReference( pParser.mAccessorLibrary, e.mChannel->mSourceTimes);
  763. e.mTimeData = &pParser.ResolveLibraryReference( pParser.mDataLibrary, e.mTimeAccessor->mSource);
  764. e.mValueAccessor = &pParser.ResolveLibraryReference( pParser.mAccessorLibrary, e.mChannel->mSourceValues);
  765. e.mValueData = &pParser.ResolveLibraryReference( pParser.mDataLibrary, e.mValueAccessor->mSource);
  766. // time count and value count must match
  767. if( e.mTimeAccessor->mCount != e.mValueAccessor->mCount)
  768. throw new ImportErrorException( boost::str( boost::format( "Time count / value count mismatch in animation channel \"%s\".") % e.mChannel->mTarget));
  769. // find bounding times
  770. startTime = std::min( startTime, ReadFloat( *e.mTimeAccessor, *e.mTimeData, 0, 0));
  771. endTime = std::max( endTime, ReadFloat( *e.mTimeAccessor, *e.mTimeData, e.mTimeAccessor->mCount-1, 0));
  772. }
  773. // create a local transformation chain of the node's transforms
  774. std::vector<Collada::Transform> transforms = srcNode->mTransforms;
  775. // now for every unique point in time, find or interpolate the key values for that time
  776. // and apply them to the transform chain. Then the node's present transformation can be calculated.
  777. float time = startTime;
  778. std::vector<aiMatrix4x4> resultTrafos;
  779. while( 1)
  780. {
  781. for( std::vector<ChannelEntry>::iterator it = entries.begin(); it != entries.end(); ++it)
  782. {
  783. ChannelEntry& e = *it;
  784. // find the keyframe behind the current point in time
  785. size_t pos = 0;
  786. float postTime;
  787. while( 1)
  788. {
  789. if( pos >= e.mTimeAccessor->mCount)
  790. break;
  791. postTime = ReadFloat( *e.mTimeAccessor, *e.mTimeData, pos, 0);
  792. if( postTime >= time)
  793. break;
  794. ++pos;
  795. }
  796. pos = std::min( pos, e.mTimeAccessor->mCount-1);
  797. // read values from there
  798. float temp[16];
  799. for( size_t c = 0; c < e.mValueAccessor->mParams.size(); ++c)
  800. temp[c] = ReadFloat( *e.mValueAccessor, *e.mValueData, pos, c);
  801. // if not exactly at the key time, interpolate with previous value set
  802. if( postTime > time && pos > 0)
  803. {
  804. float preTime = ReadFloat( *e.mTimeAccessor, *e.mTimeData, pos-1, 0);
  805. float factor = (time - postTime) / (preTime - postTime);
  806. for( size_t c = 0; c < e.mValueAccessor->mParams.size(); ++c)
  807. {
  808. float v = ReadFloat( *e.mValueAccessor, *e.mValueData, pos-1, c);
  809. temp[c] += (v - temp[6]) * factor;
  810. }
  811. }
  812. // Apply values to current transformation
  813. std::copy( temp, temp + e.mValueAccessor->mParams.size(), transforms[e.mTransformIndex].f + e.mSubElement);
  814. }
  815. // Calculate resulting transformation
  816. aiMatrix4x4 mat = pParser.CalculateResultTransform( transforms);
  817. // out of lazyness: we store the time in matrix.d4
  818. mat.d4 = time;
  819. resultTrafos.push_back( mat);
  820. // find next point in time to evaluate. That's the closest frame larger than the current in any channel
  821. float nextTime = 1e20;
  822. for( std::vector<ChannelEntry>::iterator it = entries.begin(); it != entries.end(); ++it)
  823. {
  824. ChannelEntry& e = *it;
  825. // find the next time value larger than the current
  826. size_t pos = 0;
  827. while( pos < e.mTimeAccessor->mCount)
  828. {
  829. float t = ReadFloat( *e.mTimeAccessor, *e.mTimeData, pos, 0);
  830. if( t > time)
  831. {
  832. nextTime = std::min( nextTime, t);
  833. break;
  834. }
  835. ++pos;
  836. }
  837. }
  838. // no more keys on any channel after the current time -> we're done
  839. if( nextTime > 1e19)
  840. break;
  841. // else construct next keyframe at this following time point
  842. time = nextTime;
  843. }
  844. // there should be some keyframes
  845. ai_assert( resultTrafos.size() > 0);
  846. // build an animation channel for the given node out of these trafo keys
  847. aiNodeAnim* dstAnim = new aiNodeAnim;
  848. dstAnim->mNodeName = nodeName;
  849. dstAnim->mNumPositionKeys = resultTrafos.size();
  850. dstAnim->mNumRotationKeys= resultTrafos.size();
  851. dstAnim->mNumScalingKeys = resultTrafos.size();
  852. dstAnim->mPositionKeys = new aiVectorKey[resultTrafos.size()];
  853. dstAnim->mRotationKeys = new aiQuatKey[resultTrafos.size()];
  854. dstAnim->mScalingKeys = new aiVectorKey[resultTrafos.size()];
  855. for( size_t a = 0; a < resultTrafos.size(); ++a)
  856. {
  857. const aiMatrix4x4& mat = resultTrafos[a];
  858. double time = double( mat.d4); // remember? time is stored in mat.d4
  859. dstAnim->mPositionKeys[a].mTime = time;
  860. dstAnim->mRotationKeys[a].mTime = time;
  861. dstAnim->mScalingKeys[a].mTime = time;
  862. mat.Decompose( dstAnim->mScalingKeys[a].mValue, dstAnim->mRotationKeys[a].mValue, dstAnim->mPositionKeys[a].mValue);
  863. }
  864. anims.push_back( dstAnim);
  865. }
  866. if( !anims.empty())
  867. {
  868. aiAnimation* anim = new aiAnimation;
  869. anim->mName.Set( pName);
  870. anim->mNumChannels = anims.size();
  871. anim->mChannels = new aiNodeAnim*[anims.size()];
  872. std::copy( anims.begin(), anims.end(), anim->mChannels);
  873. anim->mDuration = 0.0f;
  874. for( size_t a = 0; a < anims.size(); ++a)
  875. {
  876. anim->mDuration = std::max( anim->mDuration, anims[a]->mPositionKeys[anims[a]->mNumPositionKeys-1].mTime);
  877. anim->mDuration = std::max( anim->mDuration, anims[a]->mRotationKeys[anims[a]->mNumRotationKeys-1].mTime);
  878. anim->mDuration = std::max( anim->mDuration, anims[a]->mScalingKeys[anims[a]->mNumScalingKeys-1].mTime);
  879. }
  880. anim->mTicksPerSecond = 1;
  881. mAnims.push_back( anim);
  882. }
  883. }
  884. // ------------------------------------------------------------------------------------------------
  885. // Add a texture to a material structure
  886. void ColladaLoader::AddTexture ( Assimp::MaterialHelper& mat, const ColladaParser& pParser,
  887. const Collada::Effect& effect,
  888. const Collada::Sampler& sampler,
  889. aiTextureType type, unsigned int idx)
  890. {
  891. // first of all, basic file name
  892. mat.AddProperty( &FindFilenameForEffectTexture( pParser, effect, sampler.mName),
  893. _AI_MATKEY_TEXTURE_BASE,type,idx);
  894. // mapping mode
  895. int map = aiTextureMapMode_Clamp;
  896. if (sampler.mWrapU)
  897. map = aiTextureMapMode_Wrap;
  898. if (sampler.mWrapU && sampler.mMirrorU)
  899. map = aiTextureMapMode_Mirror;
  900. mat.AddProperty( &map, 1, _AI_MATKEY_MAPPINGMODE_U_BASE, type, idx);
  901. map = aiTextureMapMode_Clamp;
  902. if (sampler.mWrapV)
  903. map = aiTextureMapMode_Wrap;
  904. if (sampler.mWrapV && sampler.mMirrorV)
  905. map = aiTextureMapMode_Mirror;
  906. mat.AddProperty( &map, 1, _AI_MATKEY_MAPPINGMODE_V_BASE, type, idx);
  907. // UV transformation
  908. mat.AddProperty(&sampler.mTransform, 1,
  909. _AI_MATKEY_UVTRANSFORM_BASE, type, idx);
  910. // Blend mode
  911. mat.AddProperty((int*)&sampler.mOp , 1,
  912. _AI_MATKEY_TEXBLEND_BASE, type, idx);
  913. // Blend factor
  914. mat.AddProperty((float*)&sampler.mWeighting , 1,
  915. _AI_MATKEY_TEXBLEND_BASE, type, idx);
  916. // UV source index ... if we didn't resolve the mapping it is actually just
  917. // a guess but it works in most cases. We search for the frst occurence of a
  918. // number in the channel name. We assume it is the zero-based index into the
  919. // UV channel array of all corresponding meshes.
  920. if (sampler.mUVId != 0xffffffff)
  921. map = sampler.mUVId;
  922. else {
  923. map = 0xffffffff;
  924. for (std::string::const_iterator it = sampler.mUVChannel.begin();
  925. it != sampler.mUVChannel.end(); ++it)
  926. {
  927. if (IsNumeric(*it)) {
  928. map = strtol10(&(*it));
  929. break;
  930. }
  931. }
  932. if (0xffffffff == map) {
  933. DefaultLogger::get()->warn("Collada: unable to determine UV channel for texture");
  934. map = 0;
  935. }
  936. }
  937. mat.AddProperty(&map,1,_AI_MATKEY_UVWSRC_BASE,type,idx);
  938. }
  939. // ------------------------------------------------------------------------------------------------
  940. // Fills materials from the collada material definitions
  941. void ColladaLoader::FillMaterials( const ColladaParser& pParser, aiScene* pScene)
  942. {
  943. for (std::vector<std::pair<Collada::Effect*, aiMaterial*> >::iterator it = newMats.begin(),
  944. end = newMats.end(); it != end; ++it)
  945. {
  946. MaterialHelper& mat = (MaterialHelper&)*it->second;
  947. Collada::Effect& effect = *it->first;
  948. // resolve shading mode
  949. int shadeMode;
  950. if (effect.mFaceted) /* fixme */
  951. shadeMode = aiShadingMode_Flat;
  952. else {
  953. switch( effect.mShadeType)
  954. {
  955. case Collada::Shade_Constant:
  956. shadeMode = aiShadingMode_NoShading;
  957. break;
  958. case Collada::Shade_Lambert:
  959. shadeMode = aiShadingMode_Gouraud;
  960. break;
  961. case Collada::Shade_Blinn:
  962. shadeMode = aiShadingMode_Blinn;
  963. break;
  964. case Collada::Shade_Phong:
  965. shadeMode = aiShadingMode_Phong;
  966. break;
  967. default:
  968. DefaultLogger::get()->warn("Collada: Unrecognized shading mode, using gouraud shading");
  969. shadeMode = aiShadingMode_Gouraud;
  970. break;
  971. }
  972. }
  973. mat.AddProperty<int>( &shadeMode, 1, AI_MATKEY_SHADING_MODEL);
  974. // double-sided?
  975. shadeMode = effect.mDoubleSided;
  976. mat.AddProperty<int>( &shadeMode, 1, AI_MATKEY_TWOSIDED);
  977. // wireframe?
  978. shadeMode = effect.mWireframe;
  979. mat.AddProperty<int>( &shadeMode, 1, AI_MATKEY_ENABLE_WIREFRAME);
  980. // add material colors
  981. mat.AddProperty( &effect.mAmbient, 1,AI_MATKEY_COLOR_AMBIENT);
  982. mat.AddProperty( &effect.mDiffuse, 1, AI_MATKEY_COLOR_DIFFUSE);
  983. mat.AddProperty( &effect.mSpecular, 1,AI_MATKEY_COLOR_SPECULAR);
  984. mat.AddProperty( &effect.mEmissive, 1, AI_MATKEY_COLOR_EMISSIVE);
  985. mat.AddProperty( &effect.mTransparent, 1, AI_MATKEY_COLOR_TRANSPARENT);
  986. mat.AddProperty( &effect.mReflective, 1, AI_MATKEY_COLOR_REFLECTIVE);
  987. // scalar properties
  988. mat.AddProperty( &effect.mShininess, 1, AI_MATKEY_SHININESS);
  989. mat.AddProperty( &effect.mRefractIndex, 1, AI_MATKEY_REFRACTI);
  990. // add textures, if given
  991. if( !effect.mTexAmbient.mName.empty())
  992. /* It is merely a lightmap */
  993. AddTexture( mat, pParser, effect, effect.mTexAmbient, aiTextureType_LIGHTMAP);
  994. if( !effect.mTexEmissive.mName.empty())
  995. AddTexture( mat, pParser, effect, effect.mTexEmissive, aiTextureType_EMISSIVE);
  996. if( !effect.mTexSpecular.mName.empty())
  997. AddTexture( mat, pParser, effect, effect.mTexSpecular, aiTextureType_SPECULAR);
  998. if( !effect.mTexDiffuse.mName.empty())
  999. AddTexture( mat, pParser, effect, effect.mTexDiffuse, aiTextureType_DIFFUSE);
  1000. if( !effect.mTexBump.mName.empty())
  1001. AddTexture( mat, pParser, effect, effect.mTexBump, aiTextureType_HEIGHT);
  1002. if( !effect.mTexTransparent.mName.empty())
  1003. AddTexture( mat, pParser, effect, effect.mTexTransparent, aiTextureType_OPACITY);
  1004. if( !effect.mTexReflective.mName.empty())
  1005. AddTexture( mat, pParser, effect, effect.mTexReflective, aiTextureType_REFLECTION);
  1006. }
  1007. }
  1008. // ------------------------------------------------------------------------------------------------
  1009. // Constructs materials from the collada material definitions
  1010. void ColladaLoader::BuildMaterials( const ColladaParser& pParser, aiScene* pScene)
  1011. {
  1012. newMats.reserve(pParser.mMaterialLibrary.size());
  1013. for( ColladaParser::MaterialLibrary::const_iterator matIt = pParser.mMaterialLibrary.begin(); matIt != pParser.mMaterialLibrary.end(); ++matIt)
  1014. {
  1015. const Collada::Material& material = matIt->second;
  1016. // a material is only a reference to an effect
  1017. ColladaParser::EffectLibrary::const_iterator effIt = pParser.mEffectLibrary.find( material.mEffect);
  1018. if( effIt == pParser.mEffectLibrary.end())
  1019. continue;
  1020. const Collada::Effect& effect = effIt->second;
  1021. // create material
  1022. Assimp::MaterialHelper* mat = new Assimp::MaterialHelper;
  1023. aiString name( matIt->first);
  1024. mat->AddProperty(&name,AI_MATKEY_NAME);
  1025. // MEGA SUPER MONSTER HACK by Alex ... It's all my fault, yes.
  1026. // We store the reference to the effect in the material and
  1027. // return ... we'll add the actual material properties later
  1028. // after we processed all meshes. During mesh processing,
  1029. // we evaluate vertex input mappings. Afterwards we should be
  1030. // able to correctly setup source UV channels for textures.
  1031. // ... moved to ColladaLoader::FillMaterials()
  1032. // *duck*
  1033. // store the material
  1034. mMaterialIndexByName[matIt->first] = newMats.size();
  1035. newMats.push_back( std::pair<Collada::Effect*, aiMaterial*>(const_cast<Collada::Effect*>(&effect),mat) );
  1036. }
  1037. // ScenePreprocessor generates a default material automatically if none is there.
  1038. // All further code here in this loader works well without a valid material so
  1039. // we can safely let it to ScenePreprocessor.
  1040. #if 0
  1041. if( newMats.size() == 0)
  1042. {
  1043. Assimp::MaterialHelper* mat = new Assimp::MaterialHelper;
  1044. aiString name( AI_DEFAULT_MATERIAL_NAME );
  1045. mat->AddProperty( &name, AI_MATKEY_NAME);
  1046. const int shadeMode = aiShadingMode_Phong;
  1047. mat->AddProperty<int>( &shadeMode, 1, AI_MATKEY_SHADING_MODEL);
  1048. aiColor4D colAmbient( 0.2f, 0.2f, 0.2f, 1.0f), colDiffuse( 0.8f, 0.8f, 0.8f, 1.0f), colSpecular( 0.5f, 0.5f, 0.5f, 0.5f);
  1049. mat->AddProperty( &colAmbient, 1, AI_MATKEY_COLOR_AMBIENT);
  1050. mat->AddProperty( &colDiffuse, 1, AI_MATKEY_COLOR_DIFFUSE);
  1051. mat->AddProperty( &colSpecular, 1, AI_MATKEY_COLOR_SPECULAR);
  1052. const float specExp = 5.0f;
  1053. mat->AddProperty( &specExp, 1, AI_MATKEY_SHININESS);
  1054. }
  1055. #endif
  1056. }
  1057. // ------------------------------------------------------------------------------------------------
  1058. // Resolves the texture name for the given effect texture entry
  1059. const aiString& ColladaLoader::FindFilenameForEffectTexture( const ColladaParser& pParser,
  1060. const Collada::Effect& pEffect, const std::string& pName)
  1061. {
  1062. // recurse through the param references until we end up at an image
  1063. std::string name = pName;
  1064. while( 1)
  1065. {
  1066. // the given string is a param entry. Find it
  1067. Collada::Effect::ParamLibrary::const_iterator it = pEffect.mParams.find( name);
  1068. // if not found, we're at the end of the recursion. The resulting string should be the image ID
  1069. if( it == pEffect.mParams.end())
  1070. break;
  1071. // else recurse on
  1072. name = it->second.mReference;
  1073. }
  1074. // find the image referred by this name in the image library of the scene
  1075. ColladaParser::ImageLibrary::const_iterator imIt = pParser.mImageLibrary.find( name);
  1076. if( imIt == pParser.mImageLibrary.end())
  1077. {
  1078. throw new ImportErrorException( boost::str( boost::format(
  1079. "Collada: Unable to resolve effect texture entry \"%s\", ended up at ID \"%s\".") % pName % name));
  1080. }
  1081. static aiString result;
  1082. // if this is an embedded texture image setup an aiTexture for it
  1083. if (imIt->second.mFileName.empty())
  1084. {
  1085. if (imIt->second.mImageData.empty())
  1086. throw new ImportErrorException("Collada: Invalid texture, no data or file reference given");
  1087. aiTexture* tex = new aiTexture();
  1088. // setup format hint
  1089. if (imIt->second.mEmbeddedFormat.length() > 3)
  1090. DefaultLogger::get()->warn("Collada: texture format hint is too long, truncating to 3 characters");
  1091. strncpy(tex->achFormatHint,imIt->second.mEmbeddedFormat.c_str(),3);
  1092. // and copy texture data
  1093. tex->mHeight = 0;
  1094. tex->mWidth = imIt->second.mImageData.size();
  1095. tex->pcData = (aiTexel*)new char[tex->mWidth];
  1096. memcpy(tex->pcData,&imIt->second.mImageData[0],tex->mWidth);
  1097. // setup texture reference string
  1098. result.data[0] = '*';
  1099. result.length = 1 + ASSIMP_itoa10(result.data+1,MAXLEN-1,mTextures.size());
  1100. // and add this texture to the list
  1101. mTextures.push_back(tex);
  1102. }
  1103. else
  1104. {
  1105. result.Set( imIt->second.mFileName );
  1106. ConvertPath(result);
  1107. }
  1108. return result;
  1109. }
  1110. // ------------------------------------------------------------------------------------------------
  1111. // Convert a path read from a collada file to the usual representation
  1112. void ColladaLoader::ConvertPath (aiString& ss)
  1113. {
  1114. // TODO: collada spec, p 22. Handle URI correctly.
  1115. // For the moment we're just stripping the file:// away to make it work.
  1116. // Windoes doesn't seem to be able to find stuff like
  1117. // 'file://..\LWO\LWO2\MappingModes\earthSpherical.jpg'
  1118. if (0 == strncmp(ss.data,"file://",7))
  1119. {
  1120. ss.length -= 7;
  1121. memmove(ss.data,ss.data+7,ss.length);
  1122. ss.data[ss.length] = '\0';
  1123. }
  1124. }
  1125. // ------------------------------------------------------------------------------------------------
  1126. // Reads a float value from an accessor and its data array.
  1127. float ColladaLoader::ReadFloat( const Collada::Accessor& pAccessor, const Collada::Data& pData, size_t pIndex, size_t pOffset) const
  1128. {
  1129. // FIXME: (thom) Test for data type here in every access? For the moment, I leave this to the caller
  1130. size_t pos = pAccessor.mStride * pIndex + pAccessor.mOffset + pOffset;
  1131. ai_assert( pos < pData.mValues.size());
  1132. return pData.mValues[pos];
  1133. }
  1134. // ------------------------------------------------------------------------------------------------
  1135. // Reads a string value from an accessor and its data array.
  1136. const std::string& ColladaLoader::ReadString( const Collada::Accessor& pAccessor, const Collada::Data& pData, size_t pIndex) const
  1137. {
  1138. size_t pos = pAccessor.mStride * pIndex + pAccessor.mOffset;
  1139. ai_assert( pos < pData.mStrings.size());
  1140. return pData.mStrings[pos];
  1141. }
  1142. // ------------------------------------------------------------------------------------------------
  1143. // Collects all nodes into the given array
  1144. void ColladaLoader::CollectNodes( const aiNode* pNode, std::vector<const aiNode*>& poNodes) const
  1145. {
  1146. poNodes.push_back( pNode);
  1147. for( size_t a = 0; a < pNode->mNumChildren; ++a)
  1148. CollectNodes( pNode->mChildren[a], poNodes);
  1149. }
  1150. // ------------------------------------------------------------------------------------------------
  1151. // Finds a node in the collada scene by the given name
  1152. const Collada::Node* ColladaLoader::FindNode( const Collada::Node* pNode, const std::string& pName)
  1153. {
  1154. if( pNode->mName == pName)
  1155. return pNode;
  1156. for( size_t a = 0; a < pNode->mChildren.size(); ++a)
  1157. {
  1158. const Collada::Node* node = FindNode( pNode->mChildren[a], pName);
  1159. if( node)
  1160. return node;
  1161. }
  1162. return NULL;
  1163. }
  1164. #endif // !! ASSIMP_BUILD_NO_DAE_IMPORTER