HeightFieldShape.cpp 69 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951
  1. // SPDX-FileCopyrightText: 2021 Jorrit Rouwe
  2. // SPDX-License-Identifier: MIT
  3. #include <Jolt.h>
  4. #include <Physics/Collision/Shape/HeightFieldShape.h>
  5. #include <Physics/Collision/Shape/ConvexShape.h>
  6. #include <Physics/Collision/Shape/ScaleHelpers.h>
  7. #include <Physics/Collision/Shape/SphereShape.h>
  8. #include <Physics/Collision/RayCast.h>
  9. #include <Physics/Collision/ShapeCast.h>
  10. #include <Physics/Collision/CastResult.h>
  11. #include <Physics/Collision/CollidePointResult.h>
  12. #include <Physics/Collision/ShapeFilter.h>
  13. #include <Physics/Collision/CastConvexVsTriangles.h>
  14. #include <Physics/Collision/CastSphereVsTriangles.h>
  15. #include <Physics/Collision/CollideConvexVsTriangles.h>
  16. #include <Physics/Collision/CollideSphereVsTriangles.h>
  17. #include <Physics/Collision/TransformedShape.h>
  18. #include <Physics/Collision/ActiveEdges.h>
  19. #include <Physics/Collision/CollisionDispatch.h>
  20. #include <Physics/Collision/SortReverseAndStore.h>
  21. #include <Core/Profiler.h>
  22. #include <Core/StringTools.h>
  23. #include <Core/StreamIn.h>
  24. #include <Core/StreamOut.h>
  25. #include <Geometry/AABox4.h>
  26. #include <Geometry/RayTriangle.h>
  27. #include <Geometry/RayAABox.h>
  28. #include <Geometry/OrientedBox.h>
  29. #include <ObjectStream/TypeDeclarations.h>
  30. //#define JPH_DEBUG_HEIGHT_FIELD
  31. namespace JPH {
  32. #ifdef JPH_DEBUG_RENDERER
  33. bool HeightFieldShape::sDrawTriangleOutlines = false;
  34. #endif // JPH_DEBUG_RENDERER
  35. using namespace HeightFieldShapeConstants;
  36. JPH_IMPLEMENT_SERIALIZABLE_VIRTUAL(HeightFieldShapeSettings)
  37. {
  38. JPH_ADD_BASE_CLASS(HeightFieldShapeSettings, ShapeSettings)
  39. JPH_ADD_ATTRIBUTE(HeightFieldShapeSettings, mHeightSamples)
  40. JPH_ADD_ATTRIBUTE(HeightFieldShapeSettings, mOffset)
  41. JPH_ADD_ATTRIBUTE(HeightFieldShapeSettings, mScale)
  42. JPH_ADD_ATTRIBUTE(HeightFieldShapeSettings, mSampleCount)
  43. JPH_ADD_ATTRIBUTE(HeightFieldShapeSettings, mBlockSize)
  44. JPH_ADD_ATTRIBUTE(HeightFieldShapeSettings, mBitsPerSample)
  45. JPH_ADD_ATTRIBUTE(HeightFieldShapeSettings, mMaterialIndices)
  46. JPH_ADD_ATTRIBUTE(HeightFieldShapeSettings, mMaterials)
  47. }
  48. const uint HeightFieldShape::sGridOffsets[] =
  49. {
  50. 0, // level: 0, max x/y: 0, offset: 0
  51. 1, // level: 1, max x/y: 1, offset: 1
  52. 5, // level: 2, max x/y: 3, offset: 1 + 4
  53. 21, // level: 3, max x/y: 7, offset: 1 + 4 + 16
  54. 85, // level: 4, max x/y: 15, offset: 1 + 4 + 64
  55. 341, // level: 5, max x/y: 31, offset: 1 + 4 + 64 + 256
  56. 1365, // level: 6, max x/y: 63, offset: 1 + 4 + 64 + 256 + 1024
  57. 5461, // level: 7, max x/y: 127, offset: 1 + 4 + 64 + 256 + 1024 + 4096
  58. 21845, // level: 8, max x/y: 255, offset: 1 + 4 + 64 + 256 + 1024 + 4096 + ...
  59. 87381, // level: 9, max x/y: 511, offset: 1 + 4 + 64 + 256 + 1024 + 4096 + ...
  60. 349525, // level: 10, max x/y: 1023, offset: 1 + 4 + 64 + 256 + 1024 + 4096 + ...
  61. 1398101, // level: 11, max x/y: 2047, offset: 1 + 4 + 64 + 256 + 1024 + 4096 + ...
  62. 5592405, // level: 12, max x/y: 4095, offset: 1 + 4 + 64 + 256 + 1024 + 4096 + ...
  63. 22369621, // level: 13, max x/y: 8191, offset: 1 + 4 + 64 + 256 + 1024 + 4096 + ...
  64. 89478485, // level: 14, max x/y: 16383, offset: 1 + 4 + 64 + 256 + 1024 + 4096 + ...
  65. };
  66. HeightFieldShapeSettings::HeightFieldShapeSettings(const float *inSamples, Vec3Arg inOffset, Vec3Arg inScale, uint32 inSampleCount, const uint8 *inMaterialIndices, const PhysicsMaterialList &inMaterialList) :
  67. mOffset(inOffset),
  68. mScale(inScale),
  69. mSampleCount(inSampleCount)
  70. {
  71. mHeightSamples.resize(inSampleCount * inSampleCount);
  72. memcpy(&mHeightSamples[0], inSamples, inSampleCount * inSampleCount * sizeof(float));
  73. if (!inMaterialList.empty() && inMaterialIndices != nullptr)
  74. {
  75. mMaterialIndices.resize(Square(inSampleCount - 1));
  76. memcpy(&mMaterialIndices[0], inMaterialIndices, Square(inSampleCount - 1) * sizeof(uint8));
  77. mMaterials = inMaterialList;
  78. }
  79. else
  80. {
  81. JPH_ASSERT(inMaterialList.empty());
  82. JPH_ASSERT(inMaterialIndices == nullptr);
  83. }
  84. }
  85. ShapeSettings::ShapeResult HeightFieldShapeSettings::Create() const
  86. {
  87. if (mCachedResult.IsEmpty())
  88. Ref<Shape> shape = new HeightFieldShape(*this, mCachedResult);
  89. return mCachedResult;
  90. }
  91. void HeightFieldShapeSettings::DetermineMinAndMaxSample(float &outMinValue, float &outMaxValue, float &outQuantizationScale) const
  92. {
  93. // Determine min and max value
  94. outMinValue = FLT_MAX;
  95. outMaxValue = -FLT_MAX;
  96. for (float h : mHeightSamples)
  97. if (h != cNoCollisionValue)
  98. {
  99. outMinValue = min(outMinValue, h);
  100. outMaxValue = max(outMaxValue, h);
  101. }
  102. // Prevent dividing by zero by setting a minimal height difference
  103. float height_diff = max(outMaxValue - outMinValue, 1.0e-6f);
  104. // Calculate the scale factor to quantize to 16 bits
  105. outQuantizationScale = float(cMaxHeightValue16) / height_diff;
  106. }
  107. uint32 HeightFieldShapeSettings::CalculateBitsPerSampleForError(float inMaxError) const
  108. {
  109. // Start with 1 bit per sample
  110. uint32 bits_per_sample = 1;
  111. // Determine total range
  112. float min_value, max_value, scale;
  113. DetermineMinAndMaxSample(min_value, max_value, scale);
  114. if (min_value < max_value)
  115. {
  116. // Loop over all blocks
  117. for (uint y = 0; y < mSampleCount; y += mBlockSize)
  118. for (uint x = 0; x < mSampleCount; x += mBlockSize)
  119. {
  120. // Determine min and max block value + take 1 sample border just like we do while building the hierarchical grids
  121. float block_min_value = FLT_MAX, block_max_value = -FLT_MAX;
  122. for (uint bx = x; bx < min(x + mBlockSize + 1, mSampleCount); ++bx)
  123. for (uint by = y; by < min(y + mBlockSize + 1, mSampleCount); ++by)
  124. {
  125. float h = mHeightSamples[by * mSampleCount + bx];
  126. if (h != cNoCollisionValue)
  127. {
  128. block_min_value = min(block_min_value, h);
  129. block_max_value = max(block_max_value, h);
  130. }
  131. }
  132. if (block_min_value < block_max_value)
  133. {
  134. // Quantize then dequantize block min/max value
  135. block_min_value = min_value + floor((block_min_value - min_value) * scale) / scale;
  136. block_max_value = min_value + ceil((block_max_value - min_value) * scale) / scale;
  137. float block_height = block_max_value - block_min_value;
  138. // Loop over the block again
  139. for (uint bx = x; bx < x + mBlockSize; ++bx)
  140. for (uint by = y; by < y + mBlockSize; ++by)
  141. {
  142. // Get the height
  143. float height = mHeightSamples[by * mSampleCount + bx];
  144. if (height != cNoCollisionValue)
  145. {
  146. for (;;)
  147. {
  148. // Determine bitmask for sample
  149. uint32 sample_mask = (1 << bits_per_sample) - 1;
  150. // Quantize
  151. float quantized_height = floor((height - block_min_value) * float(sample_mask) / block_height);
  152. quantized_height = Clamp(quantized_height, 0.0f, float(sample_mask - 1));
  153. // Dequantize and check error
  154. float dequantized_height = block_min_value + (quantized_height + 0.5f) * block_height / float(sample_mask);
  155. if (abs(dequantized_height - height) <= inMaxError)
  156. break;
  157. // Not accurate enough, increase bits per sample
  158. bits_per_sample++;
  159. // Don't go above 8 bits per sample
  160. if (bits_per_sample == 8)
  161. return bits_per_sample;
  162. }
  163. }
  164. }
  165. }
  166. }
  167. }
  168. return bits_per_sample;
  169. }
  170. void HeightFieldShape::CalculateActiveEdges()
  171. {
  172. // Store active edges. The triangles are organized like this:
  173. // + +
  174. // | \ T1B | \ T2B
  175. // e0 e2 | \
  176. // | T1A \ | T2A \
  177. // +--e1---+-------+
  178. // | \ T3B | \ T4B
  179. // | \ | \
  180. // | T3A \ | T4A \
  181. // +-------+-------+
  182. // We store active edges e0 .. e2 as bits 0 .. 2.
  183. // We store triangles horizontally then vertically (order T1A, T2A, T3A and T4A).
  184. // The top edge and right edge of the heightfield are always active so we do not need to store them,
  185. // therefore we only need to store (mSampleCount - 1)^2 * 3-bit
  186. // The triangles T1B, T2B, T3B and T4B do not need to be stored, their active edges can be constructed from adjacent triangles.
  187. // Add 1 byte padding so we can always read 1 uint16 to get the bits that cross an 8 bit boundary
  188. uint count_min_1 = mSampleCount - 1;
  189. uint count_min_1_sq = Square(count_min_1);
  190. mActiveEdges.resize((count_min_1_sq * 3 + 7) / 8 + 1);
  191. memset(&mActiveEdges[0], 0, mActiveEdges.size());
  192. // Calculate triangle normals and make normals zero for triangles that are missing
  193. vector<Vec3> normals;
  194. normals.resize(2 * count_min_1_sq);
  195. memset(&normals[0], 0, normals.size() * sizeof(Vec3));
  196. for (uint y = 0; y < count_min_1; ++y)
  197. for (uint x = 0; x < count_min_1; ++x)
  198. if (!IsNoCollision(x, y) && !IsNoCollision(x + 1, y + 1))
  199. {
  200. Vec3 x1y1 = GetPosition(x, y);
  201. Vec3 x2y2 = GetPosition(x + 1, y + 1);
  202. uint offset = 2 * (count_min_1 * y + x);
  203. if (!IsNoCollision(x, y + 1))
  204. {
  205. Vec3 x1y2 = GetPosition(x, y + 1);
  206. normals[offset] = (x2y2 - x1y2).Cross(x1y1 - x1y2).Normalized();
  207. }
  208. if (!IsNoCollision(x + 1, y))
  209. {
  210. Vec3 x2y1 = GetPosition(x + 1, y);
  211. normals[offset + 1] = (x1y1 - x2y1).Cross(x2y2 - x2y1).Normalized();
  212. }
  213. }
  214. // Calculate active edges
  215. for (uint y = 0; y < count_min_1; ++y)
  216. for (uint x = 0; x < count_min_1; ++x)
  217. {
  218. // Calculate vertex positions.
  219. // We don't check 'no colliding' since those normals will be zero and sIsEdgeActive will return true
  220. Vec3 x1y1 = GetPosition(x, y);
  221. Vec3 x1y2 = GetPosition(x, y + 1);
  222. Vec3 x2y2 = GetPosition(x + 1, y + 1);
  223. // Calculate the edge flags (3 bits)
  224. uint offset = 2 * (count_min_1 * y + x);
  225. bool edge0_active = x == 0 || ActiveEdges::IsEdgeActive(normals[offset], normals[offset - 1], x1y2 - x1y1);
  226. bool edge1_active = y == count_min_1 - 1 || ActiveEdges::IsEdgeActive(normals[offset], normals[offset + 2 * count_min_1 + 1], x2y2 - x1y2);
  227. bool edge2_active = ActiveEdges::IsEdgeActive(normals[offset], normals[offset + 1], x1y1 - x2y2);
  228. uint16 edge_flags = (edge0_active? 0b001 : 0) | (edge1_active? 0b010 : 0) | (edge2_active? 0b100 : 0);
  229. // Store the edge flags in the array
  230. uint bit_pos = 3 * (y * count_min_1 + x);
  231. uint byte_pos = bit_pos >> 3;
  232. bit_pos &= 0b111;
  233. edge_flags <<= bit_pos;
  234. mActiveEdges[byte_pos] |= uint8(edge_flags);
  235. mActiveEdges[byte_pos + 1] |= uint8(edge_flags >> 8);
  236. }
  237. }
  238. void HeightFieldShape::StoreMaterialIndices(const vector<uint8> &inMaterialIndices)
  239. {
  240. uint count_min_1 = mSampleCount - 1;
  241. mNumBitsPerMaterialIndex = 32 - CountLeadingZeros((uint32)mMaterials.size() - 1);
  242. mMaterialIndices.resize(((Square(count_min_1) * mNumBitsPerMaterialIndex + 7) >> 3) + 1); // Add 1 byte so we don't read out of bounds when reading an uint16
  243. for (uint y = 0; y < count_min_1; ++y)
  244. for (uint x = 0; x < count_min_1; ++x)
  245. {
  246. // Read material
  247. uint sample_pos = x + y * count_min_1;
  248. uint16 material_index = uint16(inMaterialIndices[sample_pos]);
  249. // Calculate byte and bit position where the material index needs to go
  250. uint bit_pos = sample_pos * mNumBitsPerMaterialIndex;
  251. uint byte_pos = bit_pos >> 3;
  252. bit_pos &= 0b111;
  253. // Write the material index
  254. material_index <<= bit_pos;
  255. JPH_ASSERT(byte_pos + 1 < mMaterialIndices.size());
  256. mMaterialIndices[byte_pos] |= uint8(material_index);
  257. mMaterialIndices[byte_pos + 1] |= uint8(material_index >> 8);
  258. }
  259. }
  260. void HeightFieldShape::CacheValues()
  261. {
  262. mSampleMask = uint8((uint32(1) << mBitsPerSample) - 1);
  263. }
  264. HeightFieldShape::HeightFieldShape(const HeightFieldShapeSettings &inSettings, ShapeResult &outResult) :
  265. Shape(EShapeType::HeightField, EShapeSubType::HeightField, inSettings, outResult),
  266. mOffset(inSettings.mOffset),
  267. mScale(inSettings.mScale),
  268. mSampleCount(inSettings.mSampleCount),
  269. mBlockSize(inSettings.mBlockSize),
  270. mBitsPerSample(uint8(inSettings.mBitsPerSample)),
  271. mMaterials(inSettings.mMaterials)
  272. {
  273. CacheValues();
  274. // Check block size
  275. if (mBlockSize < 2 || mBlockSize > 8)
  276. {
  277. outResult.SetError("HeightFieldShape: Block size must be in the range [2, 8]!");
  278. return;
  279. }
  280. // Check sample count
  281. if (mSampleCount % mBlockSize != 0)
  282. {
  283. outResult.SetError("HeightFieldShape: Sample count must be a multiple of block size!");
  284. return;
  285. }
  286. // Check bits per sample
  287. if (inSettings.mBitsPerSample < 1 || inSettings.mBitsPerSample > 8)
  288. {
  289. outResult.SetError("HeightFieldShape: Bits per sample must be in the range [1, 8]!");
  290. return;
  291. }
  292. // We stop at mBlockSize x mBlockSize height sample blocks
  293. uint n = GetNumBlocks();
  294. // Required to be power of two to allow creating a hierarchical grid
  295. if (!IsPowerOf2(n))
  296. {
  297. outResult.SetError("HeightFieldShape: Sample count / block size must be power of 2!");
  298. return;
  299. }
  300. // We want at least 1 grid layer
  301. if (n < 2)
  302. {
  303. outResult.SetError("HeightFieldShape: Sample count too low!");
  304. return;
  305. }
  306. // Check that we don't overflow our 32 bit 'properties'
  307. if (n > (1 << cNumBitsXY))
  308. {
  309. outResult.SetError("HeightFieldShape: Sample count too high!");
  310. return;
  311. }
  312. // Check if we're not exceeding the amount of sub shape id bits
  313. if (GetSubShapeIDBitsRecursive() > SubShapeID::MaxBits)
  314. {
  315. outResult.SetError("HeightFieldShape: Size exceeds the amount of available sub shape ID bits!");
  316. return;
  317. }
  318. if (!mMaterials.empty())
  319. {
  320. // Validate materials
  321. if (mMaterials.size() > 256)
  322. {
  323. outResult.SetError("Supporting max 256 materials per height field");
  324. return;
  325. }
  326. for (uint8 s : inSettings.mMaterialIndices)
  327. if (s >= mMaterials.size())
  328. {
  329. outResult.SetError(StringFormat("Material %u is beyond material list (size: %u)", s, (uint)mMaterials.size()));
  330. return;
  331. }
  332. }
  333. else
  334. {
  335. // No materials assigned, validate that no materials have been specified
  336. if (!inSettings.mMaterialIndices.empty())
  337. {
  338. outResult.SetError("No materials present, mMaterialIndices should be empty");
  339. return;
  340. }
  341. }
  342. // Determine range
  343. float min_value, max_value, scale;
  344. inSettings.DetermineMinAndMaxSample(min_value, max_value, scale);
  345. if (min_value > max_value)
  346. {
  347. // If there is no collision with this heightmap, leave everything empty
  348. mMaterials.clear();
  349. outResult.Set(this);
  350. return;
  351. }
  352. // Quantize to uint16
  353. vector<uint16> quantized_samples;
  354. quantized_samples.reserve(mSampleCount * mSampleCount);
  355. for (float h : inSettings.mHeightSamples)
  356. if (h == cNoCollisionValue)
  357. {
  358. quantized_samples.push_back(cNoCollisionValue16);
  359. }
  360. else
  361. {
  362. // Floor the quantized height to get a lower bound for the quantized value
  363. int quantized_height = (int)floor(scale * (h - min_value));
  364. // Ensure that the height says below the max height value so we can safely add 1 to get the upper bound for the quantized value
  365. quantized_height = Clamp(quantized_height, 0, int(cMaxHeightValue16 - 1));
  366. quantized_samples.push_back(uint16(quantized_height));
  367. }
  368. // Update offset and scale to account for the compression to uint16
  369. if (min_value <= max_value) // Only when there was collision
  370. {
  371. // In GetPosition we always add 0.5 to the quantized sample in order to reduce the average error.
  372. // We want to be able to exactly quantize min_value (this is important in case the heightfield is entirely flat) so we subtract that value from min_value.
  373. min_value -= 0.5f / (scale * mSampleMask);
  374. mOffset.SetY(mOffset.GetY() + mScale.GetY() * min_value);
  375. }
  376. mScale.SetY(mScale.GetY() / scale);
  377. // Calculate amount of grids
  378. uint max_level = sGetMaxLevel(n);
  379. // Temporary data structure used during creating of a hierarchy of grids
  380. struct Range
  381. {
  382. uint16 mMin;
  383. uint16 mMax;
  384. };
  385. // Reserve size for temporary range data + reserve 1 extra for a 1x1 grid that we won't store but use for calculating the bounding box
  386. vector<vector<Range>> ranges;
  387. ranges.resize(max_level + 1);
  388. // Calculate highest detail grid by combining mBlockSize x mBlockSize height samples
  389. vector<Range> *cur_range_vector = &ranges.back();
  390. cur_range_vector->resize(n * n);
  391. Range *range_dst = &cur_range_vector->front();
  392. for (uint y = 0; y < n; ++y)
  393. for (uint x = 0; x < n; ++x)
  394. {
  395. range_dst->mMin = 0xffff;
  396. range_dst->mMax = 0;
  397. uint max_bx = x == n - 1? mBlockSize : mBlockSize + 1; // for interior blocks take 1 more because the triangles connect to the next block so we must include their height too
  398. uint max_by = y == n - 1? mBlockSize : mBlockSize + 1;
  399. for (uint by = 0; by < max_by; ++by)
  400. for (uint bx = 0; bx < max_bx; ++bx)
  401. {
  402. uint16 h = quantized_samples[(y * mBlockSize + by) * mSampleCount + (x * mBlockSize + bx)];
  403. if (h != cNoCollisionValue16)
  404. {
  405. range_dst->mMin = min(range_dst->mMin, h);
  406. range_dst->mMax = max(range_dst->mMax, uint16(h + 1)); // Add 1 to the max so we know the real value is between mMin and mMax
  407. }
  408. }
  409. ++range_dst;
  410. }
  411. // Calculate remaining grids
  412. while (n > 1)
  413. {
  414. // Get source buffer
  415. const Range *range_src = &cur_range_vector->front();
  416. // Previous array element
  417. --cur_range_vector;
  418. // Make space for this grid
  419. n >>= 1;
  420. cur_range_vector->resize(n * n);
  421. // Get target buffer
  422. range_dst = &cur_range_vector->front();
  423. // Combine the results of 2x2 ranges
  424. for (uint y = 0; y < n; ++y)
  425. for (uint x = 0; x < n; ++x)
  426. {
  427. range_dst->mMin = 0xffff;
  428. range_dst->mMax = 0;
  429. for (uint by = 0; by < 2; ++by)
  430. for (uint bx = 0; bx < 2; ++bx)
  431. {
  432. const Range &r = range_src[(y * 2 + by) * n * 2 + x * 2 + bx];
  433. range_dst->mMin = min(range_dst->mMin, r.mMin);
  434. range_dst->mMax = max(range_dst->mMax, r.mMax);
  435. }
  436. ++range_dst;
  437. }
  438. }
  439. JPH_ASSERT(cur_range_vector == &ranges.front());
  440. // Store global range for bounding box calculation
  441. mMinSample = ranges[0][0].mMin;
  442. mMaxSample = ranges[0][0].mMax;
  443. #ifdef JPH_ENABLE_ASSERTS
  444. // Validate that we did not lose range along the way
  445. uint16 minv = 0xffff, maxv = 0;
  446. for (uint16 v : quantized_samples)
  447. if (v != cNoCollisionValue16)
  448. {
  449. minv = min(minv, v);
  450. maxv = max(maxv, uint16(v + 1));
  451. }
  452. JPH_ASSERT(mMinSample == minv && mMaxSample == maxv);
  453. #endif
  454. // Now erase the first element, we need a 2x2 grid to start with
  455. ranges.erase(ranges.begin());
  456. // Create blocks
  457. mRangeBlocks.reserve(sGridOffsets[ranges.size()]);
  458. for (uint level = 0; level < ranges.size(); ++level)
  459. {
  460. JPH_ASSERT(mRangeBlocks.size() == sGridOffsets[level]);
  461. n = 1 << level;
  462. for (uint y = 0; y < n; ++y)
  463. for (uint x = 0; x < n; ++x)
  464. {
  465. // Convert from 2x2 Range structure to 1 RangeBlock structure
  466. RangeBlock rb;
  467. for (uint by = 0; by < 2; ++by)
  468. for (uint bx = 0; bx < 2; ++bx)
  469. {
  470. uint src_pos = (y * 2 + by) * n * 2 + (x * 2 + bx);
  471. uint dst_pos = by * 2 + bx;
  472. rb.mMin[dst_pos] = ranges[level][src_pos].mMin;
  473. rb.mMax[dst_pos] = ranges[level][src_pos].mMax;
  474. }
  475. // Add this block
  476. mRangeBlocks.push_back(rb);
  477. }
  478. }
  479. JPH_ASSERT(mRangeBlocks.size() == sGridOffsets[ranges.size()]);
  480. // Quantize height samples
  481. mHeightSamples.resize((mSampleCount * mSampleCount * inSettings.mBitsPerSample + 7) / 8 + 1);
  482. int sample = 0;
  483. for (uint y = 0; y < mSampleCount; ++y)
  484. for (uint x = 0; x < mSampleCount; ++x)
  485. {
  486. uint32 output_value;
  487. float h = inSettings.mHeightSamples[y * mSampleCount + x];
  488. if (h == cNoCollisionValue)
  489. {
  490. // No collision
  491. output_value = mSampleMask;
  492. }
  493. else
  494. {
  495. // Get range of block so we know what range to compress to
  496. uint bx = x / mBlockSize;
  497. uint by = y / mBlockSize;
  498. const Range &range = ranges.back()[by * (mSampleCount / mBlockSize) + bx];
  499. JPH_ASSERT(range.mMin < range.mMax);
  500. // Quantize to mBitsPerSample bits, note that mSampleMask is reserved for indicating that there's no collision.
  501. // We divide the range into mSampleMask segments and use the mid points of these segments as the quantized values.
  502. // This results in a lower error than if we had quantized our data using the lowest point of all these segments.
  503. float h_min = min_value + range.mMin / scale;
  504. float h_delta = float(range.mMax - range.mMin) / scale;
  505. float quantized_height = floor((h - h_min) * float(mSampleMask) / h_delta);
  506. output_value = uint32(Clamp((int)quantized_height, 0, int(mSampleMask) - 1)); // mSampleMask is reserved as 'no collision value'
  507. }
  508. // Store the sample
  509. uint byte_pos = sample >> 3;
  510. uint bit_pos = sample & 0b111;
  511. output_value <<= bit_pos;
  512. mHeightSamples[byte_pos] |= uint8(output_value);
  513. mHeightSamples[byte_pos + 1] |= uint8(output_value >> 8);
  514. sample += inSettings.mBitsPerSample;
  515. }
  516. // Calculate the active edges
  517. CalculateActiveEdges();
  518. // Compress material indices
  519. if (mMaterials.size() > 1)
  520. StoreMaterialIndices(inSettings.mMaterialIndices);
  521. outResult.Set(this);
  522. }
  523. inline void HeightFieldShape::sGetRangeBlockOffsetAndStride(uint inNumBlocks, uint inMaxLevel, uint &outRangeBlockOffset, uint &outRangeBlockStride)
  524. {
  525. outRangeBlockOffset = sGridOffsets[inMaxLevel - 1];
  526. outRangeBlockStride = inNumBlocks >> 1;
  527. }
  528. inline void HeightFieldShape::GetBlockOffsetAndScale(uint inBlockX, uint inBlockY, uint inRangeBlockOffset, uint inRangeBlockStride, float &outBlockOffset, float &outBlockScale) const
  529. {
  530. JPH_ASSERT(inBlockX < GetNumBlocks() && inBlockY < GetNumBlocks());
  531. // Convert to location of range block
  532. uint rbx = inBlockX >> 1;
  533. uint rby = inBlockY >> 1;
  534. uint n = ((inBlockY & 1) << 1) + (inBlockX & 1);
  535. // Calculate offset and scale
  536. const RangeBlock &block = mRangeBlocks[inRangeBlockOffset + rby * inRangeBlockStride + rbx];
  537. outBlockOffset = float(block.mMin[n]);
  538. outBlockScale = float(block.mMax[n] - block.mMin[n]) / float(mSampleMask);
  539. }
  540. inline uint8 HeightFieldShape::GetHeightSample(uint inX, uint inY) const
  541. {
  542. JPH_ASSERT(inX < mSampleCount);
  543. JPH_ASSERT(inY < mSampleCount);
  544. // Determine bit position of sample
  545. uint sample = (inY * mSampleCount + inX) * uint(mBitsPerSample);
  546. uint byte_pos = sample >> 3;
  547. uint bit_pos = sample & 0b111;
  548. // Fetch the height sample value
  549. JPH_ASSERT(byte_pos + 1 < mHeightSamples.size());
  550. const uint8 *height_samples = mHeightSamples.data() + byte_pos;
  551. uint16 height_sample = uint16(height_samples[0]) | uint16(uint16(height_samples[1]) << 8);
  552. return uint8(height_sample >> bit_pos) & mSampleMask;
  553. }
  554. inline Vec3 HeightFieldShape::GetPosition(uint inX, uint inY, float inBlockOffset, float inBlockScale, bool &outNoCollision) const
  555. {
  556. // Get quantized value
  557. uint8 height_sample = GetHeightSample(inX, inY);
  558. outNoCollision = height_sample == mSampleMask;
  559. // Add 0.5 to the quantized value to minimize the error (see constructor)
  560. return mOffset + mScale * Vec3(float(inX), inBlockOffset + (0.5f + height_sample) * inBlockScale, float(inY));
  561. }
  562. Vec3 HeightFieldShape::GetPosition(uint inX, uint inY) const
  563. {
  564. // Test if there are any samples
  565. if (mHeightSamples.empty())
  566. return mOffset + mScale * Vec3(float(inX), 0.0f, float(inY));
  567. // Get block location
  568. uint bx = inX / mBlockSize;
  569. uint by = inY / mBlockSize;
  570. // Calculate offset and stride
  571. uint num_blocks = GetNumBlocks();
  572. uint range_block_offset, range_block_stride;
  573. sGetRangeBlockOffsetAndStride(num_blocks, sGetMaxLevel(num_blocks), range_block_offset, range_block_stride);
  574. float offset, scale;
  575. GetBlockOffsetAndScale(bx, by, range_block_offset, range_block_stride, offset, scale);
  576. bool no_collision;
  577. return GetPosition(inX, inY, offset, scale, no_collision);
  578. }
  579. bool HeightFieldShape::IsNoCollision(uint inX, uint inY) const
  580. {
  581. return mHeightSamples.empty() || GetHeightSample(inX, inY) == mSampleMask;
  582. }
  583. bool HeightFieldShape::ProjectOntoSurface(Vec3Arg inLocalPosition, Vec3 &outSurfacePosition, SubShapeID &outSubShapeID) const
  584. {
  585. // Check if we have collision
  586. if (mHeightSamples.empty())
  587. return false;
  588. // Convert coordinate to integer space
  589. Vec3 integer_space = (inLocalPosition - mOffset) / mScale;
  590. // Get x coordinate and fraction
  591. float x_frac = integer_space.GetX();
  592. if (x_frac < 0.0f || x_frac >= mSampleCount - 1)
  593. return false;
  594. uint x = (uint)floor(x_frac);
  595. x_frac -= x;
  596. // Get y coordinate and fraction
  597. float y_frac = integer_space.GetZ();
  598. if (y_frac < 0.0f || y_frac >= mSampleCount - 1)
  599. return false;
  600. uint y = (uint)floor(y_frac);
  601. y_frac -= y;
  602. // If one of the diagonal points doesn't have collision, we don't have a height at this location
  603. if (IsNoCollision(x, y) || IsNoCollision(x + 1, y + 1))
  604. return false;
  605. if (y_frac >= x_frac)
  606. {
  607. // Left bottom triangle, test the 3rd point
  608. if (IsNoCollision(x, y + 1))
  609. return false;
  610. // Interpolate height value
  611. Vec3 v1 = GetPosition(x, y);
  612. Vec3 v2 = GetPosition(x, y + 1);
  613. Vec3 v3 = GetPosition(x + 1, y + 1);
  614. outSurfacePosition = v1 + y_frac * (v2 - v1) + x_frac * (v3 - v2);
  615. SubShapeIDCreator creator;
  616. outSubShapeID = EncodeSubShapeID(creator, x, y, 0);
  617. return true;
  618. }
  619. else
  620. {
  621. // Right top triangle, test the third point
  622. if (IsNoCollision(x + 1, y))
  623. return false;
  624. // Interpolate height value
  625. Vec3 v1 = GetPosition(x, y);
  626. Vec3 v2 = GetPosition(x + 1, y + 1);
  627. Vec3 v3 = GetPosition(x + 1, y);
  628. outSurfacePosition = v1 + y_frac * (v2 - v3) + x_frac * (v3 - v1);
  629. SubShapeIDCreator creator;
  630. outSubShapeID = EncodeSubShapeID(creator, x, y, 1);
  631. return true;
  632. }
  633. }
  634. MassProperties HeightFieldShape::GetMassProperties() const
  635. {
  636. // Object should always be static, return default mass properties
  637. return MassProperties();
  638. }
  639. const PhysicsMaterial *HeightFieldShape::GetMaterial(uint inX, uint inY) const
  640. {
  641. if (mMaterials.empty())
  642. return PhysicsMaterial::sDefault;
  643. if (mMaterials.size() == 1)
  644. return mMaterials[0];
  645. uint count_min_1 = mSampleCount - 1;
  646. JPH_ASSERT(inX < count_min_1);
  647. JPH_ASSERT(inY < count_min_1);
  648. // Calculate at which bit the material index starts
  649. uint bit_pos = (inX + inY * count_min_1) * mNumBitsPerMaterialIndex;
  650. uint byte_pos = bit_pos >> 3;
  651. bit_pos &= 0b111;
  652. // Read the material index
  653. JPH_ASSERT(byte_pos + 1 < mMaterialIndices.size());
  654. const uint8 *material_indices = mMaterialIndices.data() + byte_pos;
  655. uint16 material_index = uint16(material_indices[0]) + uint16(uint16(material_indices[1]) << 8);
  656. material_index >>= bit_pos;
  657. material_index &= (1 << mNumBitsPerMaterialIndex) - 1;
  658. // Return the material
  659. return mMaterials[material_index];
  660. }
  661. uint HeightFieldShape::GetSubShapeIDBits() const
  662. {
  663. // Need to store X, Y and 1 extra bit to specify the triangle number in the quad
  664. return 2 * (32 - CountLeadingZeros(mSampleCount - 1)) + 1;
  665. }
  666. SubShapeID HeightFieldShape::EncodeSubShapeID(const SubShapeIDCreator &inCreator, uint inX, uint inY, uint inTriangle) const
  667. {
  668. return inCreator.PushID((inX + inY * mSampleCount) * 2 + inTriangle, GetSubShapeIDBits()).GetID();
  669. }
  670. void HeightFieldShape::DecodeSubShapeID(const SubShapeID &inSubShapeID, uint &outX, uint &outY, uint &outTriangle) const
  671. {
  672. // Decode sub shape id
  673. SubShapeID remainder;
  674. uint32 id = inSubShapeID.PopID(GetSubShapeIDBits(), remainder);
  675. JPH_ASSERT(remainder.IsEmpty(), "Invalid subshape ID");
  676. // Get triangle index
  677. outTriangle = id & 1;
  678. id >>= 1;
  679. // Fetch the x and y coordinate
  680. outX = id % mSampleCount;
  681. outY = id / mSampleCount;
  682. }
  683. const PhysicsMaterial *HeightFieldShape::GetMaterial(const SubShapeID &inSubShapeID) const
  684. {
  685. // Decode ID
  686. uint x, y, triangle;
  687. DecodeSubShapeID(inSubShapeID, x, y, triangle);
  688. // Fetch the material
  689. return GetMaterial(x, y);
  690. }
  691. Vec3 HeightFieldShape::GetSurfaceNormal(const SubShapeID &inSubShapeID, Vec3Arg inLocalSurfacePosition) const
  692. {
  693. // Decode ID
  694. uint x, y, triangle;
  695. DecodeSubShapeID(inSubShapeID, x, y, triangle);
  696. // Fetch vertices that both triangles share
  697. Vec3 x1y1 = GetPosition(x, y);
  698. Vec3 x2y2 = GetPosition(x + 1, y + 1);
  699. // Get normal depending on which triangle was selected
  700. Vec3 normal;
  701. if (triangle == 0)
  702. {
  703. Vec3 x1y2 = GetPosition(x, y + 1);
  704. normal = (x2y2 - x1y2).Cross(x1y1 - x1y2);
  705. }
  706. else
  707. {
  708. Vec3 x2y1 = GetPosition(x + 1, y);
  709. normal = (x1y1 - x2y1).Cross(x2y2 - x2y1);
  710. }
  711. return normal.Normalized();
  712. }
  713. inline uint8 HeightFieldShape::GetEdgeFlags(uint inX, uint inY, uint inTriangle) const
  714. {
  715. if (inTriangle == 0)
  716. {
  717. // The edge flags for this triangle are directly stored, find the right 3 bits
  718. uint bit_pos = 3 * (inX + inY * (mSampleCount - 1));
  719. uint byte_pos = bit_pos >> 3;
  720. bit_pos &= 0b111;
  721. JPH_ASSERT(byte_pos + 1 < mActiveEdges.size());
  722. const uint8 *active_edges = mActiveEdges.data() + byte_pos;
  723. uint16 edge_flags = uint16(active_edges[0]) + uint16(uint16(active_edges[1]) << 8);
  724. return uint8(edge_flags >> bit_pos) & 0b111;
  725. }
  726. else
  727. {
  728. // We don't store this triangle directly, we need to look at our three neighbours to construct the edge flags
  729. uint8 edge0 = (GetEdgeFlags(inX, inY, 0) & 0b100) != 0? 0b001 : 0; // Diagonal edge
  730. uint8 edge1 = inX == mSampleCount - 1 || (GetEdgeFlags(inX + 1, inY, 0) & 0b001) != 0? 0b010 : 0; // Vertical edge
  731. uint8 edge2 = inY == 0 || (GetEdgeFlags(inX, inY - 1, 0) & 0b010) != 0? 0b100 : 0; // Horizontal edge
  732. return edge0 | edge1 | edge2;
  733. }
  734. }
  735. AABox HeightFieldShape::GetLocalBounds() const
  736. {
  737. if (mMinSample == cNoCollisionValue16)
  738. {
  739. // This whole height field shape doesn't have any collision, return the center point
  740. Vec3 center = mOffset + 0.5f * mScale * Vec3(float(mSampleCount - 1), 0.0f, float(mSampleCount - 1));
  741. return AABox(center, center);
  742. }
  743. else
  744. {
  745. // Bounding box based on min and max sample height
  746. Vec3 bmin = mOffset + mScale * Vec3(0.0f, float(mMinSample), 0.0f);
  747. Vec3 bmax = mOffset + mScale * Vec3(float(mSampleCount - 1), float(mMaxSample), float(mSampleCount - 1));
  748. return AABox(bmin, bmax);
  749. }
  750. }
  751. #ifdef JPH_DEBUG_RENDERER
  752. void HeightFieldShape::Draw(DebugRenderer *inRenderer, Mat44Arg inCenterOfMassTransform, Vec3Arg inScale, ColorArg inColor, bool inUseMaterialColors, bool inDrawWireframe) const
  753. {
  754. // Don't draw anything if we don't have any collision
  755. if (mHeightSamples.empty())
  756. return;
  757. // Reset the batch if we switch coloring mode
  758. if (mCachedUseMaterialColors != inUseMaterialColors)
  759. {
  760. mGeometry.clear();
  761. mCachedUseMaterialColors = inUseMaterialColors;
  762. }
  763. if (mGeometry.empty())
  764. {
  765. // Divide terrain in triangle batches of max 64x64x2 triangles to allow better culling of the terrain
  766. uint32 block_size = min<uint32>(mSampleCount, 64);
  767. for (uint32 by = 0; by < mSampleCount; by += block_size)
  768. for (uint32 bx = 0; bx < mSampleCount; bx += block_size)
  769. {
  770. // Create vertices for a block
  771. vector<DebugRenderer::Triangle> triangles;
  772. triangles.resize(block_size * block_size * 2);
  773. DebugRenderer::Triangle *out_tri = &triangles[0];
  774. for (uint32 y = by, max_y = min(by + block_size, mSampleCount - 1); y < max_y; ++y)
  775. for (uint32 x = bx, max_x = min(bx + block_size, mSampleCount - 1); x < max_x; ++x)
  776. if (!IsNoCollision(x, y) && !IsNoCollision(x + 1, y + 1))
  777. {
  778. Vec3 x1y1 = GetPosition(x, y);
  779. Vec3 x2y2 = GetPosition(x + 1, y + 1);
  780. Color color = inUseMaterialColors? GetMaterial(x, y)->GetDebugColor() : Color::sWhite;
  781. if (!IsNoCollision(x, y + 1))
  782. {
  783. Vec3 x1y2 = GetPosition(x, y + 1);
  784. x1y1.StoreFloat3(&out_tri->mV[0].mPosition);
  785. x1y2.StoreFloat3(&out_tri->mV[1].mPosition);
  786. x2y2.StoreFloat3(&out_tri->mV[2].mPosition);
  787. Vec3 normal = (x2y2 - x1y2).Cross(x1y1 - x1y2).Normalized();
  788. for (DebugRenderer::Vertex &v : out_tri->mV)
  789. {
  790. v.mColor = color;
  791. v.mUV = Float2(0, 0);
  792. normal.StoreFloat3(&v.mNormal);
  793. }
  794. ++out_tri;
  795. }
  796. if (!IsNoCollision(x + 1, y))
  797. {
  798. Vec3 x2y1 = GetPosition(x + 1, y);
  799. x1y1.StoreFloat3(&out_tri->mV[0].mPosition);
  800. x2y2.StoreFloat3(&out_tri->mV[1].mPosition);
  801. x2y1.StoreFloat3(&out_tri->mV[2].mPosition);
  802. Vec3 normal = (x1y1 - x2y1).Cross(x2y2 - x2y1).Normalized();
  803. for (DebugRenderer::Vertex &v : out_tri->mV)
  804. {
  805. v.mColor = color;
  806. v.mUV = Float2(0, 0);
  807. normal.StoreFloat3(&v.mNormal);
  808. }
  809. ++out_tri;
  810. }
  811. }
  812. // Resize triangles array to actual amount of triangles written
  813. size_t num_triangles = out_tri - &triangles[0];
  814. triangles.resize(num_triangles);
  815. // Create batch
  816. if (num_triangles > 0)
  817. mGeometry.push_back(new DebugRenderer::Geometry(inRenderer->CreateTriangleBatch(triangles), DebugRenderer::sCalculateBounds(&triangles[0].mV[0], int(3 * num_triangles))));
  818. }
  819. }
  820. // Get transform including scale
  821. Mat44 transform = inCenterOfMassTransform * Mat44::sScale(inScale);
  822. // Test if the shape is scaled inside out
  823. DebugRenderer::ECullMode cull_mode = ScaleHelpers::IsInsideOut(inScale)? DebugRenderer::ECullMode::CullFrontFace : DebugRenderer::ECullMode::CullBackFace;
  824. // Determine the draw mode
  825. DebugRenderer::EDrawMode draw_mode = inDrawWireframe? DebugRenderer::EDrawMode::Wireframe : DebugRenderer::EDrawMode::Solid;
  826. // Draw the geometry
  827. for (const DebugRenderer::GeometryRef &b : mGeometry)
  828. inRenderer->DrawGeometry(transform, inColor, b, cull_mode, DebugRenderer::ECastShadow::On, draw_mode);
  829. if (sDrawTriangleOutlines)
  830. {
  831. struct Visitor
  832. {
  833. JPH_INLINE explicit Visitor(const HeightFieldShape *inShape, DebugRenderer *inRenderer, Mat44Arg inTransform) :
  834. mShape(inShape),
  835. mRenderer(inRenderer),
  836. mTransform(inTransform)
  837. {
  838. }
  839. JPH_INLINE bool ShouldAbort() const
  840. {
  841. return false;
  842. }
  843. JPH_INLINE bool ShouldVisitRangeBlock([[maybe_unused]] int inStackTop) const
  844. {
  845. return true;
  846. }
  847. JPH_INLINE int VisitRangeBlock(Vec4Arg inBoundsMinX, Vec4Arg inBoundsMinY, Vec4Arg inBoundsMinZ, Vec4Arg inBoundsMaxX, Vec4Arg inBoundsMaxY, Vec4Arg inBoundsMaxZ, UVec4 &ioProperties, [[maybe_unused]] int inStackTop) const
  848. {
  849. UVec4 valid = UVec4::sOr(UVec4::sOr(Vec4::sLess(inBoundsMinX, inBoundsMaxX), Vec4::sLess(inBoundsMinY, inBoundsMaxY)), Vec4::sLess(inBoundsMinZ, inBoundsMaxZ));
  850. UVec4::sSort4True(valid, ioProperties);
  851. return valid.CountTrues();
  852. }
  853. JPH_INLINE void VisitTriangle(uint inX, uint inY, uint inTriangle, Vec3Arg inV0, Vec3Arg inV1, Vec3Arg inV2) const
  854. {
  855. // Determine active edges
  856. uint8 active_edges = mShape->GetEdgeFlags(inX, inY, inTriangle);
  857. // Loop through edges
  858. Vec3 v[] = { inV0, inV1, inV2 };
  859. for (uint edge_idx = 0; edge_idx < 3; ++edge_idx)
  860. {
  861. Vec3 v1 = mTransform * v[edge_idx];
  862. Vec3 v2 = mTransform * v[(edge_idx + 1) % 3];
  863. // Draw active edge as a green arrow, other edges as grey
  864. if (active_edges & (1 << edge_idx))
  865. mRenderer->DrawArrow(v1, v2, Color::sGreen, 0.01f);
  866. else
  867. mRenderer->DrawLine(v1, v2, Color::sGrey);
  868. }
  869. }
  870. const HeightFieldShape *mShape;
  871. DebugRenderer * mRenderer;
  872. Mat44 mTransform;
  873. };
  874. Visitor visitor(this, inRenderer, inCenterOfMassTransform * Mat44::sScale(inScale));
  875. WalkHeightField(visitor);
  876. }
  877. }
  878. #endif // JPH_DEBUG_RENDERER
  879. class HeightFieldShape::DecodingContext
  880. {
  881. public:
  882. JPH_INLINE explicit DecodingContext(const HeightFieldShape *inShape) :
  883. mShape(inShape)
  884. {
  885. static_assert(sizeof(sGridOffsets) / sizeof(uint) == cNumBitsXY + 1, "Offsets array is not long enough");
  886. // Construct root stack entry
  887. mPropertiesStack[0] = 0; // level: 0, x: 0, y: 0
  888. }
  889. template <class Visitor>
  890. JPH_INLINE void WalkHeightField(Visitor &ioVisitor)
  891. {
  892. // Early out if there's no collision
  893. if (mShape->mHeightSamples.empty())
  894. return;
  895. // Precalculate values relating to sample count
  896. uint32 sample_count = mShape->mSampleCount;
  897. UVec4 sample_count_min_1 = UVec4::sReplicate(sample_count - 1);
  898. // Precalculate values relating to block size
  899. uint32 block_size = mShape->mBlockSize;
  900. uint32 block_size_plus_1 = block_size + 1;
  901. uint num_blocks = mShape->GetNumBlocks();
  902. uint num_blocks_min_1 = num_blocks - 1;
  903. uint max_level = HeightFieldShape::sGetMaxLevel(num_blocks);
  904. // Precalculate range block offset and stride for GetBlockOffsetAndScale
  905. uint range_block_offset, range_block_stride;
  906. sGetRangeBlockOffsetAndStride(num_blocks, max_level, range_block_offset, range_block_stride);
  907. // Allocate space for vertices and 'no collision' flags
  908. int array_size = Square(block_size_plus_1);
  909. Vec3 *vertices = reinterpret_cast<Vec3 *>(alloca(array_size * sizeof(Vec3)));
  910. bool *no_collision = reinterpret_cast<bool *>(alloca(array_size * sizeof(bool)));
  911. // Splat offsets
  912. Vec4 ox = mShape->mOffset.SplatX();
  913. Vec4 oy = mShape->mOffset.SplatY();
  914. Vec4 oz = mShape->mOffset.SplatZ();
  915. // Splat scales
  916. Vec4 sx = mShape->mScale.SplatX();
  917. Vec4 sy = mShape->mScale.SplatY();
  918. Vec4 sz = mShape->mScale.SplatZ();
  919. do
  920. {
  921. // Decode properties
  922. uint32 properties_top = mPropertiesStack[mTop];
  923. uint32 x = properties_top & cMaskBitsXY;
  924. uint32 y = (properties_top >> cNumBitsXY) & cMaskBitsXY;
  925. uint32 level = properties_top >> cLevelShift;
  926. if (level >= max_level)
  927. {
  928. // Determine actual range of samples (minus one because we eventually want to iterate over the triangles, not the samples)
  929. uint32 min_x = x * block_size;
  930. uint32 max_x = min_x + block_size;
  931. uint32 min_y = y * block_size;
  932. uint32 max_y = min_y + block_size;
  933. // Decompress vertices of block at (x, y)
  934. Vec3 *dst_vertex = vertices;
  935. bool *dst_no_collision = no_collision;
  936. float block_offset, block_scale;
  937. mShape->GetBlockOffsetAndScale(x, y, range_block_offset, range_block_stride, block_offset, block_scale);
  938. for (uint32 v_y = min_y; v_y < max_y; ++v_y)
  939. {
  940. for (uint32 v_x = min_x; v_x < max_x; ++v_x)
  941. {
  942. *dst_vertex = mShape->GetPosition(v_x, v_y, block_offset, block_scale, *dst_no_collision);
  943. ++dst_vertex;
  944. ++dst_no_collision;
  945. }
  946. // Skip last column, these values come from a different block
  947. ++dst_vertex;
  948. ++dst_no_collision;
  949. }
  950. // Decompress block (x + 1, y)
  951. uint32 max_x_decrement = 0;
  952. if (x < num_blocks_min_1)
  953. {
  954. dst_vertex = vertices + block_size;
  955. dst_no_collision = no_collision + block_size;
  956. mShape->GetBlockOffsetAndScale(x + 1, y, range_block_offset, range_block_stride, block_offset, block_scale);
  957. for (uint32 v_y = min_y; v_y < max_y; ++v_y)
  958. {
  959. *dst_vertex = mShape->GetPosition(max_x, v_y, block_offset, block_scale, *dst_no_collision);
  960. dst_vertex += block_size_plus_1;
  961. dst_no_collision += block_size_plus_1;
  962. }
  963. }
  964. else
  965. max_x_decrement = 1; // We don't have a next block, one less triangle to test
  966. // Decompress block (x, y + 1)
  967. if (y < num_blocks_min_1)
  968. {
  969. uint start = block_size * block_size_plus_1;
  970. dst_vertex = vertices + start;
  971. dst_no_collision = no_collision + start;
  972. mShape->GetBlockOffsetAndScale(x, y + 1, range_block_offset, range_block_stride, block_offset, block_scale);
  973. for (uint32 v_x = min_x; v_x < max_x; ++v_x)
  974. {
  975. *dst_vertex = mShape->GetPosition(v_x, max_y, block_offset, block_scale, *dst_no_collision);
  976. ++dst_vertex;
  977. ++dst_no_collision;
  978. }
  979. // Decompress single sample of block at (x + 1, y + 1)
  980. if (x < num_blocks_min_1)
  981. {
  982. mShape->GetBlockOffsetAndScale(x + 1, y + 1, range_block_offset, range_block_stride, block_offset, block_scale);
  983. *dst_vertex = mShape->GetPosition(max_x, max_y, block_offset, block_scale, *dst_no_collision);
  984. }
  985. }
  986. else
  987. --max_y; // We don't have a next block, one less triangle to test
  988. // Update max_x (we've been using it so we couldn't update it earlier)
  989. max_x -= max_x_decrement;
  990. // We're going to divide the vertices in 4 blocks to do one more runtime sub-division, calculate the ranges of those blocks
  991. struct Range
  992. {
  993. uint32 mMinX, mMinY, mNumTrianglesX, mNumTrianglesY;
  994. };
  995. uint32 half_block_size = block_size >> 1;
  996. uint32 block_size_x = max_x - min_x - half_block_size;
  997. uint32 block_size_y = max_y - min_y - half_block_size;
  998. Range ranges[] =
  999. {
  1000. { 0, 0, half_block_size, half_block_size },
  1001. { half_block_size, 0, block_size_x, half_block_size },
  1002. { 0, half_block_size, half_block_size, block_size_y },
  1003. { half_block_size, half_block_size, block_size_x, block_size_y },
  1004. };
  1005. // Calculate the min and max of each of the blocks
  1006. Mat44 block_min, block_max;
  1007. for (int block = 0; block < 4; ++block)
  1008. {
  1009. // Get the range for this block
  1010. const Range &range = ranges[block];
  1011. uint32 start = range.mMinX + range.mMinY * block_size_plus_1;
  1012. uint32 size_x_plus_1 = range.mNumTrianglesX + 1;
  1013. uint32 size_y_plus_1 = range.mNumTrianglesY + 1;
  1014. // Calculate where to start reading
  1015. const Vec3 *src_vertex = vertices + start;
  1016. const bool *src_no_collision = no_collision + start;
  1017. uint32 stride = block_size_plus_1 - size_x_plus_1;
  1018. // Start range with a very large inside-out box
  1019. Vec3 value_min = Vec3::sReplicate(1.0e30f);
  1020. Vec3 value_max = Vec3::sReplicate(-1.0e30f);
  1021. // Loop over the samples to determine the min and max of this block
  1022. for (uint32 block_y = 0; block_y < size_y_plus_1; ++block_y)
  1023. {
  1024. for (uint32 block_x = 0; block_x < size_x_plus_1; ++block_x)
  1025. {
  1026. if (!*src_no_collision)
  1027. {
  1028. value_min = Vec3::sMin(value_min, *src_vertex);
  1029. value_max = Vec3::sMax(value_max, *src_vertex);
  1030. }
  1031. ++src_vertex;
  1032. ++src_no_collision;
  1033. }
  1034. src_vertex += stride;
  1035. src_no_collision += stride;
  1036. }
  1037. block_min.SetColumn4(block, Vec4(value_min));
  1038. block_max.SetColumn4(block, Vec4(value_max));
  1039. }
  1040. #ifdef JPH_DEBUG_HEIGHT_FIELD
  1041. // Draw the bounding boxes of the sub-nodes
  1042. for (int block = 0; block < 4; ++block)
  1043. {
  1044. AABox bounds(block_min.GetColumn3(block), block_max.GetColumn3(block));
  1045. if (bounds.IsValid())
  1046. DebugRenderer::sInstance->DrawWireBox(bounds, Color::sYellow);
  1047. }
  1048. #endif // JPH_DEBUG_HEIGHT_FIELD
  1049. // Transpose so we have the mins and maxes of each of the blocks in rows instead of columns
  1050. Mat44 transposed_min = block_min.Transposed();
  1051. Mat44 transposed_max = block_max.Transposed();
  1052. // Check which blocks collide
  1053. // Note: At this point we don't use our own stack but we do allow the visitor to use its own stack
  1054. // to store collision distances so that we can still early out when no closer hits have been found.
  1055. UVec4 colliding_blocks(0, 1, 2, 3);
  1056. int num_results = ioVisitor.VisitRangeBlock(transposed_min.GetColumn4(0), transposed_min.GetColumn4(1), transposed_min.GetColumn4(2), transposed_max.GetColumn4(0), transposed_max.GetColumn4(1), transposed_max.GetColumn4(2), colliding_blocks, mTop);
  1057. // Loop through the results backwards (closest first)
  1058. int result = num_results - 1;
  1059. while (result >= 0)
  1060. {
  1061. // Calculate the min and max of this block
  1062. uint32 block = colliding_blocks[result];
  1063. const Range &range = ranges[block];
  1064. uint32 block_min_x = min_x + range.mMinX;
  1065. uint32 block_max_x = block_min_x + range.mNumTrianglesX;
  1066. uint32 block_min_y = min_y + range.mMinY;
  1067. uint32 block_max_y = block_min_y + range.mNumTrianglesY;
  1068. // Loop triangles
  1069. for (uint32 v_y = block_min_y; v_y < block_max_y; ++v_y)
  1070. for (uint32 v_x = block_min_x; v_x < block_max_x; ++v_x)
  1071. {
  1072. // Get first vertex
  1073. const int offset = (v_y - min_y) * block_size_plus_1 + (v_x - min_x);
  1074. const Vec3 *start_vertex = vertices + offset;
  1075. const bool *start_no_collision = no_collision + offset;
  1076. // Check if vertices shared by both triangles have collision
  1077. if (!start_no_collision[0] && !start_no_collision[block_size_plus_1 + 1])
  1078. {
  1079. // Loop 2 triangles
  1080. for (uint t = 0; t < 2; ++t)
  1081. {
  1082. // Determine triangle vertices
  1083. Vec3 v0, v1, v2;
  1084. if (t == 0)
  1085. {
  1086. // Check third vertex
  1087. if (start_no_collision[block_size_plus_1])
  1088. continue;
  1089. // Get vertices for triangle
  1090. v0 = start_vertex[0];
  1091. v1 = start_vertex[block_size_plus_1];
  1092. v2 = start_vertex[block_size_plus_1 + 1];
  1093. }
  1094. else
  1095. {
  1096. // Check third vertex
  1097. if (start_no_collision[1])
  1098. continue;
  1099. // Get vertices for triangle
  1100. v0 = start_vertex[0];
  1101. v1 = start_vertex[block_size_plus_1 + 1];
  1102. v2 = start_vertex[1];
  1103. }
  1104. #ifdef JPH_DEBUG_HEIGHT_FIELD
  1105. DebugRenderer::sInstance->DrawWireTriangle(v0, v1, v2, Color::sWhite);
  1106. #endif
  1107. // Call visitor
  1108. ioVisitor.VisitTriangle(v_x, v_y, t, v0, v1, v2);
  1109. // Check if we're done
  1110. if (ioVisitor.ShouldAbort())
  1111. return;
  1112. }
  1113. }
  1114. }
  1115. // Fetch next block until we find one that the visitor wants to see
  1116. do
  1117. --result;
  1118. while (result >= 0 && !ioVisitor.ShouldVisitRangeBlock(mTop + result));
  1119. }
  1120. }
  1121. else
  1122. {
  1123. // Visit child grid
  1124. uint32 offset = sGridOffsets[level] + (1 << level) * y + x;
  1125. // Decode min/max height
  1126. UVec4 block = UVec4::sLoadInt4Aligned(reinterpret_cast<const uint32 *>(&mShape->mRangeBlocks[offset]));
  1127. Vec4 bounds_miny = oy + sy * block.Expand4Uint16Lo().ToFloat();
  1128. Vec4 bounds_maxy = oy + sy * block.Expand4Uint16Hi().ToFloat();
  1129. // Calculate size of one cell at this grid level
  1130. UVec4 internal_cell_size = UVec4::sReplicate(block_size << (max_level - level - 1)); // subtract 1 from level because we have an internal grid of 2x2
  1131. // Calculate min/max x and z
  1132. UVec4 two_x = UVec4::sReplicate(2 * x); // multiply by two because we have an internal grid of 2x2
  1133. Vec4 bounds_minx = ox + sx * (internal_cell_size * (two_x + UVec4(0, 1, 0, 1))).ToFloat();
  1134. Vec4 bounds_maxx = ox + sx * UVec4::sMin(internal_cell_size * (two_x + UVec4(1, 2, 1, 2)), sample_count_min_1).ToFloat();
  1135. UVec4 two_y = UVec4::sReplicate(2 * y);
  1136. Vec4 bounds_minz = oz + sz * (internal_cell_size * (two_y + UVec4(0, 0, 1, 1))).ToFloat();
  1137. Vec4 bounds_maxz = oz + sz * UVec4::sMin(internal_cell_size * (two_y + UVec4(1, 1, 2, 2)), sample_count_min_1).ToFloat();
  1138. // Calculate properties of child blocks
  1139. UVec4 properties = UVec4::sReplicate(((level + 1) << cLevelShift) + (y << (cNumBitsXY + 1)) + (x << 1)) + UVec4(0, 1, 1 << cNumBitsXY, (1 << cNumBitsXY) + 1);
  1140. #ifdef JPH_DEBUG_HEIGHT_FIELD
  1141. // Draw boxes
  1142. for (int i = 0; i < 4; ++i)
  1143. {
  1144. AABox b(Vec3(bounds_minx[i], bounds_miny[i], bounds_minz[i]), Vec3(bounds_maxx[i], bounds_maxy[i], bounds_maxz[i]));
  1145. if (b.IsValid())
  1146. DebugRenderer::sInstance->DrawWireBox(b, Color::sGreen);
  1147. }
  1148. #endif
  1149. // Check which sub nodes to visit
  1150. int num_results = ioVisitor.VisitRangeBlock(bounds_minx, bounds_miny, bounds_minz, bounds_maxx, bounds_maxy, bounds_maxz, properties, mTop);
  1151. // Push them onto the stack
  1152. JPH_ASSERT(mTop + 4 < cStackSize);
  1153. properties.StoreInt4(&mPropertiesStack[mTop]);
  1154. mTop += num_results;
  1155. }
  1156. // Check if we're done
  1157. if (ioVisitor.ShouldAbort())
  1158. return;
  1159. // Fetch next node until we find one that the visitor wants to see
  1160. do
  1161. --mTop;
  1162. while (mTop >= 0 && !ioVisitor.ShouldVisitRangeBlock(mTop));
  1163. }
  1164. while (mTop >= 0);
  1165. }
  1166. // This can be used to have the visitor early out (ioVisitor.ShouldAbort() returns true) and later continue again (call WalkHeightField() again)
  1167. JPH_INLINE bool IsDoneWalking() const
  1168. {
  1169. return mTop < 0;
  1170. }
  1171. private:
  1172. const HeightFieldShape * mShape;
  1173. int mTop = 0;
  1174. uint32 mPropertiesStack[cStackSize];
  1175. };
  1176. template <class Visitor>
  1177. JPH_INLINE void HeightFieldShape::WalkHeightField(Visitor &ioVisitor) const
  1178. {
  1179. DecodingContext ctx(this);
  1180. ctx.WalkHeightField(ioVisitor);
  1181. }
  1182. bool HeightFieldShape::CastRay(const RayCast &inRay, const SubShapeIDCreator &inSubShapeIDCreator, RayCastResult &ioHit) const
  1183. {
  1184. JPH_PROFILE_FUNCTION();
  1185. struct Visitor
  1186. {
  1187. JPH_INLINE explicit Visitor(const HeightFieldShape *inShape, const RayCast &inRay, const SubShapeIDCreator &inSubShapeIDCreator, RayCastResult &ioHit) :
  1188. mHit(ioHit),
  1189. mRayOrigin(inRay.mOrigin),
  1190. mRayDirection(inRay.mDirection),
  1191. mRayInvDirection(inRay.mDirection),
  1192. mShape(inShape),
  1193. mSubShapeIDCreator(inSubShapeIDCreator)
  1194. {
  1195. }
  1196. JPH_INLINE bool ShouldAbort() const
  1197. {
  1198. return mHit.mFraction <= 0.0f;
  1199. }
  1200. JPH_INLINE bool ShouldVisitRangeBlock(int inStackTop) const
  1201. {
  1202. return mDistanceStack[inStackTop] < mHit.mFraction;
  1203. }
  1204. JPH_INLINE int VisitRangeBlock(Vec4Arg inBoundsMinX, Vec4Arg inBoundsMinY, Vec4Arg inBoundsMinZ, Vec4Arg inBoundsMaxX, Vec4Arg inBoundsMaxY, Vec4Arg inBoundsMaxZ, UVec4 &ioProperties, int inStackTop)
  1205. {
  1206. // Test bounds of 4 children
  1207. Vec4 distance = RayAABox4(mRayOrigin, mRayInvDirection, inBoundsMinX, inBoundsMinY, inBoundsMinZ, inBoundsMaxX, inBoundsMaxY, inBoundsMaxZ);
  1208. // Sort so that highest values are first (we want to first process closer hits and we process stack top to bottom)
  1209. return SortReverseAndStore(distance, mHit.mFraction, ioProperties, &mDistanceStack[inStackTop]);
  1210. }
  1211. JPH_INLINE void VisitTriangle(uint inX, uint inY, uint inTriangle, Vec3Arg inV0, Vec3Arg inV1, Vec3Arg inV2)
  1212. {
  1213. float fraction = RayTriangle(mRayOrigin, mRayDirection, inV0, inV1, inV2);
  1214. if (fraction < mHit.mFraction)
  1215. {
  1216. // It's a closer hit
  1217. mHit.mFraction = fraction;
  1218. mHit.mSubShapeID2 = mShape->EncodeSubShapeID(mSubShapeIDCreator, inX, inY, inTriangle);
  1219. mReturnValue = true;
  1220. }
  1221. }
  1222. RayCastResult & mHit;
  1223. Vec3 mRayOrigin;
  1224. Vec3 mRayDirection;
  1225. RayInvDirection mRayInvDirection;
  1226. const HeightFieldShape *mShape;
  1227. SubShapeIDCreator mSubShapeIDCreator;
  1228. bool mReturnValue = false;
  1229. float mDistanceStack[cStackSize];
  1230. };
  1231. Visitor visitor(this, inRay, inSubShapeIDCreator, ioHit);
  1232. WalkHeightField(visitor);
  1233. return visitor.mReturnValue;
  1234. }
  1235. void HeightFieldShape::CastRay(const RayCast &inRay, const RayCastSettings &inRayCastSettings, const SubShapeIDCreator &inSubShapeIDCreator, CastRayCollector &ioCollector) const
  1236. {
  1237. JPH_PROFILE_FUNCTION();
  1238. struct Visitor
  1239. {
  1240. JPH_INLINE explicit Visitor(const HeightFieldShape *inShape, const RayCast &inRay, const RayCastSettings &inRayCastSettings, const SubShapeIDCreator &inSubShapeIDCreator, CastRayCollector &ioCollector) :
  1241. mCollector(ioCollector),
  1242. mRayOrigin(inRay.mOrigin),
  1243. mRayDirection(inRay.mDirection),
  1244. mRayInvDirection(inRay.mDirection),
  1245. mBackFaceMode(inRayCastSettings.mBackFaceMode),
  1246. mShape(inShape),
  1247. mSubShapeIDCreator(inSubShapeIDCreator)
  1248. {
  1249. }
  1250. JPH_INLINE bool ShouldAbort() const
  1251. {
  1252. return mCollector.ShouldEarlyOut();
  1253. }
  1254. JPH_INLINE bool ShouldVisitRangeBlock(int inStackTop) const
  1255. {
  1256. return mDistanceStack[inStackTop] < mCollector.GetEarlyOutFraction();
  1257. }
  1258. JPH_INLINE int VisitRangeBlock(Vec4Arg inBoundsMinX, Vec4Arg inBoundsMinY, Vec4Arg inBoundsMinZ, Vec4Arg inBoundsMaxX, Vec4Arg inBoundsMaxY, Vec4Arg inBoundsMaxZ, UVec4 &ioProperties, int inStackTop)
  1259. {
  1260. // Test bounds of 4 children
  1261. Vec4 distance = RayAABox4(mRayOrigin, mRayInvDirection, inBoundsMinX, inBoundsMinY, inBoundsMinZ, inBoundsMaxX, inBoundsMaxY, inBoundsMaxZ);
  1262. // Sort so that highest values are first (we want to first process closer hits and we process stack top to bottom)
  1263. return SortReverseAndStore(distance, mCollector.GetEarlyOutFraction(), ioProperties, &mDistanceStack[inStackTop]);
  1264. }
  1265. JPH_INLINE void VisitTriangle(uint inX, uint inY, uint inTriangle, Vec3Arg inV0, Vec3Arg inV1, Vec3Arg inV2) const
  1266. {
  1267. // Back facing check
  1268. if (mBackFaceMode == EBackFaceMode::IgnoreBackFaces && (inV2 - inV0).Cross(inV1 - inV0).Dot(mRayDirection) < 0)
  1269. return;
  1270. // Check the triangle
  1271. float fraction = RayTriangle(mRayOrigin, mRayDirection, inV0, inV1, inV2);
  1272. if (fraction < mCollector.GetEarlyOutFraction())
  1273. {
  1274. RayCastResult hit;
  1275. hit.mBodyID = TransformedShape::sGetBodyID(mCollector.GetContext());
  1276. hit.mFraction = fraction;
  1277. hit.mSubShapeID2 = mShape->EncodeSubShapeID(mSubShapeIDCreator, inX, inY, inTriangle);
  1278. mCollector.AddHit(hit);
  1279. }
  1280. }
  1281. CastRayCollector & mCollector;
  1282. Vec3 mRayOrigin;
  1283. Vec3 mRayDirection;
  1284. RayInvDirection mRayInvDirection;
  1285. EBackFaceMode mBackFaceMode;
  1286. const HeightFieldShape *mShape;
  1287. SubShapeIDCreator mSubShapeIDCreator;
  1288. float mDistanceStack[cStackSize];
  1289. };
  1290. Visitor visitor(this, inRay, inRayCastSettings, inSubShapeIDCreator, ioCollector);
  1291. WalkHeightField(visitor);
  1292. }
  1293. void HeightFieldShape::CollidePoint(Vec3Arg inPoint, const SubShapeIDCreator &inSubShapeIDCreator, CollidePointCollector &ioCollector) const
  1294. {
  1295. // A height field doesn't have volume, so we can't test insideness
  1296. }
  1297. void HeightFieldShape::sCastConvexVsHeightField(const ShapeCast &inShapeCast, const ShapeCastSettings &inShapeCastSettings, const Shape *inShape, Vec3Arg inScale, const ShapeFilter &inShapeFilter, Mat44Arg inCenterOfMassTransform2, const SubShapeIDCreator &inSubShapeIDCreator1, const SubShapeIDCreator &inSubShapeIDCreator2, CastShapeCollector &ioCollector)
  1298. {
  1299. JPH_PROFILE_FUNCTION();
  1300. struct Visitor : public CastConvexVsTriangles
  1301. {
  1302. using CastConvexVsTriangles::CastConvexVsTriangles;
  1303. JPH_INLINE bool ShouldAbort() const
  1304. {
  1305. return mCollector.ShouldEarlyOut();
  1306. }
  1307. JPH_INLINE bool ShouldVisitRangeBlock(int inStackTop) const
  1308. {
  1309. return mDistanceStack[inStackTop] < mCollector.GetEarlyOutFraction();
  1310. }
  1311. JPH_INLINE int VisitRangeBlock(Vec4Arg inBoundsMinX, Vec4Arg inBoundsMinY, Vec4Arg inBoundsMinZ, Vec4Arg inBoundsMaxX, Vec4Arg inBoundsMaxY, Vec4Arg inBoundsMaxZ, UVec4 &ioProperties, int inStackTop)
  1312. {
  1313. // Scale the bounding boxes of this node
  1314. Vec4 bounds_min_x, bounds_min_y, bounds_min_z, bounds_max_x, bounds_max_y, bounds_max_z;
  1315. AABox4Scale(mScale, inBoundsMinX, inBoundsMinY, inBoundsMinZ, inBoundsMaxX, inBoundsMaxY, inBoundsMaxZ, bounds_min_x, bounds_min_y, bounds_min_z, bounds_max_x, bounds_max_y, bounds_max_z);
  1316. // Enlarge them by the casted shape's box extents
  1317. AABox4EnlargeWithExtent(mBoxExtent, bounds_min_x, bounds_min_y, bounds_min_z, bounds_max_x, bounds_max_y, bounds_max_z);
  1318. // Test bounds of 4 children
  1319. Vec4 distance = RayAABox4(mBoxCenter, mInvDirection, bounds_min_x, bounds_min_y, bounds_min_z, bounds_max_x, bounds_max_y, bounds_max_z);
  1320. // Sort so that highest values are first (we want to first process closer hits and we process stack top to bottom)
  1321. return SortReverseAndStore(distance, mCollector.GetEarlyOutFraction(), ioProperties, &mDistanceStack[inStackTop]);
  1322. }
  1323. JPH_INLINE void VisitTriangle(uint inX, uint inY, uint inTriangle, Vec3Arg inV0, Vec3Arg inV1, Vec3Arg inV2)
  1324. {
  1325. // Create sub shape id for this part
  1326. SubShapeID triangle_sub_shape_id = mShape2->EncodeSubShapeID(mSubShapeIDCreator2, inX, inY, inTriangle);
  1327. // Determine active edges
  1328. uint8 active_edges = mShape2->GetEdgeFlags(inX, inY, inTriangle);
  1329. Cast(inV0, inV1, inV2, active_edges, triangle_sub_shape_id);
  1330. }
  1331. const HeightFieldShape * mShape2;
  1332. RayInvDirection mInvDirection;
  1333. Vec3 mBoxCenter;
  1334. Vec3 mBoxExtent;
  1335. SubShapeIDCreator mSubShapeIDCreator2;
  1336. float mDistanceStack[cStackSize];
  1337. };
  1338. JPH_ASSERT(inShape->GetSubType() == EShapeSubType::HeightField);
  1339. const HeightFieldShape *shape = static_cast<const HeightFieldShape *>(inShape);
  1340. Visitor visitor(inShapeCast, inShapeCastSettings, inScale, inShapeFilter, inCenterOfMassTransform2, inSubShapeIDCreator1, ioCollector);
  1341. visitor.mShape2 = shape;
  1342. visitor.mInvDirection.Set(inShapeCast.mDirection);
  1343. visitor.mBoxCenter = inShapeCast.mShapeWorldBounds.GetCenter();
  1344. visitor.mBoxExtent = inShapeCast.mShapeWorldBounds.GetExtent();
  1345. visitor.mSubShapeIDCreator2 = inSubShapeIDCreator2;
  1346. shape->WalkHeightField(visitor);
  1347. }
  1348. void HeightFieldShape::sCastSphereVsHeightField(const ShapeCast &inShapeCast, const ShapeCastSettings &inShapeCastSettings, const Shape *inShape, Vec3Arg inScale, const ShapeFilter &inShapeFilter, Mat44Arg inCenterOfMassTransform2, const SubShapeIDCreator &inSubShapeIDCreator1, const SubShapeIDCreator &inSubShapeIDCreator2, CastShapeCollector &ioCollector)
  1349. {
  1350. JPH_PROFILE_FUNCTION();
  1351. struct Visitor : public CastSphereVsTriangles
  1352. {
  1353. using CastSphereVsTriangles::CastSphereVsTriangles;
  1354. JPH_INLINE bool ShouldAbort() const
  1355. {
  1356. return mCollector.ShouldEarlyOut();
  1357. }
  1358. JPH_INLINE bool ShouldVisitRangeBlock(int inStackTop) const
  1359. {
  1360. return mDistanceStack[inStackTop] < mCollector.GetEarlyOutFraction();
  1361. }
  1362. JPH_INLINE int VisitRangeBlock(Vec4Arg inBoundsMinX, Vec4Arg inBoundsMinY, Vec4Arg inBoundsMinZ, Vec4Arg inBoundsMaxX, Vec4Arg inBoundsMaxY, Vec4Arg inBoundsMaxZ, UVec4 &ioProperties, int inStackTop)
  1363. {
  1364. // Scale the bounding boxes of this node
  1365. Vec4 bounds_min_x, bounds_min_y, bounds_min_z, bounds_max_x, bounds_max_y, bounds_max_z;
  1366. AABox4Scale(mScale, inBoundsMinX, inBoundsMinY, inBoundsMinZ, inBoundsMaxX, inBoundsMaxY, inBoundsMaxZ, bounds_min_x, bounds_min_y, bounds_min_z, bounds_max_x, bounds_max_y, bounds_max_z);
  1367. // Enlarge them by the radius of the sphere
  1368. AABox4EnlargeWithExtent(Vec3::sReplicate(mRadius), bounds_min_x, bounds_min_y, bounds_min_z, bounds_max_x, bounds_max_y, bounds_max_z);
  1369. // Test bounds of 4 children
  1370. Vec4 distance = RayAABox4(mStart, mInvDirection, bounds_min_x, bounds_min_y, bounds_min_z, bounds_max_x, bounds_max_y, bounds_max_z);
  1371. // Sort so that highest values are first (we want to first process closer hits and we process stack top to bottom)
  1372. return SortReverseAndStore(distance, mCollector.GetEarlyOutFraction(), ioProperties, &mDistanceStack[inStackTop]);
  1373. }
  1374. JPH_INLINE void VisitTriangle(uint inX, uint inY, uint inTriangle, Vec3Arg inV0, Vec3Arg inV1, Vec3Arg inV2)
  1375. {
  1376. // Create sub shape id for this part
  1377. SubShapeID triangle_sub_shape_id = mShape2->EncodeSubShapeID(mSubShapeIDCreator2, inX, inY, inTriangle);
  1378. // Determine active edges
  1379. uint8 active_edges = mShape2->GetEdgeFlags(inX, inY, inTriangle);
  1380. Cast(inV0, inV1, inV2, active_edges, triangle_sub_shape_id);
  1381. }
  1382. const HeightFieldShape * mShape2;
  1383. RayInvDirection mInvDirection;
  1384. SubShapeIDCreator mSubShapeIDCreator2;
  1385. float mDistanceStack[cStackSize];
  1386. };
  1387. JPH_ASSERT(inShape->GetSubType() == EShapeSubType::HeightField);
  1388. const HeightFieldShape *shape = static_cast<const HeightFieldShape *>(inShape);
  1389. Visitor visitor(inShapeCast, inShapeCastSettings, inScale, inShapeFilter, inCenterOfMassTransform2, inSubShapeIDCreator1, ioCollector);
  1390. visitor.mShape2 = shape;
  1391. visitor.mInvDirection.Set(inShapeCast.mDirection);
  1392. visitor.mSubShapeIDCreator2 = inSubShapeIDCreator2;
  1393. shape->WalkHeightField(visitor);
  1394. }
  1395. struct HeightFieldShape::HSGetTrianglesContext
  1396. {
  1397. HSGetTrianglesContext(const HeightFieldShape *inShape, const AABox &inBox, Vec3Arg inPositionCOM, QuatArg inRotation, Vec3Arg inScale) :
  1398. mDecodeCtx(inShape),
  1399. mShape(inShape),
  1400. mLocalBox(Mat44::sInverseRotationTranslation(inRotation, inPositionCOM), inBox),
  1401. mHeightFieldScale(inScale),
  1402. mLocalToWorld(Mat44::sRotationTranslation(inRotation, inPositionCOM) * Mat44::sScale(inScale)),
  1403. mIsInsideOut(ScaleHelpers::IsInsideOut(inScale))
  1404. {
  1405. }
  1406. bool ShouldAbort() const
  1407. {
  1408. return mShouldAbort;
  1409. }
  1410. bool ShouldVisitRangeBlock([[maybe_unused]] int inStackTop) const
  1411. {
  1412. return true;
  1413. }
  1414. int VisitRangeBlock(Vec4Arg inBoundsMinX, Vec4Arg inBoundsMinY, Vec4Arg inBoundsMinZ, Vec4Arg inBoundsMaxX, Vec4Arg inBoundsMaxY, Vec4Arg inBoundsMaxZ, UVec4 &ioProperties, [[maybe_unused]] int inStackTop) const
  1415. {
  1416. // Scale the bounding boxes of this node
  1417. Vec4 bounds_min_x, bounds_min_y, bounds_min_z, bounds_max_x, bounds_max_y, bounds_max_z;
  1418. AABox4Scale(mHeightFieldScale, inBoundsMinX, inBoundsMinY, inBoundsMinZ, inBoundsMaxX, inBoundsMaxY, inBoundsMaxZ, bounds_min_x, bounds_min_y, bounds_min_z, bounds_max_x, bounds_max_y, bounds_max_z);
  1419. // Test which nodes collide
  1420. UVec4 collides = AABox4VsBox(mLocalBox, bounds_min_x, bounds_min_y, bounds_min_z, bounds_max_x, bounds_max_y, bounds_max_z);
  1421. // Sort so the colliding ones go first
  1422. UVec4::sSort4True(collides, ioProperties);
  1423. // Return number of hits
  1424. return collides.CountTrues();
  1425. }
  1426. void VisitTriangle(uint inX, uint inY, [[maybe_unused]] uint inTriangle, Vec3Arg inV0, Vec3Arg inV1, Vec3Arg inV2)
  1427. {
  1428. // When the buffer is full and we cannot process the triangles, abort the height field walk. The next time GetTrianglesNext is called we will continue here.
  1429. if (mNumTrianglesFound + 1 > mMaxTrianglesRequested)
  1430. {
  1431. mShouldAbort = true;
  1432. return;
  1433. }
  1434. // Store vertices as Float3
  1435. if (mIsInsideOut)
  1436. {
  1437. // Reverse vertices
  1438. (mLocalToWorld * inV0).StoreFloat3(mTriangleVertices++);
  1439. (mLocalToWorld * inV2).StoreFloat3(mTriangleVertices++);
  1440. (mLocalToWorld * inV1).StoreFloat3(mTriangleVertices++);
  1441. }
  1442. else
  1443. {
  1444. // Normal scale
  1445. (mLocalToWorld * inV0).StoreFloat3(mTriangleVertices++);
  1446. (mLocalToWorld * inV1).StoreFloat3(mTriangleVertices++);
  1447. (mLocalToWorld * inV2).StoreFloat3(mTriangleVertices++);
  1448. }
  1449. // Decode material
  1450. if (mMaterials != nullptr)
  1451. *mMaterials++ = mShape->GetMaterial(inX, inY);
  1452. // Accumulate triangles found
  1453. mNumTrianglesFound++;
  1454. }
  1455. DecodingContext mDecodeCtx;
  1456. const HeightFieldShape * mShape;
  1457. OrientedBox mLocalBox;
  1458. Vec3 mHeightFieldScale;
  1459. Mat44 mLocalToWorld;
  1460. int mMaxTrianglesRequested;
  1461. Float3 * mTriangleVertices;
  1462. int mNumTrianglesFound;
  1463. const PhysicsMaterial ** mMaterials;
  1464. bool mShouldAbort;
  1465. bool mIsInsideOut;
  1466. };
  1467. void HeightFieldShape::GetTrianglesStart(GetTrianglesContext &ioContext, const AABox &inBox, Vec3Arg inPositionCOM, QuatArg inRotation, Vec3Arg inScale) const
  1468. {
  1469. static_assert(sizeof(HSGetTrianglesContext) <= sizeof(GetTrianglesContext), "GetTrianglesContext too small");
  1470. JPH_ASSERT(IsAligned(&ioContext, alignof(HSGetTrianglesContext)));
  1471. new (&ioContext) HSGetTrianglesContext(this, inBox, inPositionCOM, inRotation, inScale);
  1472. }
  1473. int HeightFieldShape::GetTrianglesNext(GetTrianglesContext &ioContext, int inMaxTrianglesRequested, Float3 *outTriangleVertices, const PhysicsMaterial **outMaterials) const
  1474. {
  1475. static_assert(cGetTrianglesMinTrianglesRequested >= 1, "cGetTrianglesMinTrianglesRequested is too small");
  1476. JPH_ASSERT(inMaxTrianglesRequested >= cGetTrianglesMinTrianglesRequested);
  1477. // Check if we're done
  1478. HSGetTrianglesContext &context = (HSGetTrianglesContext &)ioContext;
  1479. if (context.mDecodeCtx.IsDoneWalking())
  1480. return 0;
  1481. // Store parameters on context
  1482. context.mMaxTrianglesRequested = inMaxTrianglesRequested;
  1483. context.mTriangleVertices = outTriangleVertices;
  1484. context.mMaterials = outMaterials;
  1485. context.mShouldAbort = false; // Reset the abort flag
  1486. context.mNumTrianglesFound = 0;
  1487. // Continue (or start) walking the height field
  1488. context.mDecodeCtx.WalkHeightField(context);
  1489. return context.mNumTrianglesFound;
  1490. }
  1491. void HeightFieldShape::sCollideConvexVsHeightField(const Shape *inShape1, const Shape *inShape2, Vec3Arg inScale1, Vec3Arg inScale2, Mat44Arg inCenterOfMassTransform1, Mat44Arg inCenterOfMassTransform2, const SubShapeIDCreator &inSubShapeIDCreator1, const SubShapeIDCreator &inSubShapeIDCreator2, const CollideShapeSettings &inCollideShapeSettings, CollideShapeCollector &ioCollector)
  1492. {
  1493. JPH_PROFILE_FUNCTION();
  1494. // Get the shapes
  1495. JPH_ASSERT(inShape1->GetType() == EShapeType::Convex);
  1496. JPH_ASSERT(inShape2->GetType() == EShapeType::HeightField);
  1497. const ConvexShape *shape1 = static_cast<const ConvexShape *>(inShape1);
  1498. const HeightFieldShape *shape2 = static_cast<const HeightFieldShape *>(inShape2);
  1499. struct Visitor : public CollideConvexVsTriangles
  1500. {
  1501. using CollideConvexVsTriangles::CollideConvexVsTriangles;
  1502. JPH_INLINE bool ShouldAbort() const
  1503. {
  1504. return mCollector.ShouldEarlyOut();
  1505. }
  1506. JPH_INLINE bool ShouldVisitRangeBlock([[maybe_unused]] int inStackTop) const
  1507. {
  1508. return true;
  1509. }
  1510. JPH_INLINE int VisitRangeBlock(Vec4Arg inBoundsMinX, Vec4Arg inBoundsMinY, Vec4Arg inBoundsMinZ, Vec4Arg inBoundsMaxX, Vec4Arg inBoundsMaxY, Vec4Arg inBoundsMaxZ, UVec4 &ioProperties, [[maybe_unused]] int inStackTop) const
  1511. {
  1512. // Scale the bounding boxes of this node
  1513. Vec4 bounds_min_x, bounds_min_y, bounds_min_z, bounds_max_x, bounds_max_y, bounds_max_z;
  1514. AABox4Scale(mScale2, inBoundsMinX, inBoundsMinY, inBoundsMinZ, inBoundsMaxX, inBoundsMaxY, inBoundsMaxZ, bounds_min_x, bounds_min_y, bounds_min_z, bounds_max_x, bounds_max_y, bounds_max_z);
  1515. // Test which nodes collide
  1516. UVec4 collides = AABox4VsBox(mBoundsOf1InSpaceOf2, bounds_min_x, bounds_min_y, bounds_min_z, bounds_max_x, bounds_max_y, bounds_max_z);
  1517. // Sort so the colliding ones go first
  1518. UVec4::sSort4True(collides, ioProperties);
  1519. // Return number of hits
  1520. return collides.CountTrues();
  1521. }
  1522. JPH_INLINE void VisitTriangle(uint inX, uint inY, uint inTriangle, Vec3Arg inV0, Vec3Arg inV1, Vec3Arg inV2)
  1523. {
  1524. // Create ID for triangle
  1525. SubShapeID triangle_sub_shape_id = mShape2->EncodeSubShapeID(mSubShapeIDCreator2, inX, inY, inTriangle);
  1526. // Determine active edges
  1527. uint8 active_edges = mShape2->GetEdgeFlags(inX, inY, inTriangle);
  1528. Collide(inV0, inV1, inV2, active_edges, triangle_sub_shape_id);
  1529. }
  1530. const HeightFieldShape * mShape2;
  1531. SubShapeIDCreator mSubShapeIDCreator2;
  1532. };
  1533. Visitor visitor(shape1, inScale1, inScale2, inCenterOfMassTransform1, inCenterOfMassTransform2, inSubShapeIDCreator1.GetID(), inCollideShapeSettings, ioCollector);
  1534. visitor.mShape2 = shape2;
  1535. visitor.mSubShapeIDCreator2 = inSubShapeIDCreator2;
  1536. shape2->WalkHeightField(visitor);
  1537. }
  1538. void HeightFieldShape::sCollideSphereVsHeightField(const Shape *inShape1, const Shape *inShape2, Vec3Arg inScale1, Vec3Arg inScale2, Mat44Arg inCenterOfMassTransform1, Mat44Arg inCenterOfMassTransform2, const SubShapeIDCreator &inSubShapeIDCreator1, const SubShapeIDCreator &inSubShapeIDCreator2, const CollideShapeSettings &inCollideShapeSettings, CollideShapeCollector &ioCollector)
  1539. {
  1540. JPH_PROFILE_FUNCTION();
  1541. // Get the shapes
  1542. JPH_ASSERT(inShape1->GetSubType() == EShapeSubType::Sphere);
  1543. JPH_ASSERT(inShape2->GetType() == EShapeType::HeightField);
  1544. const SphereShape *shape1 = static_cast<const SphereShape *>(inShape1);
  1545. const HeightFieldShape *shape2 = static_cast<const HeightFieldShape *>(inShape2);
  1546. struct Visitor : public CollideSphereVsTriangles
  1547. {
  1548. using CollideSphereVsTriangles::CollideSphereVsTriangles;
  1549. JPH_INLINE bool ShouldAbort() const
  1550. {
  1551. return mCollector.ShouldEarlyOut();
  1552. }
  1553. JPH_INLINE bool ShouldVisitRangeBlock([[maybe_unused]] int inStackTop) const
  1554. {
  1555. return true;
  1556. }
  1557. JPH_INLINE int VisitRangeBlock(Vec4Arg inBoundsMinX, Vec4Arg inBoundsMinY, Vec4Arg inBoundsMinZ, Vec4Arg inBoundsMaxX, Vec4Arg inBoundsMaxY, Vec4Arg inBoundsMaxZ, UVec4 &ioProperties, [[maybe_unused]] int inStackTop) const
  1558. {
  1559. // Scale the bounding boxes of this node
  1560. Vec4 bounds_min_x, bounds_min_y, bounds_min_z, bounds_max_x, bounds_max_y, bounds_max_z;
  1561. AABox4Scale(mScale2, inBoundsMinX, inBoundsMinY, inBoundsMinZ, inBoundsMaxX, inBoundsMaxY, inBoundsMaxZ, bounds_min_x, bounds_min_y, bounds_min_z, bounds_max_x, bounds_max_y, bounds_max_z);
  1562. // Test which nodes collide
  1563. UVec4 collides = AABox4VsSphere(mSphereCenterIn2, mRadiusPlusMaxSeparationSq, bounds_min_x, bounds_min_y, bounds_min_z, bounds_max_x, bounds_max_y, bounds_max_z);
  1564. // Sort so the colliding ones go first
  1565. UVec4::sSort4True(collides, ioProperties);
  1566. // Return number of hits
  1567. return collides.CountTrues();
  1568. }
  1569. JPH_INLINE void VisitTriangle(uint inX, uint inY, uint inTriangle, Vec3Arg inV0, Vec3Arg inV1, Vec3Arg inV2)
  1570. {
  1571. // Create ID for triangle
  1572. SubShapeID triangle_sub_shape_id = mShape2->EncodeSubShapeID(mSubShapeIDCreator2, inX, inY, inTriangle);
  1573. // Determine active edges
  1574. uint8 active_edges = mShape2->GetEdgeFlags(inX, inY, inTriangle);
  1575. Collide(inV0, inV1, inV2, active_edges, triangle_sub_shape_id);
  1576. }
  1577. const HeightFieldShape * mShape2;
  1578. SubShapeIDCreator mSubShapeIDCreator2;
  1579. };
  1580. Visitor visitor(shape1, inScale1, inScale2, inCenterOfMassTransform1, inCenterOfMassTransform2, inSubShapeIDCreator1.GetID(), inCollideShapeSettings, ioCollector);
  1581. visitor.mShape2 = shape2;
  1582. visitor.mSubShapeIDCreator2 = inSubShapeIDCreator2;
  1583. shape2->WalkHeightField(visitor);
  1584. }
  1585. void HeightFieldShape::SaveBinaryState(StreamOut &inStream) const
  1586. {
  1587. Shape::SaveBinaryState(inStream);
  1588. inStream.Write(mOffset);
  1589. inStream.Write(mScale);
  1590. inStream.Write(mSampleCount);
  1591. inStream.Write(mBlockSize);
  1592. inStream.Write(mBitsPerSample);
  1593. inStream.Write(mMinSample);
  1594. inStream.Write(mMaxSample);
  1595. inStream.Write(mRangeBlocks);
  1596. inStream.Write(mHeightSamples);
  1597. inStream.Write(mActiveEdges);
  1598. inStream.Write(mMaterialIndices);
  1599. inStream.Write(mNumBitsPerMaterialIndex);
  1600. }
  1601. void HeightFieldShape::RestoreBinaryState(StreamIn &inStream)
  1602. {
  1603. Shape::RestoreBinaryState(inStream);
  1604. inStream.Read(mOffset);
  1605. inStream.Read(mScale);
  1606. inStream.Read(mSampleCount);
  1607. inStream.Read(mBlockSize);
  1608. inStream.Read(mBitsPerSample);
  1609. inStream.Read(mMinSample);
  1610. inStream.Read(mMaxSample);
  1611. inStream.Read(mRangeBlocks);
  1612. inStream.Read(mHeightSamples);
  1613. inStream.Read(mActiveEdges);
  1614. inStream.Read(mMaterialIndices);
  1615. inStream.Read(mNumBitsPerMaterialIndex);
  1616. CacheValues();
  1617. }
  1618. void HeightFieldShape::SaveMaterialState(PhysicsMaterialList &outMaterials) const
  1619. {
  1620. outMaterials = mMaterials;
  1621. }
  1622. void HeightFieldShape::RestoreMaterialState(const PhysicsMaterialRefC *inMaterials, uint inNumMaterials)
  1623. {
  1624. mMaterials.assign(inMaterials, inMaterials + inNumMaterials);
  1625. }
  1626. Shape::Stats HeightFieldShape::GetStats() const
  1627. {
  1628. return Stats(
  1629. sizeof(*this)
  1630. + mMaterials.size() * sizeof(Ref<PhysicsMaterial>)
  1631. + mRangeBlocks.size() * sizeof(RangeBlock)
  1632. + mHeightSamples.size() * sizeof(uint8)
  1633. + mActiveEdges.size() * sizeof(uint8)
  1634. + mMaterialIndices.size() * sizeof(uint8),
  1635. mHeightSamples.empty()? 0 : Square(mSampleCount - 1) * 2);
  1636. }
  1637. void HeightFieldShape::sRegister()
  1638. {
  1639. ShapeFunctions &f = ShapeFunctions::sGet(EShapeSubType::HeightField);
  1640. f.mConstruct = []() -> Shape * { return new HeightFieldShape; };
  1641. f.mColor = Color::sPurple;
  1642. for (EShapeSubType s : sConvexSubShapeTypes)
  1643. {
  1644. CollisionDispatch::sRegisterCollideShape(s, EShapeSubType::HeightField, sCollideConvexVsHeightField);
  1645. CollisionDispatch::sRegisterCastShape(s, EShapeSubType::HeightField, sCastConvexVsHeightField);
  1646. }
  1647. // Specialized collision functions
  1648. CollisionDispatch::sRegisterCollideShape(EShapeSubType::Sphere, EShapeSubType::HeightField, sCollideSphereVsHeightField);
  1649. CollisionDispatch::sRegisterCastShape(EShapeSubType::Sphere, EShapeSubType::HeightField, sCastSphereVsHeightField);
  1650. }
  1651. } // JPH