SensorTest.cpp 8.0 KB

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