TriangleCodecIndexed8BitPackSOA4Flags.h 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437
  1. // SPDX-FileCopyrightText: 2021 Jorrit Rouwe
  2. // SPDX-License-Identifier: MIT
  3. #pragma once
  4. #include <Jolt/Geometry/RayTriangle.h>
  5. #include <unordered_map>
  6. namespace JPH {
  7. /// Store vertices in 64 bits and indices in 8 bits + 8 bit of flags per triangle like this:
  8. ///
  9. /// TriangleBlockHeader,
  10. /// TriangleBlock (4 triangles and their flags in 16 bytes),
  11. /// TriangleBlock...
  12. ///
  13. /// Vertices are stored:
  14. ///
  15. /// VertexData (1 vertex in 64 bits),
  16. /// VertexData...
  17. ///
  18. /// They're compressed relative to the bounding box as provided by the node codec.
  19. class TriangleCodecIndexed8BitPackSOA4Flags
  20. {
  21. public:
  22. class TriangleHeader
  23. {
  24. public:
  25. Float3 mOffset; ///< Offset of all vertices
  26. Float3 mScale; ///< Scale of all vertices, vertex_position = mOffset + mScale * compressed_vertex_position
  27. };
  28. /// Size of the header (an empty struct is always > 0 bytes so this needs a separate variable)
  29. static constexpr int TriangleHeaderSize = sizeof(TriangleHeader);
  30. /// If this codec could return a different offset than the current buffer size when calling Pack()
  31. static constexpr bool ChangesOffsetOnPack = false;
  32. /// Amount of bits per component
  33. enum EComponentData : uint32
  34. {
  35. COMPONENT_BITS = 21,
  36. COMPONENT_MASK = (1 << COMPONENT_BITS) - 1,
  37. };
  38. /// Packed X and Y coordinate
  39. enum EVertexXY : uint32
  40. {
  41. COMPONENT_X = 0,
  42. COMPONENT_Y1 = COMPONENT_BITS,
  43. COMPONENT_Y1_BITS = 32 - COMPONENT_BITS,
  44. };
  45. /// Packed Z and Y coordinate
  46. enum EVertexZY : uint32
  47. {
  48. COMPONENT_Z = 0,
  49. COMPONENT_Y2 = COMPONENT_BITS,
  50. COMPONENT_Y2_BITS = 31 - COMPONENT_BITS,
  51. };
  52. /// A single packed vertex
  53. struct VertexData
  54. {
  55. uint32 mVertexXY;
  56. uint32 mVertexZY;
  57. };
  58. static_assert(sizeof(VertexData) == 8, "Compiler added padding");
  59. /// A block of 4 triangles
  60. struct TriangleBlock
  61. {
  62. uint8 mIndices[3][4]; ///< 8 bit indices to triangle vertices for 4 triangles in the form mIndices[vertex][triangle] where vertex in [0, 2] and triangle in [0, 3]
  63. uint8 mFlags[4]; ///< Triangle flags (could contain material and active edges)
  64. };
  65. static_assert(sizeof(TriangleBlock) == 16, "Compiler added padding");
  66. /// A triangle header, will be followed by one or more TriangleBlocks
  67. struct TriangleBlockHeader
  68. {
  69. const VertexData * GetVertexData() const { return reinterpret_cast<const VertexData *>(reinterpret_cast<const uint8 *>(this) + mOffsetToVertices); }
  70. const TriangleBlock * GetTriangleBlock() const { return reinterpret_cast<const TriangleBlock *>(reinterpret_cast<const uint8 *>(this) + sizeof(TriangleBlockHeader)); }
  71. uint32 mOffsetToVertices; ///< Offset from current block to start of vertices in bytes
  72. };
  73. static_assert(sizeof(TriangleBlockHeader) == 4, "Compiler added padding");
  74. /// This class is used to encode and compress triangle data into a byte buffer
  75. class EncodingContext
  76. {
  77. public:
  78. EncodingContext() :
  79. mNumTriangles(0)
  80. {
  81. }
  82. /// Get an upper bound on the amount of bytes needed to store inTriangleCount triangles
  83. uint GetPessimisticMemoryEstimate(uint inTriangleCount) const
  84. {
  85. // Worst case each triangle is alone in a block, none of the vertices are shared and we need to add 3 bytes to align the vertices
  86. return inTriangleCount * (sizeof(TriangleBlockHeader) + sizeof(TriangleBlock) + 3 * sizeof(VertexData)) + 3;
  87. }
  88. /// Pack the triangles in inContainer to ioBuffer. This stores the mMaterialIndex of a triangle in the 8 bit flags.
  89. /// Returns uint(-1) on error.
  90. uint Pack(const VertexList &inVertices, const IndexedTriangleList &inTriangles, Vec3Arg inBoundsMin, Vec3Arg inBoundsMax, ByteBuffer &ioBuffer, string &outError)
  91. {
  92. // Determine position of triangles start
  93. uint offset = (uint)ioBuffer.size();
  94. // Update stats
  95. uint tri_count = (uint)inTriangles.size();
  96. mNumTriangles += tri_count;
  97. // Allocate triangle block header
  98. TriangleBlockHeader *header = ioBuffer.Allocate<TriangleBlockHeader>();
  99. // Compute first vertex that this batch will use (ensuring there's enough room if none of the vertices are shared)
  100. uint start_vertex = Clamp((int)mVertices.size() - 256 + (int)tri_count * 3, 0, (int)mVertices.size());
  101. // Store the start vertex offset, this will later be patched to give the delta offset relative to the triangle block
  102. mOffsetsToPatch.push_back(uint((uint8 *)&header->mOffsetToVertices - &ioBuffer[0]));
  103. header->mOffsetToVertices = start_vertex * sizeof(VertexData);
  104. // Pack vertices
  105. uint padded_triangle_count = AlignUp(tri_count, 4);
  106. for (uint t = 0; t < padded_triangle_count; t += 4)
  107. {
  108. TriangleBlock *block = ioBuffer.Allocate<TriangleBlock>();
  109. for (uint vertex_nr = 0; vertex_nr < 3; ++vertex_nr)
  110. for (uint block_tri_idx = 0; block_tri_idx < 4; ++block_tri_idx)
  111. {
  112. // Fetch vertex index. Create degenerate triangles for padding triangles.
  113. bool triangle_available = t + block_tri_idx < tri_count;
  114. uint32 src_vertex_index = triangle_available? inTriangles[t + block_tri_idx].mIdx[vertex_nr] : inTriangles[tri_count - 1].mIdx[0];
  115. // Check if we've seen this vertex before and if it is in the range that we can encode
  116. uint32 vertex_index;
  117. VertexMap::const_iterator found = mVertexMap.find(src_vertex_index);
  118. if (found == mVertexMap.end() || found->second < start_vertex)
  119. {
  120. // Add vertex
  121. vertex_index = (uint32)mVertices.size();
  122. mVertexMap[src_vertex_index] = vertex_index;
  123. mVertices.push_back(inVertices[src_vertex_index]);
  124. }
  125. else
  126. {
  127. // Reuse vertex
  128. vertex_index = found->second;
  129. }
  130. // Store vertex index
  131. uint32 vertex_offset = vertex_index - start_vertex;
  132. if (vertex_offset > 0xff)
  133. {
  134. outError = "TriangleCodecIndexed8BitPackSOA4Flags: Offset doesn't fit in 8 bit";
  135. return uint(-1);
  136. }
  137. block->mIndices[vertex_nr][block_tri_idx] = (uint8)vertex_offset;
  138. // Store flags
  139. uint32 flags = triangle_available? inTriangles[t + block_tri_idx].mMaterialIndex : 0;
  140. if (flags > 0xff)
  141. {
  142. outError = "TriangleCodecIndexed8BitPackSOA4Flags: Material index doesn't fit in 8 bit";
  143. return uint(-1);
  144. }
  145. block->mFlags[block_tri_idx] = (uint8)flags;
  146. }
  147. }
  148. return offset;
  149. }
  150. /// After all triangles have been packed, this finalizes the header and triangle buffer
  151. void Finalize(TriangleHeader *ioHeader, ByteBuffer &ioBuffer) const
  152. {
  153. // Check if anything to do
  154. if (mVertices.empty())
  155. return;
  156. // Align buffer to 4 bytes
  157. uint vertices_idx = (uint)ioBuffer.Align(4);
  158. // Patch the offsets
  159. for (uint o : mOffsetsToPatch)
  160. *ioBuffer.Get<uint32>(o) += vertices_idx - o;
  161. // Calculate bounding box
  162. AABox bounds;
  163. for (const Float3 &v : mVertices)
  164. bounds.Encapsulate(Vec3(v));
  165. // Compress vertices
  166. VertexData *vertices = ioBuffer.Allocate<VertexData>(mVertices.size());
  167. Vec3 compress_scale = Vec3::sReplicate(COMPONENT_MASK) / Vec3::sMax(bounds.GetSize(), Vec3::sReplicate(1.0e-20f));
  168. for (const Float3 &v : mVertices)
  169. {
  170. UVec4 c = ((Vec3(v) - bounds.mMin) * compress_scale + Vec3::sReplicate(0.5f)).ToInt();
  171. JPH_ASSERT(c.GetX() <= COMPONENT_MASK);
  172. JPH_ASSERT(c.GetY() <= COMPONENT_MASK);
  173. JPH_ASSERT(c.GetZ() <= COMPONENT_MASK);
  174. vertices->mVertexXY = c.GetX() + (c.GetY() << COMPONENT_Y1);
  175. vertices->mVertexZY = c.GetZ() + ((c.GetY() >> COMPONENT_Y1_BITS) << COMPONENT_Y2);
  176. ++vertices;
  177. }
  178. // Store decompression information
  179. bounds.mMin.StoreFloat3(&ioHeader->mOffset);
  180. (bounds.GetSize() / Vec3::sReplicate(COMPONENT_MASK)).StoreFloat3(&ioHeader->mScale);
  181. }
  182. void GetStats(string &outTriangleCodecName, float &outVerticesPerTriangle)
  183. {
  184. // Store stats
  185. outTriangleCodecName = "Indexed8BitPackSOA4";
  186. outVerticesPerTriangle = (float)mVertices.size() / mNumTriangles;
  187. }
  188. private:
  189. using VertexMap = unordered_map<uint32, uint32>;
  190. uint mNumTriangles;
  191. vector<Float3> mVertices; ///< Output vertices, sorted according to occurrence
  192. VertexMap mVertexMap; ///< Maps from the original mesh vertex index (inVertices) to the index in our output vertices (mVertices)
  193. vector<uint> mOffsetsToPatch; ///< Offsets to the vertex buffer that need to be patched in once all nodes have been packed
  194. };
  195. /// This class is used to decode and decompress triangle data packed by the EncodingContext
  196. class DecodingContext
  197. {
  198. private:
  199. /// Private helper functions to unpack the 1 vertex of 4 triangles (outX contains the x coordinate of triangle 0 .. 3 etc.)
  200. JPH_INLINE void Unpack(const VertexData *inVertices, UVec4 inIndex, Vec4 &outX, Vec4 &outY, Vec4 &outZ) const
  201. {
  202. // Get compressed data
  203. UVec4 c1 = UVec4::sGatherInt4<8>(&inVertices->mVertexXY, inIndex);
  204. UVec4 c2 = UVec4::sGatherInt4<8>(&inVertices->mVertexZY, inIndex);
  205. // Unpack the x y and z component
  206. UVec4 xc = UVec4::sAnd(c1, UVec4::sReplicate(COMPONENT_MASK));
  207. UVec4 yc = UVec4::sOr(c1.LogicalShiftRight<COMPONENT_Y1>(), c2.LogicalShiftRight<COMPONENT_Y2>().LogicalShiftLeft<COMPONENT_Y1_BITS>());
  208. UVec4 zc = UVec4::sAnd(c2, UVec4::sReplicate(COMPONENT_MASK));
  209. // Convert to float
  210. outX = Vec4::sFusedMultiplyAdd(xc.ToFloat(), mScaleX, mOffsetX);
  211. outY = Vec4::sFusedMultiplyAdd(yc.ToFloat(), mScaleY, mOffsetY);
  212. outZ = Vec4::sFusedMultiplyAdd(zc.ToFloat(), mScaleZ, mOffsetZ);
  213. }
  214. public:
  215. JPH_INLINE DecodingContext(const TriangleHeader *inHeader, const ByteBuffer &inBuffer) :
  216. mOffsetX(Vec4::sReplicate(inHeader->mOffset.x)),
  217. mOffsetY(Vec4::sReplicate(inHeader->mOffset.y)),
  218. mOffsetZ(Vec4::sReplicate(inHeader->mOffset.z)),
  219. mScaleX(Vec4::sReplicate(inHeader->mScale.x)),
  220. mScaleY(Vec4::sReplicate(inHeader->mScale.y)),
  221. mScaleZ(Vec4::sReplicate(inHeader->mScale.z))
  222. {
  223. }
  224. /// Unpacks triangles in the format t1v1,t1v2,t1v3, t2v1,t2v2,t2v3, ...
  225. JPH_INLINE void Unpack(Vec3Arg inBoundsMin, Vec3Arg inBoundsMax, const void *inTriangleStart, uint32 inNumTriangles, Vec3 *outTriangles) const
  226. {
  227. JPH_ASSERT(inNumTriangles > 0);
  228. const TriangleBlockHeader *header = reinterpret_cast<const TriangleBlockHeader *>(inTriangleStart);
  229. const VertexData *vertices = header->GetVertexData();
  230. const TriangleBlock *t = header->GetTriangleBlock();
  231. const TriangleBlock *end = t + ((inNumTriangles + 3) >> 2);
  232. int triangles_left = inNumTriangles;
  233. do
  234. {
  235. // Get the indices for the three vertices (reads 4 bytes extra, but these are the flags so that's ok)
  236. UVec4 indices = UVec4::sLoadInt4(reinterpret_cast<const uint32 *>(&t->mIndices[0]));
  237. UVec4 iv1 = indices.Expand4Byte0();
  238. UVec4 iv2 = indices.Expand4Byte4();
  239. UVec4 iv3 = indices.Expand4Byte8();
  240. // Decompress the triangle data
  241. Vec4 v1x, v1y, v1z, v2x, v2y, v2z, v3x, v3y, v3z;
  242. Unpack(vertices, iv1, v1x, v1y, v1z);
  243. Unpack(vertices, iv2, v2x, v2y, v2z);
  244. Unpack(vertices, iv3, v3x, v3y, v3z);
  245. // Transpose it so we get normal vectors
  246. Mat44 v1 = Mat44(v1x, v1y, v1z, Vec4::sZero()).Transposed();
  247. Mat44 v2 = Mat44(v2x, v2y, v2z, Vec4::sZero()).Transposed();
  248. Mat44 v3 = Mat44(v3x, v3y, v3z, Vec4::sZero()).Transposed();
  249. // Store triangle data
  250. for (int i = 0; i < 4 && triangles_left > 0; ++i, --triangles_left)
  251. {
  252. *outTriangles++ = v1.GetColumn3(i);
  253. *outTriangles++ = v2.GetColumn3(i);
  254. *outTriangles++ = v3.GetColumn3(i);
  255. }
  256. ++t;
  257. }
  258. while (t < end);
  259. }
  260. /// Tests a ray against the packed triangles
  261. JPH_INLINE float TestRay(Vec3Arg inRayOrigin, Vec3Arg inRayDirection, Vec3Arg inBoundsMin, Vec3Arg inBoundsMax, const void *inTriangleStart, uint32 inNumTriangles, float inClosest, uint32 &outClosestTriangleIndex) const
  262. {
  263. JPH_ASSERT(inNumTriangles > 0);
  264. const TriangleBlockHeader *header = reinterpret_cast<const TriangleBlockHeader *>(inTriangleStart);
  265. const VertexData *vertices = header->GetVertexData();
  266. const TriangleBlock *t = header->GetTriangleBlock();
  267. const TriangleBlock *end = t + ((inNumTriangles + 3) >> 2);
  268. Vec4 closest = Vec4::sReplicate(inClosest);
  269. UVec4 closest_triangle_idx = UVec4::sZero();
  270. UVec4 start_triangle_idx = UVec4::sZero();
  271. do
  272. {
  273. // Get the indices for the three vertices (reads 4 bytes extra, but these are the flags so that's ok)
  274. UVec4 indices = UVec4::sLoadInt4(reinterpret_cast<const uint32 *>(&t->mIndices[0]));
  275. UVec4 iv1 = indices.Expand4Byte0();
  276. UVec4 iv2 = indices.Expand4Byte4();
  277. UVec4 iv3 = indices.Expand4Byte8();
  278. // Decompress the triangle data
  279. Vec4 v1x, v1y, v1z, v2x, v2y, v2z, v3x, v3y, v3z;
  280. Unpack(vertices, iv1, v1x, v1y, v1z);
  281. Unpack(vertices, iv2, v2x, v2y, v2z);
  282. Unpack(vertices, iv3, v3x, v3y, v3z);
  283. // Perform ray vs triangle test
  284. Vec4 distance = RayTriangle4(inRayOrigin, inRayDirection, v1x, v1y, v1z, v2x, v2y, v2z, v3x, v3y, v3z);
  285. // Update closest with the smaller values
  286. UVec4 smaller = Vec4::sLess(distance, closest);
  287. closest = Vec4::sSelect(closest, distance, smaller);
  288. // Update triangle index with the smallest values
  289. UVec4 triangle_idx = start_triangle_idx + UVec4(0, 1, 2, 3);
  290. closest_triangle_idx = UVec4::sSelect(closest_triangle_idx, triangle_idx, smaller);
  291. // Next block
  292. ++t;
  293. start_triangle_idx += UVec4::sReplicate(4);
  294. }
  295. while (t < end);
  296. // Get the smallest component
  297. Vec4::sSort4(closest, closest_triangle_idx);
  298. outClosestTriangleIndex = closest_triangle_idx.GetX();
  299. return closest.GetX();
  300. }
  301. /// Decode a single triangle
  302. inline void GetTriangle(const void *inTriangleStart, uint32 inTriangleIdx, Vec3 &outV1, Vec3 &outV2, Vec3 &outV3) const
  303. {
  304. const TriangleBlockHeader *header = reinterpret_cast<const TriangleBlockHeader *>(inTriangleStart);
  305. const VertexData *vertices = header->GetVertexData();
  306. const TriangleBlock *block = header->GetTriangleBlock() + (inTriangleIdx >> 2);
  307. uint32 block_triangle_idx = inTriangleIdx & 0b11;
  308. // Get the 3 vertices
  309. const VertexData &v1 = vertices[block->mIndices[0][block_triangle_idx]];
  310. const VertexData &v2 = vertices[block->mIndices[1][block_triangle_idx]];
  311. const VertexData &v3 = vertices[block->mIndices[2][block_triangle_idx]];
  312. // Pack the vertices
  313. UVec4 c1(v1.mVertexXY, v2.mVertexXY, v3.mVertexXY, 0);
  314. UVec4 c2(v1.mVertexZY, v2.mVertexZY, v3.mVertexZY, 0);
  315. // Unpack the x y and z component
  316. UVec4 xc = UVec4::sAnd(c1, UVec4::sReplicate(COMPONENT_MASK));
  317. UVec4 yc = UVec4::sOr(c1.LogicalShiftRight<COMPONENT_Y1>(), c2.LogicalShiftRight<COMPONENT_Y2>().LogicalShiftLeft<COMPONENT_Y1_BITS>());
  318. UVec4 zc = UVec4::sAnd(c2, UVec4::sReplicate(COMPONENT_MASK));
  319. // Convert to float
  320. Vec4 vx = Vec4::sFusedMultiplyAdd(xc.ToFloat(), mScaleX, mOffsetX);
  321. Vec4 vy = Vec4::sFusedMultiplyAdd(yc.ToFloat(), mScaleY, mOffsetY);
  322. Vec4 vz = Vec4::sFusedMultiplyAdd(zc.ToFloat(), mScaleZ, mOffsetZ);
  323. // Transpose it so we get normal vectors
  324. Mat44 trans = Mat44(vx, vy, vz, Vec4::sZero()).Transposed();
  325. outV1 = trans.GetAxisX();
  326. outV2 = trans.GetAxisY();
  327. outV3 = trans.GetAxisZ();
  328. }
  329. /// Get flags for entire triangle block
  330. JPH_INLINE static void sGetFlags(const void *inTriangleStart, uint32 inNumTriangles, uint8 *outTriangleFlags)
  331. {
  332. JPH_ASSERT(inNumTriangles > 0);
  333. const TriangleBlockHeader *header = reinterpret_cast<const TriangleBlockHeader *>(inTriangleStart);
  334. const TriangleBlock *t = header->GetTriangleBlock();
  335. const TriangleBlock *end = t + ((inNumTriangles + 3) >> 2);
  336. int triangles_left = inNumTriangles;
  337. do
  338. {
  339. for (int i = 0; i < 4 && triangles_left > 0; ++i, --triangles_left)
  340. *outTriangleFlags++ = t->mFlags[i];
  341. ++t;
  342. }
  343. while (t < end);
  344. }
  345. /// Get flags for a particular triangle
  346. JPH_INLINE static uint8 sGetFlags(const void *inTriangleStart, int inTriangleIndex)
  347. {
  348. const TriangleBlockHeader *header = reinterpret_cast<const TriangleBlockHeader *>(inTriangleStart);
  349. const TriangleBlock *first_block = header->GetTriangleBlock();
  350. return first_block[inTriangleIndex >> 2].mFlags[inTriangleIndex & 0b11];
  351. }
  352. /// Unpacks triangles and flags, convencience function
  353. JPH_INLINE void Unpack(Vec3Arg inBoundsMin, Vec3Arg inBoundsMax, const void *inTriangleStart, uint32 inNumTriangles, Vec3 *outTriangles, uint8 *outTriangleFlags) const
  354. {
  355. Unpack(inBoundsMin, inBoundsMax, inTriangleStart, inNumTriangles, outTriangles);
  356. sGetFlags(inTriangleStart, inNumTriangles, outTriangleFlags);
  357. }
  358. private:
  359. Vec4 mOffsetX;
  360. Vec4 mOffsetY;
  361. Vec4 mOffsetZ;
  362. Vec4 mScaleX;
  363. Vec4 mScaleY;
  364. Vec4 mScaleZ;
  365. };
  366. };
  367. } // JPH