HeightFieldShapeTest.cpp 9.5 KB

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