OptimizeGraph.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352
  1. /*
  2. ---------------------------------------------------------------------------
  3. Open Asset Import Library (assimp)
  4. ---------------------------------------------------------------------------
  5. Copyright (c) 2006-2025, assimp team
  6. All rights reserved.
  7. Redistribution and use of this software in source and binary forms,
  8. with or without modification, are permitted provided that the following
  9. conditions are met:
  10. * Redistributions of source code must retain the above
  11. copyright notice, this list of conditions and the
  12. following disclaimer.
  13. * Redistributions in binary form must reproduce the above
  14. copyright notice, this list of conditions and the
  15. following disclaimer in the documentation and/or other
  16. materials provided with the distribution.
  17. * Neither the name of the assimp team, nor the names of its
  18. contributors may be used to endorse or promote products
  19. derived from this software without specific prior
  20. written permission of the assimp team.
  21. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  22. "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  23. LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  24. A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  25. OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  26. SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  27. LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  28. DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  29. THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  30. (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  31. OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  32. ---------------------------------------------------------------------------
  33. */
  34. /** @file OptimizeGraph.cpp
  35. * @brief Implementation of the aiProcess_OptimizGraph step
  36. */
  37. #ifndef ASSIMP_BUILD_NO_OPTIMIZEGRAPH_PROCESS
  38. #include "OptimizeGraph.h"
  39. #include "ProcessHelper.h"
  40. #include "ConvertToLHProcess.h"
  41. #include <assimp/Exceptional.h>
  42. #include <assimp/SceneCombiner.h>
  43. #include <stdio.h>
  44. using namespace Assimp;
  45. #define AI_RESERVED_NODE_NAME "$Reserved_And_Evil"
  46. /* AI_OG_USE_HASHING enables the use of hashing to speed-up std::set lookups.
  47. * The unhashed variant should be faster, except for *very* large data sets
  48. */
  49. #ifdef AI_OG_USE_HASHING
  50. // Use our standard hashing function to compute the hash
  51. #define AI_OG_GETKEY(str) SuperFastHash(str.data, str.length)
  52. #else
  53. // Otherwise hope that std::string will utilize a static buffer
  54. // for shorter node names. This would avoid endless heap copying.
  55. #define AI_OG_GETKEY(str) std::string(str.data)
  56. #endif
  57. // ------------------------------------------------------------------------------------------------
  58. // Constructor to be privately used by Importer
  59. OptimizeGraphProcess::OptimizeGraphProcess() :
  60. mScene(),
  61. nodes_in(),
  62. nodes_out(),
  63. count_merged() {
  64. // empty
  65. }
  66. // ------------------------------------------------------------------------------------------------
  67. // Returns whether the processing step is present in the given flag field.
  68. bool OptimizeGraphProcess::IsActive(unsigned int pFlags) const {
  69. return (0 != (pFlags & aiProcess_OptimizeGraph));
  70. }
  71. // ------------------------------------------------------------------------------------------------
  72. // Setup properties for the post-processing step
  73. void OptimizeGraphProcess::SetupProperties(const Importer *pImp) {
  74. // Get value of AI_CONFIG_PP_OG_EXCLUDE_LIST
  75. std::string tmp = pImp->GetPropertyString(AI_CONFIG_PP_OG_EXCLUDE_LIST, "");
  76. AddLockedNodeList(tmp);
  77. }
  78. // ------------------------------------------------------------------------------------------------
  79. // Collect new children
  80. void OptimizeGraphProcess::CollectNewChildren(aiNode *nd, std::list<aiNode *> &nodes) {
  81. nodes_in += nd->mNumChildren;
  82. // Process children
  83. std::list<aiNode *> child_nodes;
  84. for (unsigned int i = 0; i < nd->mNumChildren; ++i) {
  85. CollectNewChildren(nd->mChildren[i], child_nodes);
  86. nd->mChildren[i] = nullptr;
  87. }
  88. // Check whether we need this node; if not we can replace it by our own children (warn, danger of incest).
  89. if (locked.find(AI_OG_GETKEY(nd->mName)) == locked.end()) {
  90. for (std::list<aiNode *>::iterator it = child_nodes.begin(); it != child_nodes.end();) {
  91. if (locked.find(AI_OG_GETKEY((*it)->mName)) == locked.end()) {
  92. (*it)->mTransformation = nd->mTransformation * (*it)->mTransformation;
  93. nodes.push_back(*it);
  94. it = child_nodes.erase(it);
  95. continue;
  96. }
  97. ++it;
  98. }
  99. if (nd->mNumMeshes || !child_nodes.empty()) {
  100. nodes.push_back(nd);
  101. } else {
  102. delete nd; /* bye, node */
  103. return;
  104. }
  105. } else {
  106. // Retain our current position in the hierarchy
  107. nodes.push_back(nd);
  108. // Now check for possible optimizations in our list of child nodes. join as many as possible
  109. aiNode *join_master = nullptr;
  110. aiMatrix4x4 inv;
  111. const LockedSetType::const_iterator end = locked.end();
  112. std::list<aiNode *> join;
  113. for (std::list<aiNode *>::iterator it = child_nodes.begin(); it != child_nodes.end();) {
  114. aiNode *child = *it;
  115. if (child->mNumChildren == 0 && locked.find(AI_OG_GETKEY(child->mName)) == end) {
  116. // There may be no instanced meshes
  117. unsigned int n = 0;
  118. for (; n < child->mNumMeshes; ++n) {
  119. if (meshes[child->mMeshes[n]] > 1) {
  120. break;
  121. }
  122. }
  123. if (n == child->mNumMeshes) {
  124. if (!join_master) {
  125. join_master = child;
  126. inv = join_master->mTransformation;
  127. inv.Inverse();
  128. } else {
  129. child->mTransformation = inv * child->mTransformation;
  130. join.push_back(child);
  131. it = child_nodes.erase(it);
  132. continue;
  133. }
  134. }
  135. }
  136. ++it;
  137. }
  138. if (join_master && !join.empty()) {
  139. join_master->mName.length = ::ai_snprintf(join_master->mName.data, AI_MAXLEN, "$MergedNode_%u", count_merged++);
  140. unsigned int out_meshes = 0;
  141. for (std::list<aiNode *>::const_iterator it = join.cbegin(); it != join.cend(); ++it) {
  142. out_meshes += (*it)->mNumMeshes;
  143. }
  144. // copy all mesh references in one array
  145. if (out_meshes) {
  146. unsigned int *meshIdxs = new unsigned int[out_meshes + join_master->mNumMeshes], *tmp = meshIdxs;
  147. for (unsigned int n = 0; n < join_master->mNumMeshes; ++n) {
  148. *tmp++ = join_master->mMeshes[n];
  149. }
  150. for (const aiNode *join_node : join) {
  151. for (unsigned int n = 0; n < join_node->mNumMeshes; ++n) {
  152. *tmp = join_node->mMeshes[n];
  153. aiMesh *mesh = mScene->mMeshes[*tmp++];
  154. // Assume the transformation is affine
  155. // manually move the mesh into the right coordinate system
  156. // Check for odd negative scale (mirror)
  157. if (join_node->mTransformation.Determinant() < 0) {
  158. // Reverse the mesh face winding order
  159. FlipWindingOrderProcess::ProcessMesh(mesh);
  160. }
  161. // Update positions, normals and tangents
  162. const aiMatrix3x3 IT = aiMatrix3x3(join_node->mTransformation).Inverse().Transpose();
  163. for (unsigned int a = 0; a < mesh->mNumVertices; ++a) {
  164. mesh->mVertices[a] *= join_node->mTransformation;
  165. if (mesh->HasNormals())
  166. mesh->mNormals[a] *= IT;
  167. if (mesh->HasTangentsAndBitangents()) {
  168. mesh->mTangents[a] *= IT;
  169. mesh->mBitangents[a] *= IT;
  170. }
  171. }
  172. }
  173. delete join_node; // bye, node
  174. }
  175. delete[] join_master->mMeshes;
  176. join_master->mMeshes = meshIdxs;
  177. join_master->mNumMeshes += out_meshes;
  178. }
  179. }
  180. }
  181. // reassign children if something changed
  182. if (child_nodes.empty() || child_nodes.size() > nd->mNumChildren) {
  183. delete[] nd->mChildren;
  184. if (!child_nodes.empty()) {
  185. nd->mChildren = new aiNode *[child_nodes.size()];
  186. } else
  187. nd->mChildren = nullptr;
  188. }
  189. nd->mNumChildren = static_cast<unsigned int>(child_nodes.size());
  190. if (nd->mChildren) {
  191. aiNode **tmp = nd->mChildren;
  192. for (std::list<aiNode *>::iterator it = child_nodes.begin(); it != child_nodes.end(); ++it) {
  193. aiNode *node = *tmp++ = *it;
  194. node->mParent = nd;
  195. }
  196. }
  197. nodes_out += static_cast<unsigned int>(child_nodes.size());
  198. }
  199. // ------------------------------------------------------------------------------------------------
  200. // Execute the post-processing step on the given scene
  201. void OptimizeGraphProcess::Execute(aiScene *pScene) {
  202. ASSIMP_LOG_DEBUG("OptimizeGraphProcess begin");
  203. nodes_in = nodes_out = count_merged = 0;
  204. mScene = pScene;
  205. meshes.resize(pScene->mNumMeshes, 0);
  206. FindInstancedMeshes(pScene->mRootNode);
  207. // build a blacklist of identifiers. If the name of a node matches one of these, we won't touch it
  208. locked.clear();
  209. for (std::list<std::string>::const_iterator it = locked_nodes.begin(); it != locked_nodes.end(); ++it) {
  210. #ifdef AI_OG_USE_HASHING
  211. locked.insert(SuperFastHash((*it).c_str()));
  212. #else
  213. locked.insert(*it);
  214. #endif
  215. }
  216. for (unsigned int i = 0; i < pScene->mNumAnimations; ++i) {
  217. for (unsigned int a = 0; a < pScene->mAnimations[i]->mNumChannels; ++a) {
  218. aiNodeAnim *anim = pScene->mAnimations[i]->mChannels[a];
  219. locked.insert(AI_OG_GETKEY(anim->mNodeName));
  220. }
  221. }
  222. for (unsigned int i = 0; i < pScene->mNumMeshes; ++i) {
  223. for (unsigned int a = 0; a < pScene->mMeshes[i]->mNumBones; ++a) {
  224. aiBone *bone = pScene->mMeshes[i]->mBones[a];
  225. locked.insert(AI_OG_GETKEY(bone->mName));
  226. // HACK: Meshes referencing bones may not be transformed; we need to look them.
  227. // The easiest way to do this is to increase their reference counters ...
  228. meshes[i] += 2;
  229. }
  230. }
  231. for (unsigned int i = 0; i < pScene->mNumCameras; ++i) {
  232. aiCamera *cam = pScene->mCameras[i];
  233. locked.insert(AI_OG_GETKEY(cam->mName));
  234. }
  235. for (unsigned int i = 0; i < pScene->mNumLights; ++i) {
  236. aiLight *lgh = pScene->mLights[i];
  237. locked.insert(AI_OG_GETKEY(lgh->mName));
  238. }
  239. // Insert a dummy master node and make it read-only
  240. aiNode *dummy_root = new aiNode(AI_RESERVED_NODE_NAME);
  241. locked.insert(AI_OG_GETKEY(dummy_root->mName));
  242. const aiString prev = pScene->mRootNode->mName;
  243. pScene->mRootNode->mParent = dummy_root;
  244. dummy_root->mChildren = new aiNode *[dummy_root->mNumChildren = 1];
  245. dummy_root->mChildren[0] = pScene->mRootNode;
  246. // Do our recursive processing of scenegraph nodes. For each node collect
  247. // a fully new list of children and allow their children to place themselves
  248. // on the same hierarchy layer as their parents.
  249. std::list<aiNode *> nodes;
  250. CollectNewChildren(dummy_root, nodes);
  251. ai_assert(nodes.size() == 1);
  252. if (dummy_root->mNumChildren == 0) {
  253. pScene->mRootNode = nullptr;
  254. throw DeadlyImportError("After optimizing the scene graph, no data remains");
  255. }
  256. if (dummy_root->mNumChildren > 1) {
  257. pScene->mRootNode = dummy_root;
  258. // Keep the dummy node but assign the name of the old root node to it
  259. pScene->mRootNode->mName = prev;
  260. } else {
  261. // Remove the dummy root node again.
  262. pScene->mRootNode = dummy_root->mChildren[0];
  263. dummy_root->mChildren[0] = nullptr;
  264. delete dummy_root;
  265. }
  266. pScene->mRootNode->mParent = nullptr;
  267. if (!DefaultLogger::isNullLogger()) {
  268. if (nodes_in != nodes_out) {
  269. ASSIMP_LOG_INFO("OptimizeGraphProcess finished; Input nodes: ", nodes_in, ", Output nodes: ", nodes_out);
  270. } else {
  271. ASSIMP_LOG_DEBUG("OptimizeGraphProcess finished");
  272. }
  273. }
  274. meshes.clear();
  275. locked.clear();
  276. }
  277. // ------------------------------------------------------------------------------------------------
  278. // Build a LUT of all instanced meshes
  279. void OptimizeGraphProcess::FindInstancedMeshes(aiNode *pNode) {
  280. for (unsigned int i = 0; i < pNode->mNumMeshes; ++i) {
  281. ++meshes[pNode->mMeshes[i]];
  282. }
  283. for (unsigned int i = 0; i < pNode->mNumChildren; ++i)
  284. FindInstancedMeshes(pNode->mChildren[i]);
  285. }
  286. #endif // !! ASSIMP_BUILD_NO_OPTIMIZEGRAPH_PROCESS