SoftBodyMotionProperties.cpp 45 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206
  1. // Jolt Physics Library (https://github.com/jrouwe/JoltPhysics)
  2. // SPDX-FileCopyrightText: 2023 Jorrit Rouwe
  3. // SPDX-License-Identifier: MIT
  4. #include <Jolt/Jolt.h>
  5. #include <Jolt/Physics/SoftBody/SoftBodyMotionProperties.h>
  6. #include <Jolt/Physics/SoftBody/SoftBodyCreationSettings.h>
  7. #include <Jolt/Physics/SoftBody/SoftBodyContactListener.h>
  8. #include <Jolt/Physics/SoftBody/SoftBodyManifold.h>
  9. #include <Jolt/Physics/PhysicsSystem.h>
  10. #include <Jolt/Physics/Body/BodyManager.h>
  11. #include <Jolt/Core/ScopeExit.h>
  12. #ifdef JPH_DEBUG_RENDERER
  13. #include <Jolt/Renderer/DebugRenderer.h>
  14. #endif // JPH_DEBUG_RENDERER
  15. JPH_NAMESPACE_BEGIN
  16. using namespace JPH::literals;
  17. void SoftBodyMotionProperties::CalculateMassAndInertia()
  18. {
  19. MassProperties mp;
  20. for (const Vertex &v : mVertices)
  21. if (v.mInvMass > 0.0f)
  22. {
  23. Vec3 pos = v.mPosition;
  24. // Accumulate mass
  25. float mass = 1.0f / v.mInvMass;
  26. mp.mMass += mass;
  27. // Inertia tensor, diagonal
  28. // See equations https://en.wikipedia.org/wiki/Moment_of_inertia section 'Inertia Tensor'
  29. for (int i = 0; i < 3; ++i)
  30. mp.mInertia(i, i) += mass * (Square(pos[(i + 1) % 3]) + Square(pos[(i + 2) % 3]));
  31. // Inertia tensor off diagonal
  32. for (int i = 0; i < 3; ++i)
  33. for (int j = 0; j < 3; ++j)
  34. if (i != j)
  35. mp.mInertia(i, j) -= mass * pos[i] * pos[j];
  36. }
  37. else
  38. {
  39. // If one vertex is kinematic, the entire body will have infinite mass and inertia
  40. SetInverseMass(0.0f);
  41. SetInverseInertia(Vec3::sZero(), Quat::sIdentity());
  42. return;
  43. }
  44. SetMassProperties(EAllowedDOFs::All, mp);
  45. }
  46. void SoftBodyMotionProperties::Initialize(const SoftBodyCreationSettings &inSettings)
  47. {
  48. // Store settings
  49. mSettings = inSettings.mSettings;
  50. mNumIterations = inSettings.mNumIterations;
  51. mPressure = inSettings.mPressure;
  52. mUpdatePosition = inSettings.mUpdatePosition;
  53. // Initialize vertices
  54. mVertices.resize(inSettings.mSettings->mVertices.size());
  55. Mat44 rotation = inSettings.mMakeRotationIdentity? Mat44::sRotation(inSettings.mRotation) : Mat44::sIdentity();
  56. for (Array<Vertex>::size_type v = 0, s = mVertices.size(); v < s; ++v)
  57. {
  58. const SoftBodySharedSettings::Vertex &in_vertex = inSettings.mSettings->mVertices[v];
  59. Vertex &out_vertex = mVertices[v];
  60. out_vertex.mPreviousPosition = out_vertex.mPosition = rotation * Vec3(in_vertex.mPosition);
  61. out_vertex.mVelocity = rotation.Multiply3x3(Vec3(in_vertex.mVelocity));
  62. out_vertex.mCollidingShapeIndex = -1;
  63. out_vertex.mHasContact = false;
  64. out_vertex.mLargestPenetration = -FLT_MAX;
  65. out_vertex.mInvMass = in_vertex.mInvMass;
  66. mLocalBounds.Encapsulate(out_vertex.mPosition);
  67. }
  68. // Allocate space for skinned vertices
  69. if (!inSettings.mSettings->mSkinnedConstraints.empty())
  70. mSkinState.resize(mVertices.size());
  71. // We don't know delta time yet, so we can't predict the bounds and use the local bounds as the predicted bounds
  72. mLocalPredictedBounds = mLocalBounds;
  73. CalculateMassAndInertia();
  74. }
  75. float SoftBodyMotionProperties::GetVolumeTimesSix() const
  76. {
  77. float six_volume = 0.0f;
  78. for (const Face &f : mSettings->mFaces)
  79. {
  80. Vec3 x1 = mVertices[f.mVertex[0]].mPosition;
  81. Vec3 x2 = mVertices[f.mVertex[1]].mPosition;
  82. Vec3 x3 = mVertices[f.mVertex[2]].mPosition;
  83. six_volume += x1.Cross(x2).Dot(x3); // We pick zero as the origin as this is the center of the bounding box so should give good accuracy
  84. }
  85. return six_volume;
  86. }
  87. void SoftBodyMotionProperties::DetermineCollidingShapes(const SoftBodyUpdateContext &inContext, const PhysicsSystem &inSystem, const BodyLockInterface &inBodyLockInterface)
  88. {
  89. JPH_PROFILE_FUNCTION();
  90. struct Collector : public CollideShapeBodyCollector
  91. {
  92. Collector(const SoftBodyUpdateContext &inContext, const PhysicsSystem &inSystem, const BodyLockInterface &inBodyLockInterface, Array<CollidingShape> &ioHits) :
  93. mContext(inContext),
  94. mInverseTransform(inContext.mCenterOfMassTransform.InversedRotationTranslation()),
  95. mBodyLockInterface(inBodyLockInterface),
  96. mCombineFriction(inSystem.GetCombineFriction()),
  97. mCombineRestitution(inSystem.GetCombineRestitution()),
  98. mHits(ioHits)
  99. {
  100. }
  101. virtual void AddHit(const BodyID &inResult) override
  102. {
  103. BodyLockRead lock(mBodyLockInterface, inResult);
  104. if (lock.Succeeded())
  105. {
  106. const Body &soft_body = *mContext.mBody;
  107. const Body &body = lock.GetBody();
  108. if (body.IsRigidBody() // TODO: We should support soft body vs soft body
  109. && soft_body.GetCollisionGroup().CanCollide(body.GetCollisionGroup()))
  110. {
  111. SoftBodyContactSettings settings;
  112. settings.mIsSensor = body.IsSensor();
  113. if (mContext.mContactListener == nullptr)
  114. {
  115. // If we have no contact listener, we can ignore sensors
  116. if (settings.mIsSensor)
  117. return;
  118. }
  119. else
  120. {
  121. // Call the contact listener to see if we should accept this contact
  122. if (mContext.mContactListener->OnSoftBodyContactValidate(soft_body, body, settings) != SoftBodyValidateResult::AcceptContact)
  123. return;
  124. // Check if there will be any interaction
  125. if (!settings.mIsSensor
  126. && settings.mInvMassScale1 == 0.0f
  127. && (body.GetMotionType() != EMotionType::Dynamic || settings.mInvMassScale2 == 0.0f))
  128. return;
  129. }
  130. CollidingShape cs;
  131. cs.mCenterOfMassTransform = (mInverseTransform * body.GetCenterOfMassTransform()).ToMat44();
  132. cs.mShape = body.GetShape();
  133. cs.mBodyID = inResult;
  134. cs.mMotionType = body.GetMotionType();
  135. cs.mIsSensor = settings.mIsSensor;
  136. cs.mUpdateVelocities = false;
  137. cs.mFriction = mCombineFriction(soft_body, SubShapeID(), body, SubShapeID());
  138. cs.mRestitution = mCombineRestitution(soft_body, SubShapeID(), body, SubShapeID());
  139. cs.mSoftBodyInvMassScale = settings.mInvMassScale1;
  140. if (cs.mMotionType == EMotionType::Dynamic)
  141. {
  142. const MotionProperties *mp = body.GetMotionProperties();
  143. cs.mInvMass = settings.mInvMassScale2 * mp->GetInverseMass();
  144. cs.mInvInertia = settings.mInvInertiaScale2 * mp->GetInverseInertiaForRotation(cs.mCenterOfMassTransform.GetRotation());
  145. cs.mOriginalLinearVelocity = cs.mLinearVelocity = mInverseTransform.Multiply3x3(mp->GetLinearVelocity());
  146. cs.mOriginalAngularVelocity = cs.mAngularVelocity = mInverseTransform.Multiply3x3(mp->GetAngularVelocity());
  147. }
  148. mHits.push_back(cs);
  149. }
  150. }
  151. }
  152. private:
  153. const SoftBodyUpdateContext &mContext;
  154. RMat44 mInverseTransform;
  155. const BodyLockInterface & mBodyLockInterface;
  156. ContactConstraintManager::CombineFunction mCombineFriction;
  157. ContactConstraintManager::CombineFunction mCombineRestitution;
  158. Array<CollidingShape> & mHits;
  159. };
  160. Collector collector(inContext, inSystem, inBodyLockInterface, mCollidingShapes);
  161. AABox bounds = mLocalBounds;
  162. bounds.Encapsulate(mLocalPredictedBounds);
  163. bounds = bounds.Transformed(inContext.mCenterOfMassTransform);
  164. bounds.ExpandBy(Vec3::sReplicate(mSettings->mVertexRadius));
  165. ObjectLayer layer = inContext.mBody->GetObjectLayer();
  166. DefaultBroadPhaseLayerFilter broadphase_layer_filter = inSystem.GetDefaultBroadPhaseLayerFilter(layer);
  167. DefaultObjectLayerFilter object_layer_filter = inSystem.GetDefaultLayerFilter(layer);
  168. inSystem.GetBroadPhaseQuery().CollideAABox(bounds, collector, broadphase_layer_filter, object_layer_filter);
  169. }
  170. void SoftBodyMotionProperties::DetermineCollisionPlanes(const SoftBodyUpdateContext &inContext, uint inVertexStart, uint inNumVertices)
  171. {
  172. JPH_PROFILE_FUNCTION();
  173. // Generate collision planes
  174. for (const CollidingShape &cs : mCollidingShapes)
  175. cs.mShape->CollideSoftBodyVertices(cs.mCenterOfMassTransform, Vec3::sReplicate(1.0f), mVertices.data() + inVertexStart, inNumVertices, inContext.mDeltaTime, inContext.mDisplacementDueToGravity, int(&cs - mCollidingShapes.data()));
  176. }
  177. void SoftBodyMotionProperties::ApplyPressure(const SoftBodyUpdateContext &inContext)
  178. {
  179. JPH_PROFILE_FUNCTION();
  180. float dt = inContext.mSubStepDeltaTime;
  181. float pressure_coefficient = mPressure;
  182. if (pressure_coefficient > 0.0f)
  183. {
  184. // Calculate total volume
  185. float six_volume = GetVolumeTimesSix();
  186. if (six_volume > 0.0f)
  187. {
  188. // Apply pressure
  189. // p = F / A = n R T / V (see https://en.wikipedia.org/wiki/Pressure)
  190. // Our pressure coefficient is n R T so the impulse is:
  191. // P = F dt = pressure_coefficient / V * A * dt
  192. float coefficient = pressure_coefficient * dt / six_volume; // Need to still multiply by 6 for the volume
  193. for (const Face &f : mSettings->mFaces)
  194. {
  195. Vec3 x1 = mVertices[f.mVertex[0]].mPosition;
  196. Vec3 x2 = mVertices[f.mVertex[1]].mPosition;
  197. Vec3 x3 = mVertices[f.mVertex[2]].mPosition;
  198. Vec3 impulse = coefficient * (x2 - x1).Cross(x3 - x1); // Area is half the cross product so need to still divide by 2
  199. for (uint32 i : f.mVertex)
  200. {
  201. Vertex &v = mVertices[i];
  202. v.mVelocity += v.mInvMass * impulse; // Want to divide by 3 because we spread over 3 vertices
  203. }
  204. }
  205. }
  206. }
  207. }
  208. void SoftBodyMotionProperties::IntegratePositions(const SoftBodyUpdateContext &inContext)
  209. {
  210. JPH_PROFILE_FUNCTION();
  211. float dt = inContext.mSubStepDeltaTime;
  212. float linear_damping = max(0.0f, 1.0f - GetLinearDamping() * dt); // See: MotionProperties::ApplyForceTorqueAndDragInternal
  213. // Integrate
  214. Vec3 sub_step_gravity = inContext.mGravity * dt;
  215. Vec3 sub_step_impulse = GetAccumulatedForce() * dt;
  216. for (Vertex &v : mVertices)
  217. if (v.mInvMass > 0.0f)
  218. {
  219. // Gravity
  220. v.mVelocity += sub_step_gravity + sub_step_impulse * v.mInvMass;
  221. // Damping
  222. v.mVelocity *= linear_damping;
  223. // Integrate
  224. v.mPreviousPosition = v.mPosition;
  225. v.mPosition += v.mVelocity * dt;
  226. }
  227. else
  228. {
  229. // Integrate
  230. v.mPreviousPosition = v.mPosition;
  231. v.mPosition += v.mVelocity * dt;
  232. }
  233. }
  234. void SoftBodyMotionProperties::ApplyDihedralBendConstraints(const SoftBodyUpdateContext &inContext, uint inStartIndex, uint inEndIndex)
  235. {
  236. JPH_PROFILE_FUNCTION();
  237. float inv_dt_sq = 1.0f / Square(inContext.mSubStepDeltaTime);
  238. for (const DihedralBend *b = mSettings->mDihedralBendConstraints.data() + inStartIndex, *b_end = mSettings->mDihedralBendConstraints.data() + inEndIndex; b < b_end; ++b)
  239. {
  240. Vertex &v0 = mVertices[b->mVertex[0]];
  241. Vertex &v1 = mVertices[b->mVertex[1]];
  242. Vertex &v2 = mVertices[b->mVertex[2]];
  243. Vertex &v3 = mVertices[b->mVertex[3]];
  244. // Get positions
  245. Vec3 x0 = v0.mPosition;
  246. Vec3 x1 = v1.mPosition;
  247. Vec3 x2 = v2.mPosition;
  248. Vec3 x3 = v3.mPosition;
  249. /*
  250. x2
  251. e1/ \e3
  252. / \
  253. x0----x1
  254. \ e0 /
  255. e2\ /e4
  256. x3
  257. */
  258. // Calculate the shared edge of the triangles
  259. Vec3 e = x1 - x0;
  260. float e_len = e.Length();
  261. if (e_len < 1.0e-6f)
  262. continue;
  263. // Calculate the normals of the triangles
  264. Vec3 x1x2 = x2 - x1;
  265. Vec3 x1x3 = x3 - x1;
  266. Vec3 n1 = (x2 - x0).Cross(x1x2);
  267. Vec3 n2 = x1x3.Cross(x3 - x0);
  268. float n1_len_sq = n1.LengthSq();
  269. float n2_len_sq = n2.LengthSq();
  270. float n1_len_sq_n2_len_sq = n1_len_sq * n2_len_sq;
  271. if (n1_len_sq_n2_len_sq < 1.0e-24f)
  272. continue;
  273. // Calculate constraint equation
  274. // As per "Strain Based Dynamics" Appendix A we need to negate the gradients when (n1 x n2) . e > 0, instead we make sure that the sign of the constraint equation is correct
  275. float sign = Sign(n2.Cross(n1).Dot(e));
  276. float d = n1.Dot(n2) / sqrt(n1_len_sq_n2_len_sq);
  277. float c = sign * ACosApproximate(d) - b->mInitialAngle;
  278. // Ensure the range is -PI to PI
  279. if (c > JPH_PI)
  280. c -= 2.0f * JPH_PI;
  281. else if (c < -JPH_PI)
  282. c += 2.0f * JPH_PI;
  283. // Calculate gradient of constraint equation
  284. // Taken from "Strain Based Dynamics" - Matthias Muller et al. (Appendix A)
  285. // with p1 = x2, p2 = x3, p3 = x0 and p4 = x1
  286. // which in turn is based on "Simulation of Clothing with Folds and Wrinkles" - R. Bridson et al. (Section 4)
  287. n1 /= n1_len_sq;
  288. n2 /= n2_len_sq;
  289. Vec3 d0c = (x1x2.Dot(e) * n1 + x1x3.Dot(e) * n2) / e_len;
  290. Vec3 d2c = e_len * n1;
  291. Vec3 d3c = e_len * n2;
  292. // The sum of the gradients must be zero (see "Strain Based Dynamics" section 4)
  293. Vec3 d1c = -d0c - d2c - d3c;
  294. // Get masses
  295. float w0 = v0.mInvMass;
  296. float w1 = v1.mInvMass;
  297. float w2 = v2.mInvMass;
  298. float w3 = v3.mInvMass;
  299. // Calculate -lambda
  300. float denom = w0 * d0c.LengthSq() + w1 * d1c.LengthSq() + w2 * d2c.LengthSq() + w3 * d3c.LengthSq() + b->mCompliance * inv_dt_sq;
  301. if (denom < 1.0e-12f)
  302. continue;
  303. float minus_lambda = c / denom;
  304. // Apply correction
  305. v0.mPosition = x0 - minus_lambda * w0 * d0c;
  306. v1.mPosition = x1 - minus_lambda * w1 * d1c;
  307. v2.mPosition = x2 - minus_lambda * w2 * d2c;
  308. v3.mPosition = x3 - minus_lambda * w3 * d3c;
  309. }
  310. }
  311. void SoftBodyMotionProperties::ApplyVolumeConstraints(const SoftBodyUpdateContext &inContext, uint inStartIndex, uint inEndIndex)
  312. {
  313. JPH_PROFILE_FUNCTION();
  314. float inv_dt_sq = 1.0f / Square(inContext.mSubStepDeltaTime);
  315. // Satisfy volume constraints
  316. for (const Volume *v = mSettings->mVolumeConstraints.data() + inStartIndex, *v_end = mSettings->mVolumeConstraints.data() + inEndIndex; v < v_end; ++v)
  317. {
  318. Vertex &v1 = mVertices[v->mVertex[0]];
  319. Vertex &v2 = mVertices[v->mVertex[1]];
  320. Vertex &v3 = mVertices[v->mVertex[2]];
  321. Vertex &v4 = mVertices[v->mVertex[3]];
  322. Vec3 x1 = v1.mPosition;
  323. Vec3 x2 = v2.mPosition;
  324. Vec3 x3 = v3.mPosition;
  325. Vec3 x4 = v4.mPosition;
  326. // Calculate constraint equation
  327. Vec3 x1x2 = x2 - x1;
  328. Vec3 x1x3 = x3 - x1;
  329. Vec3 x1x4 = x4 - x1;
  330. float c = abs(x1x2.Cross(x1x3).Dot(x1x4)) - v->mSixRestVolume;
  331. // Calculate gradient of constraint equation
  332. Vec3 d1c = (x4 - x2).Cross(x3 - x2);
  333. Vec3 d2c = x1x3.Cross(x1x4);
  334. Vec3 d3c = x1x4.Cross(x1x2);
  335. Vec3 d4c = x1x2.Cross(x1x3);
  336. // Get masses
  337. float w1 = v1.mInvMass;
  338. float w2 = v2.mInvMass;
  339. float w3 = v3.mInvMass;
  340. float w4 = v4.mInvMass;
  341. // Calculate -lambda
  342. float denom = w1 * d1c.LengthSq() + w2 * d2c.LengthSq() + w3 * d3c.LengthSq() + w4 * d4c.LengthSq() + v->mCompliance * inv_dt_sq;
  343. if (denom < 1.0e-12f)
  344. continue;
  345. float minus_lambda = c / denom;
  346. // Apply correction
  347. v1.mPosition = x1 - minus_lambda * w1 * d1c;
  348. v2.mPosition = x2 - minus_lambda * w2 * d2c;
  349. v3.mPosition = x3 - minus_lambda * w3 * d3c;
  350. v4.mPosition = x4 - minus_lambda * w4 * d4c;
  351. }
  352. }
  353. void SoftBodyMotionProperties::ApplySkinConstraints(const SoftBodyUpdateContext &inContext, uint inStartIndex, uint inEndIndex)
  354. {
  355. // Early out if nothing to do
  356. if (mSettings->mSkinnedConstraints.empty() || !mEnableSkinConstraints)
  357. return;
  358. JPH_PROFILE_FUNCTION();
  359. // We're going to iterate multiple times over the skin constraints, update the skinned position accordingly.
  360. // If we don't do this, the simulation will see a big jump and the first iteration will cause a big velocity change in the system.
  361. float factor = mSkinStatePreviousPositionValid? inContext.mNextIteration.load(std::memory_order_relaxed) / float(mNumIterations) : 1.0f;
  362. float prev_factor = 1.0f - factor;
  363. // Apply the constraints
  364. Vertex *vertices = mVertices.data();
  365. const SkinState *skin_states = mSkinState.data();
  366. for (const Skinned *s = mSettings->mSkinnedConstraints.data() + inStartIndex, *s_end = mSettings->mSkinnedConstraints.data() + inEndIndex; s < s_end; ++s)
  367. {
  368. Vertex &vertex = vertices[s->mVertex];
  369. const SkinState &skin_state = skin_states[s->mVertex];
  370. float max_distance = s->mMaxDistance * mSkinnedMaxDistanceMultiplier;
  371. // Calculate the skinned position by interpolating from previous to current position
  372. Vec3 skin_pos = prev_factor * skin_state.mPreviousPosition + factor * skin_state.mPosition;
  373. if (max_distance > 0.0f)
  374. {
  375. // Move vertex if it violated the back stop
  376. if (s->mBackStopDistance < max_distance)
  377. {
  378. // Center of the back stop sphere
  379. Vec3 center = skin_pos - skin_state.mNormal * (s->mBackStopDistance + s->mBackStopRadius);
  380. // Check if we're inside the back stop sphere
  381. Vec3 delta = vertex.mPosition - center;
  382. float delta_len_sq = delta.LengthSq();
  383. if (delta_len_sq < Square(s->mBackStopRadius))
  384. {
  385. // Push the vertex to the surface of the back stop sphere
  386. float delta_len = sqrt(delta_len_sq);
  387. vertex.mPosition = delta_len > 0.0f?
  388. center + delta * (s->mBackStopRadius / delta_len)
  389. : center + skin_state.mNormal * s->mBackStopRadius;
  390. }
  391. }
  392. // Clamp vertex distance to max distance from skinned position
  393. if (max_distance < FLT_MAX)
  394. {
  395. Vec3 delta = vertex.mPosition - skin_pos;
  396. float delta_len_sq = delta.LengthSq();
  397. float max_distance_sq = Square(max_distance);
  398. if (delta_len_sq > max_distance_sq)
  399. vertex.mPosition = skin_pos + delta * sqrt(max_distance_sq / delta_len_sq);
  400. }
  401. }
  402. else
  403. {
  404. // Kinematic: Just update the vertex position
  405. vertex.mPosition = skin_pos;
  406. }
  407. }
  408. }
  409. void SoftBodyMotionProperties::ApplyEdgeConstraints(const SoftBodyUpdateContext &inContext, uint inStartIndex, uint inEndIndex)
  410. {
  411. JPH_PROFILE_FUNCTION();
  412. float inv_dt_sq = 1.0f / Square(inContext.mSubStepDeltaTime);
  413. // Satisfy edge constraints
  414. for (const Edge *e = mSettings->mEdgeConstraints.data() + inStartIndex, *e_end = mSettings->mEdgeConstraints.data() + inEndIndex; e < e_end; ++e)
  415. {
  416. Vertex &v0 = mVertices[e->mVertex[0]];
  417. Vertex &v1 = mVertices[e->mVertex[1]];
  418. // Get positions
  419. Vec3 x0 = v0.mPosition;
  420. Vec3 x1 = v1.mPosition;
  421. // Calculate current length
  422. Vec3 delta = x1 - x0;
  423. float length = delta.Length();
  424. // Apply correction
  425. float denom = length * (v0.mInvMass + v1.mInvMass + e->mCompliance * inv_dt_sq);
  426. if (denom < 1.0e-12f)
  427. continue;
  428. Vec3 correction = delta * (length - e->mRestLength) / denom;
  429. v0.mPosition = x0 + v0.mInvMass * correction;
  430. v1.mPosition = x1 - v1.mInvMass * correction;
  431. }
  432. }
  433. void SoftBodyMotionProperties::ApplyLRAConstraints(uint inStartIndex, uint inEndIndex)
  434. {
  435. JPH_PROFILE_FUNCTION();
  436. // Satisfy LRA constraints
  437. Vertex *vertices = mVertices.data();
  438. for (const LRA *lra = mSettings->mLRAConstraints.data() + inStartIndex, *lra_end = mSettings->mLRAConstraints.data() + inEndIndex; lra < lra_end; ++lra)
  439. {
  440. JPH_ASSERT(lra->mVertex[0] < mVertices.size());
  441. JPH_ASSERT(lra->mVertex[1] < mVertices.size());
  442. const Vertex &vertex0 = vertices[lra->mVertex[0]];
  443. Vertex &vertex1 = vertices[lra->mVertex[1]];
  444. Vec3 x0 = vertex0.mPosition;
  445. Vec3 delta = vertex1.mPosition - x0;
  446. float delta_len_sq = delta.LengthSq();
  447. if (delta_len_sq > Square(lra->mMaxDistance))
  448. vertex1.mPosition = x0 + delta * lra->mMaxDistance / sqrt(delta_len_sq);
  449. }
  450. }
  451. void SoftBodyMotionProperties::ApplyCollisionConstraintsAndUpdateVelocities(const SoftBodyUpdateContext &inContext)
  452. {
  453. JPH_PROFILE_FUNCTION();
  454. float dt = inContext.mSubStepDeltaTime;
  455. float restitution_treshold = -2.0f * inContext.mGravity.Length() * dt;
  456. float vertex_radius = mSettings->mVertexRadius;
  457. for (Vertex &v : mVertices)
  458. if (v.mInvMass > 0.0f)
  459. {
  460. // Remember previous velocity for restitution calculations
  461. Vec3 prev_v = v.mVelocity;
  462. // XPBD velocity update
  463. v.mVelocity = (v.mPosition - v.mPreviousPosition) / dt;
  464. // Satisfy collision constraint
  465. if (v.mCollidingShapeIndex >= 0)
  466. {
  467. // Check if there is a collision
  468. float projected_distance = -v.mCollisionPlane.SignedDistance(v.mPosition) + vertex_radius;
  469. if (projected_distance > 0.0f)
  470. {
  471. // Remember that there was a collision
  472. v.mHasContact = true;
  473. mHasContact = true;
  474. // Sensors should not have a collision response
  475. CollidingShape &cs = mCollidingShapes[v.mCollidingShapeIndex];
  476. if (!cs.mIsSensor)
  477. {
  478. // Note that we already calculated the velocity, so this does not affect the velocity (next iteration starts by setting previous position to current position)
  479. Vec3 contact_normal = v.mCollisionPlane.GetNormal();
  480. v.mPosition += contact_normal * projected_distance;
  481. // Apply friction as described in Detailed Rigid Body Simulation with Extended Position Based Dynamics - Matthias Muller et al.
  482. // See section 3.6:
  483. // Inverse mass: w1 = 1 / m1, w2 = 1 / m2 + (r2 x n)^T I^-1 (r2 x n) = 0 for a static object
  484. // r2 are the contact point relative to the center of mass of body 2
  485. // Lagrange multiplier for contact: lambda = -c / (w1 + w2)
  486. // Where c is the constraint equation (the distance to the plane, negative because penetrating)
  487. // Contact normal force: fn = lambda / dt^2
  488. // Delta velocity due to friction dv = -vt / |vt| * min(dt * friction * fn * (w1 + w2), |vt|) = -vt * min(-friction * c / (|vt| * dt), 1)
  489. // Note that I think there is an error in the paper, I added a mass term, see: https://github.com/matthias-research/pages/issues/29
  490. // Relative velocity: vr = v1 - v2 - omega2 x r2
  491. // Normal velocity: vn = vr . contact_normal
  492. // Tangential velocity: vt = vr - contact_normal * vn
  493. // Impulse: p = dv / (w1 + w2)
  494. // Changes in particle velocities:
  495. // v1 = v1 + p / m1
  496. // v2 = v2 - p / m2 (no change when colliding with a static body)
  497. // w2 = w2 - I^-1 (r2 x p) (no change when colliding with a static body)
  498. if (cs.mMotionType == EMotionType::Dynamic)
  499. {
  500. // Calculate normal and tangential velocity (equation 30)
  501. Vec3 r2 = v.mPosition - cs.mCenterOfMassTransform.GetTranslation();
  502. Vec3 v2 = cs.GetPointVelocity(r2);
  503. Vec3 relative_velocity = v.mVelocity - v2;
  504. Vec3 v_normal = contact_normal * contact_normal.Dot(relative_velocity);
  505. Vec3 v_tangential = relative_velocity - v_normal;
  506. float v_tangential_length = v_tangential.Length();
  507. // Calculate resulting inverse mass of vertex
  508. float vertex_inv_mass = cs.mSoftBodyInvMassScale * v.mInvMass;
  509. // Calculate inverse effective mass
  510. Vec3 r2_cross_n = r2.Cross(contact_normal);
  511. float w2 = cs.mInvMass + r2_cross_n.Dot(cs.mInvInertia * r2_cross_n);
  512. float w1_plus_w2 = vertex_inv_mass + w2;
  513. if (w1_plus_w2 > 0.0f)
  514. {
  515. // Calculate delta relative velocity due to friction (modified equation 31)
  516. Vec3 dv;
  517. if (v_tangential_length > 0.0f)
  518. dv = v_tangential * min(cs.mFriction * projected_distance / (v_tangential_length * dt), 1.0f);
  519. else
  520. dv = Vec3::sZero();
  521. // Calculate delta relative velocity due to restitution (equation 35)
  522. dv += v_normal;
  523. float prev_v_normal = (prev_v - v2).Dot(contact_normal);
  524. if (prev_v_normal < restitution_treshold)
  525. dv += cs.mRestitution * prev_v_normal * contact_normal;
  526. // Calculate impulse
  527. Vec3 p = dv / w1_plus_w2;
  528. // Apply impulse to particle
  529. v.mVelocity -= p * vertex_inv_mass;
  530. // Apply impulse to rigid body
  531. cs.mLinearVelocity += p * cs.mInvMass;
  532. cs.mAngularVelocity += cs.mInvInertia * r2.Cross(p);
  533. // Mark that the velocities of the body we hit need to be updated
  534. cs.mUpdateVelocities = true;
  535. }
  536. }
  537. else if (cs.mSoftBodyInvMassScale > 0.0f)
  538. {
  539. // Body is not movable, equations are simpler
  540. // Calculate normal and tangential velocity (equation 30)
  541. Vec3 v_normal = contact_normal * contact_normal.Dot(v.mVelocity);
  542. Vec3 v_tangential = v.mVelocity - v_normal;
  543. float v_tangential_length = v_tangential.Length();
  544. // Apply friction (modified equation 31)
  545. if (v_tangential_length > 0.0f)
  546. v.mVelocity -= v_tangential * min(cs.mFriction * projected_distance / (v_tangential_length * dt), 1.0f);
  547. // Apply restitution (equation 35)
  548. v.mVelocity -= v_normal;
  549. float prev_v_normal = prev_v.Dot(contact_normal);
  550. if (prev_v_normal < restitution_treshold)
  551. v.mVelocity -= cs.mRestitution * prev_v_normal * contact_normal;
  552. }
  553. }
  554. }
  555. }
  556. }
  557. }
  558. void SoftBodyMotionProperties::UpdateSoftBodyState(SoftBodyUpdateContext &ioContext, const PhysicsSettings &inPhysicsSettings)
  559. {
  560. JPH_PROFILE_FUNCTION();
  561. // Contact callback
  562. if (mHasContact && ioContext.mContactListener != nullptr)
  563. ioContext.mContactListener->OnSoftBodyContactAdded(*ioContext.mBody, SoftBodyManifold(this));
  564. // Loop through vertices once more to update the global state
  565. float dt = ioContext.mDeltaTime;
  566. float max_linear_velocity_sq = Square(GetMaxLinearVelocity());
  567. float max_v_sq = 0.0f;
  568. Vec3 linear_velocity = Vec3::sZero(), angular_velocity = Vec3::sZero();
  569. mLocalPredictedBounds = mLocalBounds = { };
  570. mHasContact = false;
  571. for (Vertex &v : mVertices)
  572. {
  573. // Calculate max square velocity
  574. float v_sq = v.mVelocity.LengthSq();
  575. max_v_sq = max(max_v_sq, v_sq);
  576. // Clamp if velocity is too high
  577. if (v_sq > max_linear_velocity_sq)
  578. v.mVelocity *= sqrt(max_linear_velocity_sq / v_sq);
  579. // Calculate local linear/angular velocity
  580. linear_velocity += v.mVelocity;
  581. angular_velocity += v.mPosition.Cross(v.mVelocity);
  582. // Update local bounding box
  583. mLocalBounds.Encapsulate(v.mPosition);
  584. // Create predicted position for the next frame in order to detect collisions before they happen
  585. mLocalPredictedBounds.Encapsulate(v.mPosition + v.mVelocity * dt + ioContext.mDisplacementDueToGravity);
  586. // Reset collision data for the next iteration
  587. v.mCollidingShapeIndex = -1;
  588. v.mHasContact = false;
  589. v.mLargestPenetration = -FLT_MAX;
  590. }
  591. // Calculate linear/angular velocity of the body by averaging all vertices and bringing the value to world space
  592. float num_vertices_divider = float(max(int(mVertices.size()), 1));
  593. SetLinearVelocity(ioContext.mCenterOfMassTransform.Multiply3x3(linear_velocity / num_vertices_divider));
  594. SetAngularVelocity(ioContext.mCenterOfMassTransform.Multiply3x3(angular_velocity / num_vertices_divider));
  595. if (mUpdatePosition)
  596. {
  597. // Shift the body so that the position is the center of the local bounds
  598. Vec3 delta = mLocalBounds.GetCenter();
  599. ioContext.mDeltaPosition = ioContext.mCenterOfMassTransform.Multiply3x3(delta);
  600. for (Vertex &v : mVertices)
  601. v.mPosition -= delta;
  602. // Update the skin state too since we will use this position as the previous position in the next update
  603. for (SkinState &s : mSkinState)
  604. s.mPosition -= delta;
  605. JPH_IF_DEBUG_RENDERER(mSkinStateTransform.SetTranslation(mSkinStateTransform.GetTranslation() + ioContext.mDeltaPosition);)
  606. // Offset bounds to match new position
  607. mLocalBounds.Translate(-delta);
  608. mLocalPredictedBounds.Translate(-delta);
  609. }
  610. else
  611. ioContext.mDeltaPosition = Vec3::sZero();
  612. // Test if we should go to sleep
  613. if (GetAllowSleeping())
  614. {
  615. if (max_v_sq > inPhysicsSettings.mPointVelocitySleepThreshold)
  616. {
  617. ResetSleepTestTimer();
  618. ioContext.mCanSleep = ECanSleep::CannotSleep;
  619. }
  620. else
  621. ioContext.mCanSleep = AccumulateSleepTime(dt, inPhysicsSettings.mTimeBeforeSleep);
  622. }
  623. else
  624. ioContext.mCanSleep = ECanSleep::CannotSleep;
  625. // If SkinVertices is not called after this then don't use the previous position as the skin is static
  626. mSkinStatePreviousPositionValid = false;
  627. // Reset force accumulator
  628. ResetForce();
  629. }
  630. void SoftBodyMotionProperties::UpdateRigidBodyVelocities(const SoftBodyUpdateContext &inContext, BodyInterface &inBodyInterface)
  631. {
  632. JPH_PROFILE_FUNCTION();
  633. // Write back velocity deltas
  634. for (const CollidingShape &cs : mCollidingShapes)
  635. if (cs.mUpdateVelocities)
  636. inBodyInterface.AddLinearAndAngularVelocity(cs.mBodyID, inContext.mCenterOfMassTransform.Multiply3x3(cs.mLinearVelocity - cs.mOriginalLinearVelocity), inContext.mCenterOfMassTransform.Multiply3x3(cs.mAngularVelocity - cs.mOriginalAngularVelocity));
  637. // Clear colliding shapes to avoid hanging on to references to shapes
  638. mCollidingShapes.clear();
  639. }
  640. void SoftBodyMotionProperties::InitializeUpdateContext(float inDeltaTime, Body &inSoftBody, const PhysicsSystem &inSystem, SoftBodyUpdateContext &ioContext)
  641. {
  642. JPH_PROFILE_FUNCTION();
  643. // Store body
  644. ioContext.mBody = &inSoftBody;
  645. ioContext.mMotionProperties = this;
  646. ioContext.mContactListener = inSystem.GetSoftBodyContactListener();
  647. // Convert gravity to local space
  648. ioContext.mCenterOfMassTransform = inSoftBody.GetCenterOfMassTransform();
  649. ioContext.mGravity = ioContext.mCenterOfMassTransform.Multiply3x3Transposed(GetGravityFactor() * inSystem.GetGravity());
  650. // Calculate delta time for sub step
  651. ioContext.mDeltaTime = inDeltaTime;
  652. ioContext.mSubStepDeltaTime = inDeltaTime / mNumIterations;
  653. // Calculate total displacement we'll have due to gravity over all sub steps
  654. // The total displacement as produced by our integrator can be written as: Sum(i * g * dt^2, i = 0..mNumIterations).
  655. // This is bigger than 0.5 * g * dt^2 because we first increment the velocity and then update the position
  656. // Using Sum(i, i = 0..n) = n * (n + 1) / 2 we can write this as:
  657. ioContext.mDisplacementDueToGravity = (0.5f * mNumIterations * (mNumIterations + 1) * Square(ioContext.mSubStepDeltaTime)) * ioContext.mGravity;
  658. }
  659. void SoftBodyMotionProperties::StartNextIteration(const SoftBodyUpdateContext &ioContext)
  660. {
  661. ApplyPressure(ioContext);
  662. IntegratePositions(ioContext);
  663. }
  664. SoftBodyMotionProperties::EStatus SoftBodyMotionProperties::ParallelDetermineCollisionPlanes(SoftBodyUpdateContext &ioContext)
  665. {
  666. // Do a relaxed read first to see if there is any work to do (this prevents us from doing expensive atomic operations and also prevents us from continuously incrementing the counter and overflowing it)
  667. uint num_vertices = (uint)mVertices.size();
  668. if (ioContext.mNextCollisionVertex.load(memory_order_relaxed) < num_vertices)
  669. {
  670. // Fetch next batch of vertices to process
  671. uint next_vertex = ioContext.mNextCollisionVertex.fetch_add(SoftBodyUpdateContext::cVertexCollisionBatch, memory_order_acquire);
  672. if (next_vertex < num_vertices)
  673. {
  674. // Process collision planes
  675. uint num_vertices_to_process = min(SoftBodyUpdateContext::cVertexCollisionBatch, num_vertices - next_vertex);
  676. DetermineCollisionPlanes(ioContext, next_vertex, num_vertices_to_process);
  677. uint vertices_processed = ioContext.mNumCollisionVerticesProcessed.fetch_add(SoftBodyUpdateContext::cVertexCollisionBatch, memory_order_release) + num_vertices_to_process;
  678. if (vertices_processed >= num_vertices)
  679. {
  680. // Start the first iteration
  681. JPH_IF_ENABLE_ASSERTS(uint iteration =) ioContext.mNextIteration.fetch_add(1, memory_order_relaxed);
  682. JPH_ASSERT(iteration == 0);
  683. StartNextIteration(ioContext);
  684. ioContext.mState.store(SoftBodyUpdateContext::EState::ApplyConstraints, memory_order_release);
  685. }
  686. return EStatus::DidWork;
  687. }
  688. }
  689. return EStatus::NoWork;
  690. }
  691. void SoftBodyMotionProperties::ProcessGroup(const SoftBodyUpdateContext &ioContext, uint inGroupIndex)
  692. {
  693. // Determine start and end
  694. SoftBodySharedSettings::UpdateGroup start { 0, 0, 0, 0, 0 };
  695. const SoftBodySharedSettings::UpdateGroup &prev = inGroupIndex > 0? mSettings->mUpdateGroups[inGroupIndex - 1] : start;
  696. const SoftBodySharedSettings::UpdateGroup &current = mSettings->mUpdateGroups[inGroupIndex];
  697. // Process volume constraints
  698. ApplyVolumeConstraints(ioContext, prev.mVolumeEndIndex, current.mVolumeEndIndex);
  699. // Process bend constraints
  700. ApplyDihedralBendConstraints(ioContext, prev.mDihedralBendEndIndex, current.mDihedralBendEndIndex);
  701. // Process skinned constraints
  702. ApplySkinConstraints(ioContext, prev.mSkinnedEndIndex, current.mSkinnedEndIndex);
  703. // Process edges
  704. ApplyEdgeConstraints(ioContext, prev.mEdgeEndIndex, current.mEdgeEndIndex);
  705. // Process LRA constraints
  706. ApplyLRAConstraints(prev.mLRAEndIndex, current.mLRAEndIndex);
  707. }
  708. SoftBodyMotionProperties::EStatus SoftBodyMotionProperties::ParallelApplyConstraints(SoftBodyUpdateContext &ioContext, const PhysicsSettings &inPhysicsSettings)
  709. {
  710. uint num_groups = (uint)mSettings->mUpdateGroups.size();
  711. JPH_ASSERT(num_groups > 0, "SoftBodySharedSettings::Optimize should have been called!");
  712. --num_groups; // Last group is the non-parallel group, we don't want to execute it in parallel
  713. // Do a relaxed read first to see if there is any work to do (this prevents us from doing expensive atomic operations and also prevents us from continuously incrementing the counter and overflowing it)
  714. uint next_group = ioContext.mNextConstraintGroup.load(memory_order_relaxed);
  715. if (next_group < num_groups || (num_groups == 0 && next_group == 0))
  716. {
  717. // Fetch the next group process
  718. next_group = ioContext.mNextConstraintGroup.fetch_add(1, memory_order_acquire);
  719. if (next_group < num_groups || (num_groups == 0 && next_group == 0))
  720. {
  721. uint num_groups_processed = 0;
  722. if (num_groups > 0)
  723. {
  724. // Process this group
  725. ProcessGroup(ioContext, next_group);
  726. // Increment total number of groups processed
  727. num_groups_processed = ioContext.mNumConstraintGroupsProcessed.fetch_add(1, memory_order_relaxed) + 1;
  728. }
  729. if (num_groups_processed >= num_groups)
  730. {
  731. // Finish the iteration
  732. JPH_PROFILE("FinishIteration");
  733. // Process non-parallel group
  734. ProcessGroup(ioContext, num_groups);
  735. ApplyCollisionConstraintsAndUpdateVelocities(ioContext);
  736. uint iteration = ioContext.mNextIteration.fetch_add(1, memory_order_relaxed);
  737. if (iteration < mNumIterations)
  738. {
  739. // Start a new iteration
  740. StartNextIteration(ioContext);
  741. // Reset group logic
  742. ioContext.mNumConstraintGroupsProcessed.store(0, memory_order_relaxed);
  743. ioContext.mNextConstraintGroup.store(0, memory_order_release);
  744. }
  745. else
  746. {
  747. // On final iteration we update the state
  748. UpdateSoftBodyState(ioContext, inPhysicsSettings);
  749. ioContext.mState.store(SoftBodyUpdateContext::EState::Done, memory_order_release);
  750. return EStatus::Done;
  751. }
  752. }
  753. return EStatus::DidWork;
  754. }
  755. }
  756. return EStatus::NoWork;
  757. }
  758. SoftBodyMotionProperties::EStatus SoftBodyMotionProperties::ParallelUpdate(SoftBodyUpdateContext &ioContext, const PhysicsSettings &inPhysicsSettings)
  759. {
  760. switch (ioContext.mState.load(memory_order_relaxed))
  761. {
  762. case SoftBodyUpdateContext::EState::DetermineCollisionPlanes:
  763. return ParallelDetermineCollisionPlanes(ioContext);
  764. case SoftBodyUpdateContext::EState::ApplyConstraints:
  765. return ParallelApplyConstraints(ioContext, inPhysicsSettings);
  766. case SoftBodyUpdateContext::EState::Done:
  767. return EStatus::Done;
  768. default:
  769. JPH_ASSERT(false);
  770. return EStatus::NoWork;
  771. }
  772. }
  773. void SoftBodyMotionProperties::SkinVertices([[maybe_unused]] RMat44Arg inCenterOfMassTransform, const Mat44 *inJointMatrices, [[maybe_unused]] uint inNumJoints, bool inHardSkinAll, TempAllocator &ioTempAllocator)
  774. {
  775. // Calculate the skin matrices
  776. uint num_skin_matrices = uint(mSettings->mInvBindMatrices.size());
  777. uint skin_matrices_size = num_skin_matrices * sizeof(Mat44);
  778. Mat44 *skin_matrices = (Mat44 *)ioTempAllocator.Allocate(skin_matrices_size);
  779. JPH_SCOPE_EXIT([&ioTempAllocator, skin_matrices, skin_matrices_size]{ ioTempAllocator.Free(skin_matrices, skin_matrices_size); });
  780. const Mat44 *skin_matrices_end = skin_matrices + num_skin_matrices;
  781. const InvBind *inv_bind_matrix = mSettings->mInvBindMatrices.data();
  782. for (Mat44 *s = skin_matrices; s < skin_matrices_end; ++s, ++inv_bind_matrix)
  783. *s = inJointMatrices[inv_bind_matrix->mJointIndex] * inv_bind_matrix->mInvBind;
  784. // Skin the vertices
  785. JPH_IF_DEBUG_RENDERER(mSkinStateTransform = inCenterOfMassTransform;)
  786. JPH_IF_ENABLE_ASSERTS(uint num_vertices = uint(mSettings->mVertices.size());)
  787. JPH_ASSERT(mSkinState.size() == num_vertices);
  788. const SoftBodySharedSettings::Vertex *in_vertices = mSettings->mVertices.data();
  789. for (const Skinned &s : mSettings->mSkinnedConstraints)
  790. {
  791. // Get bind pose
  792. JPH_ASSERT(s.mVertex < num_vertices);
  793. Vec3 bind_pos = Vec3::sLoadFloat3Unsafe(in_vertices[s.mVertex].mPosition);
  794. // Skin vertex
  795. Vec3 pos = Vec3::sZero();
  796. for (const SkinWeight &w : s.mWeights)
  797. {
  798. // We assume that the first zero weight is the end of the list
  799. if (w.mWeight == 0.0f)
  800. break;
  801. JPH_ASSERT(w.mInvBindIndex < num_skin_matrices);
  802. pos += w.mWeight * (skin_matrices[w.mInvBindIndex] * bind_pos);
  803. }
  804. SkinState &skin_state = mSkinState[s.mVertex];
  805. skin_state.mPreviousPosition = skin_state.mPosition;
  806. skin_state.mPosition = pos;
  807. }
  808. // Calculate the normals
  809. for (const Skinned &s : mSettings->mSkinnedConstraints)
  810. {
  811. Vec3 normal = Vec3::sZero();
  812. uint32 num_faces = s.mNormalInfo >> 24;
  813. if (num_faces > 0)
  814. {
  815. // Calculate normal
  816. const uint32 *f = &mSettings->mSkinnedConstraintNormals[s.mNormalInfo & 0xffffff];
  817. const uint32 *f_end = f + num_faces;
  818. while (f < f_end)
  819. {
  820. const Face &face = mSettings->mFaces[*f];
  821. Vec3 v0 = mSkinState[face.mVertex[0]].mPosition;
  822. Vec3 v1 = mSkinState[face.mVertex[1]].mPosition;
  823. Vec3 v2 = mSkinState[face.mVertex[2]].mPosition;
  824. normal += (v1 - v0).Cross(v2 - v0).NormalizedOr(Vec3::sZero());
  825. ++f;
  826. }
  827. normal = normal.NormalizedOr(Vec3::sZero());
  828. }
  829. mSkinState[s.mVertex].mNormal = normal;
  830. }
  831. if (inHardSkinAll)
  832. {
  833. // Hard skin all vertices and reset their velocities
  834. for (const Skinned &s : mSettings->mSkinnedConstraints)
  835. {
  836. Vertex &vertex = mVertices[s.mVertex];
  837. SkinState &skin_state = mSkinState[s.mVertex];
  838. skin_state.mPreviousPosition = skin_state.mPosition;
  839. vertex.mPosition = skin_state.mPosition;
  840. vertex.mVelocity = Vec3::sZero();
  841. }
  842. }
  843. else if (!mEnableSkinConstraints)
  844. {
  845. // Hard skin only the kinematic vertices as we will not solve the skin constraints later
  846. for (const Skinned &s : mSettings->mSkinnedConstraints)
  847. if (s.mMaxDistance == 0.0f)
  848. {
  849. Vertex &vertex = mVertices[s.mVertex];
  850. vertex.mPosition = mSkinState[s.mVertex].mPosition;
  851. }
  852. }
  853. // Indicate that the previous positions are valid for the coming update
  854. mSkinStatePreviousPositionValid = true;
  855. }
  856. void SoftBodyMotionProperties::CustomUpdate(float inDeltaTime, Body &ioSoftBody, PhysicsSystem &inSystem)
  857. {
  858. JPH_PROFILE_FUNCTION();
  859. // Create update context
  860. SoftBodyUpdateContext context;
  861. InitializeUpdateContext(inDeltaTime, ioSoftBody, inSystem, context);
  862. // Determine bodies we're colliding with
  863. DetermineCollidingShapes(context, inSystem, inSystem.GetBodyLockInterface());
  864. // Call the internal update until it finishes
  865. EStatus status;
  866. const PhysicsSettings &settings = inSystem.GetPhysicsSettings();
  867. while ((status = ParallelUpdate(context, settings)) == EStatus::DidWork)
  868. continue;
  869. JPH_ASSERT(status == EStatus::Done);
  870. // Update the state of the bodies we've collided with
  871. UpdateRigidBodyVelocities(context, inSystem.GetBodyInterface());
  872. // Update position of the soft body
  873. if (mUpdatePosition)
  874. inSystem.GetBodyInterface().SetPosition(ioSoftBody.GetID(), ioSoftBody.GetPosition() + context.mDeltaPosition, EActivation::DontActivate);
  875. }
  876. #ifdef JPH_DEBUG_RENDERER
  877. void SoftBodyMotionProperties::DrawVertices(DebugRenderer *inRenderer, RMat44Arg inCenterOfMassTransform) const
  878. {
  879. for (const Vertex &v : mVertices)
  880. inRenderer->DrawMarker(inCenterOfMassTransform * v.mPosition, v.mInvMass > 0.0f? Color::sGreen : Color::sRed, 0.05f);
  881. }
  882. void SoftBodyMotionProperties::DrawVertexVelocities(DebugRenderer *inRenderer, RMat44Arg inCenterOfMassTransform) const
  883. {
  884. for (const Vertex &v : mVertices)
  885. inRenderer->DrawArrow(inCenterOfMassTransform * v.mPosition, inCenterOfMassTransform * (v.mPosition + v.mVelocity), Color::sYellow, 0.01f);
  886. }
  887. template <typename GetEndIndex, typename DrawConstraint>
  888. inline void SoftBodyMotionProperties::DrawConstraints(ESoftBodyConstraintColor inConstraintColor, const GetEndIndex &inGetEndIndex, const DrawConstraint &inDrawConstraint, ColorArg inBaseColor) const
  889. {
  890. uint start = 0;
  891. for (uint i = 0; i < (uint)mSettings->mUpdateGroups.size(); ++i)
  892. {
  893. uint end = inGetEndIndex(mSettings->mUpdateGroups[i]);
  894. Color base_color;
  895. if (inConstraintColor != ESoftBodyConstraintColor::ConstraintType)
  896. base_color = Color::sGetDistinctColor((uint)mSettings->mUpdateGroups.size() - i - 1); // Ensure that color 0 is always the last group
  897. else
  898. base_color = inBaseColor;
  899. for (uint idx = start; idx < end; ++idx)
  900. {
  901. Color color = inConstraintColor == ESoftBodyConstraintColor::ConstraintOrder? base_color * (float(idx - start) / (end - start)) : base_color;
  902. inDrawConstraint(idx, color);
  903. }
  904. start = end;
  905. }
  906. }
  907. void SoftBodyMotionProperties::DrawEdgeConstraints(DebugRenderer *inRenderer, RMat44Arg inCenterOfMassTransform, ESoftBodyConstraintColor inConstraintColor) const
  908. {
  909. DrawConstraints(inConstraintColor,
  910. [](const SoftBodySharedSettings::UpdateGroup &inGroup) {
  911. return inGroup.mEdgeEndIndex;
  912. },
  913. [this, inRenderer, &inCenterOfMassTransform](uint inIndex, ColorArg inColor) {
  914. const Edge &e = mSettings->mEdgeConstraints[inIndex];
  915. inRenderer->DrawLine(inCenterOfMassTransform * mVertices[e.mVertex[0]].mPosition, inCenterOfMassTransform * mVertices[e.mVertex[1]].mPosition, inColor);
  916. },
  917. Color::sWhite);
  918. }
  919. void SoftBodyMotionProperties::DrawBendConstraints(DebugRenderer *inRenderer, RMat44Arg inCenterOfMassTransform, ESoftBodyConstraintColor inConstraintColor) const
  920. {
  921. DrawConstraints(inConstraintColor,
  922. [](const SoftBodySharedSettings::UpdateGroup &inGroup) {
  923. return inGroup.mDihedralBendEndIndex;
  924. },
  925. [this, inRenderer, &inCenterOfMassTransform](uint inIndex, ColorArg inColor) {
  926. const DihedralBend &b = mSettings->mDihedralBendConstraints[inIndex];
  927. RVec3 x0 = inCenterOfMassTransform * mVertices[b.mVertex[0]].mPosition;
  928. RVec3 x1 = inCenterOfMassTransform * mVertices[b.mVertex[1]].mPosition;
  929. RVec3 x2 = inCenterOfMassTransform * mVertices[b.mVertex[2]].mPosition;
  930. RVec3 x3 = inCenterOfMassTransform * mVertices[b.mVertex[3]].mPosition;
  931. RVec3 c_edge = 0.5_r * (x0 + x1);
  932. RVec3 c0 = (x0 + x1 + x2) / 3.0_r;
  933. RVec3 c1 = (x0 + x1 + x3) / 3.0_r;
  934. inRenderer->DrawArrow(0.9_r * x0 + 0.1_r * x1, 0.1_r * x0 + 0.9_r * x1, inColor, 0.01f);
  935. inRenderer->DrawLine(c_edge, 0.1_r * c_edge + 0.9_r * c0, inColor);
  936. inRenderer->DrawLine(c_edge, 0.1_r * c_edge + 0.9_r * c1, inColor);
  937. },
  938. Color::sGreen);
  939. }
  940. void SoftBodyMotionProperties::DrawVolumeConstraints(DebugRenderer *inRenderer, RMat44Arg inCenterOfMassTransform, ESoftBodyConstraintColor inConstraintColor) const
  941. {
  942. DrawConstraints(inConstraintColor,
  943. [](const SoftBodySharedSettings::UpdateGroup &inGroup) {
  944. return inGroup.mVolumeEndIndex;
  945. },
  946. [this, inRenderer, &inCenterOfMassTransform](uint inIndex, ColorArg inColor) {
  947. const Volume &v = mSettings->mVolumeConstraints[inIndex];
  948. RVec3 x1 = inCenterOfMassTransform * mVertices[v.mVertex[0]].mPosition;
  949. RVec3 x2 = inCenterOfMassTransform * mVertices[v.mVertex[1]].mPosition;
  950. RVec3 x3 = inCenterOfMassTransform * mVertices[v.mVertex[2]].mPosition;
  951. RVec3 x4 = inCenterOfMassTransform * mVertices[v.mVertex[3]].mPosition;
  952. inRenderer->DrawTriangle(x1, x3, x2, inColor, DebugRenderer::ECastShadow::On);
  953. inRenderer->DrawTriangle(x2, x3, x4, inColor, DebugRenderer::ECastShadow::On);
  954. inRenderer->DrawTriangle(x1, x4, x3, inColor, DebugRenderer::ECastShadow::On);
  955. inRenderer->DrawTriangle(x1, x2, x4, inColor, DebugRenderer::ECastShadow::On);
  956. },
  957. Color::sYellow);
  958. }
  959. void SoftBodyMotionProperties::DrawSkinConstraints(DebugRenderer *inRenderer, RMat44Arg inCenterOfMassTransform, ESoftBodyConstraintColor inConstraintColor) const
  960. {
  961. DrawConstraints(inConstraintColor,
  962. [](const SoftBodySharedSettings::UpdateGroup &inGroup) {
  963. return inGroup.mSkinnedEndIndex;
  964. },
  965. [this, inRenderer, &inCenterOfMassTransform](uint inIndex, ColorArg inColor) {
  966. const Skinned &s = mSettings->mSkinnedConstraints[inIndex];
  967. const SkinState &skin_state = mSkinState[s.mVertex];
  968. inRenderer->DrawArrow(mSkinStateTransform * skin_state.mPosition, mSkinStateTransform * (skin_state.mPosition + 0.1f * skin_state.mNormal), inColor, 0.01f);
  969. inRenderer->DrawLine(mSkinStateTransform * skin_state.mPosition, inCenterOfMassTransform * mVertices[s.mVertex].mPosition, Color::sBlue);
  970. },
  971. Color::sOrange);
  972. }
  973. void SoftBodyMotionProperties::DrawLRAConstraints(DebugRenderer *inRenderer, RMat44Arg inCenterOfMassTransform, ESoftBodyConstraintColor inConstraintColor) const
  974. {
  975. DrawConstraints(inConstraintColor,
  976. [](const SoftBodySharedSettings::UpdateGroup &inGroup) {
  977. return inGroup.mLRAEndIndex;
  978. },
  979. [this, inRenderer, &inCenterOfMassTransform](uint inIndex, ColorArg inColor) {
  980. const LRA &l = mSettings->mLRAConstraints[inIndex];
  981. inRenderer->DrawLine(inCenterOfMassTransform * mVertices[l.mVertex[0]].mPosition, inCenterOfMassTransform * mVertices[l.mVertex[1]].mPosition, inColor);
  982. },
  983. Color::sGrey);
  984. }
  985. void SoftBodyMotionProperties::DrawPredictedBounds(DebugRenderer *inRenderer, RMat44Arg inCenterOfMassTransform) const
  986. {
  987. inRenderer->DrawWireBox(inCenterOfMassTransform, mLocalPredictedBounds, Color::sRed);
  988. }
  989. #endif // JPH_DEBUG_RENDERER
  990. void SoftBodyMotionProperties::SaveState(StateRecorder &inStream) const
  991. {
  992. MotionProperties::SaveState(inStream);
  993. for (const Vertex &v : mVertices)
  994. {
  995. inStream.Write(v.mPreviousPosition);
  996. inStream.Write(v.mPosition);
  997. inStream.Write(v.mVelocity);
  998. }
  999. for (const SkinState &s : mSkinState)
  1000. {
  1001. inStream.Write(s.mPreviousPosition);
  1002. inStream.Write(s.mPosition);
  1003. inStream.Write(s.mNormal);
  1004. }
  1005. inStream.Write(mLocalBounds.mMin);
  1006. inStream.Write(mLocalBounds.mMax);
  1007. inStream.Write(mLocalPredictedBounds.mMin);
  1008. inStream.Write(mLocalPredictedBounds.mMax);
  1009. }
  1010. void SoftBodyMotionProperties::RestoreState(StateRecorder &inStream)
  1011. {
  1012. MotionProperties::RestoreState(inStream);
  1013. for (Vertex &v : mVertices)
  1014. {
  1015. inStream.Read(v.mPreviousPosition);
  1016. inStream.Read(v.mPosition);
  1017. inStream.Read(v.mVelocity);
  1018. }
  1019. for (SkinState &s : mSkinState)
  1020. {
  1021. inStream.Read(s.mPreviousPosition);
  1022. inStream.Read(s.mPosition);
  1023. inStream.Read(s.mNormal);
  1024. }
  1025. inStream.Read(mLocalBounds.mMin);
  1026. inStream.Read(mLocalBounds.mMax);
  1027. inStream.Read(mLocalPredictedBounds.mMin);
  1028. inStream.Read(mLocalPredictedBounds.mMax);
  1029. }
  1030. JPH_NAMESPACE_END