HeightFieldShape.cpp 96 KB

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