SceneCombiner.cpp 36 KB

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