SceneCombiner.cpp 36 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127
  1. /*
  2. Open Asset Import Library (ASSIMP)
  3. ----------------------------------------------------------------------
  4. Copyright (c) 2006-2008, ASSIMP Development Team
  5. All rights reserved.
  6. Redistribution and use of this software in source and binary forms,
  7. with or without modification, are permitted provided that the
  8. following conditions are met:
  9. * Redistributions of source code must retain the above
  10. copyright notice, this list of conditions and the
  11. following disclaimer.
  12. * Redistributions in binary form must reproduce the above
  13. copyright notice, this list of conditions and the
  14. following disclaimer in the documentation and/or other
  15. materials provided with the distribution.
  16. * Neither the name of the ASSIMP team, nor the names of its
  17. contributors may be used to endorse or promote products
  18. derived from this software without specific prior
  19. written permission of the ASSIMP Development Team.
  20. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  21. "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  22. LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  23. A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  24. OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  25. SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  26. LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  27. DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  28. THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  29. (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  30. OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  31. ----------------------------------------------------------------------
  32. */
  33. // ----------------------------------------------------------------------------
  34. /** @file Implements Assimp::SceneCombiner. This is a smart utility
  35. * class that combines multiple scenes, meshes, ... into one. Currently
  36. * these utilities are used by the IRR and LWS loaders and the
  37. * OptimizeGraph step.
  38. */
  39. // ----------------------------------------------------------------------------
  40. #include "AssimpPCH.h"
  41. #include "SceneCombiner.h"
  42. #include "fast_atof.h"
  43. #include "Hash.h"
  44. #include "time.h"
  45. namespace Assimp {
  46. // ------------------------------------------------------------------------------------------------
  47. // Add a prefix to a string
  48. inline void PrefixString(aiString& string,const char* prefix, unsigned int len)
  49. {
  50. // If the string is already prefixed, we won't prefix it a second time
  51. if (string.length >= 1 && string.data[0] == '$')
  52. return;
  53. // Add the prefix
  54. ::memmove(string.data+len,string.data,string.length+1);
  55. ::memcpy (string.data, prefix, len);
  56. // And update the string's length
  57. string.length += len;
  58. }
  59. // ------------------------------------------------------------------------------------------------
  60. // Add node identifiers to a hashing set
  61. void SceneCombiner::AddNodeHashes(aiNode* node, std::set<unsigned int>& hashes)
  62. {
  63. // Add node name to hashing set if it is non-empty - empty nodes are allowed
  64. // and they can't have any anims assigned so its absolutely safe to duplicate them.
  65. if (node->mName.length) {
  66. hashes.insert( SuperFastHash(node->mName.data,node->mName.length) );
  67. }
  68. // Process all children recursively
  69. for (unsigned int i = 0; i < node->mNumChildren;++i)
  70. AddNodeHashes(node->mChildren[i],hashes);
  71. }
  72. // ------------------------------------------------------------------------------------------------
  73. // Add a name prefix to all nodes in a hierarchy
  74. void SceneCombiner::AddNodePrefixes(aiNode* node, const char* prefix, unsigned int len)
  75. {
  76. ai_assert(NULL != prefix);
  77. PrefixString(node->mName,prefix,len);
  78. // Process all children recursively
  79. for (unsigned int i = 0; i < node->mNumChildren;++i)
  80. AddNodePrefixes(node->mChildren[i],prefix,len);
  81. }
  82. // ------------------------------------------------------------------------------------------------
  83. // Search for matching names
  84. bool SceneCombiner::FindNameMatch(const aiString& name, std::vector<SceneHelper>& input, unsigned int cur)
  85. {
  86. const unsigned int hash = SuperFastHash(name.data, name.length);
  87. // Check whether we find a positive match in one of the given sets
  88. for (unsigned int i = 0; i < input.size(); ++i) {
  89. if (cur != i && input[i].hashes.find(hash) != input[i].hashes.end()) {
  90. return true;
  91. }
  92. }
  93. return false;
  94. }
  95. // ------------------------------------------------------------------------------------------------
  96. // Add a name prefix to all nodes in a hierarchy if a hash match is found
  97. void SceneCombiner::AddNodePrefixesChecked(aiNode* node, const char* prefix, unsigned int len,
  98. std::vector<SceneHelper>& input, unsigned int cur)
  99. {
  100. ai_assert(NULL != prefix);
  101. const unsigned int hash = SuperFastHash(node->mName.data,node->mName.length);
  102. // Check whether we find a positive match in one of the given sets
  103. for (unsigned int i = 0; i < input.size(); ++i) {
  104. if (cur != i && input[i].hashes.find(hash) != input[i].hashes.end()) {
  105. PrefixString(node->mName,prefix,len);
  106. break;
  107. }
  108. }
  109. // Process all children recursively
  110. for (unsigned int i = 0; i < node->mNumChildren;++i)
  111. AddNodePrefixesChecked(node->mChildren[i],prefix,len,input,cur);
  112. }
  113. // ------------------------------------------------------------------------------------------------
  114. // Add an offset to all mesh indices in a node graph
  115. void SceneCombiner::OffsetNodeMeshIndices (aiNode* node, unsigned int offset)
  116. {
  117. for (unsigned int i = 0; i < node->mNumMeshes;++i)
  118. node->mMeshes[i] += offset;
  119. for (unsigned int i = 0; i < node->mNumChildren;++i)
  120. OffsetNodeMeshIndices(node->mChildren[i],offset);
  121. }
  122. // ------------------------------------------------------------------------------------------------
  123. // Merges two scenes. Currently only used by the LWS loader.
  124. void SceneCombiner::MergeScenes(aiScene** _dest,std::vector<aiScene*>& src,
  125. unsigned int flags)
  126. {
  127. ai_assert(NULL != _dest);
  128. // if _dest points to NULL allocate a new scene. Otherwise clear the old and reuse it
  129. if (src.empty())
  130. {
  131. if (*_dest)
  132. {
  133. (*_dest)->~aiScene();
  134. SceneCombiner::CopySceneFlat(_dest,src[0]);
  135. }
  136. else *_dest = src[0];
  137. return;
  138. }
  139. if (*_dest)(*_dest)->~aiScene();
  140. else *_dest = new aiScene();
  141. // Create a dummy scene to serve as master for the others
  142. aiScene* master = new aiScene();
  143. master->mRootNode = new aiNode();
  144. master->mRootNode->mName.Set("<MergeRoot>");
  145. std::vector<AttachmentInfo> srcList (src.size());
  146. for (unsigned int i = 0; i < srcList.size();++i) {
  147. srcList[i] = AttachmentInfo(src[i],master->mRootNode);
  148. }
  149. // 'master' will be deleted afterwards
  150. MergeScenes (_dest, master, srcList, flags);
  151. }
  152. // ------------------------------------------------------------------------------------------------
  153. void SceneCombiner::AttachToGraph (aiNode* attach, std::vector<NodeAttachmentInfo>& srcList)
  154. {
  155. unsigned int cnt;
  156. for (cnt = 0; cnt < attach->mNumChildren;++cnt)
  157. AttachToGraph(attach->mChildren[cnt],srcList);
  158. cnt = 0;
  159. for (std::vector<NodeAttachmentInfo>::iterator it = srcList.begin();
  160. it != srcList.end(); ++it)
  161. {
  162. if ((*it).attachToNode == attach && !(*it).resolved)
  163. ++cnt;
  164. }
  165. if (cnt) {
  166. aiNode** n = new aiNode*[cnt+attach->mNumChildren];
  167. if (attach->mNumChildren) {
  168. ::memcpy(n,attach->mChildren,sizeof(void*)*attach->mNumChildren);
  169. delete[] attach->mChildren;
  170. }
  171. attach->mChildren = n;
  172. n += attach->mNumChildren;
  173. attach->mNumChildren += cnt;
  174. for (unsigned int i = 0; i < srcList.size();++i) {
  175. NodeAttachmentInfo& att = srcList[i];
  176. if (att.attachToNode == attach && !att.resolved) {
  177. *n = att.node;
  178. (**n).mParent = attach;
  179. ++n;
  180. // mark this attachment as resolved
  181. att.resolved = true;
  182. }
  183. }
  184. }
  185. }
  186. // ------------------------------------------------------------------------------------------------
  187. void SceneCombiner::AttachToGraph ( aiScene* master,
  188. std::vector<NodeAttachmentInfo>& src)
  189. {
  190. ai_assert(NULL != master);
  191. AttachToGraph(master->mRootNode,src);
  192. }
  193. // ------------------------------------------------------------------------------------------------
  194. void SceneCombiner::MergeScenes(aiScene** _dest, aiScene* master,
  195. std::vector<AttachmentInfo>& srcList,
  196. unsigned int flags)
  197. {
  198. ai_assert(NULL != _dest);
  199. // if _dest points to NULL allocate a new scene. Otherwise clear the old and reuse it
  200. if (srcList.empty())
  201. {
  202. if (*_dest)
  203. {
  204. (*_dest)->~aiScene();
  205. SceneCombiner::CopySceneFlat(_dest,master);
  206. }
  207. else *_dest = master;
  208. return;
  209. }
  210. if (*_dest)(*_dest)->~aiScene();
  211. else *_dest = new aiScene();
  212. aiScene* dest = *_dest;
  213. std::vector<SceneHelper> src (srcList.size()+1);
  214. src[0].scene = master;
  215. for (unsigned int i = 0; i < srcList.size();++i) {
  216. src[i+1] = SceneHelper( srcList[i].scene );
  217. }
  218. // this helper array specifies which scenes are duplicates of others
  219. std::vector<unsigned int> duplicates(src.size(),0xffffffff);
  220. // this helper array is used as lookup table several times
  221. std::vector<unsigned int> offset(src.size());
  222. // Find duplicate scenes
  223. for (unsigned int i = 0; i < src.size();++i)
  224. {
  225. if (duplicates[i] != i && duplicates[i] != 0xffffffff)continue;
  226. duplicates[i] = i;
  227. for ( unsigned int a = i+1; a < src.size(); ++a)
  228. {
  229. if (src[i].scene == src[a].scene)
  230. duplicates[a] = i;
  231. }
  232. }
  233. // Generate unique names for all named stuff?
  234. if (flags & AI_INT_MERGE_SCENE_GEN_UNIQUE_NAMES)
  235. {
  236. #if 0
  237. // Construct a proper random number generator
  238. boost::mt19937 rng( );
  239. boost::uniform_int<> dist(1u,1 << 24u);
  240. boost::variate_generator<boost::mt19937&, boost::uniform_int<> > rndGen(rng, dist);
  241. #endif
  242. for (unsigned int i = 1; i < src.size();++i)
  243. {
  244. //if (i != duplicates[i])
  245. //{
  246. // // duplicate scenes share the same UID
  247. // ::strcpy( src[i].id, src[duplicates[i]].id );
  248. // src[i].idlen = src[duplicates[i]].idlen;
  249. // continue;
  250. //}
  251. src[i].idlen = ::sprintf(src[i].id,"$%.6X$_",i);
  252. if (flags & AI_INT_MERGE_SCENE_GEN_UNIQUE_NAMES_IF_NECESSARY) {
  253. // Compute hashes for all identifiers in this scene and store them
  254. // in a sorted table (for convenience I'm using std::set). We hash
  255. // just the node and animation channel names, all identifiers except
  256. // the material names should be caught by doing this.
  257. AddNodeHashes(src[i]->mRootNode,src[i].hashes);
  258. for (unsigned int a = 0; a < src[i]->mNumAnimations;++a) {
  259. aiAnimation* anim = src[i]->mAnimations[a];
  260. src[i].hashes.insert(SuperFastHash(anim->mName.data,anim->mName.length));
  261. }
  262. }
  263. }
  264. }
  265. unsigned int cnt;
  266. // First find out how large the respective output arrays must be
  267. for ( unsigned int n = 0; n < src.size();++n )
  268. {
  269. SceneHelper* cur = &src[n];
  270. if (n == duplicates[n] || flags & AI_INT_MERGE_SCENE_DUPLICATES_DEEP_CPY) {
  271. dest->mNumTextures += (*cur)->mNumTextures;
  272. dest->mNumMaterials += (*cur)->mNumMaterials;
  273. dest->mNumMeshes += (*cur)->mNumMeshes;
  274. }
  275. dest->mNumLights += (*cur)->mNumLights;
  276. dest->mNumCameras += (*cur)->mNumCameras;
  277. dest->mNumAnimations += (*cur)->mNumAnimations;
  278. // Combine the flags of all scenes
  279. // We need to process them flag-by-flag here to get correct results
  280. // dest->mFlags ; //|= (*cur)->mFlags;
  281. if ((*cur)->mFlags & AI_SCENE_FLAGS_NON_VERBOSE_FORMAT) {
  282. dest->mFlags |= AI_SCENE_FLAGS_NON_VERBOSE_FORMAT;
  283. }
  284. }
  285. // generate the output texture list + an offset table for all texture indices
  286. if (dest->mNumTextures)
  287. {
  288. aiTexture** pip = dest->mTextures = new aiTexture*[dest->mNumMaterials];
  289. cnt = 0;
  290. for ( unsigned int n = 0; n < src.size();++n )
  291. {
  292. SceneHelper* cur = &src[n];
  293. for (unsigned int i = 0; i < (*cur)->mNumTextures;++i)
  294. {
  295. if (n != duplicates[n])
  296. {
  297. if ( flags & AI_INT_MERGE_SCENE_DUPLICATES_DEEP_CPY)
  298. Copy(pip,(*cur)->mTextures[i]);
  299. else continue;
  300. }
  301. else *pip = (*cur)->mTextures[i];
  302. ++pip;
  303. }
  304. offset[n] = cnt;
  305. cnt = (unsigned int)(pip - dest->mTextures);
  306. }
  307. }
  308. // generate the output material list + an offset table for all material indices
  309. if (dest->mNumMaterials)
  310. {
  311. aiMaterial** pip = dest->mMaterials = new aiMaterial*[dest->mNumMaterials];
  312. cnt = 0;
  313. for ( unsigned int n = 0; n < src.size();++n ) {
  314. SceneHelper* cur = &src[n];
  315. for (unsigned int i = 0; i < (*cur)->mNumMaterials;++i)
  316. {
  317. if (n != duplicates[n])
  318. {
  319. if ( flags & AI_INT_MERGE_SCENE_DUPLICATES_DEEP_CPY)
  320. Copy(pip,(*cur)->mMaterials[i]);
  321. else continue;
  322. }
  323. else *pip = (*cur)->mMaterials[i];
  324. if ((*cur)->mNumTextures != dest->mNumTextures) {
  325. // We need to update all texture indices of the mesh. So we need to search for
  326. // a material property called '$tex.file'
  327. for (unsigned int a = 0; a < (*pip)->mNumProperties;++a)
  328. {
  329. aiMaterialProperty* prop = (*pip)->mProperties[a];
  330. if (!strncmp(prop->mKey.data,"$tex.file",9))
  331. {
  332. // Check whether this texture is an embedded texture.
  333. // In this case the property looks like this: *<n>,
  334. // where n is the index of the texture.
  335. aiString& s = *((aiString*)prop->mData);
  336. if ('*' == s.data[0]) {
  337. // Offset the index and write it back ..
  338. const unsigned int idx = strtol10(&s.data[1]) + offset[n];
  339. ASSIMP_itoa10(&s.data[1],sizeof(s.data)-1,idx);
  340. }
  341. }
  342. // Need to generate new, unique material names?
  343. else if (!::strcmp( prop->mKey.data,"$mat.name" ) && flags & AI_INT_MERGE_SCENE_GEN_UNIQUE_MATNAMES)
  344. {
  345. aiString* pcSrc = (aiString*) prop->mData;
  346. PrefixString(*pcSrc, (*cur).id, (*cur).idlen);
  347. }
  348. }
  349. }
  350. ++pip;
  351. }
  352. offset[n] = cnt;
  353. cnt = (unsigned int)(pip - dest->mMaterials);
  354. }
  355. }
  356. // generate the output mesh list + again an offset table for all mesh indices
  357. if (dest->mNumMeshes)
  358. {
  359. aiMesh** pip = dest->mMeshes = new aiMesh*[dest->mNumMeshes];
  360. cnt = 0;
  361. for ( unsigned int n = 0; n < src.size();++n )
  362. {
  363. SceneHelper* cur = &src[n];
  364. for (unsigned int i = 0; i < (*cur)->mNumMeshes;++i)
  365. {
  366. if (n != duplicates[n]) {
  367. if ( flags & AI_INT_MERGE_SCENE_DUPLICATES_DEEP_CPY)
  368. Copy(pip, (*cur)->mMeshes[i]);
  369. else continue;
  370. }
  371. else *pip = (*cur)->mMeshes[i];
  372. // update the material index of the mesh
  373. (*pip)->mMaterialIndex += offset[n];
  374. ++pip;
  375. }
  376. // reuse the offset array - store now the mesh offset in it
  377. offset[n] = cnt;
  378. cnt = (unsigned int)(pip - dest->mMeshes);
  379. }
  380. }
  381. std::vector <NodeAttachmentInfo> nodes;
  382. nodes.reserve(srcList.size());
  383. // ----------------------------------------------------------------------------
  384. // Now generate the output node graph. We need to make those
  385. // names in the graph that are referenced by anims or lights
  386. // or cameras unique. So we add a prefix to them ... $<rand>_
  387. // We could also use a counter, but using a random value allows us to
  388. // use just one prefix if we are joining multiple scene hierarchies recursively.
  389. // Chances are quite good we don't collide, so we try that ...
  390. // ----------------------------------------------------------------------------
  391. // Allocate space for light sources, cameras and animations
  392. aiLight** ppLights = dest->mLights = (dest->mNumLights
  393. ? new aiLight*[dest->mNumLights] : NULL);
  394. aiCamera** ppCameras = dest->mCameras = (dest->mNumCameras
  395. ? new aiCamera*[dest->mNumCameras] : NULL);
  396. aiAnimation** ppAnims = dest->mAnimations = (dest->mNumAnimations
  397. ? new aiAnimation*[dest->mNumAnimations] : NULL);
  398. for ( int n = src.size()-1; n >= 0 ;--n ) /* !!! important !!! */
  399. {
  400. SceneHelper* cur = &src[n];
  401. aiNode* node;
  402. // To offset or not to offset, this is the question
  403. if (n != (int)duplicates[n])
  404. {
  405. // Get full scenegraph copy
  406. Copy( &node, (*cur)->mRootNode );
  407. OffsetNodeMeshIndices(node,offset[duplicates[n]]);
  408. if (flags & AI_INT_MERGE_SCENE_DUPLICATES_DEEP_CPY) {
  409. // (note:) they are already 'offseted' by offset[duplicates[n]]
  410. OffsetNodeMeshIndices(node,offset[n] - offset[duplicates[n]]);
  411. }
  412. }
  413. else // if (n == duplicates[n])
  414. {
  415. node = (*cur)->mRootNode;
  416. OffsetNodeMeshIndices(node,offset[n]);
  417. }
  418. if (n) // src[0] is the master node
  419. nodes.push_back(NodeAttachmentInfo( node,srcList[n-1].attachToNode,n ));
  420. // add name prefixes?
  421. if (flags & AI_INT_MERGE_SCENE_GEN_UNIQUE_NAMES) {
  422. // or the whole scenegraph
  423. if (flags & AI_INT_MERGE_SCENE_GEN_UNIQUE_NAMES_IF_NECESSARY) {
  424. AddNodePrefixesChecked(node,(*cur).id,(*cur).idlen,src,n);
  425. }
  426. else AddNodePrefixes(node,(*cur).id,(*cur).idlen);
  427. // meshes
  428. for (unsigned int i = 0; i < (*cur)->mNumMeshes;++i) {
  429. aiMesh* mesh = (*cur)->mMeshes[i];
  430. // rename all bones
  431. for (unsigned int a = 0; a < mesh->mNumBones;++a) {
  432. if (flags & AI_INT_MERGE_SCENE_GEN_UNIQUE_NAMES_IF_NECESSARY) {
  433. if (!FindNameMatch(mesh->mBones[a]->mName,src,n))
  434. continue;
  435. }
  436. PrefixString(mesh->mBones[a]->mName,(*cur).id,(*cur).idlen);
  437. }
  438. }
  439. }
  440. // --------------------------------------------------------------------
  441. // Copy light sources
  442. for (unsigned int i = 0; i < (*cur)->mNumLights;++i,++ppLights)
  443. {
  444. if (n != (int)duplicates[n]) // duplicate scene?
  445. {
  446. Copy(ppLights, (*cur)->mLights[i]);
  447. }
  448. else *ppLights = (*cur)->mLights[i];
  449. // Add name prefixes?
  450. if (flags & AI_INT_MERGE_SCENE_GEN_UNIQUE_NAMES) {
  451. if (flags & AI_INT_MERGE_SCENE_GEN_UNIQUE_NAMES_IF_NECESSARY) {
  452. if (!FindNameMatch((*ppLights)->mName,src,n))
  453. continue;
  454. }
  455. PrefixString((*ppLights)->mName,(*cur).id,(*cur).idlen);
  456. }
  457. }
  458. // --------------------------------------------------------------------
  459. // Copy cameras
  460. for (unsigned int i = 0; i < (*cur)->mNumCameras;++i,++ppCameras) {
  461. if (n != (int)duplicates[n]) // duplicate scene?
  462. {
  463. Copy(ppCameras, (*cur)->mCameras[i]);
  464. }
  465. else *ppCameras = (*cur)->mCameras[i];
  466. // Add name prefixes?
  467. if (flags & AI_INT_MERGE_SCENE_GEN_UNIQUE_NAMES) {
  468. if (flags & AI_INT_MERGE_SCENE_GEN_UNIQUE_NAMES_IF_NECESSARY) {
  469. if (!FindNameMatch((*ppCameras)->mName,src,n))
  470. continue;
  471. }
  472. PrefixString((*ppCameras)->mName,(*cur).id,(*cur).idlen);
  473. }
  474. }
  475. // --------------------------------------------------------------------
  476. // Copy animations
  477. for (unsigned int i = 0; i < (*cur)->mNumAnimations;++i,++ppAnims) {
  478. if (n != (int)duplicates[n]) // duplicate scene?
  479. {
  480. Copy(ppAnims, (*cur)->mAnimations[i]);
  481. }
  482. else *ppAnims = (*cur)->mAnimations[i];
  483. // Add name prefixes?
  484. if (flags & AI_INT_MERGE_SCENE_GEN_UNIQUE_NAMES) {
  485. if (flags & AI_INT_MERGE_SCENE_GEN_UNIQUE_NAMES_IF_NECESSARY) {
  486. if (!FindNameMatch((*ppAnims)->mName,src,n))
  487. continue;
  488. }
  489. PrefixString((*ppAnims)->mName,(*cur).id,(*cur).idlen);
  490. // don't forget to update all node animation channels
  491. for (unsigned int a = 0; a < (*ppAnims)->mNumChannels;++a) {
  492. if (flags & AI_INT_MERGE_SCENE_GEN_UNIQUE_NAMES_IF_NECESSARY) {
  493. if (!FindNameMatch((*ppAnims)->mChannels[a]->mNodeName,src,n))
  494. continue;
  495. }
  496. PrefixString((*ppAnims)->mChannels[a]->mNodeName,(*cur).id,(*cur).idlen);
  497. }
  498. }
  499. }
  500. }
  501. // Now build the output graph
  502. AttachToGraph ( master, nodes);
  503. dest->mRootNode = master->mRootNode;
  504. // Check whether we succeeded at building the output graph
  505. for (std::vector <NodeAttachmentInfo> ::iterator it = nodes.begin();
  506. it != nodes.end(); ++it)
  507. {
  508. if (!(*it).resolved) {
  509. if (flags & AI_INT_MERGE_SCENE_RESOLVE_CROSS_ATTACHMENTS) {
  510. // search for this attachment point in all other imported scenes, too.
  511. for ( unsigned int n = 0; n < src.size();++n ) {
  512. if (n != (*it).src_idx) {
  513. AttachToGraph(src[n].scene,nodes);
  514. if ((*it).resolved)
  515. break;
  516. }
  517. }
  518. }
  519. if (!(*it).resolved) {
  520. DefaultLogger::get()->error(std::string("SceneCombiner: Failed to resolve attachment ")
  521. + (*it).node->mName.data + " " + (*it).attachToNode->mName.data);
  522. }
  523. }
  524. }
  525. // now delete all input scenes. Make sure duplicate scenes aren't
  526. // deleted more than one time
  527. for ( unsigned int n = 0; n < src.size();++n ) {
  528. if (n != duplicates[n]) // duplicate scene?
  529. continue;
  530. aiScene* deleteMe = src[n].scene;
  531. // We need to delete the arrays before the destructor is called -
  532. // we are reusing the array members
  533. delete[] deleteMe->mMeshes; deleteMe->mMeshes = NULL;
  534. delete[] deleteMe->mCameras; deleteMe->mCameras = NULL;
  535. delete[] deleteMe->mLights; deleteMe->mLights = NULL;
  536. delete[] deleteMe->mMaterials; deleteMe->mMaterials = NULL;
  537. delete[] deleteMe->mAnimations; deleteMe->mAnimations = NULL;
  538. deleteMe->mRootNode = NULL;
  539. // Now we can safely delete the scene
  540. delete deleteMe;
  541. }
  542. // Check flags
  543. if (!dest->mNumMeshes || !dest->mNumMaterials) {
  544. dest->mFlags |= AI_SCENE_FLAGS_INCOMPLETE;
  545. }
  546. // We're finished
  547. }
  548. // ------------------------------------------------------------------------------------------------
  549. // Build a list of unique bones
  550. void SceneCombiner::BuildUniqueBoneList(std::list<BoneWithHash>& asBones,
  551. std::vector<aiMesh*>::const_iterator it,
  552. std::vector<aiMesh*>::const_iterator end)
  553. {
  554. unsigned int iOffset = 0;
  555. for (; it != end;++it) {
  556. for (unsigned int l = 0; l < (*it)->mNumBones;++l) {
  557. aiBone* p = (*it)->mBones[l];
  558. uint32_t itml = SuperFastHash(p->mName.data,(unsigned int)p->mName.length);
  559. std::list<BoneWithHash>::iterator it2 = asBones.begin();
  560. std::list<BoneWithHash>::iterator end2 = asBones.end();
  561. for (;it2 != end2;++it2) {
  562. if ((*it2).first == itml) {
  563. (*it2).pSrcBones.push_back(BoneSrcIndex(p,iOffset));
  564. break;
  565. }
  566. }
  567. if (end2 == it2) {
  568. // need to begin a new bone entry
  569. asBones.push_back(BoneWithHash());
  570. BoneWithHash& btz = asBones.back();
  571. // setup members
  572. btz.first = itml;
  573. btz.second = &p->mName;
  574. btz.pSrcBones.push_back(BoneSrcIndex(p,iOffset));
  575. }
  576. }
  577. iOffset += (*it)->mNumVertices;
  578. }
  579. }
  580. // ------------------------------------------------------------------------------------------------
  581. // Merge a list of bones
  582. void SceneCombiner::MergeBones(aiMesh* out,std::vector<aiMesh*>::const_iterator it,
  583. std::vector<aiMesh*>::const_iterator end)
  584. {
  585. ai_assert(NULL != out && !out->mNumBones);
  586. // find we need to build an unique list of all bones.
  587. // we work with hashes to make the comparisons MUCH faster,
  588. // at least if we have many bones.
  589. std::list<BoneWithHash> asBones;
  590. BuildUniqueBoneList(asBones, it,end);
  591. // now create the output bones
  592. out->mNumBones = 0;
  593. out->mBones = new aiBone*[asBones.size()];
  594. for (std::list<BoneWithHash>::const_iterator it = asBones.begin(),end = asBones.end(); it != end;++it) {
  595. // Allocate a bone and setup it's name
  596. aiBone* pc = out->mBones[out->mNumBones++] = new aiBone();
  597. pc->mName = aiString( *((*it).second ));
  598. std::vector< BoneSrcIndex >::const_iterator wend = (*it).pSrcBones.end();
  599. // Loop through all bones to be joined for this bone
  600. for (std::vector< BoneSrcIndex >::const_iterator wmit = (*it).pSrcBones.begin(); wmit != wend; ++wmit) {
  601. pc->mNumWeights += (*wmit).first->mNumWeights;
  602. // NOTE: different offset matrices for bones with equal names
  603. // are - at the moment - not handled correctly.
  604. if (wmit != (*it).pSrcBones.begin() && pc->mOffsetMatrix != (*wmit).first->mOffsetMatrix) {
  605. DefaultLogger::get()->warn("Bones with equal names but different offset matrices can't be joined at the moment");
  606. continue;
  607. }
  608. pc->mOffsetMatrix = (*wmit).first->mOffsetMatrix;
  609. }
  610. // Allocate the vertex weight array
  611. aiVertexWeight* avw = pc->mWeights = new aiVertexWeight[pc->mNumWeights];
  612. // And copy the final weights - adjust the vertex IDs by the
  613. // face index offset of the coresponding mesh.
  614. for (std::vector< BoneSrcIndex >::const_iterator wmit = (*it).pSrcBones.begin(); wmit != wend; ++wmit) {
  615. aiBone* pip = (*wmit).first;
  616. for (unsigned int mp = 0; mp < pip->mNumWeights;++mp,++avw) {
  617. const aiVertexWeight& vfi = pip->mWeights[mp];
  618. avw->mWeight = vfi.mWeight;
  619. avw->mVertexId = vfi.mVertexId + (*wmit).second;
  620. }
  621. }
  622. }
  623. }
  624. // ------------------------------------------------------------------------------------------------
  625. // Merge a list of meshes
  626. void SceneCombiner::MergeMeshes(aiMesh** _out,unsigned int flags,
  627. std::vector<aiMesh*>::const_iterator begin,
  628. std::vector<aiMesh*>::const_iterator end)
  629. {
  630. ai_assert(NULL != _out);
  631. if (begin == end) {
  632. *_out = NULL; // no meshes ...
  633. return;
  634. }
  635. // Allocate the output mesh
  636. aiMesh* out = *_out = new aiMesh();
  637. out->mMaterialIndex = (*begin)->mMaterialIndex;
  638. // Find out how much output storage we'll need
  639. for (std::vector<aiMesh*>::const_iterator it = begin; it != end;++it) {
  640. out->mNumVertices += (*it)->mNumVertices;
  641. out->mNumFaces += (*it)->mNumFaces;
  642. out->mNumBones += (*it)->mNumBones;
  643. // combine primitive type flags
  644. out->mPrimitiveTypes |= (*it)->mPrimitiveTypes;
  645. }
  646. if (out->mNumVertices) {
  647. aiVector3D* pv2;
  648. // copy vertex positions
  649. if ((**begin).HasPositions()) {
  650. pv2 = out->mVertices = new aiVector3D[out->mNumVertices];
  651. for (std::vector<aiMesh*>::const_iterator it = begin; it != end;++it) {
  652. if ((*it)->mVertices) {
  653. ::memcpy(pv2,(*it)->mVertices,(*it)->mNumVertices*sizeof(aiVector3D));
  654. }
  655. else DefaultLogger::get()->warn("JoinMeshes: Positions expected but input mesh contains no positions");
  656. pv2 += (*it)->mNumVertices;
  657. }
  658. }
  659. // copy normals
  660. if ((**begin).HasNormals()) {
  661. pv2 = out->mNormals = new aiVector3D[out->mNumVertices];
  662. for (std::vector<aiMesh*>::const_iterator it = begin; it != end;++it) {
  663. if ((*it)->mNormals) {
  664. ::memcpy(pv2,(*it)->mNormals,(*it)->mNumVertices*sizeof(aiVector3D));
  665. }
  666. else DefaultLogger::get()->warn("JoinMeshes: Normals expected but input mesh contains no normals");
  667. pv2 += (*it)->mNumVertices;
  668. }
  669. }
  670. // copy tangents and bitangents
  671. if ((**begin).HasTangentsAndBitangents()) {
  672. pv2 = out->mTangents = new aiVector3D[out->mNumVertices];
  673. aiVector3D* pv2b = out->mBitangents = new aiVector3D[out->mNumVertices];
  674. for (std::vector<aiMesh*>::const_iterator it = begin; it != end;++it) {
  675. if ((*it)->mTangents) {
  676. ::memcpy(pv2, (*it)->mTangents, (*it)->mNumVertices*sizeof(aiVector3D));
  677. ::memcpy(pv2b,(*it)->mBitangents,(*it)->mNumVertices*sizeof(aiVector3D));
  678. }
  679. else DefaultLogger::get()->warn("JoinMeshes: Tangents expected but input mesh contains no tangents");
  680. pv2 += (*it)->mNumVertices;
  681. pv2b += (*it)->mNumVertices;
  682. }
  683. }
  684. // copy texture coordinates
  685. unsigned int n = 0;
  686. while ((**begin).HasTextureCoords(n)) {
  687. out->mNumUVComponents[n] = (*begin)->mNumUVComponents[n];
  688. pv2 = out->mTextureCoords[n] = new aiVector3D[out->mNumVertices];
  689. for (std::vector<aiMesh*>::const_iterator it = begin; it != end;++it) {
  690. if ((*it)->mTextureCoords[n]) {
  691. ::memcpy(pv2,(*it)->mTextureCoords[n],(*it)->mNumVertices*sizeof(aiVector3D));
  692. }
  693. else DefaultLogger::get()->warn("JoinMeshes: UVs expected but input mesh contains no UVs");
  694. pv2 += (*it)->mNumVertices;
  695. }
  696. ++n;
  697. }
  698. // copy vertex colors
  699. n = 0;
  700. while ((**begin).HasVertexColors(n)) {
  701. aiColor4D* pv2 = out->mColors[n] = new aiColor4D[out->mNumVertices];
  702. for (std::vector<aiMesh*>::const_iterator it = begin; it != end;++it) {
  703. if ((*it)->mColors[n]) {
  704. ::memcpy(pv2,(*it)->mColors[n],(*it)->mNumVertices*sizeof(aiColor4D));
  705. }
  706. else DefaultLogger::get()->warn("JoinMeshes: VCs expected but input mesh contains no VCs");
  707. pv2 += (*it)->mNumVertices;
  708. }
  709. ++n;
  710. }
  711. }
  712. if (out->mNumFaces) // just for safety
  713. {
  714. // copy faces
  715. out->mFaces = new aiFace[out->mNumFaces];
  716. aiFace* pf2 = out->mFaces;
  717. unsigned int ofs = 0;
  718. for (std::vector<aiMesh*>::const_iterator it = begin; it != end;++it) {
  719. for (unsigned int m = 0; m < (*it)->mNumFaces;++m,++pf2) {
  720. aiFace& face = (*it)->mFaces[m];
  721. pf2->mNumIndices = face.mNumIndices;
  722. pf2->mIndices = face.mIndices;
  723. if (ofs) {
  724. // add the offset to the vertex
  725. for (unsigned int q = 0; q < face.mNumIndices; ++q)
  726. face.mIndices[q] += ofs;
  727. }
  728. face.mIndices = NULL;
  729. }
  730. ofs += (*it)->mNumVertices;
  731. }
  732. }
  733. // bones - as this is quite lengthy, I moved the code to a separate function
  734. if (out->mNumBones)
  735. MergeBones(out,begin,end);
  736. // delete all source meshes
  737. for (std::vector<aiMesh*>::const_iterator it = begin; it != end;++it)
  738. delete *it;
  739. }
  740. // ------------------------------------------------------------------------------------------------
  741. template <typename Type>
  742. inline void CopyPtrArray (Type**& dest, Type** src, unsigned int num)
  743. {
  744. if (!num)
  745. {
  746. dest = NULL;
  747. return;
  748. }
  749. dest = new Type*[num];
  750. for (unsigned int i = 0; i < num;++i)
  751. SceneCombiner::Copy(&dest[i],src[i]);
  752. }
  753. // ------------------------------------------------------------------------------------------------
  754. template <typename Type>
  755. inline void GetArrayCopy (Type*& dest, unsigned int num )
  756. {
  757. if (!dest)return;
  758. Type* old = dest;
  759. dest = new Type[num];
  760. ::memcpy(dest, old, sizeof(Type) * num);
  761. }
  762. // ------------------------------------------------------------------------------------------------
  763. void SceneCombiner::CopySceneFlat(aiScene** _dest,aiScene* src)
  764. {
  765. // reuse the old scene or allocate a new?
  766. if (*_dest)(*_dest)->~aiScene();
  767. else *_dest = new aiScene();
  768. ::memcpy(*_dest,src,sizeof(aiScene));
  769. }
  770. // ------------------------------------------------------------------------------------------------
  771. void SceneCombiner::CopyScene(aiScene** _dest,aiScene* src)
  772. {
  773. ai_assert(NULL != _dest && NULL != src);
  774. aiScene* dest = *_dest = new aiScene();
  775. // copy animations
  776. dest->mNumAnimations = src->mNumAnimations;
  777. CopyPtrArray(dest->mAnimations,src->mAnimations,
  778. dest->mNumAnimations);
  779. // copy textures
  780. dest->mNumTextures = src->mNumTextures;
  781. CopyPtrArray(dest->mTextures,src->mTextures,
  782. dest->mNumTextures);
  783. // copy materials
  784. dest->mNumMaterials = src->mNumMaterials;
  785. CopyPtrArray(dest->mMaterials,src->mMaterials,
  786. dest->mNumMaterials);
  787. // copy lights
  788. dest->mNumLights = src->mNumLights;
  789. CopyPtrArray(dest->mLights,src->mLights,
  790. dest->mNumLights);
  791. // copy cameras
  792. dest->mNumCameras = src->mNumCameras;
  793. CopyPtrArray(dest->mCameras,src->mCameras,
  794. dest->mNumCameras);
  795. // copy meshes
  796. dest->mNumMeshes = src->mNumMeshes;
  797. CopyPtrArray(dest->mMeshes,src->mMeshes,
  798. dest->mNumMeshes);
  799. // now - copy the root node of the scene (deep copy, too)
  800. Copy( &dest->mRootNode, src->mRootNode);
  801. // and keep the flags ...
  802. dest->mFlags = src->mFlags;
  803. }
  804. // ------------------------------------------------------------------------------------------------
  805. void SceneCombiner::Copy (aiMesh** _dest, const aiMesh* src)
  806. {
  807. ai_assert(NULL != _dest && NULL != src);
  808. aiMesh* dest = *_dest = new aiMesh();
  809. // get a flat copy
  810. ::memcpy(dest,src,sizeof(aiMesh));
  811. // and reallocate all arrays
  812. GetArrayCopy( dest->mVertices, dest->mNumVertices );
  813. GetArrayCopy( dest->mNormals , dest->mNumVertices );
  814. GetArrayCopy( dest->mTangents, dest->mNumVertices );
  815. GetArrayCopy( dest->mBitangents, dest->mNumVertices );
  816. unsigned int n = 0;
  817. while (dest->HasTextureCoords(n))
  818. GetArrayCopy( dest->mTextureCoords[n++], dest->mNumVertices );
  819. n = 0;
  820. while (dest->HasVertexColors(n))
  821. GetArrayCopy( dest->mColors[n++], dest->mNumVertices );
  822. // make a deep copy of all bones
  823. CopyPtrArray(dest->mBones,dest->mBones,dest->mNumBones);
  824. // make a deep copy of all faces
  825. GetArrayCopy(dest->mFaces,dest->mNumFaces);
  826. for (unsigned int i = 0; i < dest->mNumFaces;++i)
  827. {
  828. aiFace& f = dest->mFaces[i];
  829. GetArrayCopy(f.mIndices,f.mNumIndices);
  830. }
  831. }
  832. // ------------------------------------------------------------------------------------------------
  833. void SceneCombiner::Copy (aiMaterial** _dest, const aiMaterial* src)
  834. {
  835. ai_assert(NULL != _dest && NULL != src);
  836. MaterialHelper* dest = (MaterialHelper*) ( *_dest = new MaterialHelper() );
  837. dest->mNumAllocated = src->mNumAllocated;
  838. dest->mNumProperties = src->mNumProperties;
  839. dest->mProperties = new aiMaterialProperty* [dest->mNumAllocated];
  840. for (unsigned int i = 0; i < dest->mNumProperties;++i)
  841. {
  842. aiMaterialProperty* prop = dest->mProperties[i] = new aiMaterialProperty();
  843. aiMaterialProperty* sprop = src->mProperties[i];
  844. prop->mDataLength = sprop->mDataLength;
  845. prop->mData = new char[prop->mDataLength];
  846. ::memcpy(prop->mData,sprop->mData,prop->mDataLength);
  847. prop->mIndex = sprop->mIndex;
  848. prop->mSemantic = sprop->mSemantic;
  849. prop->mKey = sprop->mKey;
  850. prop->mType = sprop->mType;
  851. }
  852. }
  853. // ------------------------------------------------------------------------------------------------
  854. void SceneCombiner::Copy (aiTexture** _dest, const aiTexture* src)
  855. {
  856. ai_assert(NULL != _dest && NULL != src);
  857. aiTexture* dest = *_dest = new aiTexture();
  858. // get a flat copy
  859. ::memcpy(dest,src,sizeof(aiTexture));
  860. // and reallocate all arrays. We must do it manually here
  861. const char* old = (const char*)dest->pcData;
  862. if (old)
  863. {
  864. unsigned int cpy;
  865. if (!dest->mHeight)cpy = dest->mWidth;
  866. else cpy = dest->mHeight * dest->mWidth * sizeof(aiTexel);
  867. if (!cpy)
  868. {
  869. dest->pcData = NULL;
  870. return;
  871. }
  872. // the cast is legal, the aiTexel c'tor does nothing important
  873. dest->pcData = (aiTexel*) new char[cpy];
  874. ::memcpy(dest->pcData, old, cpy);
  875. }
  876. }
  877. // ------------------------------------------------------------------------------------------------
  878. void SceneCombiner::Copy (aiAnimation** _dest, const aiAnimation* src)
  879. {
  880. ai_assert(NULL != _dest && NULL != src);
  881. aiAnimation* dest = *_dest = new aiAnimation();
  882. // get a flat copy
  883. ::memcpy(dest,src,sizeof(aiAnimation));
  884. // and reallocate all arrays
  885. CopyPtrArray( dest->mChannels, src->mChannels, dest->mNumChannels );
  886. }
  887. // ------------------------------------------------------------------------------------------------
  888. void SceneCombiner::Copy (aiNodeAnim** _dest, const aiNodeAnim* src)
  889. {
  890. ai_assert(NULL != _dest && NULL != src);
  891. aiNodeAnim* dest = *_dest = new aiNodeAnim();
  892. // get a flat copy
  893. ::memcpy(dest,src,sizeof(aiNodeAnim));
  894. // and reallocate all arrays
  895. GetArrayCopy( dest->mPositionKeys, dest->mNumPositionKeys );
  896. GetArrayCopy( dest->mScalingKeys, dest->mNumScalingKeys );
  897. GetArrayCopy( dest->mRotationKeys, dest->mNumRotationKeys );
  898. }
  899. // ------------------------------------------------------------------------------------------------
  900. void SceneCombiner::Copy (aiCamera** _dest,const aiCamera* src)
  901. {
  902. ai_assert(NULL != _dest && NULL != src);
  903. aiCamera* dest = *_dest = new aiCamera();
  904. // get a flat copy, that's already OK
  905. ::memcpy(dest,src,sizeof(aiCamera));
  906. }
  907. // ------------------------------------------------------------------------------------------------
  908. void SceneCombiner::Copy (aiLight** _dest, const aiLight* src)
  909. {
  910. ai_assert(NULL != _dest && NULL != src);
  911. aiLight* dest = *_dest = new aiLight();
  912. // get a flat copy, that's already OK
  913. ::memcpy(dest,src,sizeof(aiLight));
  914. }
  915. // ------------------------------------------------------------------------------------------------
  916. void SceneCombiner::Copy (aiBone** _dest, const aiBone* src)
  917. {
  918. ai_assert(NULL != _dest && NULL != src);
  919. aiBone* dest = *_dest = new aiBone();
  920. // get a flat copy
  921. ::memcpy(dest,src,sizeof(aiBone));
  922. // and reallocate all arrays
  923. GetArrayCopy( dest->mWeights, dest->mNumWeights );
  924. }
  925. // ------------------------------------------------------------------------------------------------
  926. void SceneCombiner::Copy (aiNode** _dest, const aiNode* src)
  927. {
  928. ai_assert(NULL != _dest && NULL != src);
  929. aiNode* dest = *_dest = new aiNode();
  930. // get a flat copy
  931. ::memcpy(dest,src,sizeof(aiNode));
  932. // and reallocate all arrays
  933. GetArrayCopy( dest->mMeshes, dest->mNumMeshes );
  934. CopyPtrArray( dest->mChildren, src->mChildren,dest->mNumChildren);
  935. }
  936. }