TriangleCodecIndexed8BitPackSOA4Flags.h 16 KB

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