AABBTreeToBuffer.h 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244
  1. // SPDX-FileCopyrightText: 2021 Jorrit Rouwe
  2. // SPDX-License-Identifier: MIT
  3. #pragma once
  4. #include <Jolt/AABBTree/AABBTreeBuilder.h>
  5. #include <Jolt/Core/ByteBuffer.h>
  6. #include <Jolt/Geometry/IndexedTriangle.h>
  7. JPH_SUPPRESS_WARNINGS_STD_BEGIN
  8. #include <deque>
  9. JPH_SUPPRESS_WARNINGS_STD_END
  10. JPH_NAMESPACE_BEGIN
  11. template <class T> using Deque = std::deque<T, STLAllocator<T>>;
  12. /// Conversion algorithm that converts an AABB tree to an optimized binary buffer
  13. template <class TriangleCodec, class NodeCodec>
  14. class AABBTreeToBuffer
  15. {
  16. public:
  17. /// Header for the tree
  18. using NodeHeader = typename NodeCodec::Header;
  19. /// Size in bytes of the header of the tree
  20. static const int HeaderSize = NodeCodec::HeaderSize;
  21. /// Maximum number of children per node in the tree
  22. static const int NumChildrenPerNode = NodeCodec::NumChildrenPerNode;
  23. /// Header for the triangles
  24. using TriangleHeader = typename TriangleCodec::TriangleHeader;
  25. /// Size in bytes of the header for the triangles
  26. static const int TriangleHeaderSize = TriangleCodec::TriangleHeaderSize;
  27. /// Convert AABB tree. Returns false if failed.
  28. bool Convert(const VertexList &inVertices, const AABBTreeBuilder::Node *inRoot, const char *&outError)
  29. {
  30. const typename NodeCodec::EncodingContext node_ctx;
  31. typename TriangleCodec::EncodingContext tri_ctx(inVertices);
  32. // Estimate the amount of memory required
  33. uint tri_count = inRoot->GetTriangleCountInTree();
  34. uint node_count = inRoot->GetNodeCount();
  35. uint nodes_size = node_ctx.GetPessimisticMemoryEstimate(node_count);
  36. uint total_size = HeaderSize + TriangleHeaderSize + nodes_size + tri_ctx.GetPessimisticMemoryEstimate(tri_count);
  37. mTree.reserve(total_size);
  38. // Reset counters
  39. mNodesSize = 0;
  40. // Add headers
  41. NodeHeader *header = HeaderSize > 0? mTree.Allocate<NodeHeader>() : nullptr;
  42. TriangleHeader *triangle_header = TriangleHeaderSize > 0? mTree.Allocate<TriangleHeader>() : nullptr;
  43. struct NodeData
  44. {
  45. const AABBTreeBuilder::Node * mNode = nullptr; // Node that this entry belongs to
  46. Vec3 mNodeBoundsMin; // Quantized node bounds
  47. Vec3 mNodeBoundsMax;
  48. uint mNodeStart = uint(-1); // Start of node in mTree
  49. uint mTriangleStart = uint(-1); // Start of the triangle data in mTree
  50. uint mNumChildren = 0; // Number of children
  51. uint mChildNodeStart[NumChildrenPerNode]; // Start of the children of the node in mTree
  52. uint mChildTrianglesStart[NumChildrenPerNode]; // Start of the triangle data in mTree
  53. uint * mParentChildNodeStart = nullptr; // Where to store mNodeStart (to patch mChildNodeStart of my parent)
  54. uint * mParentTrianglesStart = nullptr; // Where to store mTriangleStart (to patch mChildTrianglesStart of my parent)
  55. };
  56. Deque<NodeData *> to_process;
  57. Deque<NodeData *> to_process_triangles;
  58. Array<NodeData> node_list;
  59. node_list.reserve(node_count); // Needed to ensure that array is not reallocated, so we can keep pointers in the array
  60. NodeData root;
  61. root.mNode = inRoot;
  62. root.mNodeBoundsMin = inRoot->mBounds.mMin;
  63. root.mNodeBoundsMax = inRoot->mBounds.mMax;
  64. node_list.push_back(root);
  65. to_process.push_back(&node_list.back());
  66. // Child nodes out of loop so we don't constantly realloc it
  67. Array<const AABBTreeBuilder::Node *> child_nodes;
  68. child_nodes.reserve(NumChildrenPerNode);
  69. for (;;)
  70. {
  71. while (!to_process.empty())
  72. {
  73. // Get the next node to process
  74. NodeData *node_data = to_process.back();
  75. to_process.pop_back();
  76. // Due to quantization box could have become bigger, not smaller
  77. JPH_ASSERT(AABox(node_data->mNodeBoundsMin, node_data->mNodeBoundsMax).Contains(node_data->mNode->mBounds), "AABBTreeToBuffer: Bounding box became smaller!");
  78. // Collect the first NumChildrenPerNode sub-nodes in the tree
  79. child_nodes.clear(); // Won't free the memory
  80. node_data->mNode->GetNChildren(NumChildrenPerNode, child_nodes);
  81. node_data->mNumChildren = (uint)child_nodes.size();
  82. // Fill in default child bounds
  83. Vec3 child_bounds_min[NumChildrenPerNode], child_bounds_max[NumChildrenPerNode];
  84. for (size_t i = 0; i < NumChildrenPerNode; ++i)
  85. if (i < child_nodes.size())
  86. {
  87. child_bounds_min[i] = child_nodes[i]->mBounds.mMin;
  88. child_bounds_max[i] = child_nodes[i]->mBounds.mMax;
  89. }
  90. else
  91. {
  92. child_bounds_min[i] = Vec3::sZero();
  93. child_bounds_max[i] = Vec3::sZero();
  94. }
  95. // Start a new node
  96. uint old_size = (uint)mTree.size();
  97. node_data->mNodeStart = node_ctx.NodeAllocate(node_data->mNode, node_data->mNodeBoundsMin, node_data->mNodeBoundsMax, child_nodes, child_bounds_min, child_bounds_max, mTree, outError);
  98. if (node_data->mNodeStart == uint(-1))
  99. return false;
  100. mNodesSize += (uint)mTree.size() - old_size;
  101. if (node_data->mNode->HasChildren())
  102. {
  103. // Insert in reverse order so we process left child first when taking nodes from the back
  104. for (int idx = int(child_nodes.size()) - 1; idx >= 0; --idx)
  105. {
  106. // Due to quantization box could have become bigger, not smaller
  107. JPH_ASSERT(AABox(child_bounds_min[idx], child_bounds_max[idx]).Contains(child_nodes[idx]->mBounds), "AABBTreeToBuffer: Bounding box became smaller!");
  108. // Add child to list of nodes to be processed
  109. NodeData child;
  110. child.mNode = child_nodes[idx];
  111. child.mNodeBoundsMin = child_bounds_min[idx];
  112. child.mNodeBoundsMax = child_bounds_max[idx];
  113. child.mParentChildNodeStart = &node_data->mChildNodeStart[idx];
  114. child.mParentTrianglesStart = &node_data->mChildTrianglesStart[idx];
  115. NodeData *old = &node_list[0];
  116. node_list.push_back(child);
  117. if (old != &node_list[0])
  118. {
  119. outError = "Internal Error: Array reallocated, memory corruption!";
  120. return false;
  121. }
  122. // Store triangles in separate list so we process them last
  123. if (node_list.back().mNode->HasChildren())
  124. to_process.push_back(&node_list.back());
  125. else
  126. to_process_triangles.push_back(&node_list.back());
  127. }
  128. }
  129. else
  130. {
  131. // Add triangles
  132. node_data->mTriangleStart = tri_ctx.Pack(node_data->mNode->mTriangles, mTree, outError);
  133. if (node_data->mTriangleStart == uint(-1))
  134. return false;
  135. }
  136. // Patch offset into parent
  137. if (node_data->mParentChildNodeStart != nullptr)
  138. {
  139. *node_data->mParentChildNodeStart = node_data->mNodeStart;
  140. *node_data->mParentTrianglesStart = node_data->mTriangleStart;
  141. }
  142. }
  143. // If we've got triangles to process, loop again with just the triangles
  144. if (to_process_triangles.empty())
  145. break;
  146. else
  147. to_process.swap(to_process_triangles);
  148. }
  149. // Finalize all nodes
  150. for (NodeData &n : node_list)
  151. if (!node_ctx.NodeFinalize(n.mNode, n.mNodeStart, n.mNumChildren, n.mChildNodeStart, n.mChildTrianglesStart, mTree, outError))
  152. return false;
  153. // Finalize the triangles
  154. tri_ctx.Finalize(inVertices, triangle_header, mTree);
  155. // Validate that we reserved enough memory
  156. if (nodes_size < mNodesSize)
  157. {
  158. outError = "Internal Error: Not enough memory reserved for nodes!";
  159. return false;
  160. }
  161. if (total_size < (uint)mTree.size())
  162. {
  163. outError = "Internal Error: Not enough memory reserved for triangles!";
  164. return false;
  165. }
  166. // Finalize the nodes
  167. if (!node_ctx.Finalize(header, inRoot, node_list[0].mNodeStart, node_list[0].mTriangleStart, outError))
  168. return false;
  169. // Shrink the tree, this will invalidate the header and triangle_header variables
  170. mTree.shrink_to_fit();
  171. return true;
  172. }
  173. /// Get resulting data
  174. inline const ByteBuffer & GetBuffer() const
  175. {
  176. return mTree;
  177. }
  178. /// Get resulting data
  179. inline ByteBuffer & GetBuffer()
  180. {
  181. return mTree;
  182. }
  183. /// Get header for tree
  184. inline const NodeHeader * GetNodeHeader() const
  185. {
  186. return mTree.Get<NodeHeader>(0);
  187. }
  188. /// Get header for triangles
  189. inline const TriangleHeader * GetTriangleHeader() const
  190. {
  191. return mTree.Get<TriangleHeader>(HeaderSize);
  192. }
  193. /// Get root of resulting tree
  194. inline const void * GetRoot() const
  195. {
  196. return mTree.Get<void>(HeaderSize + TriangleHeaderSize);
  197. }
  198. private:
  199. ByteBuffer mTree; ///< Resulting tree structure
  200. uint mNodesSize; ///< Size in bytes of the nodes in the buffer
  201. };
  202. JPH_NAMESPACE_END