HeightFieldShape.cpp 59 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728
  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/RayCast.h>
  8. #include <Physics/Collision/ShapeCast.h>
  9. #include <Physics/Collision/CastResult.h>
  10. #include <Physics/Collision/CollidePointResult.h>
  11. #include <Physics/Collision/ShapeFilter.h>
  12. #include <Physics/Collision/CastConvexVsTriangles.h>
  13. #include <Physics/Collision/CollideConvexVsTriangles.h>
  14. #include <Physics/Collision/TransformedShape.h>
  15. #include <Physics/Collision/ActiveEdges.h>
  16. #include <Core/Profiler.h>
  17. #include <Core/StringTools.h>
  18. #include <Core/StreamIn.h>
  19. #include <Core/StreamOut.h>
  20. #include <Geometry/AABox4.h>
  21. #include <Geometry/RayTriangle.h>
  22. #include <Geometry/RayAABox.h>
  23. #include <Geometry/OrientedBox.h>
  24. #include <ObjectStream/TypeDeclarations.h>
  25. //#define JPH_DEBUG_HEIGHT_FIELD
  26. namespace JPH {
  27. #ifdef JPH_DEBUG_RENDERER
  28. bool HeightFieldShape::sDrawTriangleOutlines = false;
  29. #endif // JPH_DEBUG_RENDERER
  30. using namespace HeightFieldShapeConstants;
  31. JPH_IMPLEMENT_SERIALIZABLE_VIRTUAL(HeightFieldShapeSettings)
  32. {
  33. JPH_ADD_BASE_CLASS(HeightFieldShapeSettings, ShapeSettings)
  34. JPH_ADD_ATTRIBUTE(HeightFieldShapeSettings, mHeightSamples)
  35. JPH_ADD_ATTRIBUTE(HeightFieldShapeSettings, mOffset)
  36. JPH_ADD_ATTRIBUTE(HeightFieldShapeSettings, mScale)
  37. JPH_ADD_ATTRIBUTE(HeightFieldShapeSettings, mSampleCount)
  38. JPH_ADD_ATTRIBUTE(HeightFieldShapeSettings, mBlockSize)
  39. JPH_ADD_ATTRIBUTE(HeightFieldShapeSettings, mBitsPerSample)
  40. JPH_ADD_ATTRIBUTE(HeightFieldShapeSettings, mMaterialIndices)
  41. JPH_ADD_ATTRIBUTE(HeightFieldShapeSettings, mMaterials)
  42. }
  43. JPH_IMPLEMENT_RTTI_VIRTUAL(HeightFieldShape)
  44. {
  45. JPH_ADD_BASE_CLASS(HeightFieldShape, Shape)
  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(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 < 1 || mBlockSize > 4)
  275. {
  276. outResult.SetError("HeightFieldShape: Block size must be in the range [1, 4]!");
  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, mHeightSamples 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. // Quantize to uint16
  345. vector<uint16> quantized_samples;
  346. quantized_samples.reserve(mSampleCount * mSampleCount);
  347. for (float h : inSettings.mHeightSamples)
  348. if (h == cNoCollisionValue)
  349. {
  350. quantized_samples.push_back(cNoCollisionValue16);
  351. }
  352. else
  353. {
  354. // Floor the quantized height to get a lower bound for the quantized value
  355. int quantized_height = (int)floor(scale * (h - min_value));
  356. // 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
  357. quantized_height = Clamp(quantized_height, 0, int(cMaxHeightValue16 - 1));
  358. quantized_samples.push_back(uint16(quantized_height));
  359. }
  360. // Update offset and scale to account for the compression to uint16
  361. if (min_value <= max_value) // Only when there was collision
  362. {
  363. // In GetPosition we always add 0.5 to the quantized sample in order to reduce the average error.
  364. // 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.
  365. min_value -= 0.5f / (scale * mSampleMask);
  366. mOffset.SetY(mOffset.GetY() + mScale.GetY() * min_value);
  367. }
  368. mScale.SetY(mScale.GetY() / scale);
  369. // Calculate amount of grids
  370. uint max_level = sGetMaxLevel(n);
  371. // Temporary data structure used during creating of a hierarchy of grids
  372. struct Range
  373. {
  374. uint16 mMin;
  375. uint16 mMax;
  376. };
  377. // 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
  378. vector<vector<Range>> ranges;
  379. ranges.resize(max_level + 1);
  380. // Calculate highest detail grid by combining mBlockSize x mBlockSize height samples
  381. vector<Range> *cur_range_vector = &ranges.back();
  382. cur_range_vector->resize(n * n);
  383. Range *range_dst = &cur_range_vector->front();
  384. for (uint y = 0; y < n; ++y)
  385. for (uint x = 0; x < n; ++x)
  386. {
  387. range_dst->mMin = 0xffff;
  388. range_dst->mMax = 0;
  389. 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
  390. uint max_by = y == n - 1? mBlockSize : mBlockSize + 1;
  391. for (uint by = 0; by < max_by; ++by)
  392. for (uint bx = 0; bx < max_bx; ++bx)
  393. {
  394. uint16 h = quantized_samples[(y * mBlockSize + by) * mSampleCount + (x * mBlockSize + bx)];
  395. if (h != cNoCollisionValue16)
  396. {
  397. range_dst->mMin = min(range_dst->mMin, h);
  398. 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
  399. }
  400. }
  401. ++range_dst;
  402. }
  403. // Calculate remaining grids
  404. while (n > 1)
  405. {
  406. // Get source buffer
  407. const Range *range_src = &cur_range_vector->front();
  408. // Previous array element
  409. --cur_range_vector;
  410. // Make space for this grid
  411. n >>= 1;
  412. cur_range_vector->resize(n * n);
  413. // Get target buffer
  414. range_dst = &cur_range_vector->front();
  415. // Combine the results of 2x2 ranges
  416. for (uint y = 0; y < n; ++y)
  417. for (uint x = 0; x < n; ++x)
  418. {
  419. range_dst->mMin = 0xffff;
  420. range_dst->mMax = 0;
  421. for (uint by = 0; by < 2; ++by)
  422. for (uint bx = 0; bx < 2; ++bx)
  423. {
  424. const Range &r = range_src[(y * 2 + by) * n * 2 + x * 2 + bx];
  425. range_dst->mMin = min(range_dst->mMin, r.mMin);
  426. range_dst->mMax = max(range_dst->mMax, r.mMax);
  427. }
  428. ++range_dst;
  429. }
  430. }
  431. JPH_ASSERT(cur_range_vector == &ranges.front());
  432. // Store global range for bounding box calculation
  433. mMinSample = ranges[0][0].mMin;
  434. mMaxSample = ranges[0][0].mMax;
  435. #ifdef JPH_ENABLE_ASSERTS
  436. // Validate that we did not lose range along the way
  437. uint16 minv = 0xffff, maxv = 0;
  438. for (uint16 v : quantized_samples)
  439. if (v != cNoCollisionValue16)
  440. {
  441. minv = min(minv, v);
  442. maxv = max(maxv, uint16(v + 1));
  443. }
  444. JPH_ASSERT(mMinSample == minv && mMaxSample == maxv);
  445. #endif
  446. // Now erase the first element, we need a 2x2 grid to start with
  447. ranges.erase(ranges.begin());
  448. // Create blocks
  449. mRangeBlocks.reserve(sGridOffsets[ranges.size()]);
  450. for (uint level = 0; level < ranges.size(); ++level)
  451. {
  452. JPH_ASSERT(mRangeBlocks.size() == sGridOffsets[level]);
  453. n = 1 << level;
  454. for (uint y = 0; y < n; ++y)
  455. for (uint x = 0; x < n; ++x)
  456. {
  457. // Convert from 2x2 Range structure to 1 RangeBlock structure
  458. RangeBlock rb;
  459. for (uint by = 0; by < 2; ++by)
  460. for (uint bx = 0; bx < 2; ++bx)
  461. {
  462. uint src_pos = (y * 2 + by) * n * 2 + (x * 2 + bx);
  463. uint dst_pos = by * 2 + bx;
  464. rb.mMin[dst_pos] = ranges[level][src_pos].mMin;
  465. rb.mMax[dst_pos] = ranges[level][src_pos].mMax;
  466. }
  467. // Add this block
  468. mRangeBlocks.push_back(rb);
  469. }
  470. }
  471. JPH_ASSERT(mRangeBlocks.size() == sGridOffsets[ranges.size()]);
  472. // Quantize height samples
  473. mHeightSamples.resize((mSampleCount * mSampleCount * inSettings.mBitsPerSample + 7) / 8 + 1);
  474. int sample = 0;
  475. for (uint y = 0; y < mSampleCount; ++y)
  476. for (uint x = 0; x < mSampleCount; ++x)
  477. {
  478. uint32 output_value;
  479. float h = inSettings.mHeightSamples[y * mSampleCount + x];
  480. if (h == cNoCollisionValue)
  481. {
  482. // No collision
  483. output_value = mSampleMask;
  484. }
  485. else
  486. {
  487. // Get range of block so we know what range to compress to
  488. uint bx = x / mBlockSize;
  489. uint by = y / mBlockSize;
  490. const Range &range = ranges.back()[by * (mSampleCount / mBlockSize) + bx];
  491. JPH_ASSERT(range.mMin < range.mMax);
  492. // Quantize to mBitsPerSample bits, note that mSampleMask is reserved for indicating that there's no collision.
  493. // We divide the range into mSampleMask segments and use the mid points of these segments as the quantized values.
  494. // This results in a lower error than if we had quantized our data using the lowest point of all these segments.
  495. float h_min = min_value + range.mMin / scale;
  496. float h_delta = float(range.mMax - range.mMin) / scale;
  497. float quantized_height = floor((h - h_min) * float(mSampleMask) / h_delta);
  498. output_value = uint32(Clamp((int)quantized_height, 0, int(mSampleMask) - 1)); // mSampleMask is reserved as 'no collision value'
  499. }
  500. // Store the sample
  501. uint byte_pos = sample >> 3;
  502. uint bit_pos = sample & 0b111;
  503. output_value <<= bit_pos;
  504. mHeightSamples[byte_pos] |= uint8(output_value);
  505. mHeightSamples[byte_pos + 1] |= uint8(output_value >> 8);
  506. sample += inSettings.mBitsPerSample;
  507. }
  508. // Calculate the active edges
  509. CalculateActiveEdges();
  510. // Compress material indices
  511. if (mMaterials.size() > 1)
  512. StoreMaterialIndices(inSettings.mMaterialIndices);
  513. outResult.Set(this);
  514. }
  515. inline void HeightFieldShape::sGetRangeBlockOffsetAndStride(uint inNumBlocks, uint inMaxLevel, uint &outRangeBlockOffset, uint &outRangeBlockStride)
  516. {
  517. outRangeBlockOffset = sGridOffsets[inMaxLevel - 1];
  518. outRangeBlockStride = inNumBlocks >> 1;
  519. }
  520. inline void HeightFieldShape::GetBlockOffsetAndScale(uint inBlockX, uint inBlockY, uint inRangeBlockOffset, uint inRangeBlockStride, float &outBlockOffset, float &outBlockScale) const
  521. {
  522. JPH_ASSERT(inBlockX < GetNumBlocks() && inBlockY < GetNumBlocks());
  523. // Convert to location of range block
  524. uint rbx = inBlockX >> 1;
  525. uint rby = inBlockY >> 1;
  526. uint n = ((inBlockY & 1) << 1) + (inBlockX & 1);
  527. // Calculate offset and scale
  528. const RangeBlock &block = mRangeBlocks[inRangeBlockOffset + rby * inRangeBlockStride + rbx];
  529. outBlockOffset = float(block.mMin[n]);
  530. outBlockScale = float(block.mMax[n] - block.mMin[n]) / float(mSampleMask);
  531. }
  532. inline uint8 HeightFieldShape::GetHeightSample(uint inX, uint inY) const
  533. {
  534. JPH_ASSERT(inX < mSampleCount);
  535. JPH_ASSERT(inY < mSampleCount);
  536. // Determine bit position of sample
  537. uint sample = (inY * mSampleCount + inX) * uint(mBitsPerSample);
  538. uint byte_pos = sample >> 3;
  539. uint bit_pos = sample & 0b111;
  540. // Fetch the height sample value
  541. JPH_ASSERT(byte_pos + 1 < mHeightSamples.size());
  542. const uint8 *height_samples = mHeightSamples.data() + byte_pos;
  543. uint16 height_sample = uint16(height_samples[0]) | uint16(uint16(height_samples[1]) << 8);
  544. return uint8(height_sample >> bit_pos) & mSampleMask;
  545. }
  546. inline Vec3 HeightFieldShape::GetPosition(uint inX, uint inY, float inBlockOffset, float inBlockScale, bool &outNoCollision) const
  547. {
  548. // Get quantized value
  549. uint8 height_sample = GetHeightSample(inX, inY);
  550. outNoCollision = height_sample == mSampleMask;
  551. // Add 0.5 to the quantized value to minimize the error (see constructor)
  552. return mOffset + mScale * Vec3(float(inX), inBlockOffset + (0.5f + height_sample) * inBlockScale, float(inY));
  553. }
  554. Vec3 HeightFieldShape::GetPosition(uint inX, uint inY) const
  555. {
  556. // Get block location
  557. uint bx = inX / mBlockSize;
  558. uint by = inY / mBlockSize;
  559. // Calculate offset and stride
  560. uint num_blocks = GetNumBlocks();
  561. uint range_block_offset, range_block_stride;
  562. sGetRangeBlockOffsetAndStride(num_blocks, sGetMaxLevel(num_blocks), range_block_offset, range_block_stride);
  563. float offset, scale;
  564. GetBlockOffsetAndScale(bx, by, range_block_offset, range_block_stride, offset, scale);
  565. bool no_collision;
  566. return GetPosition(inX, inY, offset, scale, no_collision);
  567. }
  568. bool HeightFieldShape::IsNoCollision(uint inX, uint inY) const
  569. {
  570. return GetHeightSample(inX, inY) == mSampleMask;
  571. }
  572. bool HeightFieldShape::ProjectOntoSurface(Vec3Arg inLocalPosition, Vec3 &outSurfacePosition, SubShapeID &outSubShapeID) const
  573. {
  574. // Convert coordinate to integer space
  575. Vec3 integer_space = (inLocalPosition - mOffset) / mScale;
  576. // Get x coordinate and fraction
  577. float x_frac = integer_space.GetX();
  578. if (x_frac < 0.0f || x_frac >= mSampleCount - 1)
  579. return false;
  580. uint x = (uint)floor(x_frac);
  581. x_frac -= x;
  582. // Get y coordinate and fraction
  583. float y_frac = integer_space.GetZ();
  584. if (y_frac < 0.0f || y_frac >= mSampleCount - 1)
  585. return false;
  586. uint y = (uint)floor(y_frac);
  587. y_frac -= y;
  588. // If one of the diagonal points doesn't have collision, we don't have a height at this location
  589. if (IsNoCollision(x, y) || IsNoCollision(x + 1, y + 1))
  590. return false;
  591. if (y_frac >= x_frac)
  592. {
  593. // Left bottom triangle, test the 3rd point
  594. if (IsNoCollision(x, y + 1))
  595. return false;
  596. // Interpolate height value
  597. Vec3 v1 = GetPosition(x, y);
  598. Vec3 v2 = GetPosition(x, y + 1);
  599. Vec3 v3 = GetPosition(x + 1, y + 1);
  600. outSurfacePosition = v1 + y_frac * (v2 - v1) + x_frac * (v3 - v2);
  601. SubShapeIDCreator creator;
  602. outSubShapeID = EncodeSubShapeID(creator, x, y, 0);
  603. return true;
  604. }
  605. else
  606. {
  607. // Right top triangle, test the third point
  608. if (IsNoCollision(x + 1, y))
  609. return false;
  610. // Interpolate height value
  611. Vec3 v1 = GetPosition(x, y);
  612. Vec3 v2 = GetPosition(x + 1, y + 1);
  613. Vec3 v3 = GetPosition(x + 1, y);
  614. outSurfacePosition = v1 + y_frac * (v2 - v3) + x_frac * (v3 - v1);
  615. SubShapeIDCreator creator;
  616. outSubShapeID = EncodeSubShapeID(creator, x, y, 1);
  617. return true;
  618. }
  619. }
  620. MassProperties HeightFieldShape::GetMassProperties() const
  621. {
  622. // Object should always be static, return default mass properties
  623. return MassProperties();
  624. }
  625. const PhysicsMaterial *HeightFieldShape::GetMaterial(uint inX, uint inY) const
  626. {
  627. if (mMaterials.empty())
  628. return PhysicsMaterial::sDefault;
  629. if (mMaterials.size() == 1)
  630. return mMaterials[0];
  631. uint count_min_1 = mSampleCount - 1;
  632. JPH_ASSERT(inX < count_min_1);
  633. JPH_ASSERT(inY < count_min_1);
  634. // Calculate at which bit the material index starts
  635. uint bit_pos = (inX + inY * count_min_1) * mNumBitsPerMaterialIndex;
  636. uint byte_pos = bit_pos >> 3;
  637. bit_pos &= 0b111;
  638. // Read the material index
  639. JPH_ASSERT(byte_pos + 1 < mMaterialIndices.size());
  640. const uint8 *material_indices = mMaterialIndices.data() + byte_pos;
  641. uint16 material_index = uint16(material_indices[0]) + uint16(uint16(material_indices[1]) << 8);
  642. material_index >>= bit_pos;
  643. material_index &= (1 << mNumBitsPerMaterialIndex) - 1;
  644. // Return the material
  645. return mMaterials[material_index];
  646. }
  647. uint HeightFieldShape::GetSubShapeIDBits() const
  648. {
  649. // Need to store X, Y and 1 extra bit to specify the triangle number in the quad
  650. return 2 * (32 - CountLeadingZeros(mSampleCount - 1)) + 1;
  651. }
  652. SubShapeID HeightFieldShape::EncodeSubShapeID(const SubShapeIDCreator &inCreator, uint inX, uint inY, uint inTriangle) const
  653. {
  654. return inCreator.PushID((inX + inY * mSampleCount) * 2 + inTriangle, GetSubShapeIDBits()).GetID();
  655. }
  656. void HeightFieldShape::DecodeSubShapeID(const SubShapeID &inSubShapeID, uint &outX, uint &outY, uint &outTriangle) const
  657. {
  658. // Decode sub shape id
  659. SubShapeID remainder;
  660. uint32 id = inSubShapeID.PopID(GetSubShapeIDBits(), remainder);
  661. JPH_ASSERT(remainder.IsEmpty(), "Invalid subshape ID");
  662. // Get triangle index
  663. outTriangle = id & 1;
  664. id >>= 1;
  665. // Fetch the x and y coordinate
  666. outX = id % mSampleCount;
  667. outY = id / mSampleCount;
  668. }
  669. const PhysicsMaterial *HeightFieldShape::GetMaterial(const SubShapeID &inSubShapeID) const
  670. {
  671. // Decode ID
  672. uint x, y, triangle;
  673. DecodeSubShapeID(inSubShapeID, x, y, triangle);
  674. // Fetch the material
  675. return GetMaterial(x, y);
  676. }
  677. Vec3 HeightFieldShape::GetSurfaceNormal(const SubShapeID &inSubShapeID, Vec3Arg inLocalSurfacePosition) const
  678. {
  679. // Decode ID
  680. uint x, y, triangle;
  681. DecodeSubShapeID(inSubShapeID, x, y, triangle);
  682. // Fetch vertices that both triangles share
  683. Vec3 x1y1 = GetPosition(x, y);
  684. Vec3 x2y2 = GetPosition(x + 1, y + 1);
  685. // Get normal depending on which triangle was selected
  686. Vec3 normal;
  687. if (triangle == 0)
  688. {
  689. Vec3 x1y2 = GetPosition(x, y + 1);
  690. normal = (x2y2 - x1y2).Cross(x1y1 - x1y2);
  691. }
  692. else
  693. {
  694. Vec3 x2y1 = GetPosition(x + 1, y);
  695. normal = (x1y1 - x2y1).Cross(x2y2 - x2y1);
  696. }
  697. return normal.Normalized();
  698. }
  699. inline uint8 HeightFieldShape::GetEdgeFlags(uint inX, uint inY, uint inTriangle) const
  700. {
  701. if (inTriangle == 0)
  702. {
  703. // The edge flags for this triangle are directly stored, find the right 3 bits
  704. uint bit_pos = 3 * (inX + inY * (mSampleCount - 1));
  705. uint byte_pos = bit_pos >> 3;
  706. bit_pos &= 0b111;
  707. JPH_ASSERT(byte_pos + 1 < mActiveEdges.size());
  708. const uint8 *active_edges = mActiveEdges.data() + byte_pos;
  709. uint16 edge_flags = uint16(active_edges[0]) + uint16(uint16(active_edges[1]) << 8);
  710. return uint8(edge_flags >> bit_pos) & 0b111;
  711. }
  712. else
  713. {
  714. // We don't store this triangle directly, we need to look at our three neighbours to construct the edge flags
  715. uint8 edge0 = (GetEdgeFlags(inX, inY, 0) & 0b100) != 0? 0b001 : 0; // Diagonal edge
  716. uint8 edge1 = inX == mSampleCount - 1 || (GetEdgeFlags(inX + 1, inY, 0) & 0b001) != 0? 0b010 : 0; // Vertical edge
  717. uint8 edge2 = inY == 0 || (GetEdgeFlags(inX, inY - 1, 0) & 0b010) != 0? 0b100 : 0; // Horizontal edge
  718. return edge0 | edge1 | edge2;
  719. }
  720. }
  721. AABox HeightFieldShape::GetLocalBounds() const
  722. {
  723. if (mMinSample == cNoCollisionValue16)
  724. {
  725. // This whole height field shape doesn't have any collision, return the center point
  726. Vec3 center = mOffset + 0.5f * mScale * Vec3(float(mSampleCount - 1), 0.0f, float(mSampleCount - 1));
  727. return AABox(center, center);
  728. }
  729. else
  730. {
  731. // Bounding box based on min and max sample height
  732. Vec3 bmin = mOffset + mScale * Vec3(0.0f, float(mMinSample), 0.0f);
  733. Vec3 bmax = mOffset + mScale * Vec3(float(mSampleCount - 1), float(mMaxSample), float(mSampleCount - 1));
  734. return AABox(bmin, bmax);
  735. }
  736. }
  737. #ifdef JPH_DEBUG_RENDERER
  738. void HeightFieldShape::Draw(DebugRenderer *inRenderer, Mat44Arg inCenterOfMassTransform, Vec3Arg inScale, ColorArg inColor, bool inUseMaterialColors, bool inDrawWireframe) const
  739. {
  740. // Reset the batch if we switch coloring mode
  741. if (mCachedUseMaterialColors != inUseMaterialColors)
  742. {
  743. mGeometry.clear();
  744. mCachedUseMaterialColors = inUseMaterialColors;
  745. }
  746. if (mGeometry.empty())
  747. {
  748. // Divide terrain in triangle batches of max 64x64x2 triangles to allow better culling of the terrain
  749. uint32 block_size = min<uint32>(mSampleCount, 64);
  750. for (uint32 by = 0; by < mSampleCount; by += block_size)
  751. for (uint32 bx = 0; bx < mSampleCount; bx += block_size)
  752. {
  753. // Create vertices for a block
  754. vector<DebugRenderer::Triangle> triangles;
  755. triangles.resize(block_size * block_size * 2);
  756. DebugRenderer::Triangle *out_tri = &triangles[0];
  757. for (uint32 y = by, max_y = min(by + block_size, mSampleCount - 1); y < max_y; ++y)
  758. for (uint32 x = bx, max_x = min(bx + block_size, mSampleCount - 1); x < max_x; ++x)
  759. if (!IsNoCollision(x, y) && !IsNoCollision(x + 1, y + 1))
  760. {
  761. Vec3 x1y1 = GetPosition(x, y);
  762. Vec3 x2y2 = GetPosition(x + 1, y + 1);
  763. Color color = inUseMaterialColors? GetMaterial(x, y)->GetDebugColor() : Color::sWhite;
  764. if (!IsNoCollision(x, y + 1))
  765. {
  766. Vec3 x1y2 = GetPosition(x, y + 1);
  767. x1y1.StoreFloat3(&out_tri->mV[0].mPosition);
  768. x1y2.StoreFloat3(&out_tri->mV[1].mPosition);
  769. x2y2.StoreFloat3(&out_tri->mV[2].mPosition);
  770. Vec3 normal = (x2y2 - x1y2).Cross(x1y1 - x1y2).Normalized();
  771. for (DebugRenderer::Vertex &v : out_tri->mV)
  772. {
  773. v.mColor = color;
  774. v.mUV = Float2(0, 0);
  775. normal.StoreFloat3(&v.mNormal);
  776. }
  777. ++out_tri;
  778. }
  779. if (!IsNoCollision(x + 1, y))
  780. {
  781. Vec3 x2y1 = GetPosition(x + 1, y);
  782. x1y1.StoreFloat3(&out_tri->mV[0].mPosition);
  783. x2y2.StoreFloat3(&out_tri->mV[1].mPosition);
  784. x2y1.StoreFloat3(&out_tri->mV[2].mPosition);
  785. Vec3 normal = (x1y1 - x2y1).Cross(x2y2 - x2y1).Normalized();
  786. for (DebugRenderer::Vertex &v : out_tri->mV)
  787. {
  788. v.mColor = color;
  789. v.mUV = Float2(0, 0);
  790. normal.StoreFloat3(&v.mNormal);
  791. }
  792. ++out_tri;
  793. }
  794. }
  795. // Resize triangles array to actual amount of triangles written
  796. size_t num_triangles = out_tri - &triangles[0];
  797. triangles.resize(num_triangles);
  798. // Create batch
  799. if (num_triangles > 0)
  800. mGeometry.push_back(new DebugRenderer::Geometry(inRenderer->CreateTriangleBatch(triangles), DebugRenderer::sCalculateBounds(&triangles[0].mV[0], int(3 * num_triangles))));
  801. }
  802. }
  803. // Get transform including scale
  804. Mat44 transform = inCenterOfMassTransform * Mat44::sScale(inScale);
  805. // Test if the shape is scaled inside out
  806. DebugRenderer::ECullMode cull_mode = ScaleHelpers::IsInsideOut(inScale)? DebugRenderer::ECullMode::CullFrontFace : DebugRenderer::ECullMode::CullBackFace;
  807. // Determine the draw mode
  808. DebugRenderer::EDrawMode draw_mode = inDrawWireframe? DebugRenderer::EDrawMode::Wireframe : DebugRenderer::EDrawMode::Solid;
  809. // Draw the geometry
  810. for (const DebugRenderer::GeometryRef &b : mGeometry)
  811. inRenderer->DrawGeometry(transform, inColor, b, cull_mode, DebugRenderer::ECastShadow::On, draw_mode);
  812. if (sDrawTriangleOutlines)
  813. {
  814. struct Visitor
  815. {
  816. JPH_INLINE explicit Visitor(const HeightFieldShape *inShape, DebugRenderer *inRenderer, Mat44Arg inTransform) :
  817. mShape(inShape),
  818. mRenderer(inRenderer),
  819. mTransform(inTransform)
  820. {
  821. }
  822. JPH_INLINE bool ShouldAbort() const
  823. {
  824. return false;
  825. }
  826. JPH_INLINE bool ShouldVisitRangeBlock([[maybe_unused]] int inStackTop) const
  827. {
  828. return true;
  829. }
  830. JPH_INLINE int VisitRangeBlock(Vec4Arg inBoundsMinX, Vec4Arg inBoundsMinY, Vec4Arg inBoundsMinZ, Vec4Arg inBoundsMaxX, Vec4Arg inBoundsMaxY, Vec4Arg inBoundsMaxZ, UVec4 &ioProperties, [[maybe_unused]] int inStackTop) const
  831. {
  832. UVec4 valid = UVec4::sOr(UVec4::sOr(Vec4::sLess(inBoundsMinX, inBoundsMaxX), Vec4::sLess(inBoundsMinY, inBoundsMaxY)), Vec4::sLess(inBoundsMinZ, inBoundsMaxZ));
  833. UVec4::sSort4True(valid, ioProperties);
  834. return valid.CountTrues();
  835. }
  836. JPH_INLINE void VisitTriangle(uint inX, uint inY, uint inTriangle, Vec3Arg inV0, Vec3Arg inV1, Vec3Arg inV2) const
  837. {
  838. // Determine active edges
  839. uint8 active_edges = mShape->GetEdgeFlags(inX, inY, inTriangle);
  840. // Loop through edges
  841. Vec3 v[] = { inV0, inV1, inV2 };
  842. for (uint edge_idx = 0; edge_idx < 3; ++edge_idx)
  843. {
  844. Vec3 v1 = mTransform * v[edge_idx];
  845. Vec3 v2 = mTransform * v[(edge_idx + 1) % 3];
  846. // Draw active edge as a green arrow, other edges as grey
  847. if (active_edges & (1 << edge_idx))
  848. mRenderer->DrawArrow(v1, v2, Color::sGreen, 0.01f);
  849. else
  850. mRenderer->DrawLine(v1, v2, Color::sGrey);
  851. }
  852. }
  853. const HeightFieldShape *mShape;
  854. DebugRenderer * mRenderer;
  855. Mat44 mTransform;
  856. };
  857. Visitor visitor(this, inRenderer, inCenterOfMassTransform * Mat44::sScale(inScale));
  858. WalkHeightField(visitor);
  859. }
  860. }
  861. #endif // JPH_DEBUG_RENDERER
  862. class HeightFieldShape::DecodingContext
  863. {
  864. public:
  865. JPH_INLINE explicit DecodingContext(const HeightFieldShape *inShape) :
  866. mShape(inShape)
  867. {
  868. static_assert(sizeof(sGridOffsets) / sizeof(uint) == cNumBitsXY + 1, "Offsets array is not long enough");
  869. // Construct root stack entry
  870. mPropertiesStack[0] = 0; // level: 0, x: 0, y: 0
  871. }
  872. template <class Visitor>
  873. JPH_INLINE void WalkHeightField(Visitor &ioVisitor)
  874. {
  875. // Precalculate values relating to sample count
  876. uint32 sample_count = mShape->mSampleCount;
  877. UVec4 sample_count_min_1 = UVec4::sReplicate(sample_count - 1);
  878. // Precalculate values relating to block size
  879. uint32 block_size = mShape->mBlockSize;
  880. uint32 block_size_plus_1 = block_size + 1;
  881. uint num_blocks = mShape->GetNumBlocks();
  882. uint num_blocks_min_1 = num_blocks - 1;
  883. uint max_level = HeightFieldShape::sGetMaxLevel(num_blocks);
  884. // Precalculate range block offset and stride for GetBlockOffsetAndScale
  885. uint range_block_offset, range_block_stride;
  886. sGetRangeBlockOffsetAndStride(num_blocks, max_level, range_block_offset, range_block_stride);
  887. // Allocate space for vertices and 'no collision' flags
  888. int array_size = Square(block_size_plus_1);
  889. Vec3 *vertices = reinterpret_cast<Vec3 *>(alloca(array_size * sizeof(Vec3)));
  890. bool *no_collision = reinterpret_cast<bool *>(alloca(array_size * sizeof(bool)));
  891. // Splat offsets
  892. Vec4 ox = mShape->mOffset.SplatX();
  893. Vec4 oy = mShape->mOffset.SplatY();
  894. Vec4 oz = mShape->mOffset.SplatZ();
  895. // Splat scales
  896. Vec4 sx = mShape->mScale.SplatX();
  897. Vec4 sy = mShape->mScale.SplatY();
  898. Vec4 sz = mShape->mScale.SplatZ();
  899. do
  900. {
  901. // Decode properties
  902. uint32 properties_top = mPropertiesStack[mTop];
  903. uint32 x = properties_top & cMaskBitsXY;
  904. uint32 y = (properties_top >> cNumBitsXY) & cMaskBitsXY;
  905. uint32 level = properties_top >> cLevelShift;
  906. if (level >= max_level)
  907. {
  908. // Determine actual range of samples (minus one because we eventually want to iterate over the triangles, not the samples)
  909. uint32 min_x = x * block_size;
  910. uint32 max_x = min_x + block_size;
  911. uint32 min_y = y * block_size;
  912. uint32 max_y = min_y + block_size;
  913. // Decompress vertices of block at (x, y)
  914. Vec3 *dst_vertex = vertices;
  915. bool *dst_no_collision = no_collision;
  916. float block_offset, block_scale;
  917. mShape->GetBlockOffsetAndScale(x, y, range_block_offset, range_block_stride, block_offset, block_scale);
  918. for (uint32 v_y = min_y; v_y < max_y; ++v_y)
  919. {
  920. for (uint32 v_x = min_x; v_x < max_x; ++v_x)
  921. {
  922. *dst_vertex = mShape->GetPosition(v_x, v_y, block_offset, block_scale, *dst_no_collision);
  923. ++dst_vertex;
  924. ++dst_no_collision;
  925. }
  926. // Skip last column, these values come from a different block
  927. ++dst_vertex;
  928. ++dst_no_collision;
  929. }
  930. // Decompress block (x + 1, y)
  931. uint32 max_x_decrement = 0;
  932. if (x < num_blocks_min_1)
  933. {
  934. dst_vertex = vertices + block_size;
  935. dst_no_collision = no_collision + block_size;
  936. mShape->GetBlockOffsetAndScale(x + 1, 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. *dst_vertex = mShape->GetPosition(max_x, v_y, block_offset, block_scale, *dst_no_collision);
  940. dst_vertex += block_size_plus_1;
  941. dst_no_collision += block_size_plus_1;
  942. }
  943. }
  944. else
  945. max_x_decrement = 1; // We don't have a next block, one less triangle to test
  946. // Decompress block (x, y + 1)
  947. if (y < num_blocks_min_1)
  948. {
  949. uint start = block_size * block_size_plus_1;
  950. dst_vertex = vertices + start;
  951. dst_no_collision = no_collision + start;
  952. mShape->GetBlockOffsetAndScale(x, y + 1, range_block_offset, range_block_stride, block_offset, block_scale);
  953. for (uint32 v_x = min_x; v_x < max_x; ++v_x)
  954. {
  955. *dst_vertex = mShape->GetPosition(v_x, max_y, block_offset, block_scale, *dst_no_collision);
  956. ++dst_vertex;
  957. ++dst_no_collision;
  958. }
  959. // Decompress single sample of block at (x + 1, y + 1)
  960. if (x < num_blocks_min_1)
  961. {
  962. mShape->GetBlockOffsetAndScale(x + 1, y + 1, range_block_offset, range_block_stride, block_offset, block_scale);
  963. *dst_vertex = mShape->GetPosition(max_x, max_y, block_offset, block_scale, *dst_no_collision);
  964. }
  965. }
  966. else
  967. --max_y; // We don't have a next block, one less triangle to test
  968. // Update max_x (we've been using it so we couldn't update it earlier)
  969. max_x -= max_x_decrement;
  970. // Loop triangles
  971. for (uint32 v_y = min_y; v_y < max_y; ++v_y)
  972. for (uint32 v_x = min_x; v_x < max_x; ++v_x)
  973. {
  974. // Get first vertex
  975. const int offset = (v_y - min_y) * block_size_plus_1 + (v_x - min_x);
  976. const Vec3 *start_vertex = vertices + offset;
  977. const bool *start_no_collision = no_collision + offset;
  978. // Check if vertices shared by both triangles have collision
  979. if (!start_no_collision[0] && !start_no_collision[block_size_plus_1 + 1])
  980. {
  981. // Loop 2 triangles
  982. for (uint t = 0; t < 2; ++t)
  983. {
  984. // Determine triangle vertices
  985. Vec3 v0, v1, v2;
  986. if (t == 0)
  987. {
  988. // Check third vertex
  989. if (start_no_collision[block_size_plus_1])
  990. continue;
  991. // Get vertices for triangle
  992. v0 = start_vertex[0];
  993. v1 = start_vertex[block_size_plus_1];
  994. v2 = start_vertex[block_size_plus_1 + 1];
  995. }
  996. else
  997. {
  998. // Check third vertex
  999. if (start_no_collision[1])
  1000. continue;
  1001. // Get vertices for triangle
  1002. v0 = start_vertex[0];
  1003. v1 = start_vertex[block_size_plus_1 + 1];
  1004. v2 = start_vertex[1];
  1005. }
  1006. // Call visitor
  1007. ioVisitor.VisitTriangle(v_x, v_y, t, v0, v1, v2);
  1008. }
  1009. }
  1010. }
  1011. }
  1012. else
  1013. {
  1014. // Visit child grid
  1015. uint32 offset = sGridOffsets[level] + (1 << level) * y + x;
  1016. // Decode min/max height
  1017. UVec4 block = UVec4::sLoadInt4Aligned(reinterpret_cast<const uint32 *>(&mShape->mRangeBlocks[offset]));
  1018. Vec4 bounds_miny = oy + sy * block.Expand4Uint16Lo().ToFloat();
  1019. Vec4 bounds_maxy = oy + sy * block.Expand4Uint16Hi().ToFloat();
  1020. // Calculate size of one cell at this grid level
  1021. UVec4 internal_cell_size = UVec4::sReplicate(block_size << (max_level - level - 1)); // subtract 1 from level because we have an internal grid of 2x2
  1022. // Calculate min/max x and z
  1023. UVec4 two_x = UVec4::sReplicate(2 * x); // multiply by two because we have an internal grid of 2x2
  1024. Vec4 bounds_minx = ox + sx * (internal_cell_size * (two_x + UVec4(0, 1, 0, 1))).ToFloat();
  1025. Vec4 bounds_maxx = ox + sx * UVec4::sMin(internal_cell_size * (two_x + UVec4(1, 2, 1, 2)), sample_count_min_1).ToFloat();
  1026. UVec4 two_y = UVec4::sReplicate(2 * y);
  1027. Vec4 bounds_minz = oz + sz * (internal_cell_size * (two_y + UVec4(0, 0, 1, 1))).ToFloat();
  1028. Vec4 bounds_maxz = oz + sz * UVec4::sMin(internal_cell_size * (two_y + UVec4(1, 1, 2, 2)), sample_count_min_1).ToFloat();
  1029. // Calculate properties of child blocks
  1030. UVec4 properties = UVec4::sReplicate(((level + 1) << cLevelShift) + (y << (cNumBitsXY + 1)) + (x << 1)) + UVec4(0, 1, 1 << cNumBitsXY, (1 << cNumBitsXY) + 1);
  1031. #ifdef JPH_DEBUG_HEIGHT_FIELD
  1032. // Draw boxes
  1033. for (int i = 0; i < 4; ++i)
  1034. {
  1035. AABox b(Vec3(bounds_minx[i], bounds_miny[i], bounds_minz[i]), Vec3(bounds_maxx[i], bounds_maxy[i], bounds_maxz[i]));
  1036. if (b.IsValid())
  1037. DebugRenderer::sInstance->DrawWireBox(b, Color::sGreen);
  1038. }
  1039. #endif
  1040. // Check which sub nodes to visit
  1041. int num_results = ioVisitor.VisitRangeBlock(bounds_minx, bounds_miny, bounds_minz, bounds_maxx, bounds_maxy, bounds_maxz, properties, mTop);
  1042. // Push them onto the stack
  1043. JPH_ASSERT(mTop + 4 < cStackSize);
  1044. properties.StoreInt4(&mPropertiesStack[mTop]);
  1045. mTop += num_results;
  1046. }
  1047. // Check if we're done
  1048. if (ioVisitor.ShouldAbort())
  1049. break;
  1050. // Fetch next node until we find one that the visitor wants to see
  1051. do
  1052. --mTop;
  1053. while (mTop >= 0 && !ioVisitor.ShouldVisitRangeBlock(mTop));
  1054. }
  1055. while (mTop >= 0);
  1056. }
  1057. // This can be used to have the visitor early out (ioVisitor.ShouldAbort() returns true) and later continue again (call WalkHeightField() again)
  1058. JPH_INLINE bool IsDoneWalking() const
  1059. {
  1060. return mTop < 0;
  1061. }
  1062. private:
  1063. const HeightFieldShape * mShape;
  1064. int mTop = 0;
  1065. uint32 mPropertiesStack[cStackSize];
  1066. };
  1067. template <class Visitor>
  1068. JPH_INLINE void HeightFieldShape::WalkHeightField(Visitor &ioVisitor) const
  1069. {
  1070. DecodingContext ctx(this);
  1071. ctx.WalkHeightField(ioVisitor);
  1072. }
  1073. bool HeightFieldShape::CastRay(const RayCast &inRay, const SubShapeIDCreator &inSubShapeIDCreator, RayCastResult &ioHit) const
  1074. {
  1075. JPH_PROFILE_FUNCTION();
  1076. struct Visitor
  1077. {
  1078. JPH_INLINE explicit Visitor(const HeightFieldShape *inShape, const RayCast &inRay, const SubShapeIDCreator &inSubShapeIDCreator, RayCastResult &ioHit) :
  1079. mHit(ioHit),
  1080. mRayOrigin(inRay.mOrigin),
  1081. mRayDirection(inRay.mDirection),
  1082. mRayInvDirection(inRay.mDirection),
  1083. mShape(inShape),
  1084. mSubShapeIDCreator(inSubShapeIDCreator)
  1085. {
  1086. }
  1087. JPH_INLINE bool ShouldAbort() const
  1088. {
  1089. return mHit.mFraction <= 0.0f;
  1090. }
  1091. JPH_INLINE bool ShouldVisitRangeBlock(int inStackTop) const
  1092. {
  1093. return mDistanceStack[inStackTop] < mHit.mFraction;
  1094. }
  1095. JPH_INLINE int VisitRangeBlock(Vec4Arg inBoundsMinX, Vec4Arg inBoundsMinY, Vec4Arg inBoundsMinZ, Vec4Arg inBoundsMaxX, Vec4Arg inBoundsMaxY, Vec4Arg inBoundsMaxZ, UVec4 &ioProperties, int inStackTop)
  1096. {
  1097. // Test bounds of 4 children
  1098. Vec4 distance = RayAABox4(mRayOrigin, mRayInvDirection, inBoundsMinX, inBoundsMinY, inBoundsMinZ, inBoundsMaxX, inBoundsMaxY, inBoundsMaxZ);
  1099. // Sort so that highest values are first (we want to first process closer hits and we process stack top to bottom)
  1100. Vec4::sSort4Reverse(distance, ioProperties);
  1101. // Count how many results are closer
  1102. UVec4 closer = Vec4::sLess(distance, Vec4::sReplicate(mHit.mFraction));
  1103. int num_results = closer.CountTrues();
  1104. // Shift the results so that only the closer ones remain
  1105. distance = distance.ReinterpretAsInt().ShiftComponents4Minus(num_results).ReinterpretAsFloat();
  1106. ioProperties = ioProperties.ShiftComponents4Minus(num_results);
  1107. distance.StoreFloat4((Float4 *)&mDistanceStack[inStackTop]);
  1108. return num_results;
  1109. }
  1110. JPH_INLINE void VisitTriangle(uint inX, uint inY, uint inTriangle, Vec3Arg inV0, Vec3Arg inV1, Vec3Arg inV2)
  1111. {
  1112. #ifdef JPH_DEBUG_HEIGHT_FIELD
  1113. float old_fraction = mHit.mFraction;
  1114. #endif
  1115. float fraction = RayTriangle(mRayOrigin, mRayDirection, inV0, inV1, inV2);
  1116. if (fraction < mHit.mFraction)
  1117. {
  1118. // It's a closer hit
  1119. mHit.mFraction = fraction;
  1120. mHit.mSubShapeID2 = mShape->EncodeSubShapeID(mSubShapeIDCreator, inX, inY, inTriangle);
  1121. mReturnValue = true;
  1122. }
  1123. #ifdef JPH_DEBUG_HEIGHT_FIELD
  1124. DebugRenderer::sInstance->DrawWireTriangle(inV0, inV1, inV2, old_fraction > mHit.mFraction? Color::sRed : Color::sCyan);
  1125. #endif
  1126. }
  1127. RayCastResult & mHit;
  1128. Vec3 mRayOrigin;
  1129. Vec3 mRayDirection;
  1130. RayInvDirection mRayInvDirection;
  1131. const HeightFieldShape *mShape;
  1132. SubShapeIDCreator mSubShapeIDCreator;
  1133. bool mReturnValue = false;
  1134. float mDistanceStack[cStackSize];
  1135. };
  1136. Visitor visitor(this, inRay, inSubShapeIDCreator, ioHit);
  1137. WalkHeightField(visitor);
  1138. return visitor.mReturnValue;
  1139. }
  1140. void HeightFieldShape::CastRay(const RayCast &inRay, const RayCastSettings &inRayCastSettings, const SubShapeIDCreator &inSubShapeIDCreator, CastRayCollector &ioCollector) const
  1141. {
  1142. JPH_PROFILE_FUNCTION();
  1143. struct Visitor
  1144. {
  1145. JPH_INLINE explicit Visitor(const HeightFieldShape *inShape, const RayCast &inRay, const RayCastSettings &inRayCastSettings, const SubShapeIDCreator &inSubShapeIDCreator, CastRayCollector &ioCollector) :
  1146. mCollector(ioCollector),
  1147. mRayOrigin(inRay.mOrigin),
  1148. mRayDirection(inRay.mDirection),
  1149. mRayInvDirection(inRay.mDirection),
  1150. mBackFaceMode(inRayCastSettings.mBackFaceMode),
  1151. mShape(inShape),
  1152. mSubShapeIDCreator(inSubShapeIDCreator)
  1153. {
  1154. }
  1155. JPH_INLINE bool ShouldAbort() const
  1156. {
  1157. return mCollector.ShouldEarlyOut();
  1158. }
  1159. JPH_INLINE bool ShouldVisitRangeBlock(int inStackTop) const
  1160. {
  1161. return mDistanceStack[inStackTop] < mCollector.GetEarlyOutFraction();
  1162. }
  1163. JPH_INLINE int VisitRangeBlock(Vec4Arg inBoundsMinX, Vec4Arg inBoundsMinY, Vec4Arg inBoundsMinZ, Vec4Arg inBoundsMaxX, Vec4Arg inBoundsMaxY, Vec4Arg inBoundsMaxZ, UVec4 &ioProperties, int inStackTop)
  1164. {
  1165. // Test bounds of 4 children
  1166. Vec4 distance = RayAABox4(mRayOrigin, mRayInvDirection, inBoundsMinX, inBoundsMinY, inBoundsMinZ, inBoundsMaxX, inBoundsMaxY, inBoundsMaxZ);
  1167. // Sort so that highest values are first (we want to first process closer hits and we process stack top to bottom)
  1168. Vec4::sSort4Reverse(distance, ioProperties);
  1169. // Count how many results are closer
  1170. UVec4 closer = Vec4::sLess(distance, Vec4::sReplicate(mCollector.GetEarlyOutFraction()));
  1171. int num_results = closer.CountTrues();
  1172. // Shift the results so that only the closer ones remain
  1173. distance = distance.ReinterpretAsInt().ShiftComponents4Minus(num_results).ReinterpretAsFloat();
  1174. ioProperties = ioProperties.ShiftComponents4Minus(num_results);
  1175. distance.StoreFloat4((Float4 *)&mDistanceStack[inStackTop]);
  1176. return num_results;
  1177. }
  1178. JPH_INLINE void VisitTriangle(uint inX, uint inY, uint inTriangle, Vec3Arg inV0, Vec3Arg inV1, Vec3Arg inV2) const
  1179. {
  1180. // Back facing check
  1181. if (mBackFaceMode == EBackFaceMode::IgnoreBackFaces && (inV2 - inV0).Cross(inV1 - inV0).Dot(mRayDirection) < 0)
  1182. return;
  1183. // Check the triangle
  1184. float fraction = RayTriangle(mRayOrigin, mRayDirection, inV0, inV1, inV2);
  1185. if (fraction < mCollector.GetEarlyOutFraction())
  1186. {
  1187. RayCastResult hit;
  1188. hit.mBodyID = TransformedShape::sGetBodyID(mCollector.GetContext());
  1189. hit.mFraction = fraction;
  1190. hit.mSubShapeID2 = mShape->EncodeSubShapeID(mSubShapeIDCreator, inX, inY, inTriangle);
  1191. mCollector.AddHit(hit);
  1192. }
  1193. }
  1194. CastRayCollector & mCollector;
  1195. Vec3 mRayOrigin;
  1196. Vec3 mRayDirection;
  1197. RayInvDirection mRayInvDirection;
  1198. EBackFaceMode mBackFaceMode;
  1199. const HeightFieldShape *mShape;
  1200. SubShapeIDCreator mSubShapeIDCreator;
  1201. float mDistanceStack[cStackSize];
  1202. };
  1203. Visitor visitor(this, inRay, inRayCastSettings, inSubShapeIDCreator, ioCollector);
  1204. WalkHeightField(visitor);
  1205. }
  1206. void HeightFieldShape::CollidePoint(Vec3Arg inPoint, const SubShapeIDCreator &inSubShapeIDCreator, CollidePointCollector &ioCollector) const
  1207. {
  1208. // First test if we're inside our bounding box
  1209. AABox bounds = GetLocalBounds();
  1210. if (bounds.Contains(inPoint))
  1211. {
  1212. // Cast a ray that's 10% longer than the heigth of our bounding box downwards to see if we hit the surface
  1213. RayCastResult result;
  1214. if (!CastRay(RayCast { inPoint, -1.1f * bounds.GetSize().GetY() * Vec3::sAxisY() }, inSubShapeIDCreator, result))
  1215. ioCollector.AddHit({ TransformedShape::sGetBodyID(ioCollector.GetContext()), inSubShapeIDCreator.GetID() });
  1216. }
  1217. }
  1218. void HeightFieldShape::CastShape(const ShapeCast &inShapeCast, const ShapeCastSettings &inShapeCastSettings, Vec3Arg inScale, const ShapeFilter &inShapeFilter, Mat44Arg inCenterOfMassTransform2, const SubShapeIDCreator &inSubShapeIDCreator1, const SubShapeIDCreator &inSubShapeIDCreator2, CastShapeCollector &ioCollector) const
  1219. {
  1220. JPH_PROFILE_FUNCTION();
  1221. struct Visitor : public CastConvexVsTriangles
  1222. {
  1223. using CastConvexVsTriangles::CastConvexVsTriangles;
  1224. JPH_INLINE bool ShouldAbort() const
  1225. {
  1226. return mCollector.ShouldEarlyOut();
  1227. }
  1228. JPH_INLINE bool ShouldVisitRangeBlock(int inStackTop) const
  1229. {
  1230. return mDistanceStack[inStackTop] < mCollector.GetEarlyOutFraction();
  1231. }
  1232. JPH_INLINE int VisitRangeBlock(Vec4Arg inBoundsMinX, Vec4Arg inBoundsMinY, Vec4Arg inBoundsMinZ, Vec4Arg inBoundsMaxX, Vec4Arg inBoundsMaxY, Vec4Arg inBoundsMaxZ, UVec4 &ioProperties, int inStackTop)
  1233. {
  1234. // Scale the bounding boxes of this node
  1235. Vec4 bounds_min_x, bounds_min_y, bounds_min_z, bounds_max_x, bounds_max_y, bounds_max_z;
  1236. 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);
  1237. // Enlarge them by the casted shape's box extents
  1238. AABox4EnlargeWithExtent(mBoxExtent, bounds_min_x, bounds_min_y, bounds_min_z, bounds_max_x, bounds_max_y, bounds_max_z);
  1239. // Test bounds of 4 children
  1240. Vec4 distance = RayAABox4(mBoxCenter, mInvDirection, bounds_min_x, bounds_min_y, bounds_min_z, bounds_max_x, bounds_max_y, bounds_max_z);
  1241. // Sort so that highest values are first (we want to first process closer hits and we process stack top to bottom)
  1242. Vec4::sSort4Reverse(distance, ioProperties);
  1243. // Count how many results are closer
  1244. UVec4 closer = Vec4::sLess(distance, Vec4::sReplicate(mCollector.GetEarlyOutFraction()));
  1245. int num_results = closer.CountTrues();
  1246. // Shift the results so that only the closer ones remain
  1247. distance = distance.ReinterpretAsInt().ShiftComponents4Minus(num_results).ReinterpretAsFloat();
  1248. ioProperties = ioProperties.ShiftComponents4Minus(num_results);
  1249. distance.StoreFloat4((Float4 *)&mDistanceStack[inStackTop]);
  1250. return num_results;
  1251. }
  1252. JPH_INLINE void VisitTriangle(uint inX, uint inY, uint inTriangle, Vec3Arg inV0, Vec3Arg inV1, Vec3Arg inV2)
  1253. {
  1254. // Create sub shape id for this part
  1255. SubShapeID triangle_sub_shape_id = mShape2->EncodeSubShapeID(mSubShapeIDCreator2, inX, inY, inTriangle);
  1256. // Determine active edges
  1257. uint8 active_edges = mShape2->GetEdgeFlags(inX, inY, inTriangle);
  1258. Cast(inV0, inV1, inV2, active_edges, triangle_sub_shape_id);
  1259. }
  1260. const HeightFieldShape * mShape2;
  1261. RayInvDirection mInvDirection;
  1262. Vec3 mBoxCenter;
  1263. Vec3 mBoxExtent;
  1264. SubShapeIDCreator mSubShapeIDCreator2;
  1265. float mDistanceStack[cStackSize];
  1266. };
  1267. Visitor visitor(inShapeCast, inShapeCastSettings, inScale, inShapeFilter, inCenterOfMassTransform2, inSubShapeIDCreator1, ioCollector);
  1268. visitor.mShape2 = this;
  1269. visitor.mInvDirection.Set(inShapeCast.mDirection);
  1270. visitor.mBoxCenter = inShapeCast.mShapeWorldBounds.GetCenter();
  1271. visitor.mBoxExtent = inShapeCast.mShapeWorldBounds.GetExtent();
  1272. visitor.mSubShapeIDCreator2 = inSubShapeIDCreator2;
  1273. WalkHeightField(visitor);
  1274. }
  1275. struct HeightFieldShape::HSGetTrianglesContext
  1276. {
  1277. HSGetTrianglesContext(const HeightFieldShape *inShape, const AABox &inBox, Vec3Arg inPositionCOM, QuatArg inRotation, Vec3Arg inScale) :
  1278. mDecodeCtx(inShape),
  1279. mShape(inShape),
  1280. mLocalBox(Mat44::sInverseRotationTranslation(inRotation, inPositionCOM), inBox),
  1281. mHeightFieldScale(inScale),
  1282. mLocalToWorld(Mat44::sRotationTranslation(inRotation, inPositionCOM) * Mat44::sScale(inScale)),
  1283. mIsInsideOut(ScaleHelpers::IsInsideOut(inScale))
  1284. {
  1285. }
  1286. bool ShouldAbort() const
  1287. {
  1288. return mShouldAbort;
  1289. }
  1290. bool ShouldVisitRangeBlock([[maybe_unused]] int inStackTop) const
  1291. {
  1292. return true;
  1293. }
  1294. int VisitRangeBlock(Vec4Arg inBoundsMinX, Vec4Arg inBoundsMinY, Vec4Arg inBoundsMinZ, Vec4Arg inBoundsMaxX, Vec4Arg inBoundsMaxY, Vec4Arg inBoundsMaxZ, UVec4 &ioProperties, [[maybe_unused]] int inStackTop) const
  1295. {
  1296. // Scale the bounding boxes of this node
  1297. Vec4 bounds_min_x, bounds_min_y, bounds_min_z, bounds_max_x, bounds_max_y, bounds_max_z;
  1298. 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);
  1299. // Test which nodes collide
  1300. UVec4 collides = AABox4VsBox(mLocalBox, bounds_min_x, bounds_min_y, bounds_min_z, bounds_max_x, bounds_max_y, bounds_max_z);
  1301. // Sort so the colliding ones go first
  1302. UVec4::sSort4True(collides, ioProperties);
  1303. // Return number of hits
  1304. return collides.CountTrues();
  1305. }
  1306. void VisitTriangle(uint inX, uint inY, [[maybe_unused]] uint inTriangle, Vec3Arg inV0, Vec3Arg inV1, Vec3Arg inV2)
  1307. {
  1308. // 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.
  1309. if (mNumTrianglesFound + 1 > mMaxTrianglesRequested)
  1310. {
  1311. mShouldAbort = true;
  1312. return;
  1313. }
  1314. // Store vertices as Float3
  1315. if (mIsInsideOut)
  1316. {
  1317. // Reverse vertices
  1318. (mLocalToWorld * inV0).StoreFloat3(mTriangleVertices++);
  1319. (mLocalToWorld * inV2).StoreFloat3(mTriangleVertices++);
  1320. (mLocalToWorld * inV1).StoreFloat3(mTriangleVertices++);
  1321. }
  1322. else
  1323. {
  1324. // Normal scale
  1325. (mLocalToWorld * inV0).StoreFloat3(mTriangleVertices++);
  1326. (mLocalToWorld * inV1).StoreFloat3(mTriangleVertices++);
  1327. (mLocalToWorld * inV2).StoreFloat3(mTriangleVertices++);
  1328. }
  1329. // Decode material
  1330. if (mMaterials != nullptr)
  1331. *mMaterials++ = mShape->GetMaterial(inX, inY);
  1332. // Accumulate triangles found
  1333. mNumTrianglesFound++;
  1334. }
  1335. DecodingContext mDecodeCtx;
  1336. const HeightFieldShape * mShape;
  1337. OrientedBox mLocalBox;
  1338. Vec3 mHeightFieldScale;
  1339. Mat44 mLocalToWorld;
  1340. int mMaxTrianglesRequested;
  1341. Float3 * mTriangleVertices;
  1342. int mNumTrianglesFound;
  1343. const PhysicsMaterial ** mMaterials;
  1344. bool mShouldAbort;
  1345. bool mIsInsideOut;
  1346. };
  1347. void HeightFieldShape::GetTrianglesStart(GetTrianglesContext &ioContext, const AABox &inBox, Vec3Arg inPositionCOM, QuatArg inRotation, Vec3Arg inScale) const
  1348. {
  1349. static_assert(sizeof(HSGetTrianglesContext) <= sizeof(GetTrianglesContext), "GetTrianglesContext too small");
  1350. JPH_ASSERT(IsAligned(&ioContext, alignof(HSGetTrianglesContext)));
  1351. new (&ioContext) HSGetTrianglesContext(this, inBox, inPositionCOM, inRotation, inScale);
  1352. }
  1353. int HeightFieldShape::GetTrianglesNext(GetTrianglesContext &ioContext, int inMaxTrianglesRequested, Float3 *outTriangleVertices, const PhysicsMaterial **outMaterials) const
  1354. {
  1355. static_assert(cGetTrianglesMinTrianglesRequested >= 1, "cGetTrianglesMinTrianglesRequested is too small");
  1356. JPH_ASSERT(inMaxTrianglesRequested >= cGetTrianglesMinTrianglesRequested);
  1357. // Check if we're done
  1358. HSGetTrianglesContext &context = (HSGetTrianglesContext &)ioContext;
  1359. if (context.mDecodeCtx.IsDoneWalking())
  1360. return 0;
  1361. // Store parameters on context
  1362. context.mMaxTrianglesRequested = inMaxTrianglesRequested;
  1363. context.mTriangleVertices = outTriangleVertices;
  1364. context.mMaterials = outMaterials;
  1365. context.mShouldAbort = false; // Reset the abort flag
  1366. context.mNumTrianglesFound = 0;
  1367. // Continue (or start) walking the height field
  1368. context.mDecodeCtx.WalkHeightField(context);
  1369. return context.mNumTrianglesFound;
  1370. }
  1371. void HeightFieldShape::sCollideConvexVsHeightField(const ConvexShape *inShape1, const HeightFieldShape *inShape2, Vec3Arg inScale1, Vec3Arg inScale2, Mat44Arg inCenterOfMassTransform1, Mat44Arg inCenterOfMassTransform2, const SubShapeIDCreator &inSubShapeIDCreator1, const SubShapeIDCreator &inSubShapeIDCreator2, const CollideShapeSettings &inCollideShapeSettings, CollideShapeCollector &ioCollector)
  1372. {
  1373. JPH_PROFILE_FUNCTION();
  1374. struct Visitor : public CollideConvexVsTriangles
  1375. {
  1376. using CollideConvexVsTriangles::CollideConvexVsTriangles;
  1377. JPH_INLINE bool ShouldAbort() const
  1378. {
  1379. return mCollector.ShouldEarlyOut();
  1380. }
  1381. JPH_INLINE bool ShouldVisitRangeBlock([[maybe_unused]] int inStackTop) const
  1382. {
  1383. return true;
  1384. }
  1385. JPH_INLINE int VisitRangeBlock(Vec4Arg inBoundsMinX, Vec4Arg inBoundsMinY, Vec4Arg inBoundsMinZ, Vec4Arg inBoundsMaxX, Vec4Arg inBoundsMaxY, Vec4Arg inBoundsMaxZ, UVec4 &ioProperties, [[maybe_unused]] int inStackTop) const
  1386. {
  1387. // Scale the bounding boxes of this node
  1388. Vec4 bounds_min_x, bounds_min_y, bounds_min_z, bounds_max_x, bounds_max_y, bounds_max_z;
  1389. 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);
  1390. // Test which nodes collide
  1391. UVec4 collides = AABox4VsBox(mBoundsOf1InSpaceOf2, bounds_min_x, bounds_min_y, bounds_min_z, bounds_max_x, bounds_max_y, bounds_max_z);
  1392. // Sort so the colliding ones go first
  1393. UVec4::sSort4True(collides, ioProperties);
  1394. // Return number of hits
  1395. return collides.CountTrues();
  1396. }
  1397. JPH_INLINE void VisitTriangle(uint inX, uint inY, uint inTriangle, Vec3Arg inV0, Vec3Arg inV1, Vec3Arg inV2)
  1398. {
  1399. // Create ID for triangle
  1400. SubShapeID triangle_sub_shape_id = mShape2->EncodeSubShapeID(mSubShapeIDCreator2, inX, inY, inTriangle);
  1401. // Determine active edges
  1402. uint8 active_edges = mShape2->GetEdgeFlags(inX, inY, inTriangle);
  1403. Collide(inV0, inV1, inV2, active_edges, triangle_sub_shape_id);
  1404. }
  1405. const HeightFieldShape * mShape2;
  1406. SubShapeIDCreator mSubShapeIDCreator2;
  1407. };
  1408. Visitor visitor(inShape1, inScale1, inScale2, inCenterOfMassTransform1, inCenterOfMassTransform2, inSubShapeIDCreator1.GetID(), inCollideShapeSettings, ioCollector);
  1409. visitor.mShape2 = inShape2;
  1410. visitor.mSubShapeIDCreator2 = inSubShapeIDCreator2;
  1411. inShape2->WalkHeightField(visitor);
  1412. }
  1413. void HeightFieldShape::SaveBinaryState(StreamOut &inStream) const
  1414. {
  1415. Shape::SaveBinaryState(inStream);
  1416. inStream.Write(mOffset);
  1417. inStream.Write(mScale);
  1418. inStream.Write(mSampleCount);
  1419. inStream.Write(mBlockSize);
  1420. inStream.Write(mBitsPerSample);
  1421. inStream.Write(mMinSample);
  1422. inStream.Write(mMaxSample);
  1423. inStream.Write(mRangeBlocks);
  1424. inStream.Write(mHeightSamples);
  1425. inStream.Write(mActiveEdges);
  1426. inStream.Write(mMaterialIndices);
  1427. inStream.Write(mNumBitsPerMaterialIndex);
  1428. }
  1429. void HeightFieldShape::RestoreBinaryState(StreamIn &inStream)
  1430. {
  1431. Shape::RestoreBinaryState(inStream);
  1432. inStream.Read(mOffset);
  1433. inStream.Read(mScale);
  1434. inStream.Read(mSampleCount);
  1435. inStream.Read(mBlockSize);
  1436. inStream.Read(mBitsPerSample);
  1437. inStream.Read(mMinSample);
  1438. inStream.Read(mMaxSample);
  1439. inStream.Read(mRangeBlocks);
  1440. inStream.Read(mHeightSamples);
  1441. inStream.Read(mActiveEdges);
  1442. inStream.Read(mMaterialIndices);
  1443. inStream.Read(mNumBitsPerMaterialIndex);
  1444. CacheValues();
  1445. }
  1446. void HeightFieldShape::SaveMaterialState(PhysicsMaterialList &outMaterials) const
  1447. {
  1448. outMaterials = mMaterials;
  1449. }
  1450. void HeightFieldShape::RestoreMaterialState(const PhysicsMaterialRefC *inMaterials, uint inNumMaterials)
  1451. {
  1452. mMaterials.assign(inMaterials, inMaterials + inNumMaterials);
  1453. }
  1454. Shape::Stats HeightFieldShape::GetStats() const
  1455. {
  1456. return Stats(
  1457. sizeof(*this)
  1458. + mMaterials.size() * sizeof(Ref<PhysicsMaterial>)
  1459. + mRangeBlocks.size() * sizeof(RangeBlock)
  1460. + mHeightSamples.size() * sizeof(uint8)
  1461. + mActiveEdges.size() * sizeof(uint8)
  1462. + mMaterialIndices.size() * sizeof(uint8),
  1463. Square(mSampleCount - 1) * 2);
  1464. }
  1465. } // JPH