17#ifndef TOYMAKERENGINE_PHYSICSTYPES_H
18#define TOYMAKERENGINE_PHYSICSTYPES_H
25#include <nlohmann/json.hpp>
49 const glm::vec3& correctionPoint,
50 const glm::vec3& correctionGradient
69 const glm::vec3& correctionRotational
91 const glm::vec3& impulsePositional,
92 const glm::vec3& impulsePoint
105 const glm::vec3& impulseRotational
117 const glm::vec3& impulsePositional,
118 const glm::vec3& impulsePoint
129 const glm::vec3& impulseRotational
143 using Traits = uint8_t;
328 return std::numeric_limits<float>::max();
338 assert(isNumber(mass) &&
isPositiveStrict(mass) &&
"Mass must be a valid positive number");
339 if(mass == std::numeric_limits<float>::max()) {
365 &&
"Rotational inertia must be valid positive number for each axis"
368 rotationalInertia.x == std::numeric_limits<float>::max()? 0.f: 1.f / rotationalInertia.x,
369 rotationalInertia.y == std::numeric_limits<float>::max()? 0.f: 1.f / rotationalInertia.y,
370 rotationalInertia.z == std::numeric_limits<float>::max()? 0.f: 1.f / rotationalInertia.z,
381 &&
"Restitution coefficient must be non negative and cannot exceed 1"
400 assert(
false &&
"Unrecognized physics type specified");
416 assert(
false &&
"Unrecognized physics type specified");
496 using ParticipantID = std::size_t;
497 using ParticipantTable = std::unordered_map<
500 std::reference_wrapper<ObjectBounds>,
501 std::reference_wrapper<PhysicsState>
519 const ParticipantTable& states,
531 const ParticipantTable& states,
557 template<u
int8_t LagrangeCount>
565 template<uint8_t... ints>
624 template <
typename TParameter, u
int8_t LagrangeCount>
633 std::unordered_map<BaseConstraint::ParticipantID, TParameter>
mParameters {};
647 void setParameter(BaseConstraint::ParticipantID participant,
const TParameter& parameter);
653 inline TParameter
getParameter(BaseConstraint::ParticipantID participant)
const {
667 const std::unordered_map<BaseConstraint::ParticipantID, TParameter>&
getParameters()
const;
780 const ParticipantTable& states,
789 const ParticipantTable& states,
805 inline void from_json(
806 const nlohmann::json& json,
813 if(json.at(
"mass").is_string() && json.at(
"mass") ==
"infinity") {
814 mass = std::numeric_limits<float>::max();
816 mass = json.at(
"mass");
819 physics.setMass(mass);
820 physics.setMode(json.at(
"mode"));
822 if(json.find(
"collision_response") != json.end()) {
825 physics.setCollisionResponse(response);
829 if(json.find(
"velocity") != json.end()) {
830 physics.mVelocity = glm::vec3 {
831 json.at(
"velocity")[0],
832 json.at(
"velocity")[1],
833 json.at(
"velocity")[2],
835 assert(isNumber(physics.mVelocity) &&
isFinite(physics.mVelocity) &&
"Velocity must be sensible");
838 if(json.find(
"angular_velocity") != json.end()) {
839 physics.mAngularVelocity = glm::vec3 {
840 json.at(
"angular_velocity")[0],
841 json.at(
"angular_velocity")[1],
842 json.at(
"angular_velocity")[2],
844 assert(isNumber(physics.mAngularVelocity) &&
isFinite(physics.mAngularVelocity) &&
"Angular velocity must be sensible");
847 if(json.find(
"force") != json.end()) {
848 physics.mForce = glm::vec3 {
853 assert(isNumber(physics.mForce) &&
isFinite(physics.mForce) &&
"Force must be sensible");
856 if(json.find(
"torque") != json.end()) {
857 physics.mForce = glm::vec3 {
858 json.at(
"torque")[0],
859 json.at(
"torque")[1],
860 json.at(
"torque")[2],
862 assert(isNumber(physics.mTorque) &&
isFinite(physics.mTorque) &&
"Torque must be sensible");
865 if(json.find(
"coefficient_friction_static") != json.end()) {
866 physics.mCoefficientFrictionStatic = json.at(
"coefficient_friction_static");
867 assert(physics.mCoefficientFrictionStatic >= 0.f &&
"Coefficient friction must be non-negative");
870 if(json.find(
"coefficient_friction_dynamic") != json.end()) {
871 physics.mCoefficientFrictionDynamic = json.at(
"coefficient_friction_dynamic");
872 assert(physics.mCoefficientFrictionDynamic >= 0.f &&
"Coefficient friction must be non-negative");
875 if(json.find(
"coefficient_restitution") != json.end()) {
876 physics.setCoefficientRestitution(json.at(
"coefficient_restitution"));
881 nlohmann::json& json,
884 const float mass { physics.getMass() };
885 std::vector<PhysicsState::CollisionResponse> collisionResponse {};
894 mass != std::numeric_limits<float>::max()?
895 nlohmann::json::object({
"mass", mass }):
896 nlohmann::json::object({
"mass",
"infinity" }),
897 {
"mode", physics.getMode() },
898 {
"collision_response", collisionResponse },
899 {
"coefficient_friction_static", physics.mCoefficientFrictionStatic },
900 {
"coefficient_friction_dynamic", physics.mCoefficientFrictionDynamic },
901 {
"coefficient_restitution", physics.mCoefficientRestitution },
905 template <u
int8_t LagrangeCount>
910 template <u
int8_t LagrangeCount>
915 template <u
int8_t LagrangeCount>
921 template <u
int8_t LagrangeCount>
923 resetLagrange(std::make_integer_sequence<uint8_t, LagrangeCount>());
926 template<u
int8_t LagrangeCount>
927 template<uint8_t ...indices>
929 ((mLagrangeMultipliers[indices] = mLagrangeDeltas[indices] = 0.f), ...);
932 template<
typename TParameter, u
int8_t LagrangeCount>
937 template<
typename TParameter, u
int8_t LagrangeCount>
942 template <
typename TParameter, u
int8_t LagrangeCount>
Base class for constraints.
Definition types.hpp:475
virtual void applyConstraintVelocity(const ParticipantTable &states, float substepSeconds)
Applies velocity-based constraint to current set of bounds and physics states.
Definition types.hpp:530
BaseConstraint(float compliance)
Initializes this constraint.
Definition types.hpp:493
virtual void resetLagrange()
Resets all lagrange multipliers, preparing them for a new sequence of constraint solve substeps.
Definition types.hpp:540
float mCompliance
Value greater than equal to zero, inverse of the physical stiffness of this constraint.
Definition types.hpp:486
void setCompliance(float newCompliance)
Sets the compliance value for this constraint.
Definition types.cpp:40
virtual void applyConstraintPosition(const ParticipantTable &states, float substepSeconds)
Applies positional constraint to current set of bounds and physics states.
Definition types.hpp:518
float getCompliance() const
Gets the current compliance value for this constraint.
Definition types.cpp:45
void applyLagrangeDelta(float delta, uint8_t index)
Adds a delta to a lagrange value located at index.
Definition types.hpp:916
const std::array< float, LagrangeCount > & getLagrangeDelta() const
Gets the latest lagrange delta applied to a constraint.
Definition types.hpp:911
const std::array< float, LagrangeCount > & getLagrange() const
Gets the current Lagrange multiplier values for this constraint.
Definition types.hpp:906
Constraint(float compliance)
Initializes this constraint with some initial compliance value.
Definition types.hpp:590
void resetLagrange(std::integer_sequence< uint8_t, ints... > index)
Private implementation for each lagrange multiplier index in need of a reset.
std::array< float, LagrangeCount > mLagrangeDeltas
The last delta applied to the Lagrange multiplier for this constraint.
Definition types.hpp:583
void resetLagrange() override
Sets all lagrange multipliers to 0 in preparation for the next physics update.
Definition types.hpp:922
std::array< float, LagrangeCount > mLagrangeMultipliers
The Lagrange multiplier, computed every substep since the start of the physics simulation till the cu...
Definition types.hpp:577
void setParameter(BaseConstraint::ParticipantID participant, const TParameter ¶meter)
Adds a parameter for this constraint.
Definition types.hpp:933
const std::unordered_map< BaseConstraint::ParticipantID, TParameter > & getParameters() const
Returns all parameters known to this constraint.
Definition types.hpp:943
void removeParameter(BaseConstraint::ParticipantID participant)
Removes a parameter belonging to a particular constraint participant.
Definition types.hpp:938
std::unordered_map< BaseConstraint::ParticipantID, TParameter > mParameters
A set of parameters associated with each entity.
Definition types.hpp:633
TParameter getParameter(BaseConstraint::ParticipantID participant) const
Gets parameter belonging to a particular constraint participant.
Definition types.hpp:653
ParametrizedConstraint(float compliance)
Initializes this constraint with some initial compliance value.
Definition types.hpp:640
CollisionResponse
Defines how the object this component is attached to responds to collisions.
Definition types.hpp:190
float computeGeneralizedInverseMassPositional(const ObjectBounds &object, const PhysicsState &physics, const glm::vec3 &correctionPoint, const glm::vec3 &correctionGradient)
Computes the generalized inverse mass used for positional corrections applied by constraints.
Definition types.cpp:411
glm::mat3 computeInertiaRotationalWorld(const glm::vec3 &rotationalInertiaLocal, const glm::quat &orientation)
Returns an objects rotation tensor in the global frame given its tensor in the local frame according ...
ObjectBounds applyImpulseObject(ObjectBounds object, const PhysicsState &physics, const glm::vec3 &impulsePositional, const glm::vec3 &impulsePoint)
Returns object bounds in state it would be post application of a positional impulse.
Definition types.cpp:444
float computeGeneralizedInverseMassRotational(const ObjectBounds &object, const PhysicsState &physics, const glm::vec3 &correctionRotational)
Computes the generalized inverse mass used by constraints to apply strictly rotational corrections.
Definition types.cpp:431
Mode
Defines how the object this component is attached to responds to physics updates.
Definition types.hpp:152
PhysicsState applyImpulsePhysics(const ObjectBounds &object, PhysicsState physics, const glm::vec3 &impulsePositional, const glm::vec3 &impulsePoint)
Returns new physics state after application of global impulse.
Definition types.cpp:468
@ COLLISION_SIGNAL
Whether this object's collision events should be reported (via signal).
Definition types.hpp:201
@ COLLISION_SEPARATE
Whether this object should be separated from the object it collides with.
Definition types.hpp:195
@ MODE_KINEMATIC
Trait indicating that this object will undergo position and orientation updates according to its tran...
Definition types.hpp:168
@ MODE_STATIC
Trait indicating that this object won't undergo any physics system updates whatsoever.
Definition types.hpp:174
@ MODE_DYNAMIC
Trait indicating that this object responds to external forces, including those set externally,...
Definition types.hpp:158
bool isPositiveStrict(float number)
Tests whether a number is strictly positive.
Definition types.hpp:81
bool isNonNegative(float number)
Tests whether a number is non-negative.
Definition types.hpp:112
bool isFinite(float number)
Tests whether a given number is finite.
Definition types.hpp:57
Namespace containing all class definitions and functions related to the ToyMaker engine.
Definition application.hpp:25
Classes and structs representing data related to the engine's spatial query system (the precursor to ...
glm::vec3 mRelativePointContactB
The contact point of object B relative to its own frame.
Definition types.hpp:720
float mCollisionVelocity
The velocity of A's point of contact relative to B at the time the collision took place.
Definition types.hpp:734
float mPenetrationDepth
The shortest distance an object must move along the contact normal in order to be separated from the ...
Definition types.hpp:741
void updateCollisionData(const Collision &collision, const PhysicsState &physicsA, const ObjectBounds &boundsA, const ObjectBounds &boundsAPrev, const PhysicsState &physicsB, const ObjectBounds &boundsB, const ObjectBounds &boundsBPrev)
Caches collision related information shared across position and velocity corrections.
Definition types.cpp:51
glm::vec3 mRelativePointContactA
The contact point of object A relative to its own frame.
Definition types.hpp:702
glm::vec3 mLastPointContactB
The projected last point of contact of object B participating in this constraint.
Definition types.hpp:708
void applyConstraintPosition(const ParticipantTable &states, float substepSeconds) override
Separates intersecting/colliding objects and applies static friction.
Definition types.cpp:140
void updateCollisionDataPartial(const PhysicsState &physicsA, const ObjectBounds &boundsA, const PhysicsState &physicsB, const ObjectBounds &boundsB)
Performs a partial collision data update based on result from previous physics substep.
Definition types.cpp:106
bool mCollided
Whether or not two objects are currently intersecting (and therefore whether they should be separated...
Definition types.hpp:684
void applyConstraintVelocity(const ParticipantTable &states, float substepSeconds) override
Applies dynamic friction.
Definition types.cpp:290
glm::vec3 mCurrentPointContactB
The contact point of object B participating in this constraint in world space.
Definition types.hpp:714
CollisionConstraint()
Initializes constraint with collision data from two potentially intersecting objects.
Definition types.cpp:49
glm::vec3 mCurrentPointContactA
The contact point of object A participating in this constraint in world space.
Definition types.hpp:696
glm::vec3 mContactNormal
Upon collision, points in the direction object B would need to move in order to be separated from obj...
Definition types.hpp:727
glm::vec3 mLastPointContactA
The projected last point of contact of object A participating in this constraint.
Definition types.hpp:690
Data representing everything about a collision.
Definition types.hpp:897
A component defining the true bounds of a spatially queryable object situated somewhere in the world.
Definition types.hpp:926
Component representing the physics state of the body it's attached to at some particular point in tim...
Definition types.hpp:142
glm::vec3 mAngularVelocity
The angular velocity of this object.
Definition types.hpp:251
Mode getMode() const
Returns the physics type associated with this object.
Definition types.hpp:390
void applyForceGlobal(const glm::vec3 &force, const glm::vec3 &atPosition, const ObjectBounds &bounds)
Applies a force force at position atPosition, updating the torque and central force of an object whos...
Definition types.cpp:16
float mCoefficientFrictionStatic
The friction coefficient of the force that prevents relative motion between the surface of two object...
Definition types.hpp:273
bool separatesOnCollision() const
Whether this object is configured to separate from another object it collides with.
Definition types.hpp:429
static const Traits MaskCollisionResponse
Mask used to retrieve the section of an object's physics traits that indicate its collision response ...
Definition types.hpp:209
Traits mTraits
Defines a set of flags that determines how this object responds to physics updates.
Definition types.hpp:296
void setMass(float mass)
Sets the mass of this object.
Definition types.hpp:337
void setCollisionResponse(CollisionResponse response)
Sets a flag related to this object's collision response behaviour.
Definition types.hpp:450
void unsetCollisionResponse(CollisionResponse response)
Unsets a flag related to this object's collision response behaviour.
Definition types.hpp:458
void setRotationalInertia(const glm::vec3 &rotationalInertia)
Sets the rotational inertia for this object along each axis in the object's local frame.
Definition types.hpp:362
glm::vec3 mTorque
Proportional to sum of all forces acting perpendicular to the vector going from the point at which th...
Definition types.hpp:235
void applyForceLocal(const glm::vec3 &force, const glm::vec3 &atPosition, const ObjectBounds &bounds)
Applies a force force at position atPosition, updating the torque and central force of an object whos...
Definition types.cpp:8
void setCoefficientRestitution(float newCoefficient)
Sets the coefficient of restitution for this object.
Definition types.hpp:378
bool signalsOnCollision() const
Whether this object is configured to report when it makes contact with another object.
Definition types.hpp:442
glm::vec3 mForce
The sum of all the forces acting on this object's center of mass, causing it to move through space.
Definition types.hpp:225
void setMode(Mode mode)
Sets the physics type associated with this object.
Definition types.hpp:408
float mMassInverse
The inverse of this object's mass.
Definition types.hpp:266
glm::vec3 mVelocity
The velocity of this object.
Definition types.hpp:243
float mCoefficientRestitution
The fraction of the net kinetic energy prior to a collision retained by a pair of objects after the c...
Definition types.hpp:289
glm::vec3 getRotationalInertia() const
Gets the rotational inertia for this object along each axis in the object's local frame.
Definition types.hpp:350
float mCoefficientFrictionDynamic
The friction coefficient of the force that hinders motion between the surface of two objects when the...
Definition types.hpp:280
glm::vec3 mRotationalInertiaInverse
The inverse of this object's resistance to rotational change.
Definition types.hpp:260
static std::string getComponentTypeName()
Fetches the component type string associated with this class.
Definition types.hpp:216
float getMass() const
Gets the mass of this object.
Definition types.hpp:326
static const Traits MaskMode
Mask used to retrieve the section of an object's physics traits that indicate its update mode.
Definition types.hpp:182