HeightFieldShape.cpp 98 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673
  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/Physics/Collision/CollideSoftBodyVerticesVsTriangles.h>
  23. #include <Jolt/Core/Profiler.h>
  24. #include <Jolt/Core/StringTools.h>
  25. #include <Jolt/Core/StreamIn.h>
  26. #include <Jolt/Core/StreamOut.h>
  27. #include <Jolt/Core/TempAllocator.h>
  28. #include <Jolt/Geometry/AABox4.h>
  29. #include <Jolt/Geometry/RayTriangle.h>
  30. #include <Jolt/Geometry/RayAABox.h>
  31. #include <Jolt/Geometry/OrientedBox.h>
  32. #include <Jolt/ObjectStream/TypeDeclarations.h>
  33. //#define JPH_DEBUG_HEIGHT_FIELD
  34. JPH_NAMESPACE_BEGIN
  35. #ifdef JPH_DEBUG_RENDERER
  36. bool HeightFieldShape::sDrawTriangleOutlines = false;
  37. #endif // JPH_DEBUG_RENDERER
  38. using namespace HeightFieldShapeConstants;
  39. JPH_IMPLEMENT_SERIALIZABLE_VIRTUAL(HeightFieldShapeSettings)
  40. {
  41. JPH_ADD_BASE_CLASS(HeightFieldShapeSettings, ShapeSettings)
  42. JPH_ADD_ATTRIBUTE(HeightFieldShapeSettings, mHeightSamples)
  43. JPH_ADD_ATTRIBUTE(HeightFieldShapeSettings, mOffset)
  44. JPH_ADD_ATTRIBUTE(HeightFieldShapeSettings, mScale)
  45. JPH_ADD_ATTRIBUTE(HeightFieldShapeSettings, mMinHeightValue)
  46. JPH_ADD_ATTRIBUTE(HeightFieldShapeSettings, mMaxHeightValue)
  47. JPH_ADD_ATTRIBUTE(HeightFieldShapeSettings, mMaterialsCapacity)
  48. JPH_ADD_ATTRIBUTE(HeightFieldShapeSettings, mSampleCount)
  49. JPH_ADD_ATTRIBUTE(HeightFieldShapeSettings, mBlockSize)
  50. JPH_ADD_ATTRIBUTE(HeightFieldShapeSettings, mBitsPerSample)
  51. JPH_ADD_ATTRIBUTE(HeightFieldShapeSettings, mMaterialIndices)
  52. JPH_ADD_ATTRIBUTE(HeightFieldShapeSettings, mMaterials)
  53. JPH_ADD_ATTRIBUTE(HeightFieldShapeSettings, mActiveEdgeCosThresholdAngle)
  54. }
  55. const uint HeightFieldShape::sGridOffsets[] =
  56. {
  57. 0, // level: 0, max x/y: 0, offset: 0
  58. 1, // level: 1, max x/y: 1, offset: 1
  59. 5, // level: 2, max x/y: 3, offset: 1 + 4
  60. 21, // level: 3, max x/y: 7, offset: 1 + 4 + 16
  61. 85, // level: 4, max x/y: 15, offset: 1 + 4 + 16 + 64
  62. 341, // level: 5, max x/y: 31, offset: 1 + 4 + 16 + 64 + 256
  63. 1365, // level: 6, max x/y: 63, offset: 1 + 4 + 16 + 64 + 256 + 1024
  64. 5461, // level: 7, max x/y: 127, offset: 1 + 4 + 16 + 64 + 256 + 1024 + 4096
  65. 21845, // level: 8, max x/y: 255, offset: 1 + 4 + 16 + 64 + 256 + 1024 + 4096 + ...
  66. 87381, // level: 9, max x/y: 511, offset: 1 + 4 + 16 + 64 + 256 + 1024 + 4096 + ...
  67. 349525, // level: 10, max x/y: 1023, offset: 1 + 4 + 16 + 64 + 256 + 1024 + 4096 + ...
  68. 1398101, // level: 11, max x/y: 2047, offset: 1 + 4 + 16 + 64 + 256 + 1024 + 4096 + ...
  69. 5592405, // level: 12, max x/y: 4095, offset: 1 + 4 + 16 + 64 + 256 + 1024 + 4096 + ...
  70. 22369621, // level: 13, max x/y: 8191, offset: 1 + 4 + 16 + 64 + 256 + 1024 + 4096 + ...
  71. 89478485, // level: 14, max x/y: 16383, offset: 1 + 4 + 16 + 64 + 256 + 1024 + 4096 + ...
  72. };
  73. HeightFieldShapeSettings::HeightFieldShapeSettings(const float *inSamples, Vec3Arg inOffset, Vec3Arg inScale, uint32 inSampleCount, const uint8 *inMaterialIndices, const PhysicsMaterialList &inMaterialList) :
  74. mOffset(inOffset),
  75. mScale(inScale),
  76. mSampleCount(inSampleCount)
  77. {
  78. mHeightSamples.assign(inSamples, inSamples + Square(inSampleCount));
  79. if (!inMaterialList.empty() && inMaterialIndices != nullptr)
  80. {
  81. mMaterialIndices.assign(inMaterialIndices, inMaterialIndices + Square(inSampleCount - 1));
  82. mMaterials = inMaterialList;
  83. }
  84. else
  85. {
  86. JPH_ASSERT(inMaterialList.empty());
  87. JPH_ASSERT(inMaterialIndices == nullptr);
  88. }
  89. }
  90. ShapeSettings::ShapeResult HeightFieldShapeSettings::Create() const
  91. {
  92. if (mCachedResult.IsEmpty())
  93. Ref<Shape> shape = new HeightFieldShape(*this, mCachedResult);
  94. return mCachedResult;
  95. }
  96. void HeightFieldShapeSettings::DetermineMinAndMaxSample(float &outMinValue, float &outMaxValue, float &outQuantizationScale) const
  97. {
  98. // Determine min and max value
  99. outMinValue = mMinHeightValue;
  100. outMaxValue = mMaxHeightValue;
  101. for (float h : mHeightSamples)
  102. if (h != cNoCollisionValue)
  103. {
  104. outMinValue = min(outMinValue, h);
  105. outMaxValue = max(outMaxValue, h);
  106. }
  107. // Prevent dividing by zero by setting a minimal height difference
  108. float height_diff = max(outMaxValue - outMinValue, 1.0e-6f);
  109. // Calculate the scale factor to quantize to 16 bits
  110. outQuantizationScale = float(cMaxHeightValue16) / height_diff;
  111. }
  112. uint32 HeightFieldShapeSettings::CalculateBitsPerSampleForError(float inMaxError) const
  113. {
  114. // Start with 1 bit per sample
  115. uint32 bits_per_sample = 1;
  116. // Determine total range
  117. float min_value, max_value, scale;
  118. DetermineMinAndMaxSample(min_value, max_value, scale);
  119. if (min_value < max_value)
  120. {
  121. // Loop over all blocks
  122. for (uint y = 0; y < mSampleCount; y += mBlockSize)
  123. for (uint x = 0; x < mSampleCount; x += mBlockSize)
  124. {
  125. // Determine min and max block value + take 1 sample border just like we do while building the hierarchical grids
  126. float block_min_value = FLT_MAX, block_max_value = -FLT_MAX;
  127. for (uint bx = x; bx < min(x + mBlockSize + 1, mSampleCount); ++bx)
  128. for (uint by = y; by < min(y + mBlockSize + 1, mSampleCount); ++by)
  129. {
  130. float h = mHeightSamples[by * mSampleCount + bx];
  131. if (h != cNoCollisionValue)
  132. {
  133. block_min_value = min(block_min_value, h);
  134. block_max_value = max(block_max_value, h);
  135. }
  136. }
  137. if (block_min_value < block_max_value)
  138. {
  139. // Quantize then dequantize block min/max value
  140. block_min_value = min_value + floor((block_min_value - min_value) * scale) / scale;
  141. block_max_value = min_value + ceil((block_max_value - min_value) * scale) / scale;
  142. float block_height = block_max_value - block_min_value;
  143. // Loop over the block again
  144. for (uint bx = x; bx < x + mBlockSize; ++bx)
  145. for (uint by = y; by < y + mBlockSize; ++by)
  146. {
  147. // Get the height
  148. float height = mHeightSamples[by * mSampleCount + bx];
  149. if (height != cNoCollisionValue)
  150. {
  151. for (;;)
  152. {
  153. // Determine bitmask for sample
  154. uint32 sample_mask = (1 << bits_per_sample) - 1;
  155. // Quantize
  156. float quantized_height = floor((height - block_min_value) * float(sample_mask) / block_height);
  157. quantized_height = Clamp(quantized_height, 0.0f, float(sample_mask - 1));
  158. // Dequantize and check error
  159. float dequantized_height = block_min_value + (quantized_height + 0.5f) * block_height / float(sample_mask);
  160. if (abs(dequantized_height - height) <= inMaxError)
  161. break;
  162. // Not accurate enough, increase bits per sample
  163. bits_per_sample++;
  164. // Don't go above 8 bits per sample
  165. if (bits_per_sample == 8)
  166. return bits_per_sample;
  167. }
  168. }
  169. }
  170. }
  171. }
  172. }
  173. return bits_per_sample;
  174. }
  175. void HeightFieldShape::CalculateActiveEdges(uint inX, uint inY, uint inSizeX, uint inSizeY, const float *inHeights, uint inHeightsStartX, uint inHeightsStartY, intptr_t inHeightsStride, float inHeightsScale, float inActiveEdgeCosThresholdAngle, TempAllocator &inAllocator)
  176. {
  177. // Allocate temporary buffer for normals
  178. uint normals_size = 2 * inSizeX * inSizeY * sizeof(Vec3);
  179. Vec3 *normals = (Vec3 *)inAllocator.Allocate(normals_size);
  180. // Calculate triangle normals and make normals zero for triangles that are missing
  181. Vec3 *out_normal = normals;
  182. for (uint y = 0; y < inSizeY; ++y)
  183. for (uint x = 0; x < inSizeX; ++x)
  184. {
  185. // Get height on diagonal
  186. const float *height_samples = inHeights + (inY - inHeightsStartY + y) * inHeightsStride + (inX - inHeightsStartX + x);
  187. float x1y1_h = height_samples[0];
  188. float x2y2_h = height_samples[inHeightsStride + 1];
  189. if (x1y1_h != cNoCollisionValue && x2y2_h != cNoCollisionValue)
  190. {
  191. // Calculate normal for lower left triangle (e.g. T1A)
  192. float x1y2_h = height_samples[inHeightsStride];
  193. if (x1y2_h != cNoCollisionValue)
  194. {
  195. Vec3 x2y2_minus_x1y2(mScale.GetX(), inHeightsScale * (x2y2_h - x1y2_h), 0);
  196. Vec3 x1y1_minus_x1y2(0, inHeightsScale * (x1y1_h - x1y2_h), -mScale.GetZ());
  197. out_normal[0] = x2y2_minus_x1y2.Cross(x1y1_minus_x1y2).Normalized();
  198. }
  199. else
  200. out_normal[0] = Vec3::sZero();
  201. // Calculate normal for upper right triangle (e.g. T1B)
  202. float x2y1_h = height_samples[1];
  203. if (x2y1_h != cNoCollisionValue)
  204. {
  205. Vec3 x1y1_minus_x2y1(-mScale.GetX(), inHeightsScale * (x1y1_h - x2y1_h), 0);
  206. Vec3 x2y2_minus_x2y1(0, inHeightsScale * (x2y2_h - x2y1_h), mScale.GetZ());
  207. out_normal[1] = x1y1_minus_x2y1.Cross(x2y2_minus_x2y1).Normalized();
  208. }
  209. else
  210. out_normal[1] = Vec3::sZero();
  211. }
  212. else
  213. {
  214. out_normal[0] = Vec3::sZero();
  215. out_normal[1] = Vec3::sZero();
  216. }
  217. out_normal += 2;
  218. }
  219. // Calculate active edges
  220. const Vec3 *in_normal = normals;
  221. uint global_bit_pos = 3 * (inY * (mSampleCount - 1) + inX);
  222. for (uint y = 0; y < inSizeY; ++y)
  223. {
  224. for (uint x = 0; x < inSizeX; ++x)
  225. {
  226. // Get vertex heights
  227. const float *height_samples = inHeights + (inY - inHeightsStartY + y) * inHeightsStride + (inX - inHeightsStartX + x);
  228. float x1y1_h = height_samples[0];
  229. float x1y2_h = height_samples[inHeightsStride];
  230. float x2y2_h = height_samples[inHeightsStride + 1];
  231. bool x1y1_valid = x1y1_h != cNoCollisionValue;
  232. bool x1y2_valid = x1y2_h != cNoCollisionValue;
  233. bool x2y2_valid = x2y2_h != cNoCollisionValue;
  234. // Calculate the edge flags (3 bits)
  235. // See diagram in the next function for the edge numbering
  236. uint16 edge_mask = 0b111;
  237. uint16 edge_flags = 0;
  238. // Edge 0
  239. if (x == 0)
  240. edge_mask &= 0b110; // We need normal x - 1 which we didn't calculate, don't update this edge
  241. else if (x1y1_valid && x1y2_valid)
  242. {
  243. Vec3 edge0_direction(0, inHeightsScale * (x1y2_h - x1y1_h), mScale.GetZ());
  244. if (ActiveEdges::IsEdgeActive(in_normal[0], in_normal[-1], edge0_direction, inActiveEdgeCosThresholdAngle))
  245. edge_flags |= 0b001;
  246. }
  247. // Edge 1
  248. if (y == inSizeY - 1)
  249. edge_mask &= 0b101; // We need normal y + 1 which we didn't calculate, don't update this edge
  250. else if (x1y2_valid && x2y2_valid)
  251. {
  252. Vec3 edge1_direction(mScale.GetX(), inHeightsScale * (x2y2_h - x1y2_h), 0);
  253. if (ActiveEdges::IsEdgeActive(in_normal[0], in_normal[2 * inSizeX + 1], edge1_direction, inActiveEdgeCosThresholdAngle))
  254. edge_flags |= 0b010;
  255. }
  256. // Edge 2
  257. if (x1y1_valid && x2y2_valid)
  258. {
  259. Vec3 edge2_direction(-mScale.GetX(), inHeightsScale * (x1y1_h - x2y2_h), -mScale.GetZ());
  260. if (ActiveEdges::IsEdgeActive(in_normal[0], in_normal[1], edge2_direction, inActiveEdgeCosThresholdAngle))
  261. edge_flags |= 0b100;
  262. }
  263. // Store the edge flags in the array
  264. uint byte_pos = global_bit_pos >> 3;
  265. uint bit_pos = global_bit_pos & 0b111;
  266. JPH_ASSERT(byte_pos < mActiveEdgesSize);
  267. uint8 *edge_flags_ptr = &mActiveEdges[byte_pos];
  268. uint16 combined_edge_flags = uint16(edge_flags_ptr[0]) | uint16(uint16(edge_flags_ptr[1]) << 8);
  269. combined_edge_flags &= ~(edge_mask << bit_pos);
  270. combined_edge_flags |= edge_flags << bit_pos;
  271. edge_flags_ptr[0] = uint8(combined_edge_flags);
  272. edge_flags_ptr[1] = uint8(combined_edge_flags >> 8);
  273. in_normal += 2;
  274. global_bit_pos += 3;
  275. }
  276. global_bit_pos += 3 * (mSampleCount - 1 - inSizeX);
  277. }
  278. // Free temporary buffer for normals
  279. inAllocator.Free(normals, normals_size);
  280. }
  281. void HeightFieldShape::CalculateActiveEdges(const HeightFieldShapeSettings &inSettings)
  282. {
  283. /*
  284. Store active edges. The triangles are organized like this:
  285. x --->
  286. y + +
  287. | \ T1B | \ T2B
  288. | e0 e2 | \
  289. | | T1A \ | T2A \
  290. V +--e1---+-------+
  291. | \ T3B | \ T4B
  292. | \ | \
  293. | T3A \ | T4A \
  294. +-------+-------+
  295. We store active edges e0 .. e2 as bits 0 .. 2.
  296. We store triangles horizontally then vertically (order T1A, T2A, T3A and T4A).
  297. The top edge and right edge of the heightfield are always active so we do not need to store them,
  298. therefore we only need to store (mSampleCount - 1)^2 * 3-bit
  299. The triangles T1B, T2B, T3B and T4B do not need to be stored, their active edges can be constructed from adjacent triangles.
  300. Add 1 byte padding so we can always read 1 uint16 to get the bits that cross an 8 bit boundary
  301. */
  302. // Make all edges active (if mSampleCount is bigger than inSettings.mSampleCount we need to fill up the padding,
  303. // also edges at x = 0 and y = inSettings.mSampleCount - 1 are not updated)
  304. memset(mActiveEdges, 0xff, mActiveEdgesSize);
  305. // Now clear the edges that are not active
  306. TempAllocatorMalloc allocator;
  307. CalculateActiveEdges(0, 0, inSettings.mSampleCount - 1, inSettings.mSampleCount - 1, inSettings.mHeightSamples.data(), 0, 0, inSettings.mSampleCount, inSettings.mScale.GetY(), inSettings.mActiveEdgeCosThresholdAngle, allocator);
  308. }
  309. void HeightFieldShape::StoreMaterialIndices(const HeightFieldShapeSettings &inSettings)
  310. {
  311. // We need to account for any rounding of the sample count to the nearest block size
  312. uint in_count_min_1 = inSettings.mSampleCount - 1;
  313. uint out_count_min_1 = mSampleCount - 1;
  314. mNumBitsPerMaterialIndex = 32 - CountLeadingZeros(max((uint32)mMaterials.size(), inSettings.mMaterialsCapacity) - 1);
  315. mMaterialIndices.resize(((Square(out_count_min_1) * mNumBitsPerMaterialIndex + 7) >> 3) + 1, 0); // Add 1 byte so we don't read out of bounds when reading an uint16
  316. if (mMaterials.size() > 1)
  317. for (uint y = 0; y < out_count_min_1; ++y)
  318. for (uint x = 0; x < out_count_min_1; ++x)
  319. {
  320. // Read material
  321. uint16 material_index = x < in_count_min_1 && y < in_count_min_1? uint16(inSettings.mMaterialIndices[x + y * in_count_min_1]) : 0;
  322. // Calculate byte and bit position where the material index needs to go
  323. uint sample_pos = x + y * out_count_min_1;
  324. uint bit_pos = sample_pos * mNumBitsPerMaterialIndex;
  325. uint byte_pos = bit_pos >> 3;
  326. bit_pos &= 0b111;
  327. // Write the material index
  328. material_index <<= bit_pos;
  329. JPH_ASSERT(byte_pos + 1 < mMaterialIndices.size());
  330. mMaterialIndices[byte_pos] |= uint8(material_index);
  331. mMaterialIndices[byte_pos + 1] |= uint8(material_index >> 8);
  332. }
  333. }
  334. void HeightFieldShape::CacheValues()
  335. {
  336. mSampleMask = uint8((uint32(1) << mBitsPerSample) - 1);
  337. }
  338. void HeightFieldShape::AllocateBuffers()
  339. {
  340. uint num_blocks = GetNumBlocks();
  341. uint max_stride = (num_blocks + 1) >> 1;
  342. mRangeBlocksSize = sGridOffsets[sGetMaxLevel(num_blocks) - 1] + Square(max_stride);
  343. mHeightSamplesSize = (mSampleCount * mSampleCount * mBitsPerSample + 7) / 8 + 1;
  344. mActiveEdgesSize = (Square(mSampleCount - 1) * 3 + 7) / 8 + 1; // See explanation at HeightFieldShape::CalculateActiveEdges
  345. JPH_ASSERT(mRangeBlocks == nullptr && mHeightSamples == nullptr && mActiveEdges == nullptr);
  346. void *data = AlignedAllocate(mRangeBlocksSize * sizeof(RangeBlock) + mHeightSamplesSize + mActiveEdgesSize, alignof(RangeBlock));
  347. mRangeBlocks = reinterpret_cast<RangeBlock *>(data);
  348. mHeightSamples = reinterpret_cast<uint8 *>(mRangeBlocks + mRangeBlocksSize);
  349. mActiveEdges = mHeightSamples + mHeightSamplesSize;
  350. }
  351. HeightFieldShape::HeightFieldShape(const HeightFieldShapeSettings &inSettings, ShapeResult &outResult) :
  352. Shape(EShapeType::HeightField, EShapeSubType::HeightField, inSettings, outResult),
  353. mOffset(inSettings.mOffset),
  354. mScale(inSettings.mScale),
  355. mSampleCount(((inSettings.mSampleCount + inSettings.mBlockSize - 1) / inSettings.mBlockSize) * inSettings.mBlockSize), // Round sample count to nearest block size
  356. mBlockSize(inSettings.mBlockSize),
  357. mBitsPerSample(uint8(inSettings.mBitsPerSample))
  358. {
  359. CacheValues();
  360. // Reserve a bigger materials list if requested
  361. if (inSettings.mMaterialsCapacity > 0)
  362. mMaterials.reserve(inSettings.mMaterialsCapacity);
  363. mMaterials = inSettings.mMaterials;
  364. // Check block size
  365. if (mBlockSize < 2 || mBlockSize > 8)
  366. {
  367. outResult.SetError("HeightFieldShape: Block size must be in the range [2, 8]!");
  368. return;
  369. }
  370. // Check bits per sample
  371. if (inSettings.mBitsPerSample < 1 || inSettings.mBitsPerSample > 8)
  372. {
  373. outResult.SetError("HeightFieldShape: Bits per sample must be in the range [1, 8]!");
  374. return;
  375. }
  376. // We stop at mBlockSize x mBlockSize height sample blocks
  377. uint num_blocks = GetNumBlocks();
  378. // We want at least 1 grid layer
  379. if (num_blocks < 2)
  380. {
  381. outResult.SetError("HeightFieldShape: Sample count too low!");
  382. return;
  383. }
  384. // Check that we don't overflow our 32 bit 'properties'
  385. if (num_blocks > (1 << cNumBitsXY))
  386. {
  387. outResult.SetError("HeightFieldShape: Sample count too high!");
  388. return;
  389. }
  390. // Check if we're not exceeding the amount of sub shape id bits
  391. if (GetSubShapeIDBitsRecursive() > SubShapeID::MaxBits)
  392. {
  393. outResult.SetError("HeightFieldShape: Size exceeds the amount of available sub shape ID bits!");
  394. return;
  395. }
  396. if (!mMaterials.empty())
  397. {
  398. // Validate materials
  399. if (mMaterials.size() > 256)
  400. {
  401. outResult.SetError("Supporting max 256 materials per height field");
  402. return;
  403. }
  404. for (uint8 s : inSettings.mMaterialIndices)
  405. if (s >= mMaterials.size())
  406. {
  407. outResult.SetError(StringFormat("Material %u is beyond material list (size: %u)", s, (uint)mMaterials.size()));
  408. return;
  409. }
  410. }
  411. else
  412. {
  413. // No materials assigned, validate that no materials have been specified
  414. if (!inSettings.mMaterialIndices.empty())
  415. {
  416. outResult.SetError("No materials present, mMaterialIndices should be empty");
  417. return;
  418. }
  419. }
  420. // Determine range
  421. float min_value, max_value, scale;
  422. inSettings.DetermineMinAndMaxSample(min_value, max_value, scale);
  423. if (min_value > max_value)
  424. {
  425. // If there is no collision with this heightmap, leave everything empty
  426. mMaterials.clear();
  427. outResult.Set(this);
  428. return;
  429. }
  430. // Allocate space for this shape
  431. AllocateBuffers();
  432. // Quantize to uint16
  433. Array<uint16> quantized_samples;
  434. quantized_samples.reserve(mSampleCount * mSampleCount);
  435. for (uint y = 0; y < inSettings.mSampleCount; ++y)
  436. {
  437. for (uint x = 0; x < inSettings.mSampleCount; ++x)
  438. {
  439. float h = inSettings.mHeightSamples[x + y * inSettings.mSampleCount];
  440. if (h == cNoCollisionValue)
  441. {
  442. quantized_samples.push_back(cNoCollisionValue16);
  443. }
  444. else
  445. {
  446. // Floor the quantized height to get a lower bound for the quantized value
  447. int quantized_height = (int)floor(scale * (h - min_value));
  448. // 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
  449. quantized_height = Clamp(quantized_height, 0, int(cMaxHeightValue16 - 1));
  450. quantized_samples.push_back(uint16(quantized_height));
  451. }
  452. }
  453. // Pad remaining columns with no collision
  454. for (uint x = inSettings.mSampleCount; x < mSampleCount; ++x)
  455. quantized_samples.push_back(cNoCollisionValue16);
  456. }
  457. // Pad remaining rows with no collision
  458. for (uint y = inSettings.mSampleCount; y < mSampleCount; ++y)
  459. for (uint x = 0; x < mSampleCount; ++x)
  460. quantized_samples.push_back(cNoCollisionValue16);
  461. // Update offset and scale to account for the compression to uint16
  462. if (min_value <= max_value) // Only when there was collision
  463. {
  464. // In GetPosition we always add 0.5 to the quantized sample in order to reduce the average error.
  465. // 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.
  466. min_value -= 0.5f / (scale * mSampleMask);
  467. mOffset.SetY(mOffset.GetY() + mScale.GetY() * min_value);
  468. }
  469. mScale.SetY(mScale.GetY() / scale);
  470. // Calculate amount of grids
  471. uint max_level = sGetMaxLevel(num_blocks);
  472. // Temporary data structure used during creating of a hierarchy of grids
  473. struct Range
  474. {
  475. uint16 mMin;
  476. uint16 mMax;
  477. };
  478. // 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
  479. Array<Array<Range>> ranges;
  480. ranges.resize(max_level + 1);
  481. // Calculate highest detail grid by combining mBlockSize x mBlockSize height samples
  482. Array<Range> *cur_range_vector = &ranges.back();
  483. uint num_blocks_pow2 = GetNextPowerOf2(num_blocks); // We calculate the range blocks as if the heightfield was a power of 2, when we save the range blocks we'll ignore the extra samples (this makes downsampling easier)
  484. cur_range_vector->resize(num_blocks_pow2 * num_blocks_pow2);
  485. Range *range_dst = &cur_range_vector->front();
  486. for (uint y = 0; y < num_blocks_pow2; ++y)
  487. for (uint x = 0; x < num_blocks_pow2; ++x)
  488. {
  489. range_dst->mMin = 0xffff;
  490. range_dst->mMax = 0;
  491. uint max_bx = x == num_blocks_pow2 - 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
  492. uint max_by = y == num_blocks_pow2 - 1? mBlockSize : mBlockSize + 1;
  493. for (uint by = 0; by < max_by; ++by)
  494. for (uint bx = 0; bx < max_bx; ++bx)
  495. {
  496. uint sx = x * mBlockSize + bx;
  497. uint sy = y * mBlockSize + by;
  498. if (sx < mSampleCount && sy < mSampleCount)
  499. {
  500. uint16 h = quantized_samples[sy * mSampleCount + sx];
  501. if (h != cNoCollisionValue16)
  502. {
  503. range_dst->mMin = min(range_dst->mMin, h);
  504. 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
  505. }
  506. }
  507. }
  508. ++range_dst;
  509. }
  510. // Calculate remaining grids
  511. for (uint n = num_blocks_pow2 >> 1; n >= 1; n >>= 1)
  512. {
  513. // Get source buffer
  514. const Range *range_src = &cur_range_vector->front();
  515. // Previous array element
  516. --cur_range_vector;
  517. // Make space for this grid
  518. cur_range_vector->resize(n * n);
  519. // Get target buffer
  520. range_dst = &cur_range_vector->front();
  521. // Combine the results of 2x2 ranges
  522. for (uint y = 0; y < n; ++y)
  523. for (uint x = 0; x < n; ++x)
  524. {
  525. range_dst->mMin = 0xffff;
  526. range_dst->mMax = 0;
  527. for (uint by = 0; by < 2; ++by)
  528. for (uint bx = 0; bx < 2; ++bx)
  529. {
  530. const Range &r = range_src[(y * 2 + by) * n * 2 + x * 2 + bx];
  531. range_dst->mMin = min(range_dst->mMin, r.mMin);
  532. range_dst->mMax = max(range_dst->mMax, r.mMax);
  533. }
  534. ++range_dst;
  535. }
  536. }
  537. JPH_ASSERT(cur_range_vector == &ranges.front());
  538. // Store global range for bounding box calculation
  539. mMinSample = ranges[0][0].mMin;
  540. mMaxSample = ranges[0][0].mMax;
  541. #ifdef JPH_ENABLE_ASSERTS
  542. // Validate that we did not lose range along the way
  543. uint16 minv = 0xffff, maxv = 0;
  544. for (uint16 v : quantized_samples)
  545. if (v != cNoCollisionValue16)
  546. {
  547. minv = min(minv, v);
  548. maxv = max(maxv, uint16(v + 1));
  549. }
  550. JPH_ASSERT(mMinSample == minv && mMaxSample == maxv);
  551. #endif
  552. // Now erase the first element, we need a 2x2 grid to start with
  553. ranges.erase(ranges.begin());
  554. // Create blocks
  555. uint max_stride = (num_blocks + 1) >> 1;
  556. RangeBlock *current_block = mRangeBlocks;
  557. for (uint level = 0; level < ranges.size(); ++level)
  558. {
  559. JPH_ASSERT(uint(current_block - mRangeBlocks) == sGridOffsets[level]);
  560. uint in_n = 1 << level;
  561. uint out_n = min(in_n, max_stride); // At the most detailed level we store a non-power of 2 number of blocks
  562. for (uint y = 0; y < out_n; ++y)
  563. for (uint x = 0; x < out_n; ++x)
  564. {
  565. // Convert from 2x2 Range structure to 1 RangeBlock structure
  566. RangeBlock &rb = *current_block++;
  567. for (uint by = 0; by < 2; ++by)
  568. for (uint bx = 0; bx < 2; ++bx)
  569. {
  570. uint src_pos = (y * 2 + by) * 2 * in_n + (x * 2 + bx);
  571. uint dst_pos = by * 2 + bx;
  572. rb.mMin[dst_pos] = ranges[level][src_pos].mMin;
  573. rb.mMax[dst_pos] = ranges[level][src_pos].mMax;
  574. }
  575. }
  576. }
  577. JPH_ASSERT(uint32(current_block - mRangeBlocks) == mRangeBlocksSize);
  578. // Quantize height samples
  579. memset(mHeightSamples, 0, mHeightSamplesSize);
  580. int sample = 0;
  581. for (uint y = 0; y < mSampleCount; ++y)
  582. for (uint x = 0; x < mSampleCount; ++x)
  583. {
  584. uint32 output_value;
  585. float h = x < inSettings.mSampleCount && y < inSettings.mSampleCount? inSettings.mHeightSamples[x + y * inSettings.mSampleCount] : cNoCollisionValue;
  586. if (h == cNoCollisionValue)
  587. {
  588. // No collision
  589. output_value = mSampleMask;
  590. }
  591. else
  592. {
  593. // Get range of block so we know what range to compress to
  594. uint bx = x / mBlockSize;
  595. uint by = y / mBlockSize;
  596. const Range &range = ranges.back()[by * num_blocks_pow2 + bx];
  597. JPH_ASSERT(range.mMin < range.mMax);
  598. // Quantize to mBitsPerSample bits, note that mSampleMask is reserved for indicating that there's no collision.
  599. // We divide the range into mSampleMask segments and use the mid points of these segments as the quantized values.
  600. // This results in a lower error than if we had quantized our data using the lowest point of all these segments.
  601. float h_min = min_value + range.mMin / scale;
  602. float h_delta = float(range.mMax - range.mMin) / scale;
  603. float quantized_height = floor((h - h_min) * float(mSampleMask) / h_delta);
  604. output_value = uint32(Clamp((int)quantized_height, 0, int(mSampleMask) - 1)); // mSampleMask is reserved as 'no collision value'
  605. }
  606. // Store the sample
  607. uint byte_pos = sample >> 3;
  608. uint bit_pos = sample & 0b111;
  609. output_value <<= bit_pos;
  610. JPH_ASSERT(byte_pos + 1 < mHeightSamplesSize);
  611. mHeightSamples[byte_pos] |= uint8(output_value);
  612. mHeightSamples[byte_pos + 1] |= uint8(output_value >> 8);
  613. sample += inSettings.mBitsPerSample;
  614. }
  615. // Calculate the active edges
  616. CalculateActiveEdges(inSettings);
  617. // Compress material indices
  618. if (mMaterials.size() > 1 || inSettings.mMaterialsCapacity > 1)
  619. StoreMaterialIndices(inSettings);
  620. outResult.Set(this);
  621. }
  622. HeightFieldShape::~HeightFieldShape()
  623. {
  624. if (mRangeBlocks != nullptr)
  625. AlignedFree(mRangeBlocks);
  626. }
  627. inline void HeightFieldShape::sGetRangeBlockOffsetAndStride(uint inNumBlocks, uint inMaxLevel, uint &outRangeBlockOffset, uint &outRangeBlockStride)
  628. {
  629. outRangeBlockOffset = sGridOffsets[inMaxLevel - 1];
  630. outRangeBlockStride = (inNumBlocks + 1) >> 1;
  631. }
  632. inline void HeightFieldShape::GetRangeBlock(uint inBlockX, uint inBlockY, uint inRangeBlockOffset, uint inRangeBlockStride, RangeBlock *&outBlock, uint &outIndexInBlock)
  633. {
  634. JPH_ASSERT(inBlockX < GetNumBlocks() && inBlockY < GetNumBlocks());
  635. // Convert to location of range block
  636. uint rbx = inBlockX >> 1;
  637. uint rby = inBlockY >> 1;
  638. outIndexInBlock = ((inBlockY & 1) << 1) + (inBlockX & 1);
  639. uint offset = inRangeBlockOffset + rby * inRangeBlockStride + rbx;
  640. JPH_ASSERT(offset < mRangeBlocksSize);
  641. outBlock = mRangeBlocks + offset;
  642. }
  643. inline void HeightFieldShape::GetBlockOffsetAndScale(uint inBlockX, uint inBlockY, uint inRangeBlockOffset, uint inRangeBlockStride, float &outBlockOffset, float &outBlockScale) const
  644. {
  645. JPH_ASSERT(inBlockX < GetNumBlocks() && inBlockY < GetNumBlocks());
  646. // Convert to location of range block
  647. uint rbx = inBlockX >> 1;
  648. uint rby = inBlockY >> 1;
  649. uint n = ((inBlockY & 1) << 1) + (inBlockX & 1);
  650. // Calculate offset and scale
  651. uint offset = inRangeBlockOffset + rby * inRangeBlockStride + rbx;
  652. JPH_ASSERT(offset < mRangeBlocksSize);
  653. const RangeBlock &block = mRangeBlocks[offset];
  654. outBlockOffset = float(block.mMin[n]);
  655. outBlockScale = float(block.mMax[n] - block.mMin[n]) / float(mSampleMask);
  656. }
  657. inline uint8 HeightFieldShape::GetHeightSample(uint inX, uint inY) const
  658. {
  659. JPH_ASSERT(inX < mSampleCount);
  660. JPH_ASSERT(inY < mSampleCount);
  661. // Determine bit position of sample
  662. uint sample = (inY * mSampleCount + inX) * uint(mBitsPerSample);
  663. uint byte_pos = sample >> 3;
  664. uint bit_pos = sample & 0b111;
  665. // Fetch the height sample value
  666. JPH_ASSERT(byte_pos + 1 < mHeightSamplesSize);
  667. const uint8 *height_samples = mHeightSamples + byte_pos;
  668. uint16 height_sample = uint16(height_samples[0]) | uint16(uint16(height_samples[1]) << 8);
  669. return uint8(height_sample >> bit_pos) & mSampleMask;
  670. }
  671. inline Vec3 HeightFieldShape::GetPosition(uint inX, uint inY, float inBlockOffset, float inBlockScale, bool &outNoCollision) const
  672. {
  673. // Get quantized value
  674. uint8 height_sample = GetHeightSample(inX, inY);
  675. outNoCollision = height_sample == mSampleMask;
  676. // Add 0.5 to the quantized value to minimize the error (see constructor)
  677. return mOffset + mScale * Vec3(float(inX), inBlockOffset + (0.5f + height_sample) * inBlockScale, float(inY));
  678. }
  679. Vec3 HeightFieldShape::GetPosition(uint inX, uint inY) const
  680. {
  681. // Test if there are any samples
  682. if (mHeightSamplesSize == 0)
  683. return mOffset + mScale * Vec3(float(inX), 0.0f, float(inY));
  684. // Get block location
  685. uint bx = inX / mBlockSize;
  686. uint by = inY / mBlockSize;
  687. // Calculate offset and stride
  688. uint num_blocks = GetNumBlocks();
  689. uint range_block_offset, range_block_stride;
  690. sGetRangeBlockOffsetAndStride(num_blocks, sGetMaxLevel(num_blocks), range_block_offset, range_block_stride);
  691. float offset, scale;
  692. GetBlockOffsetAndScale(bx, by, range_block_offset, range_block_stride, offset, scale);
  693. bool no_collision;
  694. return GetPosition(inX, inY, offset, scale, no_collision);
  695. }
  696. bool HeightFieldShape::IsNoCollision(uint inX, uint inY) const
  697. {
  698. return mHeightSamplesSize == 0 || GetHeightSample(inX, inY) == mSampleMask;
  699. }
  700. bool HeightFieldShape::ProjectOntoSurface(Vec3Arg inLocalPosition, Vec3 &outSurfacePosition, SubShapeID &outSubShapeID) const
  701. {
  702. // Check if we have collision
  703. if (mHeightSamplesSize == 0)
  704. return false;
  705. // Convert coordinate to integer space
  706. Vec3 integer_space = (inLocalPosition - mOffset) / mScale;
  707. // Get x coordinate and fraction
  708. float x_frac = integer_space.GetX();
  709. if (x_frac < 0.0f || x_frac >= mSampleCount - 1)
  710. return false;
  711. uint x = (uint)floor(x_frac);
  712. x_frac -= x;
  713. // Get y coordinate and fraction
  714. float y_frac = integer_space.GetZ();
  715. if (y_frac < 0.0f || y_frac >= mSampleCount - 1)
  716. return false;
  717. uint y = (uint)floor(y_frac);
  718. y_frac -= y;
  719. // If one of the diagonal points doesn't have collision, we don't have a height at this location
  720. if (IsNoCollision(x, y) || IsNoCollision(x + 1, y + 1))
  721. return false;
  722. if (y_frac >= x_frac)
  723. {
  724. // Left bottom triangle, test the 3rd point
  725. if (IsNoCollision(x, y + 1))
  726. return false;
  727. // Interpolate height value
  728. Vec3 v1 = GetPosition(x, y);
  729. Vec3 v2 = GetPosition(x, y + 1);
  730. Vec3 v3 = GetPosition(x + 1, y + 1);
  731. outSurfacePosition = v1 + y_frac * (v2 - v1) + x_frac * (v3 - v2);
  732. SubShapeIDCreator creator;
  733. outSubShapeID = EncodeSubShapeID(creator, x, y, 0);
  734. return true;
  735. }
  736. else
  737. {
  738. // Right top triangle, test the third point
  739. if (IsNoCollision(x + 1, y))
  740. return false;
  741. // Interpolate height value
  742. Vec3 v1 = GetPosition(x, y);
  743. Vec3 v2 = GetPosition(x + 1, y + 1);
  744. Vec3 v3 = GetPosition(x + 1, y);
  745. outSurfacePosition = v1 + y_frac * (v2 - v3) + x_frac * (v3 - v1);
  746. SubShapeIDCreator creator;
  747. outSubShapeID = EncodeSubShapeID(creator, x, y, 1);
  748. return true;
  749. }
  750. }
  751. void HeightFieldShape::GetHeights(uint inX, uint inY, uint inSizeX, uint inSizeY, float *outHeights, intptr_t inHeightsStride) const
  752. {
  753. if (inSizeX == 0 || inSizeY == 0)
  754. return;
  755. JPH_ASSERT(inX % mBlockSize == 0 && inY % mBlockSize == 0);
  756. JPH_ASSERT(inX < mSampleCount && inY < mSampleCount);
  757. JPH_ASSERT(inX + inSizeX <= mSampleCount && inY + inSizeY <= mSampleCount);
  758. // Test if there are any samples
  759. if (mHeightSamplesSize == 0)
  760. {
  761. // No samples, return the offset
  762. float offset = mOffset.GetY();
  763. for (uint y = 0; y < inSizeY; ++y, outHeights += inHeightsStride)
  764. for (uint x = 0; x < inSizeX; ++x)
  765. outHeights[x] = offset;
  766. }
  767. else
  768. {
  769. // Calculate offset and stride
  770. uint num_blocks = GetNumBlocks();
  771. uint range_block_offset, range_block_stride;
  772. sGetRangeBlockOffsetAndStride(num_blocks, sGetMaxLevel(num_blocks), range_block_offset, range_block_stride);
  773. // Loop over blocks
  774. uint block_start_x = inX / mBlockSize;
  775. uint block_start_y = inY / mBlockSize;
  776. uint num_blocks_x = inSizeX / mBlockSize;
  777. uint num_blocks_y = inSizeY / mBlockSize;
  778. for (uint block_y = 0; block_y < num_blocks_y; ++block_y)
  779. for (uint block_x = 0; block_x < num_blocks_x; ++block_x)
  780. {
  781. // Get offset and scale for block
  782. float offset, scale;
  783. GetBlockOffsetAndScale(block_start_x + block_x, block_start_y + block_y, range_block_offset, range_block_stride, offset, scale);
  784. // Adjust by global offset and scale
  785. // Note: This is the math applied in GetPosition() written out to reduce calculations in the inner loop
  786. scale *= mScale.GetY();
  787. offset = mOffset.GetY() + mScale.GetY() * offset + 0.5f * scale;
  788. // Loop over samples in block
  789. for (uint sample_y = 0; sample_y < mBlockSize; ++sample_y)
  790. for (uint sample_x = 0; sample_x < mBlockSize; ++sample_x)
  791. {
  792. // Calculate output coordinate
  793. uint output_x = block_x * mBlockSize + sample_x;
  794. uint output_y = block_y * mBlockSize + sample_y;
  795. // Get quantized value
  796. uint8 height_sample = GetHeightSample(inX + output_x, inY + output_y);
  797. // Dequantize
  798. float h = height_sample != mSampleMask? offset + height_sample * scale : cNoCollisionValue;
  799. outHeights[output_y * inHeightsStride + output_x] = h;
  800. }
  801. }
  802. }
  803. }
  804. void HeightFieldShape::SetHeights(uint inX, uint inY, uint inSizeX, uint inSizeY, const float *inHeights, intptr_t inHeightsStride, TempAllocator &inAllocator, float inActiveEdgeCosThresholdAngle)
  805. {
  806. if (inSizeX == 0 || inSizeY == 0)
  807. return;
  808. JPH_ASSERT(mHeightSamplesSize > 0);
  809. JPH_ASSERT(inX % mBlockSize == 0 && inY % mBlockSize == 0);
  810. JPH_ASSERT(inX < mSampleCount && inY < mSampleCount);
  811. JPH_ASSERT(inX + inSizeX <= mSampleCount && inY + inSizeY <= mSampleCount);
  812. // If we have a block in negative x/y direction, we will affect its range so we need to take it into account
  813. bool need_temp_heights = false;
  814. uint affected_x = inX;
  815. uint affected_y = inY;
  816. uint affected_size_x = inSizeX;
  817. uint affected_size_y = inSizeY;
  818. if (inX > 0) { affected_x -= mBlockSize; affected_size_x += mBlockSize; need_temp_heights = true; }
  819. if (inY > 0) { affected_y -= mBlockSize; affected_size_y += mBlockSize; need_temp_heights = true; }
  820. // If we have a block in positive x/y direction, our ranges are affected by it so we need to take it into account
  821. uint heights_size_x = affected_size_x;
  822. uint heights_size_y = affected_size_y;
  823. if (inX + inSizeX < mSampleCount) { heights_size_x += mBlockSize; need_temp_heights = true; }
  824. if (inY + inSizeY < mSampleCount) { heights_size_y += mBlockSize; need_temp_heights = true; }
  825. // Get heights for affected area
  826. const float *heights;
  827. intptr_t heights_stride;
  828. float *temp_heights;
  829. if (need_temp_heights)
  830. {
  831. // Fetch the surrounding height data (note we're forced to recompress this data with a potentially different range so there will be some precision loss here)
  832. temp_heights = (float *)inAllocator.Allocate(heights_size_x * heights_size_y * sizeof(float));
  833. heights = temp_heights;
  834. heights_stride = heights_size_x;
  835. // We need to fill in the following areas:
  836. //
  837. // +-----------------+
  838. // | 2 |
  839. // |---+---------+---|
  840. // | | | |
  841. // | 3 | 1 | 4 |
  842. // | | | |
  843. // |---+---------+---|
  844. // | 5 |
  845. // +-----------------+
  846. //
  847. // 1. The area that is affected by the new heights (we just copy these)
  848. // 2-5. These areas are either needed to calculate the range of the affected blocks or they need to be recompressed with a different range
  849. uint offset_x = inX - affected_x;
  850. uint offset_y = inY - affected_y;
  851. // Area 2
  852. GetHeights(affected_x, affected_y, heights_size_x, offset_y, temp_heights, heights_size_x);
  853. float *area3_start = temp_heights + offset_y * heights_size_x;
  854. // Area 3
  855. GetHeights(affected_x, inY, offset_x, inSizeY, area3_start, heights_size_x);
  856. // Area 1
  857. float *area1_start = area3_start + offset_x;
  858. for (uint y = 0; y < inSizeY; ++y, area1_start += heights_size_x, inHeights += inHeightsStride)
  859. memcpy(area1_start, inHeights, inSizeX * sizeof(float));
  860. // Area 4
  861. uint area4_x = inX + inSizeX;
  862. GetHeights(area4_x, inY, affected_x + heights_size_x - area4_x, inSizeY, area3_start + area4_x - affected_x, heights_size_x);
  863. // Area 5
  864. uint area5_y = inY + inSizeY;
  865. float *area5_start = temp_heights + (area5_y - affected_y) * heights_size_x;
  866. GetHeights(affected_x, area5_y, heights_size_x, affected_y + heights_size_y - area5_y, area5_start, heights_size_x);
  867. }
  868. else
  869. {
  870. // We can directly use the input buffer because there are no extra edges to take into account
  871. heights = inHeights;
  872. heights_stride = inHeightsStride;
  873. temp_heights = nullptr;
  874. }
  875. // Calculate offset and stride
  876. uint num_blocks = GetNumBlocks();
  877. uint range_block_offset, range_block_stride;
  878. uint max_level = sGetMaxLevel(num_blocks);
  879. sGetRangeBlockOffsetAndStride(num_blocks, max_level, range_block_offset, range_block_stride);
  880. // Loop over blocks
  881. uint block_start_x = affected_x / mBlockSize;
  882. uint block_start_y = affected_y / mBlockSize;
  883. uint num_blocks_x = affected_size_x / mBlockSize;
  884. uint num_blocks_y = affected_size_y / mBlockSize;
  885. for (uint block_y = 0, sample_start_y = 0; block_y < num_blocks_y; ++block_y, sample_start_y += mBlockSize)
  886. for (uint block_x = 0, sample_start_x = 0; block_x < num_blocks_x; ++block_x, sample_start_x += mBlockSize)
  887. {
  888. // Determine quantized min and max value for block
  889. // Note that we need to include 1 extra row in the positive x/y direction to account for connecting triangles
  890. int min_value = 0xffff;
  891. int max_value = 0;
  892. uint sample_x_end = min(sample_start_x + mBlockSize + 1, mSampleCount - affected_x);
  893. uint sample_y_end = min(sample_start_y + mBlockSize + 1, mSampleCount - affected_y);
  894. for (uint sample_y = sample_start_y; sample_y < sample_y_end; ++sample_y)
  895. for (uint sample_x = sample_start_x; sample_x < sample_x_end; ++sample_x)
  896. {
  897. float h = heights[sample_y * heights_stride + sample_x];
  898. if (h != cNoCollisionValue)
  899. {
  900. int quantized_height = Clamp((int)floor((h - mOffset.GetY()) / mScale.GetY()), 0, int(cMaxHeightValue16 - 1));
  901. min_value = min(min_value, quantized_height);
  902. max_value = max(max_value, quantized_height + 1);
  903. }
  904. }
  905. if (min_value > max_value)
  906. min_value = max_value = cNoCollisionValue16;
  907. // Update range for block
  908. RangeBlock *range_block;
  909. uint index_in_block;
  910. GetRangeBlock(block_start_x + block_x, block_start_y + block_y, range_block_offset, range_block_stride, range_block, index_in_block);
  911. range_block->mMin[index_in_block] = uint16(min_value);
  912. range_block->mMax[index_in_block] = uint16(max_value);
  913. // Get offset and scale for block
  914. float offset_block = float(min_value);
  915. float scale_block = float(max_value - min_value) / float(mSampleMask);
  916. // Calculate scale and offset using the formula used in GetPosition() solved for the quantized height (excluding 0.5 because we round down while quantizing)
  917. float scale = scale_block * mScale.GetY();
  918. float offset = mOffset.GetY() + offset_block * mScale.GetY();
  919. // Loop over samples in block
  920. sample_x_end = sample_start_x + mBlockSize;
  921. sample_y_end = sample_start_y + mBlockSize;
  922. for (uint sample_y = sample_start_y; sample_y < sample_y_end; ++sample_y)
  923. for (uint sample_x = sample_start_x; sample_x < sample_x_end; ++sample_x)
  924. {
  925. // Quantize height
  926. float h = heights[sample_y * heights_stride + sample_x];
  927. uint8 quantized_height = h != cNoCollisionValue? uint8(Clamp((int)floor((h - offset) / scale), 0, int(mSampleMask) - 1)) : mSampleMask;
  928. // Determine bit position of sample
  929. uint sample = ((affected_y + sample_y) * mSampleCount + affected_x + sample_x) * uint(mBitsPerSample);
  930. uint byte_pos = sample >> 3;
  931. uint bit_pos = sample & 0b111;
  932. // Update the height value sample
  933. JPH_ASSERT(byte_pos + 1 < mHeightSamplesSize);
  934. uint8 *height_samples = mHeightSamples + byte_pos;
  935. uint16 height_sample = uint16(height_samples[0]) | uint16(uint16(height_samples[1]) << 8);
  936. height_sample &= ~(uint16(mSampleMask) << bit_pos);
  937. height_sample |= uint16(quantized_height) << bit_pos;
  938. height_samples[0] = uint8(height_sample);
  939. height_samples[1] = uint8(height_sample >> 8);
  940. }
  941. }
  942. // Update active edges
  943. // Note that we must take an extra row on all sides to account for connecting triangles
  944. uint ae_x = inX > 1? inX - 2 : 0;
  945. uint ae_y = inY > 1? inY - 2 : 0;
  946. uint ae_sx = min(inX + inSizeX + 1, mSampleCount - 1) - ae_x;
  947. uint ae_sy = min(inY + inSizeY + 1, mSampleCount - 1) - ae_y;
  948. CalculateActiveEdges(ae_x, ae_y, ae_sx, ae_sy, heights, affected_x, affected_y, heights_stride, 1.0f, inActiveEdgeCosThresholdAngle, inAllocator);
  949. // Free temporary buffer
  950. if (temp_heights != nullptr)
  951. inAllocator.Free(temp_heights, heights_size_x * heights_size_y * sizeof(float));
  952. // Update hierarchy of range blocks
  953. while (max_level > 1)
  954. {
  955. // Get offset and stride for destination blocks
  956. uint dst_range_block_offset, dst_range_block_stride;
  957. sGetRangeBlockOffsetAndStride(num_blocks >> 1, max_level - 1, dst_range_block_offset, dst_range_block_stride);
  958. // If we're starting halfway through a 2x2 block, we need to process one extra block since we take steps of 2 blocks below
  959. uint block_x_end = (block_start_x & 1) && block_start_x + num_blocks_x < num_blocks? num_blocks_x + 1 : num_blocks_x;
  960. uint block_y_end = (block_start_y & 1) && block_start_y + num_blocks_y < num_blocks? num_blocks_y + 1 : num_blocks_y;
  961. // Loop over all affected blocks
  962. for (uint block_y = 0; block_y < block_y_end; block_y += 2)
  963. for (uint block_x = 0; block_x < block_x_end; block_x += 2)
  964. {
  965. // Get source range block
  966. RangeBlock *src_range_block;
  967. uint index_in_src_block;
  968. GetRangeBlock(block_start_x + block_x, block_start_y + block_y, range_block_offset, range_block_stride, src_range_block, index_in_src_block);
  969. // Determine quantized min and max value for the entire 2x2 block
  970. uint16 min_value = 0xffff;
  971. uint16 max_value = 0;
  972. for (uint i = 0; i < 4; ++i)
  973. if (src_range_block->mMin[i] != cNoCollisionValue16)
  974. {
  975. min_value = min(min_value, src_range_block->mMin[i]);
  976. max_value = max(max_value, src_range_block->mMax[i]);
  977. }
  978. // Write to destination block
  979. RangeBlock *dst_range_block;
  980. uint index_in_dst_block;
  981. GetRangeBlock((block_start_x + block_x) >> 1, (block_start_y + block_y) >> 1, dst_range_block_offset, dst_range_block_stride, dst_range_block, index_in_dst_block);
  982. dst_range_block->mMin[index_in_dst_block] = uint16(min_value);
  983. dst_range_block->mMax[index_in_dst_block] = uint16(max_value);
  984. }
  985. // Go up one level
  986. --max_level;
  987. num_blocks >>= 1;
  988. block_start_x >>= 1;
  989. block_start_y >>= 1;
  990. num_blocks_x = min((num_blocks_x + 1) >> 1, num_blocks);
  991. num_blocks_y = min((num_blocks_y + 1) >> 1, num_blocks);
  992. // Update stride and offset for source to old destination
  993. range_block_offset = dst_range_block_offset;
  994. range_block_stride = dst_range_block_stride;
  995. }
  996. // Calculate new min and max sample for the entire height field
  997. mMinSample = 0xffff;
  998. mMaxSample = 0;
  999. for (uint i = 0; i < 4; ++i)
  1000. if (mRangeBlocks[0].mMin[i] != cNoCollisionValue16)
  1001. {
  1002. mMinSample = min(mMinSample, mRangeBlocks[0].mMin[i]);
  1003. mMaxSample = max(mMaxSample, mRangeBlocks[0].mMax[i]);
  1004. }
  1005. #ifdef JPH_DEBUG_RENDERER
  1006. // Invalidate temporary rendering data
  1007. mGeometry.clear();
  1008. #endif
  1009. }
  1010. void HeightFieldShape::GetMaterials(uint inX, uint inY, uint inSizeX, uint inSizeY, uint8 *outMaterials, intptr_t inMaterialsStride) const
  1011. {
  1012. if (inSizeX == 0 || inSizeY == 0)
  1013. return;
  1014. if (mMaterialIndices.empty())
  1015. {
  1016. // Return all 0's
  1017. for (uint y = 0; y < inSizeY; ++y)
  1018. {
  1019. uint8 *out_indices = outMaterials + y * inMaterialsStride;
  1020. for (uint x = 0; x < inSizeX; ++x)
  1021. *out_indices++ = 0;
  1022. }
  1023. return;
  1024. }
  1025. JPH_ASSERT(inX < mSampleCount && inY < mSampleCount);
  1026. JPH_ASSERT(inX + inSizeX < mSampleCount && inY + inSizeY < mSampleCount);
  1027. uint count_min_1 = mSampleCount - 1;
  1028. uint16 material_index_mask = uint16((1 << mNumBitsPerMaterialIndex) - 1);
  1029. for (uint y = 0; y < inSizeY; ++y)
  1030. {
  1031. // Calculate input position
  1032. uint bit_pos = (inX + (inY + y) * count_min_1) * mNumBitsPerMaterialIndex;
  1033. const uint8 *in_indices = mMaterialIndices.data() + (bit_pos >> 3);
  1034. bit_pos &= 0b111;
  1035. // Calculate output position
  1036. uint8 *out_indices = outMaterials + y * inMaterialsStride;
  1037. for (uint x = 0; x < inSizeX; ++x)
  1038. {
  1039. // Get material index
  1040. uint16 material_index = uint16(in_indices[0]) + uint16(uint16(in_indices[1]) << 8);
  1041. material_index >>= bit_pos;
  1042. material_index &= material_index_mask;
  1043. *out_indices = uint8(material_index);
  1044. // Go to the next index
  1045. bit_pos += mNumBitsPerMaterialIndex;
  1046. in_indices += bit_pos >> 3;
  1047. bit_pos &= 0b111;
  1048. ++out_indices;
  1049. }
  1050. }
  1051. }
  1052. bool HeightFieldShape::SetMaterials(uint inX, uint inY, uint inSizeX, uint inSizeY, const uint8 *inMaterials, intptr_t inMaterialsStride, const PhysicsMaterialList *inMaterialList, TempAllocator &inAllocator)
  1053. {
  1054. if (inSizeX == 0 || inSizeY == 0)
  1055. return true;
  1056. JPH_ASSERT(inX < mSampleCount && inY < mSampleCount);
  1057. JPH_ASSERT(inX + inSizeX < mSampleCount && inY + inSizeY < mSampleCount);
  1058. // Remap materials
  1059. uint material_remap_table_size = uint(inMaterialList != nullptr? inMaterialList->size() : mMaterials.size());
  1060. uint8 *material_remap_table = (uint8 *)inAllocator.Allocate(material_remap_table_size);
  1061. if (inMaterialList != nullptr)
  1062. {
  1063. // Conservatively reserve more space if the incoming material list is bigger
  1064. if (inMaterialList->size() > mMaterials.size())
  1065. mMaterials.reserve(inMaterialList->size());
  1066. // Create a remap table
  1067. uint8 *remap_entry = material_remap_table;
  1068. for (const PhysicsMaterial *material : *inMaterialList)
  1069. {
  1070. // Try to find it in the existing list
  1071. PhysicsMaterialList::const_iterator it = std::find(mMaterials.begin(), mMaterials.end(), material);
  1072. if (it != mMaterials.end())
  1073. {
  1074. // Found it, calculate index
  1075. *remap_entry = uint8(it - mMaterials.begin());
  1076. }
  1077. else
  1078. {
  1079. // Not found, add it
  1080. if (mMaterials.size() >= 256)
  1081. {
  1082. // We can't have more than 256 materials since we use uint8 as indices
  1083. inAllocator.Free(material_remap_table, material_remap_table_size);
  1084. return false;
  1085. }
  1086. *remap_entry = uint8(mMaterials.size());
  1087. mMaterials.push_back(material);
  1088. }
  1089. ++remap_entry;
  1090. }
  1091. }
  1092. else
  1093. {
  1094. // No remapping
  1095. for (uint i = 0; i < material_remap_table_size; ++i)
  1096. material_remap_table[i] = uint8(i);
  1097. }
  1098. if (mMaterials.size() == 1)
  1099. {
  1100. // Only 1 material, we don't need to store the material indices
  1101. return true;
  1102. }
  1103. // Check if we need to resize the material indices array
  1104. uint count_min_1 = mSampleCount - 1;
  1105. uint32 new_bits_per_material_index = 32 - CountLeadingZeros((uint32)mMaterials.size() - 1);
  1106. JPH_ASSERT(mNumBitsPerMaterialIndex <= 8 && new_bits_per_material_index <= 8);
  1107. if (new_bits_per_material_index > mNumBitsPerMaterialIndex)
  1108. {
  1109. // Resize the material indices array
  1110. mMaterialIndices.resize(((Square(count_min_1) * new_bits_per_material_index + 7) >> 3) + 1, 0); // Add 1 byte so we don't read out of bounds when reading an uint16
  1111. // Calculate old and new mask
  1112. uint16 old_material_index_mask = uint16((1 << mNumBitsPerMaterialIndex) - 1);
  1113. uint16 new_material_index_mask = uint16((1 << new_bits_per_material_index) - 1);
  1114. // Loop through the array backwards to avoid overwriting data
  1115. int in_bit_pos = (count_min_1 * count_min_1 - 1) * mNumBitsPerMaterialIndex;
  1116. const uint8 *in_indices = mMaterialIndices.data() + (in_bit_pos >> 3);
  1117. in_bit_pos &= 0b111;
  1118. int out_bit_pos = (count_min_1 * count_min_1 - 1) * new_bits_per_material_index;
  1119. uint8 *out_indices = mMaterialIndices.data() + (out_bit_pos >> 3);
  1120. out_bit_pos &= 0b111;
  1121. while (out_indices >= mMaterialIndices.data())
  1122. {
  1123. // Read the material index
  1124. uint16 material_index = uint16(in_indices[0]) + uint16(uint16(in_indices[1]) << 8);
  1125. material_index >>= in_bit_pos;
  1126. material_index &= old_material_index_mask;
  1127. // Write the material index
  1128. uint16 output_data = uint16(out_indices[0]) + uint16(uint16(out_indices[1]) << 8);
  1129. output_data &= ~(new_material_index_mask << out_bit_pos);
  1130. output_data |= material_index << out_bit_pos;
  1131. out_indices[0] = uint8(output_data);
  1132. out_indices[1] = uint8(output_data >> 8);
  1133. // Go to the previous index
  1134. in_bit_pos -= int(mNumBitsPerMaterialIndex);
  1135. in_indices += in_bit_pos >> 3;
  1136. in_bit_pos &= 0b111;
  1137. out_bit_pos -= int(new_bits_per_material_index);
  1138. out_indices += out_bit_pos >> 3;
  1139. out_bit_pos &= 0b111;
  1140. }
  1141. // Accept the new bits per material index
  1142. mNumBitsPerMaterialIndex = new_bits_per_material_index;
  1143. }
  1144. uint16 material_index_mask = uint16((1 << mNumBitsPerMaterialIndex) - 1);
  1145. for (uint y = 0; y < inSizeY; ++y)
  1146. {
  1147. // Calculate input position
  1148. const uint8 *in_indices = inMaterials + y * inMaterialsStride;
  1149. // Calculate output position
  1150. uint bit_pos = (inX + (inY + y) * count_min_1) * mNumBitsPerMaterialIndex;
  1151. uint8 *out_indices = mMaterialIndices.data() + (bit_pos >> 3);
  1152. bit_pos &= 0b111;
  1153. for (uint x = 0; x < inSizeX; ++x)
  1154. {
  1155. // Update material
  1156. uint16 output_data = uint16(out_indices[0]) + uint16(uint16(out_indices[1]) << 8);
  1157. output_data &= ~(material_index_mask << bit_pos);
  1158. output_data |= material_remap_table[*in_indices] << bit_pos;
  1159. out_indices[0] = uint8(output_data);
  1160. out_indices[1] = uint8(output_data >> 8);
  1161. // Go to the next index
  1162. in_indices++;
  1163. bit_pos += mNumBitsPerMaterialIndex;
  1164. out_indices += bit_pos >> 3;
  1165. bit_pos &= 0b111;
  1166. }
  1167. }
  1168. // Free the remapping table
  1169. inAllocator.Free(material_remap_table, material_remap_table_size);
  1170. return true;
  1171. }
  1172. MassProperties HeightFieldShape::GetMassProperties() const
  1173. {
  1174. // Object should always be static, return default mass properties
  1175. return MassProperties();
  1176. }
  1177. const PhysicsMaterial *HeightFieldShape::GetMaterial(uint inX, uint inY) const
  1178. {
  1179. if (mMaterials.empty())
  1180. return PhysicsMaterial::sDefault;
  1181. if (mMaterials.size() == 1)
  1182. return mMaterials[0];
  1183. uint count_min_1 = mSampleCount - 1;
  1184. JPH_ASSERT(inX < count_min_1);
  1185. JPH_ASSERT(inY < count_min_1);
  1186. // Calculate at which bit the material index starts
  1187. uint bit_pos = (inX + inY * count_min_1) * mNumBitsPerMaterialIndex;
  1188. uint byte_pos = bit_pos >> 3;
  1189. bit_pos &= 0b111;
  1190. // Read the material index
  1191. JPH_ASSERT(byte_pos + 1 < mMaterialIndices.size());
  1192. const uint8 *material_indices = mMaterialIndices.data() + byte_pos;
  1193. uint16 material_index = uint16(material_indices[0]) + uint16(uint16(material_indices[1]) << 8);
  1194. material_index >>= bit_pos;
  1195. material_index &= (1 << mNumBitsPerMaterialIndex) - 1;
  1196. // Return the material
  1197. return mMaterials[material_index];
  1198. }
  1199. uint HeightFieldShape::GetSubShapeIDBits() const
  1200. {
  1201. // Need to store X, Y and 1 extra bit to specify the triangle number in the quad
  1202. return 2 * (32 - CountLeadingZeros(mSampleCount - 1)) + 1;
  1203. }
  1204. SubShapeID HeightFieldShape::EncodeSubShapeID(const SubShapeIDCreator &inCreator, uint inX, uint inY, uint inTriangle) const
  1205. {
  1206. return inCreator.PushID((inX + inY * mSampleCount) * 2 + inTriangle, GetSubShapeIDBits()).GetID();
  1207. }
  1208. void HeightFieldShape::DecodeSubShapeID(const SubShapeID &inSubShapeID, uint &outX, uint &outY, uint &outTriangle) const
  1209. {
  1210. // Decode sub shape id
  1211. SubShapeID remainder;
  1212. uint32 id = inSubShapeID.PopID(GetSubShapeIDBits(), remainder);
  1213. JPH_ASSERT(remainder.IsEmpty(), "Invalid subshape ID");
  1214. // Get triangle index
  1215. outTriangle = id & 1;
  1216. id >>= 1;
  1217. // Fetch the x and y coordinate
  1218. outX = id % mSampleCount;
  1219. outY = id / mSampleCount;
  1220. }
  1221. const PhysicsMaterial *HeightFieldShape::GetMaterial(const SubShapeID &inSubShapeID) const
  1222. {
  1223. // Decode ID
  1224. uint x, y, triangle;
  1225. DecodeSubShapeID(inSubShapeID, x, y, triangle);
  1226. // Fetch the material
  1227. return GetMaterial(x, y);
  1228. }
  1229. Vec3 HeightFieldShape::GetSurfaceNormal(const SubShapeID &inSubShapeID, Vec3Arg inLocalSurfacePosition) const
  1230. {
  1231. // Decode ID
  1232. uint x, y, triangle;
  1233. DecodeSubShapeID(inSubShapeID, x, y, triangle);
  1234. // Fetch vertices that both triangles share
  1235. Vec3 x1y1 = GetPosition(x, y);
  1236. Vec3 x2y2 = GetPosition(x + 1, y + 1);
  1237. // Get normal depending on which triangle was selected
  1238. Vec3 normal;
  1239. if (triangle == 0)
  1240. {
  1241. Vec3 x1y2 = GetPosition(x, y + 1);
  1242. normal = (x2y2 - x1y2).Cross(x1y1 - x1y2);
  1243. }
  1244. else
  1245. {
  1246. Vec3 x2y1 = GetPosition(x + 1, y);
  1247. normal = (x1y1 - x2y1).Cross(x2y2 - x2y1);
  1248. }
  1249. return normal.Normalized();
  1250. }
  1251. void HeightFieldShape::GetSupportingFace(const SubShapeID &inSubShapeID, Vec3Arg inDirection, Vec3Arg inScale, Mat44Arg inCenterOfMassTransform, SupportingFace &outVertices) const
  1252. {
  1253. // Decode ID
  1254. uint x, y, triangle;
  1255. DecodeSubShapeID(inSubShapeID, x, y, triangle);
  1256. // Fetch the triangle
  1257. outVertices.resize(3);
  1258. outVertices[0] = GetPosition(x, y);
  1259. Vec3 v2 = GetPosition(x + 1, y + 1);
  1260. if (triangle == 0)
  1261. {
  1262. outVertices[1] = GetPosition(x, y + 1);
  1263. outVertices[2] = v2;
  1264. }
  1265. else
  1266. {
  1267. outVertices[1] = v2;
  1268. outVertices[2] = GetPosition(x + 1, y);
  1269. }
  1270. // Flip triangle if scaled inside out
  1271. if (ScaleHelpers::IsInsideOut(inScale))
  1272. swap(outVertices[1], outVertices[2]);
  1273. // Transform to world space
  1274. Mat44 transform = inCenterOfMassTransform.PreScaled(inScale);
  1275. for (Vec3 &v : outVertices)
  1276. v = transform * v;
  1277. }
  1278. inline uint8 HeightFieldShape::GetEdgeFlags(uint inX, uint inY, uint inTriangle) const
  1279. {
  1280. JPH_ASSERT(inX < mSampleCount - 1 && inY < mSampleCount - 1);
  1281. if (inTriangle == 0)
  1282. {
  1283. // The edge flags for this triangle are directly stored, find the right 3 bits
  1284. uint bit_pos = 3 * (inX + inY * (mSampleCount - 1));
  1285. uint byte_pos = bit_pos >> 3;
  1286. bit_pos &= 0b111;
  1287. JPH_ASSERT(byte_pos + 1 < mActiveEdgesSize);
  1288. const uint8 *active_edges = mActiveEdges + byte_pos;
  1289. uint16 edge_flags = uint16(active_edges[0]) + uint16(uint16(active_edges[1]) << 8);
  1290. return uint8(edge_flags >> bit_pos) & 0b111;
  1291. }
  1292. else
  1293. {
  1294. // We don't store this triangle directly, we need to look at our three neighbours to construct the edge flags
  1295. uint8 edge0 = (GetEdgeFlags(inX, inY, 0) & 0b100) != 0? 0b001 : 0; // Diagonal edge
  1296. uint8 edge1 = inX == mSampleCount - 2 || (GetEdgeFlags(inX + 1, inY, 0) & 0b001) != 0? 0b010 : 0; // Vertical edge
  1297. uint8 edge2 = inY == 0 || (GetEdgeFlags(inX, inY - 1, 0) & 0b010) != 0? 0b100 : 0; // Horizontal edge
  1298. return edge0 | edge1 | edge2;
  1299. }
  1300. }
  1301. AABox HeightFieldShape::GetLocalBounds() const
  1302. {
  1303. if (mMinSample == cNoCollisionValue16)
  1304. {
  1305. // This whole height field shape doesn't have any collision, return the center point
  1306. Vec3 center = mOffset + 0.5f * mScale * Vec3(float(mSampleCount - 1), 0.0f, float(mSampleCount - 1));
  1307. return AABox(center, center);
  1308. }
  1309. else
  1310. {
  1311. // Bounding box based on min and max sample height
  1312. Vec3 bmin = mOffset + mScale * Vec3(0.0f, float(mMinSample), 0.0f);
  1313. Vec3 bmax = mOffset + mScale * Vec3(float(mSampleCount - 1), float(mMaxSample), float(mSampleCount - 1));
  1314. return AABox(bmin, bmax);
  1315. }
  1316. }
  1317. #ifdef JPH_DEBUG_RENDERER
  1318. void HeightFieldShape::Draw(DebugRenderer *inRenderer, RMat44Arg inCenterOfMassTransform, Vec3Arg inScale, ColorArg inColor, bool inUseMaterialColors, bool inDrawWireframe) const
  1319. {
  1320. // Don't draw anything if we don't have any collision
  1321. if (mHeightSamplesSize == 0)
  1322. return;
  1323. // Reset the batch if we switch coloring mode
  1324. if (mCachedUseMaterialColors != inUseMaterialColors)
  1325. {
  1326. mGeometry.clear();
  1327. mCachedUseMaterialColors = inUseMaterialColors;
  1328. }
  1329. if (mGeometry.empty())
  1330. {
  1331. // Divide terrain in triangle batches of max 64x64x2 triangles to allow better culling of the terrain
  1332. uint32 block_size = min<uint32>(mSampleCount, 64);
  1333. for (uint32 by = 0; by < mSampleCount; by += block_size)
  1334. for (uint32 bx = 0; bx < mSampleCount; bx += block_size)
  1335. {
  1336. // Create vertices for a block
  1337. Array<DebugRenderer::Triangle> triangles;
  1338. triangles.resize(block_size * block_size * 2);
  1339. DebugRenderer::Triangle *out_tri = &triangles[0];
  1340. for (uint32 y = by, max_y = min(by + block_size, mSampleCount - 1); y < max_y; ++y)
  1341. for (uint32 x = bx, max_x = min(bx + block_size, mSampleCount - 1); x < max_x; ++x)
  1342. if (!IsNoCollision(x, y) && !IsNoCollision(x + 1, y + 1))
  1343. {
  1344. Vec3 x1y1 = GetPosition(x, y);
  1345. Vec3 x2y2 = GetPosition(x + 1, y + 1);
  1346. Color color = inUseMaterialColors? GetMaterial(x, y)->GetDebugColor() : Color::sWhite;
  1347. if (!IsNoCollision(x, y + 1))
  1348. {
  1349. Vec3 x1y2 = GetPosition(x, y + 1);
  1350. x1y1.StoreFloat3(&out_tri->mV[0].mPosition);
  1351. x1y2.StoreFloat3(&out_tri->mV[1].mPosition);
  1352. x2y2.StoreFloat3(&out_tri->mV[2].mPosition);
  1353. Vec3 normal = (x2y2 - x1y2).Cross(x1y1 - x1y2).Normalized();
  1354. for (DebugRenderer::Vertex &v : out_tri->mV)
  1355. {
  1356. v.mColor = color;
  1357. v.mUV = Float2(0, 0);
  1358. normal.StoreFloat3(&v.mNormal);
  1359. }
  1360. ++out_tri;
  1361. }
  1362. if (!IsNoCollision(x + 1, y))
  1363. {
  1364. Vec3 x2y1 = GetPosition(x + 1, y);
  1365. x1y1.StoreFloat3(&out_tri->mV[0].mPosition);
  1366. x2y2.StoreFloat3(&out_tri->mV[1].mPosition);
  1367. x2y1.StoreFloat3(&out_tri->mV[2].mPosition);
  1368. Vec3 normal = (x1y1 - x2y1).Cross(x2y2 - x2y1).Normalized();
  1369. for (DebugRenderer::Vertex &v : out_tri->mV)
  1370. {
  1371. v.mColor = color;
  1372. v.mUV = Float2(0, 0);
  1373. normal.StoreFloat3(&v.mNormal);
  1374. }
  1375. ++out_tri;
  1376. }
  1377. }
  1378. // Resize triangles array to actual amount of triangles written
  1379. size_t num_triangles = out_tri - &triangles[0];
  1380. triangles.resize(num_triangles);
  1381. // Create batch
  1382. if (num_triangles > 0)
  1383. mGeometry.push_back(new DebugRenderer::Geometry(inRenderer->CreateTriangleBatch(triangles), DebugRenderer::sCalculateBounds(&triangles[0].mV[0], int(3 * num_triangles))));
  1384. }
  1385. }
  1386. // Get transform including scale
  1387. RMat44 transform = inCenterOfMassTransform.PreScaled(inScale);
  1388. // Test if the shape is scaled inside out
  1389. DebugRenderer::ECullMode cull_mode = ScaleHelpers::IsInsideOut(inScale)? DebugRenderer::ECullMode::CullFrontFace : DebugRenderer::ECullMode::CullBackFace;
  1390. // Determine the draw mode
  1391. DebugRenderer::EDrawMode draw_mode = inDrawWireframe? DebugRenderer::EDrawMode::Wireframe : DebugRenderer::EDrawMode::Solid;
  1392. // Draw the geometry
  1393. for (const DebugRenderer::GeometryRef &b : mGeometry)
  1394. inRenderer->DrawGeometry(transform, inColor, b, cull_mode, DebugRenderer::ECastShadow::On, draw_mode);
  1395. if (sDrawTriangleOutlines)
  1396. {
  1397. struct Visitor
  1398. {
  1399. JPH_INLINE explicit Visitor(const HeightFieldShape *inShape, DebugRenderer *inRenderer, RMat44Arg inTransform) :
  1400. mShape(inShape),
  1401. mRenderer(inRenderer),
  1402. mTransform(inTransform)
  1403. {
  1404. }
  1405. JPH_INLINE bool ShouldAbort() const
  1406. {
  1407. return false;
  1408. }
  1409. JPH_INLINE bool ShouldVisitRangeBlock([[maybe_unused]] int inStackTop) const
  1410. {
  1411. return true;
  1412. }
  1413. JPH_INLINE int VisitRangeBlock(Vec4Arg inBoundsMinX, Vec4Arg inBoundsMinY, Vec4Arg inBoundsMinZ, Vec4Arg inBoundsMaxX, Vec4Arg inBoundsMaxY, Vec4Arg inBoundsMaxZ, UVec4 &ioProperties, [[maybe_unused]] int inStackTop) const
  1414. {
  1415. UVec4 valid = Vec4::sLessOrEqual(inBoundsMinY, inBoundsMaxY);
  1416. return CountAndSortTrues(valid, ioProperties);
  1417. }
  1418. JPH_INLINE void VisitTriangle(uint inX, uint inY, uint inTriangle, Vec3Arg inV0, Vec3Arg inV1, Vec3Arg inV2) const
  1419. {
  1420. // Determine active edges
  1421. uint8 active_edges = mShape->GetEdgeFlags(inX, inY, inTriangle);
  1422. // Loop through edges
  1423. Vec3 v[] = { inV0, inV1, inV2 };
  1424. for (uint edge_idx = 0; edge_idx < 3; ++edge_idx)
  1425. {
  1426. RVec3 v1 = mTransform * v[edge_idx];
  1427. RVec3 v2 = mTransform * v[(edge_idx + 1) % 3];
  1428. // Draw active edge as a green arrow, other edges as grey
  1429. if (active_edges & (1 << edge_idx))
  1430. mRenderer->DrawArrow(v1, v2, Color::sGreen, 0.01f);
  1431. else
  1432. mRenderer->DrawLine(v1, v2, Color::sGrey);
  1433. }
  1434. }
  1435. const HeightFieldShape *mShape;
  1436. DebugRenderer * mRenderer;
  1437. RMat44 mTransform;
  1438. };
  1439. Visitor visitor(this, inRenderer, inCenterOfMassTransform.PreScaled(inScale));
  1440. WalkHeightField(visitor);
  1441. }
  1442. }
  1443. #endif // JPH_DEBUG_RENDERER
  1444. class HeightFieldShape::DecodingContext
  1445. {
  1446. public:
  1447. JPH_INLINE explicit DecodingContext(const HeightFieldShape *inShape) :
  1448. mShape(inShape)
  1449. {
  1450. static_assert(sizeof(sGridOffsets) / sizeof(uint) == cNumBitsXY + 1, "Offsets array is not long enough");
  1451. // Construct root stack entry
  1452. mPropertiesStack[0] = 0; // level: 0, x: 0, y: 0
  1453. }
  1454. template <class Visitor>
  1455. JPH_INLINE void WalkHeightField(Visitor &ioVisitor)
  1456. {
  1457. // Early out if there's no collision
  1458. if (mShape->mHeightSamplesSize == 0)
  1459. return;
  1460. // Precalculate values relating to sample count
  1461. uint32 sample_count = mShape->mSampleCount;
  1462. UVec4 sample_count_min_1 = UVec4::sReplicate(sample_count - 1);
  1463. // Precalculate values relating to block size
  1464. uint32 block_size = mShape->mBlockSize;
  1465. uint32 block_size_plus_1 = block_size + 1;
  1466. uint num_blocks = mShape->GetNumBlocks();
  1467. uint num_blocks_min_1 = num_blocks - 1;
  1468. uint max_level = HeightFieldShape::sGetMaxLevel(num_blocks);
  1469. uint32 max_stride = (num_blocks + 1) >> 1;
  1470. // Precalculate range block offset and stride for GetBlockOffsetAndScale
  1471. uint range_block_offset, range_block_stride;
  1472. sGetRangeBlockOffsetAndStride(num_blocks, max_level, range_block_offset, range_block_stride);
  1473. // Allocate space for vertices and 'no collision' flags
  1474. int array_size = Square(block_size_plus_1);
  1475. Vec3 *vertices = reinterpret_cast<Vec3 *>(JPH_STACK_ALLOC(array_size * sizeof(Vec3)));
  1476. bool *no_collision = reinterpret_cast<bool *>(JPH_STACK_ALLOC(array_size * sizeof(bool)));
  1477. // Splat offsets
  1478. Vec4 ox = mShape->mOffset.SplatX();
  1479. Vec4 oy = mShape->mOffset.SplatY();
  1480. Vec4 oz = mShape->mOffset.SplatZ();
  1481. // Splat scales
  1482. Vec4 sx = mShape->mScale.SplatX();
  1483. Vec4 sy = mShape->mScale.SplatY();
  1484. Vec4 sz = mShape->mScale.SplatZ();
  1485. do
  1486. {
  1487. // Decode properties
  1488. uint32 properties_top = mPropertiesStack[mTop];
  1489. uint32 x = properties_top & cMaskBitsXY;
  1490. uint32 y = (properties_top >> cNumBitsXY) & cMaskBitsXY;
  1491. uint32 level = properties_top >> cLevelShift;
  1492. if (level >= max_level)
  1493. {
  1494. // Determine actual range of samples (minus one because we eventually want to iterate over the triangles, not the samples)
  1495. uint32 min_x = x * block_size;
  1496. uint32 max_x = min_x + block_size;
  1497. uint32 min_y = y * block_size;
  1498. uint32 max_y = min_y + block_size;
  1499. // Decompress vertices of block at (x, y)
  1500. Vec3 *dst_vertex = vertices;
  1501. bool *dst_no_collision = no_collision;
  1502. float block_offset, block_scale;
  1503. mShape->GetBlockOffsetAndScale(x, y, range_block_offset, range_block_stride, block_offset, block_scale);
  1504. for (uint32 v_y = min_y; v_y < max_y; ++v_y)
  1505. {
  1506. for (uint32 v_x = min_x; v_x < max_x; ++v_x)
  1507. {
  1508. *dst_vertex = mShape->GetPosition(v_x, v_y, block_offset, block_scale, *dst_no_collision);
  1509. ++dst_vertex;
  1510. ++dst_no_collision;
  1511. }
  1512. // Skip last column, these values come from a different block
  1513. ++dst_vertex;
  1514. ++dst_no_collision;
  1515. }
  1516. // Decompress block (x + 1, y)
  1517. uint32 max_x_decrement = 0;
  1518. if (x < num_blocks_min_1)
  1519. {
  1520. dst_vertex = vertices + block_size;
  1521. dst_no_collision = no_collision + block_size;
  1522. mShape->GetBlockOffsetAndScale(x + 1, y, range_block_offset, range_block_stride, block_offset, block_scale);
  1523. for (uint32 v_y = min_y; v_y < max_y; ++v_y)
  1524. {
  1525. *dst_vertex = mShape->GetPosition(max_x, v_y, block_offset, block_scale, *dst_no_collision);
  1526. dst_vertex += block_size_plus_1;
  1527. dst_no_collision += block_size_plus_1;
  1528. }
  1529. }
  1530. else
  1531. max_x_decrement = 1; // We don't have a next block, one less triangle to test
  1532. // Decompress block (x, y + 1)
  1533. if (y < num_blocks_min_1)
  1534. {
  1535. uint start = block_size * block_size_plus_1;
  1536. dst_vertex = vertices + start;
  1537. dst_no_collision = no_collision + start;
  1538. mShape->GetBlockOffsetAndScale(x, y + 1, range_block_offset, range_block_stride, block_offset, block_scale);
  1539. for (uint32 v_x = min_x; v_x < max_x; ++v_x)
  1540. {
  1541. *dst_vertex = mShape->GetPosition(v_x, max_y, block_offset, block_scale, *dst_no_collision);
  1542. ++dst_vertex;
  1543. ++dst_no_collision;
  1544. }
  1545. // Decompress single sample of block at (x + 1, y + 1)
  1546. if (x < num_blocks_min_1)
  1547. {
  1548. mShape->GetBlockOffsetAndScale(x + 1, y + 1, range_block_offset, range_block_stride, block_offset, block_scale);
  1549. *dst_vertex = mShape->GetPosition(max_x, max_y, block_offset, block_scale, *dst_no_collision);
  1550. }
  1551. }
  1552. else
  1553. --max_y; // We don't have a next block, one less triangle to test
  1554. // Update max_x (we've been using it so we couldn't update it earlier)
  1555. max_x -= max_x_decrement;
  1556. // We're going to divide the vertices in 4 blocks to do one more runtime sub-division, calculate the ranges of those blocks
  1557. struct Range
  1558. {
  1559. uint32 mMinX, mMinY, mNumTrianglesX, mNumTrianglesY;
  1560. };
  1561. uint32 half_block_size = block_size >> 1;
  1562. uint32 block_size_x = max_x - min_x - half_block_size;
  1563. uint32 block_size_y = max_y - min_y - half_block_size;
  1564. Range ranges[] =
  1565. {
  1566. { 0, 0, half_block_size, half_block_size },
  1567. { half_block_size, 0, block_size_x, half_block_size },
  1568. { 0, half_block_size, half_block_size, block_size_y },
  1569. { half_block_size, half_block_size, block_size_x, block_size_y },
  1570. };
  1571. // Calculate the min and max of each of the blocks
  1572. Mat44 block_min, block_max;
  1573. for (int block = 0; block < 4; ++block)
  1574. {
  1575. // Get the range for this block
  1576. const Range &range = ranges[block];
  1577. uint32 start = range.mMinX + range.mMinY * block_size_plus_1;
  1578. uint32 size_x_plus_1 = range.mNumTrianglesX + 1;
  1579. uint32 size_y_plus_1 = range.mNumTrianglesY + 1;
  1580. // Calculate where to start reading
  1581. const Vec3 *src_vertex = vertices + start;
  1582. const bool *src_no_collision = no_collision + start;
  1583. uint32 stride = block_size_plus_1 - size_x_plus_1;
  1584. // Start range with a very large inside-out box
  1585. Vec3 value_min = Vec3::sReplicate(1.0e30f);
  1586. Vec3 value_max = Vec3::sReplicate(-1.0e30f);
  1587. // Loop over the samples to determine the min and max of this block
  1588. for (uint32 block_y = 0; block_y < size_y_plus_1; ++block_y)
  1589. {
  1590. for (uint32 block_x = 0; block_x < size_x_plus_1; ++block_x)
  1591. {
  1592. if (!*src_no_collision)
  1593. {
  1594. value_min = Vec3::sMin(value_min, *src_vertex);
  1595. value_max = Vec3::sMax(value_max, *src_vertex);
  1596. }
  1597. ++src_vertex;
  1598. ++src_no_collision;
  1599. }
  1600. src_vertex += stride;
  1601. src_no_collision += stride;
  1602. }
  1603. block_min.SetColumn4(block, Vec4(value_min));
  1604. block_max.SetColumn4(block, Vec4(value_max));
  1605. }
  1606. #ifdef JPH_DEBUG_HEIGHT_FIELD
  1607. // Draw the bounding boxes of the sub-nodes
  1608. for (int block = 0; block < 4; ++block)
  1609. {
  1610. AABox bounds(block_min.GetColumn3(block), block_max.GetColumn3(block));
  1611. if (bounds.IsValid())
  1612. DebugRenderer::sInstance->DrawWireBox(bounds, Color::sYellow);
  1613. }
  1614. #endif // JPH_DEBUG_HEIGHT_FIELD
  1615. // Transpose so we have the mins and maxes of each of the blocks in rows instead of columns
  1616. Mat44 transposed_min = block_min.Transposed();
  1617. Mat44 transposed_max = block_max.Transposed();
  1618. // Check which blocks collide
  1619. // Note: At this point we don't use our own stack but we do allow the visitor to use its own stack
  1620. // to store collision distances so that we can still early out when no closer hits have been found.
  1621. UVec4 colliding_blocks(0, 1, 2, 3);
  1622. 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);
  1623. // Loop through the results backwards (closest first)
  1624. int result = num_results - 1;
  1625. while (result >= 0)
  1626. {
  1627. // Calculate the min and max of this block
  1628. uint32 block = colliding_blocks[result];
  1629. const Range &range = ranges[block];
  1630. uint32 block_min_x = min_x + range.mMinX;
  1631. uint32 block_max_x = block_min_x + range.mNumTrianglesX;
  1632. uint32 block_min_y = min_y + range.mMinY;
  1633. uint32 block_max_y = block_min_y + range.mNumTrianglesY;
  1634. // Loop triangles
  1635. for (uint32 v_y = block_min_y; v_y < block_max_y; ++v_y)
  1636. for (uint32 v_x = block_min_x; v_x < block_max_x; ++v_x)
  1637. {
  1638. // Get first vertex
  1639. const int offset = (v_y - min_y) * block_size_plus_1 + (v_x - min_x);
  1640. const Vec3 *start_vertex = vertices + offset;
  1641. const bool *start_no_collision = no_collision + offset;
  1642. // Check if vertices shared by both triangles have collision
  1643. if (!start_no_collision[0] && !start_no_collision[block_size_plus_1 + 1])
  1644. {
  1645. // Loop 2 triangles
  1646. for (uint t = 0; t < 2; ++t)
  1647. {
  1648. // Determine triangle vertices
  1649. Vec3 v0, v1, v2;
  1650. if (t == 0)
  1651. {
  1652. // Check third vertex
  1653. if (start_no_collision[block_size_plus_1])
  1654. continue;
  1655. // Get vertices for triangle
  1656. v0 = start_vertex[0];
  1657. v1 = start_vertex[block_size_plus_1];
  1658. v2 = start_vertex[block_size_plus_1 + 1];
  1659. }
  1660. else
  1661. {
  1662. // Check third vertex
  1663. if (start_no_collision[1])
  1664. continue;
  1665. // Get vertices for triangle
  1666. v0 = start_vertex[0];
  1667. v1 = start_vertex[block_size_plus_1 + 1];
  1668. v2 = start_vertex[1];
  1669. }
  1670. #ifdef JPH_DEBUG_HEIGHT_FIELD
  1671. DebugRenderer::sInstance->DrawWireTriangle(RVec3(v0), RVec3(v1), RVec3(v2), Color::sWhite);
  1672. #endif
  1673. // Call visitor
  1674. ioVisitor.VisitTriangle(v_x, v_y, t, v0, v1, v2);
  1675. // Check if we're done
  1676. if (ioVisitor.ShouldAbort())
  1677. return;
  1678. }
  1679. }
  1680. }
  1681. // Fetch next block until we find one that the visitor wants to see
  1682. do
  1683. --result;
  1684. while (result >= 0 && !ioVisitor.ShouldVisitRangeBlock(mTop + result));
  1685. }
  1686. }
  1687. else
  1688. {
  1689. // Visit child grid
  1690. uint32 stride = min(1U << level, max_stride); // At the most detailed level we store a non-power of 2 number of blocks
  1691. uint32 offset = sGridOffsets[level] + stride * y + x;
  1692. // Decode min/max height
  1693. JPH_ASSERT(offset < mShape->mRangeBlocksSize);
  1694. UVec4 block = UVec4::sLoadInt4Aligned(reinterpret_cast<const uint32 *>(&mShape->mRangeBlocks[offset]));
  1695. Vec4 bounds_miny = oy + sy * block.Expand4Uint16Lo().ToFloat();
  1696. Vec4 bounds_maxy = oy + sy * block.Expand4Uint16Hi().ToFloat();
  1697. // Calculate size of one cell at this grid level
  1698. UVec4 internal_cell_size = UVec4::sReplicate(block_size << (max_level - level - 1)); // subtract 1 from level because we have an internal grid of 2x2
  1699. // Calculate min/max x and z
  1700. UVec4 two_x = UVec4::sReplicate(2 * x); // multiply by two because we have an internal grid of 2x2
  1701. Vec4 bounds_minx = ox + sx * (internal_cell_size * (two_x + UVec4(0, 1, 0, 1))).ToFloat();
  1702. Vec4 bounds_maxx = ox + sx * UVec4::sMin(internal_cell_size * (two_x + UVec4(1, 2, 1, 2)), sample_count_min_1).ToFloat();
  1703. UVec4 two_y = UVec4::sReplicate(2 * y);
  1704. Vec4 bounds_minz = oz + sz * (internal_cell_size * (two_y + UVec4(0, 0, 1, 1))).ToFloat();
  1705. Vec4 bounds_maxz = oz + sz * UVec4::sMin(internal_cell_size * (two_y + UVec4(1, 1, 2, 2)), sample_count_min_1).ToFloat();
  1706. // Calculate properties of child blocks
  1707. UVec4 properties = UVec4::sReplicate(((level + 1) << cLevelShift) + (y << (cNumBitsXY + 1)) + (x << 1)) + UVec4(0, 1, 1 << cNumBitsXY, (1 << cNumBitsXY) + 1);
  1708. #ifdef JPH_DEBUG_HEIGHT_FIELD
  1709. // Draw boxes
  1710. for (int i = 0; i < 4; ++i)
  1711. {
  1712. AABox b(Vec3(bounds_minx[i], bounds_miny[i], bounds_minz[i]), Vec3(bounds_maxx[i], bounds_maxy[i], bounds_maxz[i]));
  1713. if (b.IsValid())
  1714. DebugRenderer::sInstance->DrawWireBox(b, Color::sGreen);
  1715. }
  1716. #endif
  1717. // Check which sub nodes to visit
  1718. int num_results = ioVisitor.VisitRangeBlock(bounds_minx, bounds_miny, bounds_minz, bounds_maxx, bounds_maxy, bounds_maxz, properties, mTop);
  1719. // Push them onto the stack
  1720. JPH_ASSERT(mTop + 4 < cStackSize);
  1721. properties.StoreInt4(&mPropertiesStack[mTop]);
  1722. mTop += num_results;
  1723. }
  1724. // Check if we're done
  1725. if (ioVisitor.ShouldAbort())
  1726. return;
  1727. // Fetch next node until we find one that the visitor wants to see
  1728. do
  1729. --mTop;
  1730. while (mTop >= 0 && !ioVisitor.ShouldVisitRangeBlock(mTop));
  1731. }
  1732. while (mTop >= 0);
  1733. }
  1734. // This can be used to have the visitor early out (ioVisitor.ShouldAbort() returns true) and later continue again (call WalkHeightField() again)
  1735. JPH_INLINE bool IsDoneWalking() const
  1736. {
  1737. return mTop < 0;
  1738. }
  1739. private:
  1740. const HeightFieldShape * mShape;
  1741. int mTop = 0;
  1742. uint32 mPropertiesStack[cStackSize];
  1743. };
  1744. template <class Visitor>
  1745. void HeightFieldShape::WalkHeightField(Visitor &ioVisitor) const
  1746. {
  1747. DecodingContext ctx(this);
  1748. ctx.WalkHeightField(ioVisitor);
  1749. }
  1750. bool HeightFieldShape::CastRay(const RayCast &inRay, const SubShapeIDCreator &inSubShapeIDCreator, RayCastResult &ioHit) const
  1751. {
  1752. JPH_PROFILE_FUNCTION();
  1753. struct Visitor
  1754. {
  1755. JPH_INLINE explicit Visitor(const HeightFieldShape *inShape, const RayCast &inRay, const SubShapeIDCreator &inSubShapeIDCreator, RayCastResult &ioHit) :
  1756. mHit(ioHit),
  1757. mRayOrigin(inRay.mOrigin),
  1758. mRayDirection(inRay.mDirection),
  1759. mRayInvDirection(inRay.mDirection),
  1760. mShape(inShape),
  1761. mSubShapeIDCreator(inSubShapeIDCreator)
  1762. {
  1763. }
  1764. JPH_INLINE bool ShouldAbort() const
  1765. {
  1766. return mHit.mFraction <= 0.0f;
  1767. }
  1768. JPH_INLINE bool ShouldVisitRangeBlock(int inStackTop) const
  1769. {
  1770. return mDistanceStack[inStackTop] < mHit.mFraction;
  1771. }
  1772. JPH_INLINE int VisitRangeBlock(Vec4Arg inBoundsMinX, Vec4Arg inBoundsMinY, Vec4Arg inBoundsMinZ, Vec4Arg inBoundsMaxX, Vec4Arg inBoundsMaxY, Vec4Arg inBoundsMaxZ, UVec4 &ioProperties, int inStackTop)
  1773. {
  1774. // Test bounds of 4 children
  1775. Vec4 distance = RayAABox4(mRayOrigin, mRayInvDirection, inBoundsMinX, inBoundsMinY, inBoundsMinZ, inBoundsMaxX, inBoundsMaxY, inBoundsMaxZ);
  1776. // Sort so that highest values are first (we want to first process closer hits and we process stack top to bottom)
  1777. return SortReverseAndStore(distance, mHit.mFraction, ioProperties, &mDistanceStack[inStackTop]);
  1778. }
  1779. JPH_INLINE void VisitTriangle(uint inX, uint inY, uint inTriangle, Vec3Arg inV0, Vec3Arg inV1, Vec3Arg inV2)
  1780. {
  1781. float fraction = RayTriangle(mRayOrigin, mRayDirection, inV0, inV1, inV2);
  1782. if (fraction < mHit.mFraction)
  1783. {
  1784. // It's a closer hit
  1785. mHit.mFraction = fraction;
  1786. mHit.mSubShapeID2 = mShape->EncodeSubShapeID(mSubShapeIDCreator, inX, inY, inTriangle);
  1787. mReturnValue = true;
  1788. }
  1789. }
  1790. RayCastResult & mHit;
  1791. Vec3 mRayOrigin;
  1792. Vec3 mRayDirection;
  1793. RayInvDirection mRayInvDirection;
  1794. const HeightFieldShape *mShape;
  1795. SubShapeIDCreator mSubShapeIDCreator;
  1796. bool mReturnValue = false;
  1797. float mDistanceStack[cStackSize];
  1798. };
  1799. Visitor visitor(this, inRay, inSubShapeIDCreator, ioHit);
  1800. WalkHeightField(visitor);
  1801. return visitor.mReturnValue;
  1802. }
  1803. void HeightFieldShape::CastRay(const RayCast &inRay, const RayCastSettings &inRayCastSettings, const SubShapeIDCreator &inSubShapeIDCreator, CastRayCollector &ioCollector, const ShapeFilter &inShapeFilter) const
  1804. {
  1805. JPH_PROFILE_FUNCTION();
  1806. // Test shape filter
  1807. if (!inShapeFilter.ShouldCollide(this, inSubShapeIDCreator.GetID()))
  1808. return;
  1809. struct Visitor
  1810. {
  1811. JPH_INLINE explicit Visitor(const HeightFieldShape *inShape, const RayCast &inRay, const RayCastSettings &inRayCastSettings, const SubShapeIDCreator &inSubShapeIDCreator, CastRayCollector &ioCollector) :
  1812. mCollector(ioCollector),
  1813. mRayOrigin(inRay.mOrigin),
  1814. mRayDirection(inRay.mDirection),
  1815. mRayInvDirection(inRay.mDirection),
  1816. mBackFaceMode(inRayCastSettings.mBackFaceMode),
  1817. mShape(inShape),
  1818. mSubShapeIDCreator(inSubShapeIDCreator)
  1819. {
  1820. }
  1821. JPH_INLINE bool ShouldAbort() const
  1822. {
  1823. return mCollector.ShouldEarlyOut();
  1824. }
  1825. JPH_INLINE bool ShouldVisitRangeBlock(int inStackTop) const
  1826. {
  1827. return mDistanceStack[inStackTop] < mCollector.GetEarlyOutFraction();
  1828. }
  1829. JPH_INLINE int VisitRangeBlock(Vec4Arg inBoundsMinX, Vec4Arg inBoundsMinY, Vec4Arg inBoundsMinZ, Vec4Arg inBoundsMaxX, Vec4Arg inBoundsMaxY, Vec4Arg inBoundsMaxZ, UVec4 &ioProperties, int inStackTop)
  1830. {
  1831. // Test bounds of 4 children
  1832. Vec4 distance = RayAABox4(mRayOrigin, mRayInvDirection, inBoundsMinX, inBoundsMinY, inBoundsMinZ, inBoundsMaxX, inBoundsMaxY, inBoundsMaxZ);
  1833. // Sort so that highest values are first (we want to first process closer hits and we process stack top to bottom)
  1834. return SortReverseAndStore(distance, mCollector.GetEarlyOutFraction(), ioProperties, &mDistanceStack[inStackTop]);
  1835. }
  1836. JPH_INLINE void VisitTriangle(uint inX, uint inY, uint inTriangle, Vec3Arg inV0, Vec3Arg inV1, Vec3Arg inV2) const
  1837. {
  1838. // Back facing check
  1839. if (mBackFaceMode == EBackFaceMode::IgnoreBackFaces && (inV2 - inV0).Cross(inV1 - inV0).Dot(mRayDirection) < 0)
  1840. return;
  1841. // Check the triangle
  1842. float fraction = RayTriangle(mRayOrigin, mRayDirection, inV0, inV1, inV2);
  1843. if (fraction < mCollector.GetEarlyOutFraction())
  1844. {
  1845. RayCastResult hit;
  1846. hit.mBodyID = TransformedShape::sGetBodyID(mCollector.GetContext());
  1847. hit.mFraction = fraction;
  1848. hit.mSubShapeID2 = mShape->EncodeSubShapeID(mSubShapeIDCreator, inX, inY, inTriangle);
  1849. mCollector.AddHit(hit);
  1850. }
  1851. }
  1852. CastRayCollector & mCollector;
  1853. Vec3 mRayOrigin;
  1854. Vec3 mRayDirection;
  1855. RayInvDirection mRayInvDirection;
  1856. EBackFaceMode mBackFaceMode;
  1857. const HeightFieldShape *mShape;
  1858. SubShapeIDCreator mSubShapeIDCreator;
  1859. float mDistanceStack[cStackSize];
  1860. };
  1861. Visitor visitor(this, inRay, inRayCastSettings, inSubShapeIDCreator, ioCollector);
  1862. WalkHeightField(visitor);
  1863. }
  1864. void HeightFieldShape::CollidePoint(Vec3Arg inPoint, const SubShapeIDCreator &inSubShapeIDCreator, CollidePointCollector &ioCollector, const ShapeFilter &inShapeFilter) const
  1865. {
  1866. // A height field doesn't have volume, so we can't test insideness
  1867. }
  1868. void HeightFieldShape::CollideSoftBodyVertices(Mat44Arg inCenterOfMassTransform, Vec3Arg inScale, SoftBodyVertex *ioVertices, uint inNumVertices, [[maybe_unused]] float inDeltaTime, [[maybe_unused]] Vec3Arg inDisplacementDueToGravity, int inCollidingShapeIndex) const
  1869. {
  1870. JPH_PROFILE_FUNCTION();
  1871. struct Visitor : public CollideSoftBodyVerticesVsTriangles
  1872. {
  1873. using CollideSoftBodyVerticesVsTriangles::CollideSoftBodyVerticesVsTriangles;
  1874. JPH_INLINE bool ShouldAbort() const
  1875. {
  1876. return false;
  1877. }
  1878. JPH_INLINE bool ShouldVisitRangeBlock([[maybe_unused]] int inStackTop) const
  1879. {
  1880. return mDistanceStack[inStackTop] < mClosestDistanceSq;
  1881. }
  1882. JPH_INLINE int VisitRangeBlock(Vec4Arg inBoundsMinX, Vec4Arg inBoundsMinY, Vec4Arg inBoundsMinZ, Vec4Arg inBoundsMaxX, Vec4Arg inBoundsMaxY, Vec4Arg inBoundsMaxZ, UVec4 &ioProperties, int inStackTop)
  1883. {
  1884. // Get distance to vertex
  1885. Vec4 dist_sq = AABox4DistanceSqToPoint(mLocalPosition, inBoundsMinX, inBoundsMinY, inBoundsMinZ, inBoundsMaxX, inBoundsMaxY, inBoundsMaxZ);
  1886. // Sort so that highest values are first (we want to first process closer hits and we process stack top to bottom)
  1887. return SortReverseAndStore(dist_sq, mClosestDistanceSq, ioProperties, &mDistanceStack[inStackTop]);
  1888. }
  1889. JPH_INLINE void VisitTriangle([[maybe_unused]] uint inX, [[maybe_unused]] uint inY, [[maybe_unused]] uint inTriangle, Vec3Arg inV0, Vec3Arg inV1, Vec3Arg inV2)
  1890. {
  1891. ProcessTriangle(inV0, inV1, inV2);
  1892. }
  1893. float mDistanceStack[cStackSize];
  1894. };
  1895. Visitor visitor(inCenterOfMassTransform, inScale);
  1896. for (SoftBodyVertex *v = ioVertices, *sbv_end = ioVertices + inNumVertices; v < sbv_end; ++v)
  1897. if (v->mInvMass > 0.0f)
  1898. {
  1899. visitor.StartVertex(*v);
  1900. WalkHeightField(visitor);
  1901. visitor.FinishVertex(*v, inCollidingShapeIndex);
  1902. }
  1903. }
  1904. 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)
  1905. {
  1906. JPH_PROFILE_FUNCTION();
  1907. struct Visitor : public CastConvexVsTriangles
  1908. {
  1909. using CastConvexVsTriangles::CastConvexVsTriangles;
  1910. JPH_INLINE bool ShouldAbort() const
  1911. {
  1912. return mCollector.ShouldEarlyOut();
  1913. }
  1914. JPH_INLINE bool ShouldVisitRangeBlock(int inStackTop) const
  1915. {
  1916. return mDistanceStack[inStackTop] < mCollector.GetPositiveEarlyOutFraction();
  1917. }
  1918. JPH_INLINE int VisitRangeBlock(Vec4Arg inBoundsMinX, Vec4Arg inBoundsMinY, Vec4Arg inBoundsMinZ, Vec4Arg inBoundsMaxX, Vec4Arg inBoundsMaxY, Vec4Arg inBoundsMaxZ, UVec4 &ioProperties, int inStackTop)
  1919. {
  1920. // Scale the bounding boxes of this node
  1921. Vec4 bounds_min_x, bounds_min_y, bounds_min_z, bounds_max_x, bounds_max_y, bounds_max_z;
  1922. 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);
  1923. // Enlarge them by the casted shape's box extents
  1924. AABox4EnlargeWithExtent(mBoxExtent, bounds_min_x, bounds_min_y, bounds_min_z, bounds_max_x, bounds_max_y, bounds_max_z);
  1925. // Test bounds of 4 children
  1926. Vec4 distance = RayAABox4(mBoxCenter, mInvDirection, bounds_min_x, bounds_min_y, bounds_min_z, bounds_max_x, bounds_max_y, bounds_max_z);
  1927. // Clear distance for invalid bounds
  1928. distance = Vec4::sSelect(Vec4::sReplicate(FLT_MAX), distance, Vec4::sLessOrEqual(inBoundsMinY, inBoundsMaxY));
  1929. // Sort so that highest values are first (we want to first process closer hits and we process stack top to bottom)
  1930. return SortReverseAndStore(distance, mCollector.GetPositiveEarlyOutFraction(), ioProperties, &mDistanceStack[inStackTop]);
  1931. }
  1932. JPH_INLINE void VisitTriangle(uint inX, uint inY, uint inTriangle, Vec3Arg inV0, Vec3Arg inV1, Vec3Arg inV2)
  1933. {
  1934. // Create sub shape id for this part
  1935. SubShapeID triangle_sub_shape_id = mShape2->EncodeSubShapeID(mSubShapeIDCreator2, inX, inY, inTriangle);
  1936. // Determine active edges
  1937. uint8 active_edges = mShape2->GetEdgeFlags(inX, inY, inTriangle);
  1938. Cast(inV0, inV1, inV2, active_edges, triangle_sub_shape_id);
  1939. }
  1940. const HeightFieldShape * mShape2;
  1941. RayInvDirection mInvDirection;
  1942. Vec3 mBoxCenter;
  1943. Vec3 mBoxExtent;
  1944. SubShapeIDCreator mSubShapeIDCreator2;
  1945. float mDistanceStack[cStackSize];
  1946. };
  1947. JPH_ASSERT(inShape->GetSubType() == EShapeSubType::HeightField);
  1948. const HeightFieldShape *shape = static_cast<const HeightFieldShape *>(inShape);
  1949. Visitor visitor(inShapeCast, inShapeCastSettings, inScale, inCenterOfMassTransform2, inSubShapeIDCreator1, ioCollector);
  1950. visitor.mShape2 = shape;
  1951. visitor.mInvDirection.Set(inShapeCast.mDirection);
  1952. visitor.mBoxCenter = inShapeCast.mShapeWorldBounds.GetCenter();
  1953. visitor.mBoxExtent = inShapeCast.mShapeWorldBounds.GetExtent();
  1954. visitor.mSubShapeIDCreator2 = inSubShapeIDCreator2;
  1955. shape->WalkHeightField(visitor);
  1956. }
  1957. 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)
  1958. {
  1959. JPH_PROFILE_FUNCTION();
  1960. struct Visitor : public CastSphereVsTriangles
  1961. {
  1962. using CastSphereVsTriangles::CastSphereVsTriangles;
  1963. JPH_INLINE bool ShouldAbort() const
  1964. {
  1965. return mCollector.ShouldEarlyOut();
  1966. }
  1967. JPH_INLINE bool ShouldVisitRangeBlock(int inStackTop) const
  1968. {
  1969. return mDistanceStack[inStackTop] < mCollector.GetPositiveEarlyOutFraction();
  1970. }
  1971. JPH_INLINE int VisitRangeBlock(Vec4Arg inBoundsMinX, Vec4Arg inBoundsMinY, Vec4Arg inBoundsMinZ, Vec4Arg inBoundsMaxX, Vec4Arg inBoundsMaxY, Vec4Arg inBoundsMaxZ, UVec4 &ioProperties, int inStackTop)
  1972. {
  1973. // Scale the bounding boxes of this node
  1974. Vec4 bounds_min_x, bounds_min_y, bounds_min_z, bounds_max_x, bounds_max_y, bounds_max_z;
  1975. 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);
  1976. // Enlarge them by the radius of the sphere
  1977. AABox4EnlargeWithExtent(Vec3::sReplicate(mRadius), bounds_min_x, bounds_min_y, bounds_min_z, bounds_max_x, bounds_max_y, bounds_max_z);
  1978. // Test bounds of 4 children
  1979. Vec4 distance = RayAABox4(mStart, mInvDirection, bounds_min_x, bounds_min_y, bounds_min_z, bounds_max_x, bounds_max_y, bounds_max_z);
  1980. // Clear distance for invalid bounds
  1981. distance = Vec4::sSelect(Vec4::sReplicate(FLT_MAX), distance, Vec4::sLessOrEqual(inBoundsMinY, inBoundsMaxY));
  1982. // Sort so that highest values are first (we want to first process closer hits and we process stack top to bottom)
  1983. return SortReverseAndStore(distance, mCollector.GetPositiveEarlyOutFraction(), ioProperties, &mDistanceStack[inStackTop]);
  1984. }
  1985. JPH_INLINE void VisitTriangle(uint inX, uint inY, uint inTriangle, Vec3Arg inV0, Vec3Arg inV1, Vec3Arg inV2)
  1986. {
  1987. // Create sub shape id for this part
  1988. SubShapeID triangle_sub_shape_id = mShape2->EncodeSubShapeID(mSubShapeIDCreator2, inX, inY, inTriangle);
  1989. // Determine active edges
  1990. uint8 active_edges = mShape2->GetEdgeFlags(inX, inY, inTriangle);
  1991. Cast(inV0, inV1, inV2, active_edges, triangle_sub_shape_id);
  1992. }
  1993. const HeightFieldShape * mShape2;
  1994. RayInvDirection mInvDirection;
  1995. SubShapeIDCreator mSubShapeIDCreator2;
  1996. float mDistanceStack[cStackSize];
  1997. };
  1998. JPH_ASSERT(inShape->GetSubType() == EShapeSubType::HeightField);
  1999. const HeightFieldShape *shape = static_cast<const HeightFieldShape *>(inShape);
  2000. Visitor visitor(inShapeCast, inShapeCastSettings, inScale, inCenterOfMassTransform2, inSubShapeIDCreator1, ioCollector);
  2001. visitor.mShape2 = shape;
  2002. visitor.mInvDirection.Set(inShapeCast.mDirection);
  2003. visitor.mSubShapeIDCreator2 = inSubShapeIDCreator2;
  2004. shape->WalkHeightField(visitor);
  2005. }
  2006. struct HeightFieldShape::HSGetTrianglesContext
  2007. {
  2008. HSGetTrianglesContext(const HeightFieldShape *inShape, const AABox &inBox, Vec3Arg inPositionCOM, QuatArg inRotation, Vec3Arg inScale) :
  2009. mDecodeCtx(inShape),
  2010. mShape(inShape),
  2011. mLocalBox(Mat44::sInverseRotationTranslation(inRotation, inPositionCOM), inBox),
  2012. mHeightFieldScale(inScale),
  2013. mLocalToWorld(Mat44::sRotationTranslation(inRotation, inPositionCOM) * Mat44::sScale(inScale)),
  2014. mIsInsideOut(ScaleHelpers::IsInsideOut(inScale))
  2015. {
  2016. }
  2017. bool ShouldAbort() const
  2018. {
  2019. return mShouldAbort;
  2020. }
  2021. bool ShouldVisitRangeBlock([[maybe_unused]] int inStackTop) const
  2022. {
  2023. return true;
  2024. }
  2025. int VisitRangeBlock(Vec4Arg inBoundsMinX, Vec4Arg inBoundsMinY, Vec4Arg inBoundsMinZ, Vec4Arg inBoundsMaxX, Vec4Arg inBoundsMaxY, Vec4Arg inBoundsMaxZ, UVec4 &ioProperties, [[maybe_unused]] int inStackTop) const
  2026. {
  2027. // Scale the bounding boxes of this node
  2028. Vec4 bounds_min_x, bounds_min_y, bounds_min_z, bounds_max_x, bounds_max_y, bounds_max_z;
  2029. 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);
  2030. // Test which nodes collide
  2031. UVec4 collides = AABox4VsBox(mLocalBox, bounds_min_x, bounds_min_y, bounds_min_z, bounds_max_x, bounds_max_y, bounds_max_z);
  2032. // Filter out invalid bounding boxes
  2033. collides = UVec4::sAnd(collides, Vec4::sLessOrEqual(inBoundsMinY, inBoundsMaxY));
  2034. return CountAndSortTrues(collides, ioProperties);
  2035. }
  2036. void VisitTriangle(uint inX, uint inY, [[maybe_unused]] uint inTriangle, Vec3Arg inV0, Vec3Arg inV1, Vec3Arg inV2)
  2037. {
  2038. // 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.
  2039. if (mNumTrianglesFound + 1 > mMaxTrianglesRequested)
  2040. {
  2041. mShouldAbort = true;
  2042. return;
  2043. }
  2044. // Store vertices as Float3
  2045. if (mIsInsideOut)
  2046. {
  2047. // Reverse vertices
  2048. (mLocalToWorld * inV0).StoreFloat3(mTriangleVertices++);
  2049. (mLocalToWorld * inV2).StoreFloat3(mTriangleVertices++);
  2050. (mLocalToWorld * inV1).StoreFloat3(mTriangleVertices++);
  2051. }
  2052. else
  2053. {
  2054. // Normal scale
  2055. (mLocalToWorld * inV0).StoreFloat3(mTriangleVertices++);
  2056. (mLocalToWorld * inV1).StoreFloat3(mTriangleVertices++);
  2057. (mLocalToWorld * inV2).StoreFloat3(mTriangleVertices++);
  2058. }
  2059. // Decode material
  2060. if (mMaterials != nullptr)
  2061. *mMaterials++ = mShape->GetMaterial(inX, inY);
  2062. // Accumulate triangles found
  2063. mNumTrianglesFound++;
  2064. }
  2065. DecodingContext mDecodeCtx;
  2066. const HeightFieldShape * mShape;
  2067. OrientedBox mLocalBox;
  2068. Vec3 mHeightFieldScale;
  2069. Mat44 mLocalToWorld;
  2070. int mMaxTrianglesRequested;
  2071. Float3 * mTriangleVertices;
  2072. int mNumTrianglesFound;
  2073. const PhysicsMaterial ** mMaterials;
  2074. bool mShouldAbort;
  2075. bool mIsInsideOut;
  2076. };
  2077. void HeightFieldShape::GetTrianglesStart(GetTrianglesContext &ioContext, const AABox &inBox, Vec3Arg inPositionCOM, QuatArg inRotation, Vec3Arg inScale) const
  2078. {
  2079. static_assert(sizeof(HSGetTrianglesContext) <= sizeof(GetTrianglesContext), "GetTrianglesContext too small");
  2080. JPH_ASSERT(IsAligned(&ioContext, alignof(HSGetTrianglesContext)));
  2081. new (&ioContext) HSGetTrianglesContext(this, inBox, inPositionCOM, inRotation, inScale);
  2082. }
  2083. int HeightFieldShape::GetTrianglesNext(GetTrianglesContext &ioContext, int inMaxTrianglesRequested, Float3 *outTriangleVertices, const PhysicsMaterial **outMaterials) const
  2084. {
  2085. static_assert(cGetTrianglesMinTrianglesRequested >= 1, "cGetTrianglesMinTrianglesRequested is too small");
  2086. JPH_ASSERT(inMaxTrianglesRequested >= cGetTrianglesMinTrianglesRequested);
  2087. // Check if we're done
  2088. HSGetTrianglesContext &context = (HSGetTrianglesContext &)ioContext;
  2089. if (context.mDecodeCtx.IsDoneWalking())
  2090. return 0;
  2091. // Store parameters on context
  2092. context.mMaxTrianglesRequested = inMaxTrianglesRequested;
  2093. context.mTriangleVertices = outTriangleVertices;
  2094. context.mMaterials = outMaterials;
  2095. context.mShouldAbort = false; // Reset the abort flag
  2096. context.mNumTrianglesFound = 0;
  2097. // Continue (or start) walking the height field
  2098. context.mDecodeCtx.WalkHeightField(context);
  2099. return context.mNumTrianglesFound;
  2100. }
  2101. 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)
  2102. {
  2103. JPH_PROFILE_FUNCTION();
  2104. // Get the shapes
  2105. JPH_ASSERT(inShape1->GetType() == EShapeType::Convex);
  2106. JPH_ASSERT(inShape2->GetType() == EShapeType::HeightField);
  2107. const ConvexShape *shape1 = static_cast<const ConvexShape *>(inShape1);
  2108. const HeightFieldShape *shape2 = static_cast<const HeightFieldShape *>(inShape2);
  2109. struct Visitor : public CollideConvexVsTriangles
  2110. {
  2111. using CollideConvexVsTriangles::CollideConvexVsTriangles;
  2112. JPH_INLINE bool ShouldAbort() const
  2113. {
  2114. return mCollector.ShouldEarlyOut();
  2115. }
  2116. JPH_INLINE bool ShouldVisitRangeBlock([[maybe_unused]] int inStackTop) const
  2117. {
  2118. return true;
  2119. }
  2120. JPH_INLINE int VisitRangeBlock(Vec4Arg inBoundsMinX, Vec4Arg inBoundsMinY, Vec4Arg inBoundsMinZ, Vec4Arg inBoundsMaxX, Vec4Arg inBoundsMaxY, Vec4Arg inBoundsMaxZ, UVec4 &ioProperties, [[maybe_unused]] int inStackTop) const
  2121. {
  2122. // Scale the bounding boxes of this node
  2123. Vec4 bounds_min_x, bounds_min_y, bounds_min_z, bounds_max_x, bounds_max_y, bounds_max_z;
  2124. 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);
  2125. // Test which nodes collide
  2126. UVec4 collides = AABox4VsBox(mBoundsOf1InSpaceOf2, bounds_min_x, bounds_min_y, bounds_min_z, bounds_max_x, bounds_max_y, bounds_max_z);
  2127. // Filter out invalid bounding boxes
  2128. collides = UVec4::sAnd(collides, Vec4::sLessOrEqual(inBoundsMinY, inBoundsMaxY));
  2129. return CountAndSortTrues(collides, ioProperties);
  2130. }
  2131. JPH_INLINE void VisitTriangle(uint inX, uint inY, uint inTriangle, Vec3Arg inV0, Vec3Arg inV1, Vec3Arg inV2)
  2132. {
  2133. // Create ID for triangle
  2134. SubShapeID triangle_sub_shape_id = mShape2->EncodeSubShapeID(mSubShapeIDCreator2, inX, inY, inTriangle);
  2135. // Determine active edges
  2136. uint8 active_edges = mShape2->GetEdgeFlags(inX, inY, inTriangle);
  2137. Collide(inV0, inV1, inV2, active_edges, triangle_sub_shape_id);
  2138. }
  2139. const HeightFieldShape * mShape2;
  2140. SubShapeIDCreator mSubShapeIDCreator2;
  2141. };
  2142. Visitor visitor(shape1, inScale1, inScale2, inCenterOfMassTransform1, inCenterOfMassTransform2, inSubShapeIDCreator1.GetID(), inCollideShapeSettings, ioCollector);
  2143. visitor.mShape2 = shape2;
  2144. visitor.mSubShapeIDCreator2 = inSubShapeIDCreator2;
  2145. shape2->WalkHeightField(visitor);
  2146. }
  2147. 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)
  2148. {
  2149. JPH_PROFILE_FUNCTION();
  2150. // Get the shapes
  2151. JPH_ASSERT(inShape1->GetSubType() == EShapeSubType::Sphere);
  2152. JPH_ASSERT(inShape2->GetType() == EShapeType::HeightField);
  2153. const SphereShape *shape1 = static_cast<const SphereShape *>(inShape1);
  2154. const HeightFieldShape *shape2 = static_cast<const HeightFieldShape *>(inShape2);
  2155. struct Visitor : public CollideSphereVsTriangles
  2156. {
  2157. using CollideSphereVsTriangles::CollideSphereVsTriangles;
  2158. JPH_INLINE bool ShouldAbort() const
  2159. {
  2160. return mCollector.ShouldEarlyOut();
  2161. }
  2162. JPH_INLINE bool ShouldVisitRangeBlock([[maybe_unused]] int inStackTop) const
  2163. {
  2164. return true;
  2165. }
  2166. JPH_INLINE int VisitRangeBlock(Vec4Arg inBoundsMinX, Vec4Arg inBoundsMinY, Vec4Arg inBoundsMinZ, Vec4Arg inBoundsMaxX, Vec4Arg inBoundsMaxY, Vec4Arg inBoundsMaxZ, UVec4 &ioProperties, [[maybe_unused]] int inStackTop) const
  2167. {
  2168. // Scale the bounding boxes of this node
  2169. Vec4 bounds_min_x, bounds_min_y, bounds_min_z, bounds_max_x, bounds_max_y, bounds_max_z;
  2170. 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);
  2171. // Test which nodes collide
  2172. UVec4 collides = AABox4VsSphere(mSphereCenterIn2, mRadiusPlusMaxSeparationSq, bounds_min_x, bounds_min_y, bounds_min_z, bounds_max_x, bounds_max_y, bounds_max_z);
  2173. // Filter out invalid bounding boxes
  2174. collides = UVec4::sAnd(collides, Vec4::sLessOrEqual(inBoundsMinY, inBoundsMaxY));
  2175. return CountAndSortTrues(collides, ioProperties);
  2176. }
  2177. JPH_INLINE void VisitTriangle(uint inX, uint inY, uint inTriangle, Vec3Arg inV0, Vec3Arg inV1, Vec3Arg inV2)
  2178. {
  2179. // Create ID for triangle
  2180. SubShapeID triangle_sub_shape_id = mShape2->EncodeSubShapeID(mSubShapeIDCreator2, inX, inY, inTriangle);
  2181. // Determine active edges
  2182. uint8 active_edges = mShape2->GetEdgeFlags(inX, inY, inTriangle);
  2183. Collide(inV0, inV1, inV2, active_edges, triangle_sub_shape_id);
  2184. }
  2185. const HeightFieldShape * mShape2;
  2186. SubShapeIDCreator mSubShapeIDCreator2;
  2187. };
  2188. Visitor visitor(shape1, inScale1, inScale2, inCenterOfMassTransform1, inCenterOfMassTransform2, inSubShapeIDCreator1.GetID(), inCollideShapeSettings, ioCollector);
  2189. visitor.mShape2 = shape2;
  2190. visitor.mSubShapeIDCreator2 = inSubShapeIDCreator2;
  2191. shape2->WalkHeightField(visitor);
  2192. }
  2193. void HeightFieldShape::SaveBinaryState(StreamOut &inStream) const
  2194. {
  2195. Shape::SaveBinaryState(inStream);
  2196. inStream.Write(mOffset);
  2197. inStream.Write(mScale);
  2198. inStream.Write(mSampleCount);
  2199. inStream.Write(mBlockSize);
  2200. inStream.Write(mBitsPerSample);
  2201. inStream.Write(mMinSample);
  2202. inStream.Write(mMaxSample);
  2203. inStream.Write(mMaterialIndices);
  2204. inStream.Write(mNumBitsPerMaterialIndex);
  2205. if (mRangeBlocks != nullptr)
  2206. {
  2207. inStream.Write(true);
  2208. inStream.WriteBytes(mRangeBlocks, mRangeBlocksSize * sizeof(RangeBlock) + mHeightSamplesSize + mActiveEdgesSize);
  2209. }
  2210. else
  2211. {
  2212. inStream.Write(false);
  2213. }
  2214. }
  2215. void HeightFieldShape::RestoreBinaryState(StreamIn &inStream)
  2216. {
  2217. Shape::RestoreBinaryState(inStream);
  2218. inStream.Read(mOffset);
  2219. inStream.Read(mScale);
  2220. inStream.Read(mSampleCount);
  2221. inStream.Read(mBlockSize);
  2222. inStream.Read(mBitsPerSample);
  2223. inStream.Read(mMinSample);
  2224. inStream.Read(mMaxSample);
  2225. inStream.Read(mMaterialIndices);
  2226. inStream.Read(mNumBitsPerMaterialIndex);
  2227. // We don't have the exact number of reserved materials anymore, but ensure that our array is big enough
  2228. // TODO: Next time when we bump the binary serialization format of this class we should store the capacity and allocate the right amount, for now we accept a little bit of waste
  2229. mMaterials.reserve(PhysicsMaterialList::size_type(1) << mNumBitsPerMaterialIndex);
  2230. CacheValues();
  2231. bool has_heights = false;
  2232. inStream.Read(has_heights);
  2233. if (has_heights)
  2234. {
  2235. AllocateBuffers();
  2236. inStream.ReadBytes(mRangeBlocks, mRangeBlocksSize * sizeof(RangeBlock) + mHeightSamplesSize + mActiveEdgesSize);
  2237. }
  2238. }
  2239. void HeightFieldShape::SaveMaterialState(PhysicsMaterialList &outMaterials) const
  2240. {
  2241. outMaterials = mMaterials;
  2242. }
  2243. void HeightFieldShape::RestoreMaterialState(const PhysicsMaterialRefC *inMaterials, uint inNumMaterials)
  2244. {
  2245. mMaterials.assign(inMaterials, inMaterials + inNumMaterials);
  2246. }
  2247. Shape::Stats HeightFieldShape::GetStats() const
  2248. {
  2249. return Stats(
  2250. sizeof(*this)
  2251. + mMaterials.size() * sizeof(Ref<PhysicsMaterial>)
  2252. + mRangeBlocksSize * sizeof(RangeBlock)
  2253. + mHeightSamplesSize * sizeof(uint8)
  2254. + mActiveEdgesSize * sizeof(uint8)
  2255. + mMaterialIndices.size() * sizeof(uint8),
  2256. mHeightSamplesSize == 0? 0 : Square(mSampleCount - 1) * 2);
  2257. }
  2258. void HeightFieldShape::sRegister()
  2259. {
  2260. ShapeFunctions &f = ShapeFunctions::sGet(EShapeSubType::HeightField);
  2261. f.mConstruct = []() -> Shape * { return new HeightFieldShape; };
  2262. f.mColor = Color::sPurple;
  2263. for (EShapeSubType s : sConvexSubShapeTypes)
  2264. {
  2265. CollisionDispatch::sRegisterCollideShape(s, EShapeSubType::HeightField, sCollideConvexVsHeightField);
  2266. CollisionDispatch::sRegisterCastShape(s, EShapeSubType::HeightField, sCastConvexVsHeightField);
  2267. CollisionDispatch::sRegisterCastShape(EShapeSubType::HeightField, s, CollisionDispatch::sReversedCastShape);
  2268. CollisionDispatch::sRegisterCollideShape(EShapeSubType::HeightField, s, CollisionDispatch::sReversedCollideShape);
  2269. }
  2270. // Specialized collision functions
  2271. CollisionDispatch::sRegisterCollideShape(EShapeSubType::Sphere, EShapeSubType::HeightField, sCollideSphereVsHeightField);
  2272. CollisionDispatch::sRegisterCastShape(EShapeSubType::Sphere, EShapeSubType::HeightField, sCastSphereVsHeightField);
  2273. }
  2274. JPH_NAMESPACE_END