HeightFieldShape.cpp 66 KB

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