HeightFieldShape.cpp 70 KB

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