2
0

HeightFieldShapeTest.cpp 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267
  1. // Jolt Physics Library (https://github.com/jrouwe/JoltPhysics)
  2. // SPDX-FileCopyrightText: 2021 Jorrit Rouwe
  3. // SPDX-License-Identifier: MIT
  4. #include <TestFramework.h>
  5. #include <Tests/Shapes/HeightFieldShapeTest.h>
  6. #include <Math/Perlin.h>
  7. #include <Jolt/Physics/Collision/Shape/BoxShape.h>
  8. #include <Jolt/Physics/Body/BodyCreationSettings.h>
  9. #include <Jolt/Physics/Collision/PhysicsMaterialSimple.h>
  10. #include <Jolt/Physics/Collision/CastResult.h>
  11. #include <Jolt/Physics/Collision/RayCast.h>
  12. #include <Application/DebugUI.h>
  13. #include <Utils/ReadData.h>
  14. #include <Utils/Log.h>
  15. #include <Utils/DebugRendererSP.h>
  16. #include <Layers.h>
  17. JPH_IMPLEMENT_RTTI_VIRTUAL(HeightFieldShapeTest)
  18. {
  19. JPH_ADD_BASE_CLASS(HeightFieldShapeTest, Test)
  20. }
  21. static int sTerrainType = 0;
  22. static const char *sTerrainTypes[] = {
  23. "Procedural Terrain 2^N",
  24. "Procedural Terrain 2^N + 1",
  25. "Heightfield 1",
  26. "Flat 2^N",
  27. "Flat 2^N + 1",
  28. "No Collision 2^N",
  29. "No Collision 2^N + 1"
  30. };
  31. void HeightFieldShapeTest::Initialize()
  32. {
  33. if (sTerrainType == 0 || sTerrainType == 1)
  34. {
  35. const int n = sTerrainType == 0? 128 : 129;
  36. const float cell_size = 1.0f;
  37. const float max_height = 5.0f;
  38. // Create height samples
  39. mTerrainSize = n;
  40. mTerrain.resize(n * n);
  41. for (int y = 0; y < n; ++y)
  42. for (int x = 0; x < n; ++x)
  43. mTerrain[y * n + x] = max_height * PerlinNoise3(float(x) * 8.0f / n, 0, float(y) * 8.0f / n, 256, 256, 256);
  44. // Make some holes
  45. mTerrain[2 * n + 2] = HeightFieldShapeConstants::cNoCollisionValue;
  46. for (int y = 4; y < 33; ++y)
  47. for (int x = 4; x < 33; ++x)
  48. mTerrain[y * n + x] = HeightFieldShapeConstants::cNoCollisionValue;
  49. // Make material indices
  50. uint8 max_material_index = 0;
  51. mMaterialIndices.resize(Square(n - 1));
  52. for (int y = 0; y < n - 1; ++y)
  53. for (int x = 0; x < n - 1; ++x)
  54. {
  55. uint8 material_index = uint8(round((Vec3(x * cell_size, 0, y * cell_size) - Vec3(n * cell_size / 2, 0, n * cell_size / 2)).Length() / 10.0f));
  56. max_material_index = max(max_material_index, material_index);
  57. mMaterialIndices[y * (n - 1) + x] = material_index;
  58. }
  59. // Mark the corners to validate that materials and heights match
  60. mTerrain[0] = 0.0f;
  61. mTerrain[n - 1] = 10.0f;
  62. mTerrain[(n - 1) * n] = 20.0f;
  63. mTerrain[n * n - 1] = 30.0f;
  64. mMaterialIndices[0] = 0;
  65. mMaterialIndices[n - 2] = 1;
  66. mMaterialIndices[(n - 2) * (n - 1)] = 2;
  67. mMaterialIndices[Square(n - 1) - 1] = 3;
  68. // Create materials
  69. for (uint8 i = 0; i <= max_material_index; ++i)
  70. mMaterials.push_back(new PhysicsMaterialSimple("Material " + ConvertToString(uint(i)), Color::sGetDistinctColor(i)));
  71. // Determine scale and offset (deliberately apply extra offset and scale in Y direction)
  72. mTerrainOffset = Vec3(-0.5f * cell_size * n, -2.0f, -0.5f * cell_size * n);
  73. mTerrainScale = Vec3(cell_size, 1.5f, cell_size);
  74. }
  75. else if (sTerrainType == 2)
  76. {
  77. const int n = 1024;
  78. const float cell_size = 0.5f;
  79. // Get height samples
  80. Array<uint8> data = ReadData("Assets/heightfield1.bin");
  81. if (data.size() != sizeof(float) * n * n)
  82. FatalError("Invalid file size");
  83. mTerrainSize = n;
  84. mTerrain.resize(n * n);
  85. memcpy(mTerrain.data(), data.data(), n * n * sizeof(float));
  86. // Determine scale and offset
  87. mTerrainOffset = Vec3(-0.5f * cell_size * n, 0.0f, -0.5f * cell_size * n);
  88. mTerrainScale = Vec3(cell_size, 1.0f, cell_size);
  89. }
  90. else if (sTerrainType == 3 || sTerrainType == 4)
  91. {
  92. const int n = sTerrainType == 3? 128 : 129;
  93. const float cell_size = 1.0f;
  94. const float height = JPH_PI;
  95. // Determine scale and offset
  96. mTerrainOffset = Vec3(-0.5f * cell_size * n, 0.0f, -0.5f * cell_size * n);
  97. mTerrainScale = Vec3(cell_size, 1.0f, cell_size);
  98. // Mark the entire terrain as single height
  99. mTerrainSize = n;
  100. mTerrain.resize(n * n);
  101. for (float &v : mTerrain)
  102. v = height;
  103. }
  104. else if (sTerrainType == 5 || sTerrainType == 6)
  105. {
  106. const int n = sTerrainType == 4? 128 : 129;
  107. const float cell_size = 1.0f;
  108. // Determine scale and offset
  109. mTerrainOffset = Vec3(-0.5f * cell_size * n, 0.0f, -0.5f * cell_size * n);
  110. mTerrainScale = Vec3(cell_size, 1.0f, cell_size);
  111. // Mark the entire terrain as no collision
  112. mTerrainSize = n;
  113. mTerrain.resize(n * n);
  114. for (float &v : mTerrain)
  115. v = HeightFieldShapeConstants::cNoCollisionValue;
  116. }
  117. // Create height field
  118. HeightFieldShapeSettings settings(mTerrain.data(), mTerrainOffset, mTerrainScale, mTerrainSize, mMaterialIndices.data(), mMaterials);
  119. settings.mBlockSize = 1 << sBlockSizeShift;
  120. settings.mBitsPerSample = sBitsPerSample;
  121. mHeightField = static_cast<const HeightFieldShape *>(settings.Create().Get().GetPtr());
  122. Body &terrain = *mBodyInterface->CreateBody(BodyCreationSettings(mHeightField, RVec3::sZero(), Quat::sIdentity(), EMotionType::Static, Layers::NON_MOVING));
  123. mBodyInterface->AddBody(terrain.GetID(), EActivation::DontActivate);
  124. // Validate it
  125. float max_diff = -1.0f;
  126. uint max_diff_x = 0, max_diff_y = 0;
  127. float min_height = FLT_MAX, max_height = -FLT_MAX, avg_diff = 0.0f;
  128. for (uint y = 0; y < mTerrainSize; ++y)
  129. for (uint x = 0; x < mTerrainSize; ++x)
  130. {
  131. float h1 = mTerrain[y * mTerrainSize + x];
  132. if (h1 != HeightFieldShapeConstants::cNoCollisionValue)
  133. {
  134. h1 = mTerrainOffset.GetY() + mTerrainScale.GetY() * h1;
  135. if (mHeightField->IsNoCollision(x, y))
  136. FatalError("No collision where there should be");
  137. float h2 = mHeightField->GetPosition(x, y).GetY();
  138. float diff = abs(h2 - h1);
  139. if (diff > max_diff)
  140. {
  141. max_diff = diff;
  142. max_diff_x = x;
  143. max_diff_y = y;
  144. }
  145. min_height = min(min_height, h1);
  146. max_height = max(max_height, h1);
  147. avg_diff += diff;
  148. }
  149. else
  150. {
  151. if (!mHeightField->IsNoCollision(x, y))
  152. FatalError("Collision where there shouldn't be");
  153. }
  154. }
  155. // Calculate relative error
  156. float rel_error = min_height < max_height? 100.0f * max_diff / (max_height - min_height) : 0.0f;
  157. // Max error we expect given sBitsPerSample (normally the error should be much lower because we quantize relative to the block rather than the full height)
  158. float max_error = 0.5f * 100.0f / ((1 << sBitsPerSample) - 1);
  159. // Calculate average
  160. avg_diff /= mTerrainSize * mTerrainSize;
  161. // Calculate amount of memory used
  162. Shape::Stats stats = mHeightField->GetStats();
  163. // Trace stats
  164. Trace("Block size: %d, bits per sample: %d, min height: %g, max height: %g, avg diff: %g, max diff: %g at (%d, %d), relative error: %g%%, size: %u bytes", 1 << sBlockSizeShift, sBitsPerSample, (double)min_height, (double)max_height, (double)avg_diff, (double)max_diff, max_diff_x, max_diff_y, (double)rel_error, stats.mSizeBytes);
  165. if (rel_error > max_error)
  166. FatalError("Error too big!");
  167. // Determine terrain height
  168. RayCastResult result;
  169. RVec3 start(0, 1000, 0);
  170. Vec3 direction(0, -2000, 0);
  171. RRayCast ray { start, direction };
  172. if (mPhysicsSystem->GetNarrowPhaseQuery().CastRay(ray, result, SpecifiedBroadPhaseLayerFilter(BroadPhaseLayers::NON_MOVING), SpecifiedObjectLayerFilter(Layers::NON_MOVING)))
  173. mHitPos = ray.GetPointOnRay(result.mFraction);
  174. // Dynamic body
  175. Body &body1 = *mBodyInterface->CreateBody(BodyCreationSettings(new BoxShape(Vec3(0.5f, 1.0f, 2.0f)), mHitPos + Vec3(0, 10, 0), Quat::sIdentity(), EMotionType::Dynamic, Layers::MOVING));
  176. mBodyInterface->AddBody(body1.GetID(), EActivation::Activate);
  177. }
  178. void HeightFieldShapeTest::PrePhysicsUpdate(const PreUpdateParams &inParams)
  179. {
  180. // Test the 'GetHeight' function and draw a marker on the surface
  181. Vec3 test_pos = Vec3(inParams.mCameraState.mPos) + 10.0f * inParams.mCameraState.mForward, surface_pos;
  182. SubShapeID sub_shape_id;
  183. if (mHeightField->ProjectOntoSurface(test_pos, surface_pos, sub_shape_id))
  184. {
  185. Vec3 surface_normal = mHeightField->GetSurfaceNormal(sub_shape_id, surface_pos);
  186. DrawMarkerSP(mDebugRenderer, surface_pos, Color::sWhite, 1.0f);
  187. DrawArrowSP(mDebugRenderer, surface_pos, surface_pos + surface_normal, Color::sRed, 0.1f);
  188. }
  189. // Draw the original uncompressed terrain
  190. if (sShowOriginalTerrain)
  191. for (uint y = 0; y < mTerrainSize; ++y)
  192. for (uint x = 0; x < mTerrainSize; ++x)
  193. {
  194. // Get original height
  195. float h = mTerrain[y * mTerrainSize + x];
  196. if (h == HeightFieldShapeConstants::cNoCollisionValue)
  197. continue;
  198. // Get original position
  199. Vec3 original = mTerrainOffset + mTerrainScale * Vec3(float(x), h, float(y));
  200. // Get compressed position
  201. Vec3 compressed = mHeightField->GetPosition(x, y);
  202. // Draw marker that is red when error is too big and green when not
  203. const float cMaxError = 0.1f;
  204. float error = (original - compressed).Length();
  205. uint8 c = uint8(round(255.0f * min(error / cMaxError, 1.0f)));
  206. DrawMarkerSP(mDebugRenderer, original, Color(c, 255 - c, 0, 255), 0.1f);
  207. }
  208. }
  209. void HeightFieldShapeTest::GetInitialCamera(CameraState &ioState) const
  210. {
  211. // Correct camera pos for hit position
  212. ioState.mPos += mHitPos;
  213. }
  214. void HeightFieldShapeTest::CreateSettingsMenu(DebugUI *inUI, UIElement *inSubMenu)
  215. {
  216. inUI->CreateTextButton(inSubMenu, "Select Terrain", [this, inUI]() {
  217. UIElement *terrain_name = inUI->CreateMenu();
  218. for (uint i = 0; i < size(sTerrainTypes); ++i)
  219. inUI->CreateTextButton(terrain_name, sTerrainTypes[i], [this, i]() { sTerrainType = i; RestartTest(); });
  220. inUI->ShowMenu(terrain_name);
  221. });
  222. inUI->CreateTextButton(inSubMenu, "Configuration Settings", [this, inUI]() {
  223. UIElement *terrain_settings = inUI->CreateMenu();
  224. inUI->CreateComboBox(terrain_settings, "Block Size", { "2", "4", "8" }, sBlockSizeShift - 1, [=](int inItem) { sBlockSizeShift = inItem + 1; });
  225. inUI->CreateSlider(terrain_settings, "Bits Per Sample", (float)sBitsPerSample, 1.0f, 8.0f, 1.0f, [=](float inValue) { sBitsPerSample = (int)inValue; });
  226. inUI->CreateTextButton(terrain_settings, "Accept", [this]() { RestartTest(); });
  227. inUI->ShowMenu(terrain_settings);
  228. });
  229. inUI->CreateCheckBox(inSubMenu, "Show Original Terrain", sShowOriginalTerrain, [](UICheckBox::EState inState) { sShowOriginalTerrain = inState == UICheckBox::STATE_CHECKED; });
  230. }