SensorTest.cpp 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247
  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/General/SensorTest.h>
  6. #include <Jolt/Physics/Collision/Shape/BoxShape.h>
  7. #include <Jolt/Physics/Collision/Shape/SphereShape.h>
  8. #include <Jolt/Physics/Body/BodyCreationSettings.h>
  9. #include <Jolt/ObjectStream/ObjectStreamIn.h>
  10. #include <Utils/RagdollLoader.h>
  11. #include <Utils/Log.h>
  12. #include <Utils/AssetStream.h>
  13. #include <Layers.h>
  14. #include <Renderer/DebugRendererImp.h>
  15. JPH_IMPLEMENT_RTTI_VIRTUAL(SensorTest)
  16. {
  17. JPH_ADD_BASE_CLASS(SensorTest, Test)
  18. }
  19. SensorTest::~SensorTest()
  20. {
  21. // Destroy the ragdoll
  22. mRagdoll->RemoveFromPhysicsSystem();
  23. mRagdoll = nullptr;
  24. }
  25. void SensorTest::Initialize()
  26. {
  27. // Floor
  28. CreateFloor(400.0f);
  29. {
  30. // A static sensor that attracts dynamic bodies that enter its area
  31. BodyCreationSettings sensor_settings(new SphereShape(10.0f), RVec3(0, 10, 0), Quat::sIdentity(), EMotionType::Static, Layers::SENSOR);
  32. sensor_settings.mIsSensor = true;
  33. mSensorID[StaticAttractor] = mBodyInterface->CreateAndAddBody(sensor_settings, EActivation::DontActivate);
  34. }
  35. {
  36. // A static sensor that only detects active bodies
  37. BodyCreationSettings sensor_settings(new BoxShape(Vec3::sReplicate(5.0f)), RVec3(-10, 5.1f, 0), Quat::sIdentity(), EMotionType::Static, Layers::SENSOR);
  38. sensor_settings.mIsSensor = true;
  39. mSensorID[StaticSensor] = mBodyInterface->CreateAndAddBody(sensor_settings, EActivation::DontActivate);
  40. }
  41. {
  42. // A kinematic sensor that also detects sleeping bodies
  43. BodyCreationSettings sensor_settings(new BoxShape(Vec3::sReplicate(5.0f)), RVec3(10, 5.1f, 0), Quat::sIdentity(), EMotionType::Kinematic, Layers::SENSOR);
  44. sensor_settings.mIsSensor = true;
  45. mSensorID[KinematicSensor] = mBodyInterface->CreateAndAddBody(sensor_settings, EActivation::Activate);
  46. }
  47. {
  48. // A kinematic sensor that also detects static bodies
  49. BodyCreationSettings sensor_settings(new BoxShape(Vec3::sReplicate(5.0f)), RVec3(25, 5.1f, 0), Quat::sIdentity(), EMotionType::Kinematic, Layers::MOVING); // Put in a layer that collides with static
  50. sensor_settings.mIsSensor = true;
  51. sensor_settings.mCollideKinematicVsNonDynamic = true;
  52. mSensorID[SensorDetectingStatic] = mBodyInterface->CreateAndAddBody(sensor_settings, EActivation::Activate);
  53. }
  54. // Dynamic bodies
  55. for (int i = 0; i < 15; ++i)
  56. mBodyInterface->CreateAndAddBody(BodyCreationSettings(new BoxShape(Vec3(0.1f, 0.5f, 0.2f)), RVec3(-15.0f + i * 3.0f, 25, 0), Quat::sIdentity(), EMotionType::Dynamic, Layers::MOVING), EActivation::Activate);
  57. // Static bodies
  58. RVec3 static_positions[] = { RVec3(-14, 1, 4), RVec3(6, 1, 4), RVec3(21, 1, 4) };
  59. for (const RVec3 &p : static_positions)
  60. mBodyInterface->CreateAndAddBody(BodyCreationSettings(new BoxShape(Vec3::sReplicate(0.5f)), p, Quat::sIdentity(), EMotionType::Static, Layers::NON_MOVING), EActivation::Activate);
  61. #ifdef JPH_OBJECT_STREAM
  62. // Load ragdoll
  63. Ref<RagdollSettings> ragdoll_settings = RagdollLoader::sLoad("Human.tof", EMotionType::Dynamic);
  64. if (ragdoll_settings == nullptr)
  65. FatalError("Could not load ragdoll");
  66. #else
  67. Ref<RagdollSettings> ragdoll_settings = RagdollLoader::sCreate();
  68. #endif // JPH_OBJECT_STREAM
  69. // Create pose
  70. SkeletonPose ragdoll_pose;
  71. ragdoll_pose.SetSkeleton(ragdoll_settings->GetSkeleton());
  72. {
  73. #ifdef JPH_OBJECT_STREAM
  74. Ref<SkeletalAnimation> animation;
  75. AssetStream stream("Human/dead_pose1.tof", std::ios::in);
  76. if (!ObjectStreamIn::sReadObject(stream.Get(), animation))
  77. FatalError("Could not open animation");
  78. animation->Sample(0.0f, ragdoll_pose);
  79. #else
  80. Ref<Ragdoll> temp_ragdoll = ragdoll_settings->CreateRagdoll(0, 0, mPhysicsSystem);
  81. temp_ragdoll->GetPose(ragdoll_pose);
  82. ragdoll_pose.CalculateJointStates();
  83. #endif // JPH_OBJECT_STREAM
  84. }
  85. ragdoll_pose.SetRootOffset(RVec3(0, 30, 0));
  86. ragdoll_pose.CalculateJointMatrices();
  87. // Create ragdoll
  88. mRagdoll = ragdoll_settings->CreateRagdoll(1, 0, mPhysicsSystem);
  89. mRagdoll->SetPose(ragdoll_pose);
  90. mRagdoll->AddToPhysicsSystem(EActivation::Activate);
  91. // Create kinematic body
  92. BodyCreationSettings kinematic_settings(new BoxShape(Vec3(0.25f, 0.5f, 1.0f)), RVec3(-20, 10, 0), Quat::sIdentity(), EMotionType::Kinematic, Layers::MOVING);
  93. Body &kinematic = *mBodyInterface->CreateBody(kinematic_settings);
  94. mKinematicBodyID = kinematic.GetID();
  95. mBodyInterface->AddBody(kinematic.GetID(), EActivation::Activate);
  96. }
  97. void SensorTest::PrePhysicsUpdate(const PreUpdateParams &inParams)
  98. {
  99. // Update time
  100. mTime += inParams.mDeltaTime;
  101. // Move kinematic body
  102. RVec3 kinematic_pos = RVec3(-20.0f * Cos(mTime), 10, 0);
  103. mBodyInterface->MoveKinematic(mKinematicBodyID, kinematic_pos, Quat::sIdentity(), inParams.mDeltaTime);
  104. // Draw if body is in sensor
  105. Color sensor_color[] = { Color::sRed, Color::sGreen, Color::sBlue, Color::sPurple };
  106. for (int sensor = 0; sensor < NumSensors; ++sensor)
  107. for (const BodyAndCount &body_and_count : mBodiesInSensor[sensor])
  108. {
  109. AABox bounds = mBodyInterface->GetTransformedShape(body_and_count.mBodyID).GetWorldSpaceBounds();
  110. bounds.ExpandBy(Vec3::sReplicate(0.01f * sensor));
  111. mDebugRenderer->DrawWireBox(bounds, sensor_color[sensor]);
  112. }
  113. // Apply forces to dynamic bodies in sensor
  114. lock_guard lock(mMutex);
  115. RVec3 center(0, 10, 0);
  116. float centrifugal_force = 10.0f;
  117. Vec3 gravity = mPhysicsSystem->GetGravity();
  118. for (const BodyAndCount &body_and_count : mBodiesInSensor[StaticAttractor])
  119. {
  120. BodyLockWrite body_lock(mPhysicsSystem->GetBodyLockInterface(), body_and_count.mBodyID);
  121. if (body_lock.Succeeded())
  122. {
  123. Body &body = body_lock.GetBody();
  124. if (body.IsKinematic())
  125. continue;
  126. // Calculate centrifugal acceleration
  127. Vec3 acceleration = Vec3(center - body.GetPosition());
  128. float length = acceleration.Length();
  129. if (length > 0.0f)
  130. acceleration *= centrifugal_force / length;
  131. else
  132. acceleration = Vec3::sZero();
  133. // Draw acceleration
  134. mDebugRenderer->DrawArrow(body.GetPosition(), body.GetPosition() + acceleration, Color::sGreen, 0.1f);
  135. // Cancel gravity
  136. acceleration -= gravity;
  137. // Apply as force
  138. body.AddForce(acceleration / body.GetMotionProperties()->GetInverseMass());
  139. }
  140. }
  141. }
  142. void SensorTest::OnContactAdded(const Body &inBody1, const Body &inBody2, const ContactManifold &inManifold, ContactSettings &ioSettings)
  143. {
  144. for (int sensor = 0; sensor < NumSensors; ++sensor)
  145. {
  146. BodyID sensor_id = mSensorID[sensor];
  147. // Check which body is the sensor
  148. BodyID body_id;
  149. if (inBody1.GetID() == sensor_id)
  150. body_id = inBody2.GetID();
  151. else if (inBody2.GetID() == sensor_id)
  152. body_id = inBody1.GetID();
  153. else
  154. continue;
  155. lock_guard lock(mMutex);
  156. // Add to list and make sure that the list remains sorted for determinism (contacts can be added from multiple threads)
  157. BodyAndCount body_and_count { body_id, 1 };
  158. BodiesInSensor &bodies_in_sensor = mBodiesInSensor[sensor];
  159. BodiesInSensor::iterator b = lower_bound(bodies_in_sensor.begin(), bodies_in_sensor.end(), body_and_count);
  160. if (b != bodies_in_sensor.end() && b->mBodyID == body_id)
  161. {
  162. // This is the right body, increment reference
  163. b->mCount++;
  164. return;
  165. }
  166. bodies_in_sensor.insert(b, body_and_count);
  167. }
  168. }
  169. void SensorTest::OnContactRemoved(const SubShapeIDPair &inSubShapePair)
  170. {
  171. for (int sensor = 0; sensor < NumSensors; ++sensor)
  172. {
  173. BodyID sensor_id = mSensorID[sensor];
  174. // Check which body is the sensor
  175. BodyID body_id;
  176. if (inSubShapePair.GetBody1ID() == sensor_id)
  177. body_id = inSubShapePair.GetBody2ID();
  178. else if (inSubShapePair.GetBody2ID() == sensor_id)
  179. body_id = inSubShapePair.GetBody1ID();
  180. else
  181. continue;
  182. lock_guard lock(mMutex);
  183. // Remove from list
  184. BodyAndCount body_and_count { body_id, 1 };
  185. BodiesInSensor &bodies_in_sensor = mBodiesInSensor[sensor];
  186. BodiesInSensor::iterator b = lower_bound(bodies_in_sensor.begin(), bodies_in_sensor.end(), body_and_count);
  187. if (b != bodies_in_sensor.end() && b->mBodyID == body_id)
  188. {
  189. // This is the right body, increment reference
  190. JPH_ASSERT(b->mCount > 0);
  191. b->mCount--;
  192. // When last reference remove from the list
  193. if (b->mCount == 0)
  194. bodies_in_sensor.erase(b);
  195. return;
  196. }
  197. JPH_ASSERT(false, "Body pair not found");
  198. }
  199. }
  200. void SensorTest::SaveState(StateRecorder &inStream) const
  201. {
  202. inStream.Write(mTime);
  203. for (const BodiesInSensor &b : mBodiesInSensor)
  204. inStream.Write(b);
  205. }
  206. void SensorTest::RestoreState(StateRecorder &inStream)
  207. {
  208. inStream.Read(mTime);
  209. for (BodiesInSensor &b : mBodiesInSensor)
  210. inStream.Read(b);
  211. }