SensorTest.cpp 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245
  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 attracts 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.mCollideKinematicVsNonDynamic = 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. #ifdef JPH_OBJECT_STREAM
  61. // Load ragdoll
  62. Ref<RagdollSettings> ragdoll_settings = RagdollLoader::sLoad("Assets/Human.tof", EMotionType::Dynamic);
  63. if (ragdoll_settings == nullptr)
  64. FatalError("Could not load ragdoll");
  65. #else
  66. Ref<RagdollSettings> ragdoll_settings = RagdollLoader::sCreate();
  67. #endif // JPH_OBJECT_STREAM
  68. // Create pose
  69. SkeletonPose ragdoll_pose;
  70. ragdoll_pose.SetSkeleton(ragdoll_settings->GetSkeleton());
  71. {
  72. #ifdef JPH_OBJECT_STREAM
  73. Ref<SkeletalAnimation> animation;
  74. if (!ObjectStreamIn::sReadObject("Assets/Human/Dead_Pose1.tof", animation))
  75. FatalError("Could not open animation");
  76. animation->Sample(0.0f, ragdoll_pose);
  77. #else
  78. Ref<Ragdoll> temp_ragdoll = ragdoll_settings->CreateRagdoll(0, 0, mPhysicsSystem);
  79. temp_ragdoll->GetPose(ragdoll_pose);
  80. ragdoll_pose.CalculateJointStates();
  81. #endif // JPH_OBJECT_STREAM
  82. }
  83. ragdoll_pose.SetRootOffset(RVec3(0, 30, 0));
  84. ragdoll_pose.CalculateJointMatrices();
  85. // Create ragdoll
  86. mRagdoll = ragdoll_settings->CreateRagdoll(1, 0, mPhysicsSystem);
  87. mRagdoll->SetPose(ragdoll_pose);
  88. mRagdoll->AddToPhysicsSystem(EActivation::Activate);
  89. // Create kinematic body
  90. BodyCreationSettings kinematic_settings(new BoxShape(Vec3(0.25f, 0.5f, 1.0f)), RVec3(-20, 10, 0), Quat::sIdentity(), EMotionType::Kinematic, Layers::MOVING);
  91. Body &kinematic = *mBodyInterface->CreateBody(kinematic_settings);
  92. mKinematicBodyID = kinematic.GetID();
  93. mBodyInterface->AddBody(kinematic.GetID(), EActivation::Activate);
  94. }
  95. void SensorTest::PrePhysicsUpdate(const PreUpdateParams &inParams)
  96. {
  97. // Update time
  98. mTime += inParams.mDeltaTime;
  99. // Move kinematic body
  100. RVec3 kinematic_pos = RVec3(-20.0f * Cos(mTime), 10, 0);
  101. mBodyInterface->MoveKinematic(mKinematicBodyID, kinematic_pos, Quat::sIdentity(), inParams.mDeltaTime);
  102. // Draw if body is in sensor
  103. Color sensor_color[] = { Color::sRed, Color::sGreen, Color::sBlue, Color::sPurple };
  104. for (int sensor = 0; sensor < NumSensors; ++sensor)
  105. for (const BodyAndCount &body_and_count : mBodiesInSensor[sensor])
  106. {
  107. AABox bounds = mBodyInterface->GetTransformedShape(body_and_count.mBodyID).GetWorldSpaceBounds();
  108. bounds.ExpandBy(Vec3::sReplicate(0.01f * sensor));
  109. mDebugRenderer->DrawWireBox(bounds, sensor_color[sensor]);
  110. }
  111. // Apply forces to dynamic bodies in sensor
  112. lock_guard lock(mMutex);
  113. RVec3 center(0, 10, 0);
  114. float centrifugal_force = 10.0f;
  115. Vec3 gravity = mPhysicsSystem->GetGravity();
  116. for (const BodyAndCount &body_and_count : mBodiesInSensor[StaticAttractor])
  117. {
  118. BodyLockWrite body_lock(mPhysicsSystem->GetBodyLockInterface(), body_and_count.mBodyID);
  119. if (body_lock.Succeeded())
  120. {
  121. Body &body = body_lock.GetBody();
  122. if (body.IsKinematic())
  123. continue;
  124. // Calculate centrifugal acceleration
  125. Vec3 acceleration = Vec3(center - body.GetPosition());
  126. float length = acceleration.Length();
  127. if (length > 0.0f)
  128. acceleration *= centrifugal_force / length;
  129. else
  130. acceleration = Vec3::sZero();
  131. // Draw acceleration
  132. mDebugRenderer->DrawArrow(body.GetPosition(), body.GetPosition() + acceleration, Color::sGreen, 0.1f);
  133. // Cancel gravity
  134. acceleration -= gravity;
  135. // Apply as force
  136. body.AddForce(acceleration / body.GetMotionProperties()->GetInverseMass());
  137. }
  138. }
  139. }
  140. void SensorTest::OnContactAdded(const Body &inBody1, const Body &inBody2, const ContactManifold &inManifold, ContactSettings &ioSettings)
  141. {
  142. for (int sensor = 0; sensor < NumSensors; ++sensor)
  143. {
  144. BodyID sensor_id = mSensorID[sensor];
  145. // Check which body is the sensor
  146. BodyID body_id;
  147. if (inBody1.GetID() == sensor_id)
  148. body_id = inBody2.GetID();
  149. else if (inBody2.GetID() == sensor_id)
  150. body_id = inBody1.GetID();
  151. else
  152. continue;
  153. lock_guard lock(mMutex);
  154. // Add to list and make sure that the list remains sorted for determinism (contacts can be added from multiple threads)
  155. BodyAndCount body_and_count { body_id, 1 };
  156. BodiesInSensor &bodies_in_sensor = mBodiesInSensor[sensor];
  157. BodiesInSensor::iterator b = lower_bound(bodies_in_sensor.begin(), bodies_in_sensor.end(), body_and_count);
  158. if (b != bodies_in_sensor.end() && b->mBodyID == body_id)
  159. {
  160. // This is the right body, increment reference
  161. b->mCount++;
  162. return;
  163. }
  164. bodies_in_sensor.insert(b, body_and_count);
  165. }
  166. }
  167. void SensorTest::OnContactRemoved(const SubShapeIDPair &inSubShapePair)
  168. {
  169. for (int sensor = 0; sensor < NumSensors; ++sensor)
  170. {
  171. BodyID sensor_id = mSensorID[sensor];
  172. // Check which body is the sensor
  173. BodyID body_id;
  174. if (inSubShapePair.GetBody1ID() == sensor_id)
  175. body_id = inSubShapePair.GetBody2ID();
  176. else if (inSubShapePair.GetBody2ID() == sensor_id)
  177. body_id = inSubShapePair.GetBody1ID();
  178. else
  179. continue;
  180. lock_guard lock(mMutex);
  181. // Remove from list
  182. BodyAndCount body_and_count { body_id, 1 };
  183. BodiesInSensor &bodies_in_sensor = mBodiesInSensor[sensor];
  184. BodiesInSensor::iterator b = lower_bound(bodies_in_sensor.begin(), bodies_in_sensor.end(), body_and_count);
  185. if (b != bodies_in_sensor.end() && b->mBodyID == body_id)
  186. {
  187. // This is the right body, increment reference
  188. JPH_ASSERT(b->mCount > 0);
  189. b->mCount--;
  190. // When last reference remove from the list
  191. if (b->mCount == 0)
  192. bodies_in_sensor.erase(b);
  193. return;
  194. }
  195. JPH_ASSERT(false, "Body pair not found");
  196. }
  197. }
  198. void SensorTest::SaveState(StateRecorder &inStream) const
  199. {
  200. inStream.Write(mTime);
  201. for (const BodiesInSensor &b : mBodiesInSensor)
  202. inStream.Write(b);
  203. }
  204. void SensorTest::RestoreState(StateRecorder &inStream)
  205. {
  206. inStream.Read(mTime);
  207. for (BodiesInSensor &b : mBodiesInSensor)
  208. inStream.Read(b);
  209. }