diff --git a/.classpath b/.classpath
index 9724b2f..b6b4ba5 100644
--- a/.classpath
+++ b/.classpath
@@ -1,6 +1,11 @@
+
+
+
+
+
@@ -71,5 +76,6 @@
+
diff --git a/jege/bin/binTest/test/atriaSoft/etk/math/testTransformation3D.class b/jege/bin/binTest/test/atriaSoft/etk/math/testTransformation3D.class
new file mode 100644
index 0000000..65efadc
Binary files /dev/null and b/jege/bin/binTest/test/atriaSoft/etk/math/testTransformation3D.class differ
diff --git a/res/person.blend1 b/res/person.blend1
new file mode 100644
index 0000000..e5f4438
Binary files /dev/null and b/res/person.blend1 differ
diff --git a/src/org/atriaSoft/ephysics/body/Body.java b/src/org/atriaSoft/ephysics/body/Body.java
new file mode 100644
index 0000000..1173503
--- /dev/null
+++ b/src/org/atriaSoft/ephysics/body/Body.java
@@ -0,0 +1,141 @@
+package org.atriaSoft.ephysics.body;
+
+/**
+ * @brief Represent a body of the physics engine. You should not
+ * instantiante this class but instantiate the CollisionBody or RigidBody
+ * classes instead.
+ */
+class Body {
+ protected long id; //!< ID of the body
+ protected boolean isAlreadyInIsland; //!< True if the body has already been added in an island (for sleeping technique)
+ protected boolean isAllowedToSleep; //!< True if the body is allowed to go to sleep for better efficiency
+ /**
+ * @brief True if the body is active.
+ * An inactive body does not participate in collision detection, is not simulated and will not be hit in a ray casting query.
+ * A body is active by default. If you set this value to "false", all the proxy shapes of this body will be removed from the broad-phase.
+ * If you set this value to "true", all the proxy shapes will be added to the broad-phase.
+ * A joint connected to an inactive body will also be inactive.
+ */
+ protected boolean isActive;
+ protected boolean isSleeping; //!< True if the body is sleeping (for sleeping technique)
+ protected float sleepTime; //!< Elapsed time since the body velocity was bellow the sleep velocity
+ protected Object userData; //!< Pointer that can be used to attach user data to the body
+ /**
+ * @brief Constructor
+ * @param[in] id ID of the new body
+ */
+ public Body(long id) {
+ this.id = id;
+ this.isAlreadyInIsland = false;
+ this.isAllowedToSleep = true;
+ this.isActive = true;
+ this.isSleeping = false;
+ this.sleepTime = 0;
+ this.userData = null;
+ }
+ /**
+ * @brief Return the id of the body
+ * @return The ID of the body
+ */
+ public long getID() {
+ return this.id;
+ }
+ /**
+ * @brief Return whether or not the body is allowed to sleep
+ * @return True if the body is allowed to sleep and false otherwise
+ */
+ public boolean isAllowedToSleep() {
+ return this.isAllowedToSleep;
+ }
+ /**
+ * @brief Set whether or not the body is allowed to go to sleep
+ * @param[in] isAllowedToSleep True if the body is allowed to sleep
+ */
+ public void setIsAllowedToSleep(boolean isAllowedToSleep) {
+ this.isAllowedToSleep = isAllowedToSleep;
+ if (!this.isAllowedToSleep) {
+ setIsSleeping(false);
+ }
+ }
+ /**
+ * @brief Return whether or not the body is sleeping
+ * @return True if the body is currently sleeping and false otherwise
+ */
+ public boolean isSleeping() {
+ return this.isSleeping;
+ }
+ /**
+ * @brief Return true if the body is active
+ * @return True if the body currently active and false otherwise
+ */
+ public boolean isActive() {
+ return this.isActive;
+ }
+ /**
+ * @brief Set whether or not the body is active
+ * @param[in] isActive True if you want to activate the body
+ */
+ public void setIsActive(boolean isActive) {
+ this.isActive = isActive;
+ }
+ /**
+ * @brief Set the variable to know whether or not the body is sleeping
+ * @param[in] isSleeping Set the new status
+ */
+ public void setIsSleeping(boolean isSleeping) {
+ if (isSleeping) {
+ this.sleepTime = 0.0f;
+ } else {
+ if (this.isSleeping) {
+ this.sleepTime = 0.0f;
+ }
+ }
+ this.isSleeping = isSleeping;
+ }
+ /**
+ * @brief Return a pointer to the user data attached to this body
+ * @return A pointer to the user data you have attached to the body
+ */
+ public Object getUserData() {
+ return this.userData;
+ }
+ /**
+ * @brief Attach user data to this body
+ * @param[in] userData A pointer to the user data you want to attach to the body
+ */
+ public void setUserData(Object userData) {
+ this.userData = userData;
+ }
+ /**
+ * @brief Smaller than operator
+ * @param[in] obj Other object to compare
+ * @return true if the current element is smaller
+ */
+ public boolean isLess( Body obj) {
+ return (this.id < obj.this.id);
+ }
+ /**
+ * @brief Larger than operator
+ * @param[in] obj Other object to compare
+ * @return true if the current element is Bigger
+ */
+ public boolean isUpper( Body obj) {
+ return (this.id > obj.this.id);
+ }
+ /**
+ * @brief Equal operator
+ * @param[in] obj Other object to compare
+ * @return true if the curretn element is equal
+ */
+ public boolean isEqual( Body obj) {
+ return (this.id == obj.this.id);
+ }
+ /**
+ * @brief Not equal operator
+ * @param[in] obj Other object to compare
+ * @return true if the curretn element is NOT equal
+ */
+ public boolean isDifferent( Body obj) {
+ return (this.id != obj.this.id);
+ }
+}
diff --git a/src/org/atriaSoft/ephysics/body/CollisionBody.cpp b/src/org/atriaSoft/ephysics/body/CollisionBody.cpp
new file mode 100644
index 0000000..51e158e
--- /dev/null
+++ b/src/org/atriaSoft/ephysics/body/CollisionBody.cpp
@@ -0,0 +1,238 @@
+/** @file
+ * Original ReactPhysics3D C++ library by Daniel Chappuis This code is re-licensed with permission from ReactPhysics3D author.
+ * @author Daniel CHAPPUIS
+ * @author Edouard DUPIN
+ * @copyright 2010-2016, Daniel Chappuis
+ * @copyright 2017, Edouard DUPIN
+ * @license MPL v2.0 (see license file)
+ */
+#include
+#include
+#include
+
+// We want to use the ReactPhysics3D namespace
+using namespace ephysics;
+
+
+CollisionBody::CollisionBody( etk::Transform3D transform, CollisionWorld world, long id):
+ Body(id),
+ this.type(DYNAMIC),
+ this.transform(transform),
+ this.proxyCollisionShapes(null),
+ this.numberCollisionShapes(0),
+ this.contactManifoldsList(null),
+ this.world(world) {
+
+ Log.debug(" set transform: " << transform);
+ if (isnan(transform.getPosition().x()) == true) { // check NAN
+ Log.critical(" set transform: " << transform);
+ }
+ if (isinf(transform.getOrientation().z()) == true) {
+ Log.critical(" set transform: " << transform);
+ }
+}
+
+CollisionBody::~CollisionBody() {
+ assert(this.contactManifoldsList == null);
+
+ // Remove all the proxy collision shapes of the body
+ removeAllCollisionShapes();
+}
+
+inline void CollisionBody::setType(BodyType type) {
+ this.type = type;
+ if (this.type == STATIC) {
+ // Update the broad-phase state of the body
+ updateBroadPhaseState();
+ }
+}
+
+void CollisionBody::setTransform( etk::Transform3D transform) {
+ Log.debug(" set transform: " << this.transform << " ==> " << transform);
+ if (isnan(transform.getPosition().x()) == true) { // check NAN
+ Log.critical(" set transform: " << this.transform << " ==> " << transform);
+ }
+ if (isinf(transform.getOrientation().z()) == true) {
+ Log.critical(" set transform: " << this.transform << " ==> " << transform);
+ }
+ this.transform = transform;
+ updateBroadPhaseState();
+}
+
+ProxyShape* CollisionBody::addCollisionShape(CollisionShape* collisionShape,
+ etk::Transform3D transform) {
+ // Create a proxy collision shape to attach the collision shape to the body
+ ProxyShape* proxyShape = ETKNEW(ProxyShape, this, collisionShape,transform, float(1));
+ // Add it to the list of proxy collision shapes of the body
+ if (this.proxyCollisionShapes == null) {
+ this.proxyCollisionShapes = proxyShape;
+ } else {
+ proxyShape->this.next = this.proxyCollisionShapes;
+ this.proxyCollisionShapes = proxyShape;
+ }
+ AABB aabb;
+ collisionShape->computeAABB(aabb, this.transform * transform);
+ this.world.this.collisionDetection.addProxyCollisionShape(proxyShape, aabb);
+ this.numberCollisionShapes++;
+ return proxyShape;
+}
+
+void CollisionBody::removeCollisionShape( ProxyShape* proxyShape) {
+ ProxyShape* current = this.proxyCollisionShapes;
+ // If the the first proxy shape is the one to remove
+ if (current == proxyShape) {
+ this.proxyCollisionShapes = current->this.next;
+ if (this.isActive) {
+ this.world.this.collisionDetection.removeProxyCollisionShape(current);
+ }
+ ETKDELETE(ProxyShape, current);
+ current = null;
+ this.numberCollisionShapes--;
+ return;
+ }
+ // Look for the proxy shape that contains the collision shape in parameter
+ while(current->this.next != null) {
+ // If we have found the collision shape to remove
+ if (current->this.next == proxyShape) {
+ // Remove the proxy collision shape
+ ProxyShape* elementToRemove = current->this.next;
+ current->this.next = elementToRemove->this.next;
+ if (this.isActive) {
+ this.world.this.collisionDetection.removeProxyCollisionShape(elementToRemove);
+ }
+ ETKDELETE(ProxyShape, elementToRemove);
+ elementToRemove = null;
+ this.numberCollisionShapes--;
+ return;
+ }
+ // Get the next element in the list
+ current = current->this.next;
+ }
+}
+
+
+void CollisionBody::removeAllCollisionShapes() {
+ ProxyShape* current = this.proxyCollisionShapes;
+ // Look for the proxy shape that contains the collision shape in parameter
+ while(current != null) {
+ // Remove the proxy collision shape
+ ProxyShape* nextElement = current->this.next;
+ if (this.isActive) {
+ this.world.this.collisionDetection.removeProxyCollisionShape(current);
+ }
+ ETKDELETE(ProxyShape, current);
+ // Get the next element in the list
+ current = nextElement;
+ }
+ this.proxyCollisionShapes = null;
+}
+
+
+void CollisionBody::resetContactManifoldsList() {
+ // Delete the linked list of contact manifolds of that body
+ ContactManifoldListElement* currentElement = this.contactManifoldsList;
+ while (currentElement != null) {
+ ContactManifoldListElement* nextElement = currentElement->next;
+ // Delete the current element
+ ETKDELETE(ContactManifoldListElement, currentElement);
+ currentElement = nextElement;
+ }
+ this.contactManifoldsList = null;
+}
+
+
+void CollisionBody::updateBroadPhaseState() {
+ // For all the proxy collision shapes of the body
+ for (ProxyShape* shape = this.proxyCollisionShapes; shape != null; shape = shape->this.next) {
+ // Update the proxy
+ updateProxyShapeInBroadPhase(shape);
+ }
+}
+
+
+void CollisionBody::updateProxyShapeInBroadPhase(ProxyShape* proxyShape, boolean forceReinsert) {
+ AABB aabb;
+ proxyShape->getCollisionShape()->computeAABB(aabb, this.transform * proxyShape->getLocalToBodyTransform());
+ this.world.this.collisionDetection.updateProxyCollisionShape(proxyShape, aabb, vec3(0, 0, 0), forceReinsert);
+}
+
+
+void CollisionBody::setIsActive(boolean isActive) {
+ // If the state does not change
+ if (this.isActive == isActive) {
+ return;
+ }
+ Body::setIsActive(isActive);
+ // If we have to activate the body
+ if (isActive == true) {
+ for (ProxyShape* shape = this.proxyCollisionShapes; shape != null; shape = shape->this.next) {
+ AABB aabb;
+ shape->getCollisionShape()->computeAABB(aabb, this.transform * shape->this.localToBodyTransform);
+ this.world.this.collisionDetection.addProxyCollisionShape(shape, aabb);
+ }
+ } else {
+ for (ProxyShape* shape = this.proxyCollisionShapes; shape != null; shape = shape->this.next) {
+ this.world.this.collisionDetection.removeProxyCollisionShape(shape);
+ }
+ resetContactManifoldsList();
+ }
+}
+
+
+void CollisionBody::askForBroadPhaseCollisionCheck() {
+ for (ProxyShape* shape = this.proxyCollisionShapes; shape != null; shape = shape->this.next) {
+ this.world.this.collisionDetection.askForBroadPhaseCollisionCheck(shape);
+ }
+}
+
+
+int CollisionBody::resetIsAlreadyInIslandAndCountManifolds() {
+ this.isAlreadyInIsland = false;
+ int nbManifolds = 0;
+ // Reset the this.isAlreadyInIsland variable of the contact manifolds for this body
+ ContactManifoldListElement* currentElement = this.contactManifoldsList;
+ while (currentElement != null) {
+ currentElement->contactManifold->this.isAlreadyInIsland = false;
+ currentElement = currentElement->next;
+ nbManifolds++;
+ }
+ return nbManifolds;
+}
+
+boolean CollisionBody::testPointInside( vec3 worldPoint) {
+ for (ProxyShape* shape = this.proxyCollisionShapes; shape != null; shape = shape->this.next) {
+ if (shape->testPointInside(worldPoint)) return true;
+ }
+ return false;
+}
+
+boolean CollisionBody::raycast( Ray ray, RaycastInfo raycastInfo) {
+ if (this.isActive == false) {
+ return false;
+ }
+ boolean isHit = false;
+ Ray rayTemp(ray);
+ for (ProxyShape* shape = this.proxyCollisionShapes; shape != null; shape = shape->this.next) {
+ // Test if the ray hits the collision shape
+ if (shape->raycast(rayTemp, raycastInfo)) {
+ rayTemp.maxFraction = raycastInfo.hitFraction;
+ isHit = true;
+ }
+ }
+ return isHit;
+}
+
+AABB CollisionBody::getAABB() {
+ AABB bodyAABB;
+ if (this.proxyCollisionShapes == null) {
+ return bodyAABB;
+ }
+ this.proxyCollisionShapes->getCollisionShape()->computeAABB(bodyAABB, this.transform * this.proxyCollisionShapes->getLocalToBodyTransform());
+ for (ProxyShape* shape = this.proxyCollisionShapes->this.next; shape != null; shape = shape->this.next) {
+ AABB aabb;
+ shape->getCollisionShape()->computeAABB(aabb, this.transform * shape->getLocalToBodyTransform());
+ bodyAABB.mergeWithAABB(aabb);
+ }
+ return bodyAABB;
+}
+
diff --git a/src/org/atriaSoft/ephysics/body/CollisionBody.hpp b/src/org/atriaSoft/ephysics/body/CollisionBody.hpp
new file mode 100644
index 0000000..8da0d5b
--- /dev/null
+++ b/src/org/atriaSoft/ephysics/body/CollisionBody.hpp
@@ -0,0 +1,209 @@
+/** @file
+ * Original ReactPhysics3D C++ library by Daniel Chappuis This code is re-licensed with permission from ReactPhysics3D author.
+ * @author Daniel CHAPPUIS
+ * @author Edouard DUPIN
+ * @copyright 2010-2016, Daniel Chappuis
+ * @copyright 2017, Edouard DUPIN
+ * @license MPL v2.0 (see license file)
+ */
+#pragma once
+#include
+#include
+#include
+#include
+#include
+#include
+
+namespace ephysics {
+ struct ContactManifoldListElement;
+ class ProxyShape;
+ class CollisionWorld;
+ /**
+ * @brief Define the type of the body
+ */
+ enum BodyType {
+ STATIC, //!< A static body has infinite mass, zero velocity but the position can be changed manually. A static body does not collide with other static or kinematic bodies.
+ KINEMATIC, //!< A kinematic body has infinite mass, the velocity can be changed manually and its position is computed by the physics engine. A kinematic body does not collide with other static or kinematic bodies.
+ DYNAMIC //!< A dynamic body has non-zero mass, non-zero velocity determined by forces and its position is determined by the physics engine. A dynamic body can collide with other dynamic, static or kinematic bodies.
+ };
+ /**
+ * @brief This class represents a body that is able to collide with others bodies. This class inherits from the Body class.
+ */
+ class CollisionBody : public Body {
+ protected :
+ BodyType this.type; //!< Type of body (static, kinematic or dynamic)
+ etk::Transform3D this.transform; //!< Position and orientation of the body
+ ProxyShape* this.proxyCollisionShapes; //!< First element of the linked list of proxy collision shapes of this body
+ int this.numberCollisionShapes; //!< Number of collision shapes
+ ContactManifoldListElement* this.contactManifoldsList; //!< First element of the linked list of contact manifolds involving this body
+ CollisionWorld this.world; //!< Reference to the world the body belongs to
+ /// Private copy-ructor
+ CollisionBody( CollisionBody body) = delete;
+ /// Private assignment operator
+ CollisionBody operator=( CollisionBody body) = delete;
+ /**
+ * @brief Reset the contact manifold lists
+ */
+ void resetContactManifoldsList();
+ /**
+ * @brief Remove all the collision shapes
+ */
+ void removeAllCollisionShapes();
+ /**
+ * @brief Update the broad-phase state for this body (because it has moved for instance)
+ */
+ virtual void updateBroadPhaseState() ;
+ /**
+ * @brief Update the broad-phase state of a proxy collision shape of the body
+ */
+ void updateProxyShapeInBroadPhase(ProxyShape* proxyShape, boolean forceReinsert = false) ;
+ /**
+ * @brief Ask the broad-phase to test again the collision shapes of the body for collision (as if the body has moved).
+ */
+ void askForBroadPhaseCollisionCheck() ;
+ /**
+ * @brief Reset the this.isAlreadyInIsland variable of the body and contact manifolds.
+ * This method also returns the number of contact manifolds of the body.
+ */
+ int resetIsAlreadyInIslandAndCountManifolds();
+ public :
+ /**
+ * @brief Constructor
+ * @param[in] transform The transform of the body
+ * @param[in] world The physics world where the body is created
+ * @param[in] id ID of the body
+ */
+ CollisionBody( etk::Transform3D transform, CollisionWorld world, long id);
+ /**
+ * @brief Destructor
+ */
+ virtual ~CollisionBody();
+ /**
+ * @brief Return the type of the body
+ * @return the type of the body (STATIC, KINEMATIC, DYNAMIC)
+ */
+ BodyType getType() {
+ return this.type;
+ }
+ /**
+ * @brief Set the type of the body
+ * @param[in] type The type of the body (STATIC, KINEMATIC, DYNAMIC)
+ */
+ virtual void setType(BodyType type);
+ /**
+ * @brief Set whether or not the body is active
+ * @param[in] isActive True if you want to activate the body
+ */
+ virtual void setIsActive(boolean isActive);
+ /**
+ * @brief Return the current position and orientation
+ * @return The current transformation of the body that transforms the local-space of the body into world-space
+ */
+ etk::Transform3D getTransform() {
+ return this.transform;
+ }
+ /**
+ * @brief Set the current position and orientation
+ * @param transform The transformation of the body that transforms the local-space of the body into world-space
+ */
+ virtual void setTransform( etk::Transform3D transform);
+ /**
+ * @brief Add a collision shape to the body. Note that you can share a collision shape between several bodies using the same collision shape instance to
+ * when you add the shape to the different bodies. Do not forget to delete the collision shape you have created at the end of your program.
+ *
+ * This method will return a pointer to a new proxy shape. A proxy shape is an object that links a collision shape and a given body. You can use the
+ * returned proxy shape to get and set information about the corresponding collision shape for that body.
+ * @param[in] collisionShape A pointer to the collision shape you want to add to the body
+ * @param[in] transform The transformation of the collision shape that transforms the local-space of the collision shape into the local-space of the body
+ * @return A pointer to the proxy shape that has been created to link the body to the new collision shape you have added.
+ */
+ ProxyShape* addCollisionShape(CollisionShape* collisionShape, etk::Transform3D transform);
+ /**
+ * @brief Remove a collision shape from the body
+ * To remove a collision shape, you need to specify the pointer to the proxy shape that has been returned when you have added the collision shape to the body
+ * @param[in] proxyShape The pointer of the proxy shape you want to remove
+ */
+ virtual void removeCollisionShape( ProxyShape* proxyShape);
+ /**
+ * @brief Get the first element of the linked list of contact manifolds involving this body
+ * @return A pointer to the first element of the linked-list with the contact manifolds of this body
+ */
+ ContactManifoldListElement* getContactManifoldsList() {
+ return this.contactManifoldsList;
+ }
+ /**
+ * @brief Return true if a point is inside the collision body
+ * This method returns true if a point is inside any collision shape of the body
+ * @param[in] worldPoint The point to test (in world-space coordinates)
+ * @return True if the point is inside the body
+ */
+ boolean testPointInside( vec3 worldPoint) ;
+ /**
+ * @brief Raycast method with feedback information
+ * The method returns the closest hit among all the collision shapes of the body
+ * @param[in] ray The ray used to raycast agains the body
+ * @param[out] raycastInfo Structure that contains the result of the raycasting (valid only if the method returned true)
+ * @return True if the ray hit the body and false otherwise
+ */
+ boolean raycast( Ray ray, RaycastInfo raycastInfo);
+ /**
+ * @brief Compute and return the AABB of the body by merging all proxy shapes AABBs
+ * @return The axis-aligned bounding box (AABB) of the body in world-space coordinates
+ */
+ AABB getAABB() ;
+ /**
+ * @brief Get the linked list of proxy shapes of that body
+ * @return The pointer of the first proxy shape of the linked-list of all the
+ * proxy shapes of the body
+ */
+ ProxyShape* getProxyShapesList() {
+ return this.proxyCollisionShapes;
+ }
+ /**
+ * @brief Get the linked list of proxy shapes of that body
+ * @return The pointer of the first proxy shape of the linked-list of all the proxy shapes of the body
+ */
+ ProxyShape* getProxyShapesList() {
+ return this.proxyCollisionShapes;
+ }
+ /**
+ * @brief Get the world-space coordinates of a point given the local-space coordinates of the body
+ * @param[in] localPoint A point in the local-space coordinates of the body
+ * @return The point in world-space coordinates
+ */
+ vec3 getWorldPoint( vec3 localPoint) {
+ return this.transform * localPoint;
+ }
+ /**
+ * @brief Get the world-space vector of a vector given in local-space coordinates of the body
+ * @param[in] localVector A vector in the local-space coordinates of the body
+ * @return The vector in world-space coordinates
+ */
+ vec3 getWorldVector( vec3 localVector) {
+ return this.transform.getOrientation() * localVector;
+ }
+ /**
+ * @brief Get the body local-space coordinates of a point given in the world-space coordinates
+ * @param[in] worldPoint A point in world-space coordinates
+ * @return The point in the local-space coordinates of the body
+ */
+ vec3 getLocalPoint( vec3 worldPoint) {
+ return this.transform.getInverse() * worldPoint;
+ }
+ /**
+ * @brief Get the body local-space coordinates of a vector given in the world-space coordinates
+ * @param[in] worldVector A vector in world-space coordinates
+ * @return The vector in the local-space coordinates of the body
+ */
+ vec3 getLocalVector( vec3 worldVector) {
+ return this.transform.getOrientation().getInverse() * worldVector;
+ }
+ friend class CollisionWorld;
+ friend class DynamicsWorld;
+ friend class CollisionDetection;
+ friend class BroadPhaseAlgorithm;
+ friend class ConvexMeshShape;
+ friend class ProxyShape;
+ };
+}
+
diff --git a/src/org/atriaSoft/ephysics/body/RigidBody.cpp b/src/org/atriaSoft/ephysics/body/RigidBody.cpp
new file mode 100644
index 0000000..0a366d6
--- /dev/null
+++ b/src/org/atriaSoft/ephysics/body/RigidBody.cpp
@@ -0,0 +1,316 @@
+/** @file
+ * Original ReactPhysics3D C++ library by Daniel Chappuis This code is re-licensed with permission from ReactPhysics3D author.
+ * @author Daniel CHAPPUIS
+ * @author Edouard DUPIN
+ * @copyright 2010-2016, Daniel Chappuis
+ * @copyright 2017, Edouard DUPIN
+ * @license MPL v2.0 (see license file)
+ */
+#include
+#include
+#include
+#include
+#include
+
+using namespace ephysics;
+
+
+RigidBody::RigidBody( etk::Transform3D transform, CollisionWorld world, long id):
+ CollisionBody(transform, world, id),
+ this.initMass(1.0f),
+ this.centerOfMassLocal(0, 0, 0),
+ this.centerOfMassWorld(transform.getPosition()),
+ this.isGravityEnabled(true),
+ this.linearDamping(0.0f),
+ this.angularDamping(float(0.0)),
+ this.jointsList(null) {
+ // Compute the inverse mass
+ this.massInverse = 1.0f / this.initMass;
+}
+
+RigidBody::~RigidBody() {
+ assert(this.jointsList == null);
+}
+
+
+void RigidBody::setType(BodyType type) {
+ if (this.type == type) {
+ return;
+ }
+ CollisionBody::setType(type);
+ recomputeMassInformation();
+ if (this.type == STATIC) {
+ // Reset the velocity to zero
+ this.linearVelocity.setZero();
+ this.angularVelocity.setZero();
+ }
+ if ( this.type == STATIC
+ || this.type == KINEMATIC) {
+ // Reset the inverse mass and inverse inertia tensor to zero
+ this.massInverse = 0.0f;
+ this.inertiaTensorLocal.setZero();
+ this.inertiaTensorLocalInverse.setZero();
+ } else {
+ this.massInverse = 1.0f / this.initMass;
+ this.inertiaTensorLocalInverse = this.inertiaTensorLocal.getInverse();
+ }
+ setIsSleeping(false);
+ resetContactManifoldsList();
+ // Ask the broad-phase to test again the collision shapes of the body for collision detection (as if the body has moved)
+ askForBroadPhaseCollisionCheck();
+ this.externalForce.setZero();
+ this.externalTorque.setZero();
+}
+
+
+void RigidBody::setInertiaTensorLocal( etk::Matrix3x3 inertiaTensorLocal) {
+ if (this.type != DYNAMIC) {
+ return;
+ }
+ this.inertiaTensorLocal = inertiaTensorLocal;
+ this.inertiaTensorLocalInverse = this.inertiaTensorLocal.getInverse();
+}
+
+
+void RigidBody::setCenterOfMassLocal( vec3 centerOfMassLocal) {
+ if (this.type != DYNAMIC) {
+ return;
+ }
+ vec3 oldCenterOfMass = this.centerOfMassWorld;
+ this.centerOfMassLocal = centerOfMassLocal;
+ this.centerOfMassWorld = this.transform * this.centerOfMassLocal;
+ this.linearVelocity += this.angularVelocity.cross(this.centerOfMassWorld - oldCenterOfMass);
+}
+
+
+void RigidBody::setMass(float mass) {
+ if (this.type != DYNAMIC) {
+ return;
+ }
+ this.initMass = mass;
+ if (this.initMass > 0.0f) {
+ this.massInverse = 1.0f / this.initMass;
+ } else {
+ this.initMass = 1.0f;
+ this.massInverse = 1.0f;
+ }
+}
+
+void RigidBody::removeJointFrothis.jointsList( Joint* joint) {
+ assert(joint != null);
+ assert(this.jointsList != null);
+ // Remove the joint from the linked list of the joints of the first body
+ if (this.jointsList->joint == joint) { // If the first element is the one to remove
+ JointListElement* elementToRemove = this.jointsList;
+ this.jointsList = elementToRemove->next;
+ ETKDELETE(JointListElement, elementToRemove);
+ elementToRemove = null;
+ }
+ else { // If the element to remove is not the first one in the list
+ JointListElement* currentElement = this.jointsList;
+ while (currentElement->next != null) {
+ if (currentElement->next->joint == joint) {
+ JointListElement* elementToRemove = currentElement->next;
+ currentElement->next = elementToRemove->next;
+ ETKDELETE(JointListElement, elementToRemove);
+ elementToRemove = null;
+ break;
+ }
+ currentElement = currentElement->next;
+ }
+ }
+}
+
+
+ProxyShape* RigidBody::addCollisionShape(CollisionShape* collisionShape,
+ etk::Transform3D transform,
+ float mass) {
+ assert(mass > 0.0f);
+ // Create a new proxy collision shape to attach the collision shape to the body
+ ProxyShape* proxyShape = ETKNEW(ProxyShape, this, collisionShape, transform, mass);
+ // Add it to the list of proxy collision shapes of the body
+ if (this.proxyCollisionShapes == null) {
+ this.proxyCollisionShapes = proxyShape;
+ } else {
+ proxyShape->this.next = this.proxyCollisionShapes;
+ this.proxyCollisionShapes = proxyShape;
+ }
+ // Compute the world-space AABB of the new collision shape
+ AABB aabb;
+ collisionShape->computeAABB(aabb, this.transform * transform);
+ // Notify the collision detection about this new collision shape
+ this.world.this.collisionDetection.addProxyCollisionShape(proxyShape, aabb);
+ this.numberCollisionShapes++;
+ recomputeMassInformation();
+ return proxyShape;
+}
+
+void RigidBody::removeCollisionShape( ProxyShape* proxyShape) {
+ CollisionBody::removeCollisionShape(proxyShape);
+ recomputeMassInformation();
+}
+
+
+void RigidBody::setLinearVelocity( vec3 linearVelocity) {
+ if (this.type == STATIC) {
+ return;
+ }
+ this.linearVelocity = linearVelocity;
+ if (this.linearVelocity.length2() > 0.0f) {
+ setIsSleeping(false);
+ }
+}
+
+
+void RigidBody::setAngularVelocity( vec3 angularVelocity) {
+ if (this.type == STATIC) {
+ return;
+ }
+ this.angularVelocity = angularVelocity;
+ if (this.angularVelocity.length2() > 0.0f) {
+ setIsSleeping(false);
+ }
+}
+
+void RigidBody::setIsSleeping(boolean isSleeping) {
+ if (isSleeping) {
+ this.linearVelocity.setZero();
+ this.angularVelocity.setZero();
+ this.externalForce.setZero();
+ this.externalTorque.setZero();
+ }
+ Body::setIsSleeping(isSleeping);
+}
+
+void RigidBody::updateTransformWithCenterOfMass() {
+ // Translate the body according to the translation of the center of mass position
+ this.transform.setPosition(this.centerOfMassWorld - this.transform.getOrientation() * this.centerOfMassLocal);
+ if (isnan(this.transform.getPosition().x()) == true) {
+ Log.critical("updateTransformWithCenterOfMass: " << this.transform);
+ }
+ if (isinf(this.transform.getOrientation().z()) == true) {
+ Log.critical(" set transform: " << this.transform);
+ }
+}
+
+void RigidBody::setTransform( etk::Transform3D transform) {
+ Log.debug(" set transform: " << this.transform << " ==> " << transform);
+ if (isnan(transform.getPosition().x()) == true) {
+ Log.critical(" set transform: " << this.transform << " ==> " << transform);
+ }
+ if (isinf(transform.getOrientation().z()) == true) {
+ Log.critical(" set transform: " << this.transform << " ==> " << transform);
+ }
+ this.transform = transform;
+ vec3 oldCenterOfMass = this.centerOfMassWorld;
+ // Compute the new center of mass in world-space coordinates
+ this.centerOfMassWorld = this.transform * this.centerOfMassLocal;
+ // Update the linear velocity of the center of mass
+ this.linearVelocity += this.angularVelocity.cross(this.centerOfMassWorld - oldCenterOfMass);
+ updateBroadPhaseState();
+}
+
+void RigidBody::recomputeMassInformation() {
+ this.initMass = 0.0f;
+ this.massInverse = 0.0f;
+ this.inertiaTensorLocal.setZero();
+ this.inertiaTensorLocalInverse.setZero();
+ this.centerOfMassLocal.setZero();
+ // If it is STATIC or KINEMATIC body
+ if (this.type == STATIC || this.type == KINEMATIC) {
+ this.centerOfMassWorld = this.transform.getPosition();
+ return;
+ }
+ assert(this.type == DYNAMIC);
+ // Compute the total mass of the body
+ for (ProxyShape* shape = this.proxyCollisionShapes; shape != NULL; shape = shape->this.next) {
+ this.initMass += shape->getMass();
+ this.centerOfMassLocal += shape->getLocalToBodyTransform().getPosition() * shape->getMass();
+ }
+ if (this.initMass > 0.0f) {
+ this.massInverse = 1.0f / this.initMass;
+ } else {
+ this.initMass = 1.0f;
+ this.massInverse = 1.0f;
+ }
+ // Compute the center of mass
+ vec3 oldCenterOfMass = this.centerOfMassWorld;
+ this.centerOfMassLocal *= this.massInverse;
+ this.centerOfMassWorld = this.transform * this.centerOfMassLocal;
+ // Compute the total mass and inertia tensor using all the collision shapes
+ for (ProxyShape* shape = this.proxyCollisionShapes; shape != null; shape = shape->this.next) {
+ // Get the inertia tensor of the collision shape in its local-space
+ etk::Matrix3x3 inertiaTensor;
+ shape->getCollisionShape()->computeLocalInertiaTensor(inertiaTensor, shape->getMass());
+ // Convert the collision shape inertia tensor into the local-space of the body
+ etk::Transform3D shapeTransform = shape->getLocalToBodyTransform();
+ etk::Matrix3x3 rotationMatrix = shapeTransform.getOrientation().getMatrix();
+ inertiaTensor = rotationMatrix * inertiaTensor * rotationMatrix.getTranspose();
+ // Use the parallel axis theorem to convert the inertia tensor w.r.t the collision shape
+ // center into a inertia tensor w.r.t to the body origin.
+ vec3 offset = shapeTransform.getPosition() - this.centerOfMassLocal;
+ float offsetSquare = offset.length2();
+ vec3 off1 = offset * (-offset.x());
+ vec3 off2 = offset * (-offset.y());
+ vec3 off3 = offset * (-offset.z());
+ etk::Matrix3x3 offsetMatrix(off1.x()+offsetSquare, off1.y(), off1.z(),
+ off2.x(), off2.y()+offsetSquare, off2.z(),
+ off3.x(), off3.y(), off3.z()+offsetSquare);
+ offsetMatrix *= shape->getMass();
+ this.inertiaTensorLocal += inertiaTensor + offsetMatrix;
+ }
+ // Compute the local inverse inertia tensor
+ this.inertiaTensorLocalInverse = this.inertiaTensorLocal.getInverse();
+ // Update the linear velocity of the center of mass
+ this.linearVelocity += this.angularVelocity.cross(this.centerOfMassWorld - oldCenterOfMass);
+}
+
+
+void RigidBody::updateBroadPhaseState() {
+ PROFILE("RigidBody::updateBroadPhaseState()");
+ DynamicsWorld world = staticcast(this.world);
+ vec3 displacement = world.this.timeStep * this.linearVelocity;
+ // For all the proxy collision shapes of the body
+ for (ProxyShape* shape = this.proxyCollisionShapes; shape != null; shape = shape->this.next) {
+ // Recompute the world-space AABB of the collision shape
+ AABB aabb;
+ Log.verbose(" : " << aabb.getMin() << " " << aabb.getMax());
+ Log.verbose(" this.transform: " << this.transform);
+ shape->getCollisionShape()->computeAABB(aabb, this.transform *shape->getLocalToBodyTransform());
+ Log.verbose(" : " << aabb.getMin() << " " << aabb.getMax());
+ // Update the broad-phase state for the proxy collision shape
+ this.world.this.collisionDetection.updateProxyCollisionShape(shape, aabb, displacement);
+ }
+}
+
+
+void RigidBody::applyForceToCenterOfMass( vec3 force) {
+ if (this.type != DYNAMIC) {
+ return;
+ }
+ if (this.isSleeping) {
+ setIsSleeping(false);
+ }
+ this.externalForce += force;
+}
+
+void RigidBody::applyForce( vec3 force, vec3 point) {
+ if (this.type != DYNAMIC) {
+ return;
+ }
+ if (this.isSleeping) {
+ setIsSleeping(false);
+ }
+ this.externalForce += force;
+ this.externalTorque += (point - this.centerOfMassWorld).cross(force);
+}
+
+void RigidBody::applyTorque( vec3 torque) {
+ if (this.type != DYNAMIC) {
+ return;
+ }
+ if (this.isSleeping) {
+ setIsSleeping(false);
+ }
+ this.externalTorque += torque;
+}
\ No newline at end of file
diff --git a/src/org/atriaSoft/ephysics/body/RigidBody.hpp b/src/org/atriaSoft/ephysics/body/RigidBody.hpp
new file mode 100644
index 0000000..4a7c85d
--- /dev/null
+++ b/src/org/atriaSoft/ephysics/body/RigidBody.hpp
@@ -0,0 +1,294 @@
+/** @file
+ * Original ReactPhysics3D C++ library by Daniel Chappuis This code is re-licensed with permission from ReactPhysics3D author.
+ * @author Daniel CHAPPUIS
+ * @author Edouard DUPIN
+ * @copyright 2010-2016, Daniel Chappuis
+ * @copyright 2017, Edouard DUPIN
+ * @license MPL v2.0 (see license file)
+ */
+#pragma once
+
+#include
+#include
+#include
+
+namespace ephysics {
+
+ // Class declarations
+ struct JointListElement;
+ class Joint;
+ class DynamicsWorld;
+
+ /**
+ * @brief This class represents a rigid body of the physics
+ * engine. A rigid body is a non-deformable body that
+ * has a ant mass. This class inherits from the
+ * CollisionBody class.
+ */
+ class RigidBody : public CollisionBody {
+ protected :
+ float this.initMass; //!< Intial mass of the body
+ vec3 this.centerOfMassLocal; //!< Center of mass of the body in local-space coordinates. The center of mass can therefore be different from the body origin
+ vec3 this.centerOfMassWorld; //!< Center of mass of the body in world-space coordinates
+ vec3 this.linearVelocity; //!< Linear velocity of the body
+ vec3 this.angularVelocity; //!< Angular velocity of the body
+ vec3 this.externalForce; //!< Current external force on the body
+ vec3 this.externalTorque; //!< Current external torque on the body
+ etk::Matrix3x3 this.inertiaTensorLocal; //!< Local inertia tensor of the body (in local-space) with respect to the center of mass of the body
+ etk::Matrix3x3 this.inertiaTensorLocalInverse; //!< Inverse of the inertia tensor of the body
+ float this.massInverse; //!< Inverse of the mass of the body
+ boolean this.isGravityEnabled; //!< True if the gravity needs to be applied to this rigid body
+ Material this.material; //!< Material properties of the rigid body
+ float this.linearDamping; //!< Linear velocity damping factor
+ float this.angularDamping; //!< Angular velocity damping factor
+ JointListElement* this.jointsList; //!< First element of the linked list of joints involving this body
+ /// Private copy-ructor
+ RigidBody( RigidBody body);
+ /// Private assignment operator
+ RigidBody operator=( RigidBody body);
+ /**
+ * @brief Remove a joint from the joints list
+ */
+ void removeJointFrothis.jointsList( Joint* joint);
+ /**
+ * @brief Update the transform of the body after a change of the center of mass
+ */
+ void updateTransformWithCenterOfMass();
+ void updateBroadPhaseState() override;
+ public :
+ /**
+ * @brief Constructor
+ * @param transform The transformation of the body
+ * @param world The world where the body has been added
+ * @param id The ID of the body
+ */
+ RigidBody( etk::Transform3D transform, CollisionWorld world, long id);
+ /**
+ * @brief Virtual Destructor
+ */
+ virtual ~RigidBody();
+ void setType(BodyType type) override;
+ /**
+ * @brief Set the current position and orientation
+ * @param[in] transform The transformation of the body that transforms the local-space of the body into world-space
+ */
+ void setTransform( etk::Transform3D transform) override;
+ /**
+ * @brief Get the mass of the body
+ * @return The mass (in kilograms) of the body
+ */
+ float getMass() {
+ return this.initMass;
+ }
+ /**
+ * @brief Get the linear velocity
+ * @return The linear velocity vector of the body
+ */
+ vec3 getLinearVelocity() {
+ return this.linearVelocity;
+ }
+ /**
+ * @brief Set the linear velocity of the rigid body.
+ * @param[in] linearVelocity Linear velocity vector of the body
+ */
+ void setLinearVelocity( vec3 linearVelocity);
+ /**
+ * @brief Get the angular velocity of the body
+ * @return The angular velocity vector of the body
+ */
+ vec3 getAngularVelocity() {
+ return this.angularVelocity;
+ }
+ /**
+ * @brief Set the angular velocity.
+ * @param[in] angularVelocity The angular velocity vector of the body
+ */
+ void setAngularVelocity( vec3 angularVelocity);
+ /**
+ * @brief Set the variable to know whether or not the body is sleeping
+ * @param[in] isSleeping New sleeping state of the body
+ */
+ virtual void setIsSleeping(boolean isSleeping);
+ /**
+ * @brief Get the local inertia tensor of the body (in local-space coordinates)
+ * @return The 3x3 inertia tensor matrix of the body
+ */
+ etk::Matrix3x3 getInertiaTensorLocal() {
+ return this.inertiaTensorLocal;
+ }
+ /**
+ * @brief Set the local inertia tensor of the body (in local-space coordinates)
+ * @param[in] inertiaTensorLocal The 3x3 inertia tensor matrix of the body in local-space coordinates
+ */
+ void setInertiaTensorLocal( etk::Matrix3x3 inertiaTensorLocal);
+ /**
+ * @brief Set the local center of mass of the body (in local-space coordinates)
+ * @param[in] centerOfMassLocal The center of mass of the body in local-space coordinates
+ */
+ void setCenterOfMassLocal( vec3 centerOfMassLocal);
+ /**
+ * @brief Set the mass of the rigid body
+ * @param[in] mass The mass (in kilograms) of the body
+ */
+ void setMass(float mass);
+ /**
+ * @brief Get the inertia tensor in world coordinates.
+ * The inertia tensor Iw in world coordinates is computed
+ * with the local inertia tensor Ib in body coordinates
+ * by Iw = R * Ib * R^T
+ * where R is the rotation matrix (and R^T its transpose) of
+ * the current orientation quaternion of the body
+ * @return The 3x3 inertia tensor matrix of the body in world-space coordinates
+ */
+ etk::Matrix3x3 getInertiaTensorWorld() {
+ // Compute and return the inertia tensor in world coordinates
+ return this.transform.getOrientation().getMatrix() * this.inertiaTensorLocal *
+ this.transform.getOrientation().getMatrix().getTranspose();
+ }
+ /**
+ * @brief Get the inverse of the inertia tensor in world coordinates.
+ * The inertia tensor Iw in world coordinates is computed with the
+ * local inverse inertia tensor Ib^-1 in body coordinates
+ * by Iw = R * Ib^-1 * R^T
+ * where R is the rotation matrix (and R^T its transpose) of the
+ * current orientation quaternion of the body
+ * @return The 3x3 inverse inertia tensor matrix of the body in world-space coordinates
+ */
+ etk::Matrix3x3 getInertiaTensorInverseWorld() {
+ // TODO : DO NOT RECOMPUTE THE MATRIX MULTIPLICATION EVERY TIME. WE NEED TO STORE THE
+ // INVERSE WORLD TENSOR IN THE CLASS AND UPLDATE IT WHEN THE ORIENTATION OF THE BODY CHANGES
+ // Compute and return the inertia tensor in world coordinates
+ return this.transform.getOrientation().getMatrix() * this.inertiaTensorLocalInverse *
+ this.transform.getOrientation().getMatrix().getTranspose();
+ }
+ /**
+ * @brief get the need of gravity appling to this rigid body
+ * @return True if the gravity is applied to the body
+ */
+ boolean isGravityEnabled() {
+ return this.isGravityEnabled;
+ }
+ /**
+ * @brief Set the variable to know if the gravity is applied to this rigid body
+ * @param[in] isEnabled True if you want the gravity to be applied to this body
+ */
+ void enableGravity(boolean isEnabled) {
+ this.isGravityEnabled = isEnabled;
+ }
+ /**
+ * @brief get a reference to the material properties of the rigid body
+ * @return A reference to the material of the body
+ */
+ Material getMaterial() {
+ return this.material;
+ }
+ /**
+ * @brief Set a new material for this rigid body
+ * @param[in] material The material you want to set to the body
+ */
+ void setMaterial( Material material) {
+ this.material = material;
+ }
+ /**
+ * @brief Get the linear velocity damping factor
+ * @return The linear damping factor of this body
+ */
+ float getLinearDamping() {
+ return this.linearDamping;
+ }
+ /**
+ * @brief Set the linear damping factor. This is the ratio of the linear velocity that the body will lose every at seconds of simulation.
+ * @param[in] linearDamping The linear damping factor of this body
+ */
+ void setLinearDamping(float linearDamping) {
+ assert(linearDamping >= 0.0f);
+ this.linearDamping = linearDamping;
+ }
+ /**
+ * @brief Get the angular velocity damping factor
+ * @return The angular damping factor of this body
+ */
+ float getAngularDamping() {
+ return this.angularDamping;
+ }
+ /**
+ * @brief Set the angular damping factor. This is the ratio of the angular velocity that the body will lose at every seconds of simulation.
+ * @param[in] angularDamping The angular damping factor of this body
+ */
+ void setAngularDamping(float angularDamping) {
+ assert(angularDamping >= 0.0f);
+ this.angularDamping = angularDamping;
+ }
+ /**
+ * @brief Get the first element of the linked list of joints involving this body
+ * @return The first element of the linked-list of all the joints involving this body
+ */
+ JointListElement* getJointsList() {
+ return this.jointsList;
+ }
+ /**
+ * @brief Get the first element of the linked list of joints involving this body
+ * @return The first element of the linked-list of all the joints involving this body
+ */
+ JointListElement* getJointsList() {
+ return this.jointsList;
+ }
+ /**
+ * @brief Apply an external force to the body at its center of mass.
+ * If the body is sleeping, calling this method will wake it up. Note that the
+ * force will we added to the sum of the applied forces and that this sum will be
+ * reset to zero at the end of each call of the DynamicsWorld::update() method.
+ * You can only apply a force to a dynamic body otherwise, this method will do nothing.
+ * @param[in] force The external force to apply on the center of mass of the body
+ */
+ void applyForceToCenterOfMass( vec3 force);
+ /**
+ * @brief Apply an external force to the body at a given point (in world-space coordinates).
+ * If the point is not at the center of mass of the body, it will also
+ * generate some torque and therefore, change the angular velocity of the body.
+ * If the body is sleeping, calling this method will wake it up. Note that the
+ * force will we added to the sum of the applied forces and that this sum will be
+ * reset to zero at the end of each call of the DynamicsWorld::update() method.
+ * You can only apply a force to a dynamic body otherwise, this method will do nothing.
+ * @param[in] force The force to apply on the body
+ * @param[in] point The point where the force is applied (in world-space coordinates)
+ */
+ void applyForce( vec3 force, vec3 point);
+ /**
+ * @brief Apply an external torque to the body.
+ * If the body is sleeping, calling this method will wake it up. Note that the
+ * force will we added to the sum of the applied torques and that this sum will be
+ * reset to zero at the end of each call of the DynamicsWorld::update() method.
+ * You can only apply a force to a dynamic body otherwise, this method will do nothing.
+ * @param[in] torque The external torque to apply on the body
+ */
+ void applyTorque( vec3 torque);
+ /**
+ * @brief Add a collision shape to the body.
+ * When you add a collision shape to the body, an intternal copy of this collision shape will be created internally.
+ * Therefore, you can delete it right after calling this method or use it later to add it to another body.
+ * This method will return a pointer to a new proxy shape. A proxy shape is an object that links a collision shape and a given body.
+ * You can use the returned proxy shape to get and set information about the corresponding collision shape for that body.
+ * @param[in] collisionShape The collision shape you want to add to the body
+ * @param[in] transform The transformation of the collision shape that transforms the local-space of the collision shape into the local-space of the body
+ * @param[in] mass Mass (in kilograms) of the collision shape you want to add
+ * @return A pointer to the proxy shape that has been created to link the body to the new collision shape you have added.
+ */
+ ProxyShape* addCollisionShape(CollisionShape* collisionShape,
+ etk::Transform3D transform,
+ float mass);
+ virtual void removeCollisionShape( ProxyShape* proxyShape) override;
+ /**
+ * @brief Recompute the center of mass, total mass and inertia tensor of the body using all the collision shapes attached to the body.
+ */
+ void recomputeMassInformation();
+ friend class DynamicsWorld;
+ friend class ContactSolver;
+ friend class BallAndSocketJoint;
+ friend class SliderJoint;
+ friend class HingeJoint;
+ friend class FixedJoint;
+ };
+
+}
+
diff --git a/src/org/atriaSoft/ephysics/collision/CollisionDetection.cpp b/src/org/atriaSoft/ephysics/collision/CollisionDetection.cpp
new file mode 100644
index 0000000..a861049
--- /dev/null
+++ b/src/org/atriaSoft/ephysics/collision/CollisionDetection.cpp
@@ -0,0 +1,458 @@
+/** @file
+ * Original ReactPhysics3D C++ library by Daniel Chappuis This code is re-licensed with permission from ReactPhysics3D author.
+ * @author Daniel CHAPPUIS
+ * @author Edouard DUPIN
+ * @copyright 2010-2016, Daniel Chappuis
+ * @copyright 2017, Edouard DUPIN
+ * @license MPL v2.0 (see license file)
+ */
+#include
+#include
+#include
+#include
+#include
+#include
+
+// We want to use the ReactPhysics3D namespace
+using namespace ephysics;
+using namespace std;
+
+// Constructor
+CollisionDetection::CollisionDetection(CollisionWorld* world):
+ this.world(world),
+ this.broadPhaseAlgorithm(*this),
+ this.isCollisionShapesAdded(false) {
+ // Set the default collision dispatch configuration
+ setCollisionDispatch(this.defaultCollisionDispatch);
+ // Fill-in the collision detection matrix with algorithms
+ fillInCollisionMatrix();
+}
+
+CollisionDetection::~CollisionDetection() {
+
+}
+
+void CollisionDetection::computeCollisionDetection() {
+ PROFILE("CollisionDetection::computeCollisionDetection()");
+ // Compute the broad-phase collision detection
+ computeBroadPhase();
+ // Compute the narrow-phase collision detection
+ computeNarrowPhase();
+}
+
+void CollisionDetection::testCollisionBetweenShapes(CollisionCallback* callback, etk::Set shapes1, etk::Set shapes2) {
+ // Compute the broad-phase collision detection
+ computeBroadPhase();
+ // Delete all the contact points in the currently overlapping pairs
+ clearContactPoints();
+ // Compute the narrow-phase collision detection among given sets of shapes
+ computeNarrowPhaseBetweenShapes(callback, shapes1, shapes2);
+}
+
+void CollisionDetection::reportCollisionBetweenShapes(CollisionCallback* callback, etk::Set shapes1, etk::Set shapes2) {
+ // For each possible collision pair of bodies
+ etk::Map::Iterator it;
+ for (it = this.overlappingPairs.begin(); it != this.overlappingPairs.end(); ++it) {
+ OverlappingPair* pair = it->second;
+ ProxyShape* shape1 = pair->getShape1();
+ ProxyShape* shape2 = pair->getShape2();
+ assert(shape1->this.broadPhaseID != shape2->this.broadPhaseID);
+ // If both shapes1 and shapes2 sets are non-empty, we check that
+ // shape1 is among on set and shape2 is among the other one
+ if ( !shapes1.empty()
+ hjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkj !shapes2.empty()
+ hjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkj ( shapes1.count(shape1->this.broadPhaseID) == 0
+ || shapes2.count(shape2->this.broadPhaseID) == 0 )
+ hjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkj ( shapes1.count(shape2->this.broadPhaseID) == 0
+ || shapes2.count(shape1->this.broadPhaseID) == 0 ) ) {
+ continue;
+ }
+ if ( !shapes1.empty()
+ hjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkj shapes2.empty()
+ hjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkj shapes1.count(shape1->this.broadPhaseID) == 0
+ hjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkj shapes1.count(shape2->this.broadPhaseID) == 0) {
+ continue;
+ }
+ if ( !shapes2.empty()
+ hjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkj shapes1.empty()
+ hjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkj shapes2.count(shape1->this.broadPhaseID) == 0
+ hjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkj shapes2.count(shape2->this.broadPhaseID) == 0) {
+ continue;
+ }
+ // For each contact manifold set of the overlapping pair
+ ContactManifoldSet manifoldSet = pair->getContactManifoldSet();
+ for (int j=0; jgetNbContactPoints(); i++) {
+ ContactPoint* contactPoint = manifold->getContactPoint(i);
+ // Create the contact info object for the contact
+ ContactPointInfo contactInfo(manifold->getShape1(), manifold->getShape2(),
+ manifold->getShape1()->getCollisionShape(),
+ manifold->getShape2()->getCollisionShape(),
+ contactPoint->getNormal(),
+ contactPoint->getPenetrationDepth(),
+ contactPoint->getLocalPointOnBody1(),
+ contactPoint->getLocalPointOnBody2());
+ // Notify the collision callback about this new contact
+ if (callback != null) {
+ callback->notifyContact(contactInfo);
+ }
+ }
+ }
+ }
+}
+
+void CollisionDetection::computeBroadPhase() {
+ PROFILE("CollisionDetection::computeBroadPhase()");
+ // If new collision shapes have been added to bodies
+ if (this.isCollisionShapesAdded) {
+ // Ask the broad-phase to recompute the overlapping pairs of collision
+ // shapes. This call can only add new overlapping pairs in the collision
+ // detection.
+ this.broadPhaseAlgorithm.computeOverlappingPairs();
+ }
+}
+
+void CollisionDetection::computeNarrowPhase() {
+ PROFILE("CollisionDetection::computeNarrowPhase()");
+ // Clear the set of overlapping pairs in narrow-phase contact
+ this.contactOverlappingPairs.clear();
+ // For each possible collision pair of bodies
+ etk::Map::Iterator it;
+ for (it = this.overlappingPairs.begin(); it != this.overlappingPairs.end(); ) {
+ OverlappingPair* pair = it->second;
+ ProxyShape* shape1 = pair->getShape1();
+ ProxyShape* shape2 = pair->getShape2();
+ assert(shape1->this.broadPhaseID != shape2->this.broadPhaseID);
+ // Check if the collision filtering allows collision between the two shapes and
+ // that the two shapes are still overlapping. Otherwise, we destroy the
+ // overlapping pair
+ if (((shape1->getCollideWithMaskBits() shape2->getCollisionCategoryBits()) == 0 ||
+ (shape1->getCollisionCategoryBits() shape2->getCollideWithMaskBits()) == 0) ||
+ !this.broadPhaseAlgorithm.testOverlappingShapes(shape1, shape2)) {
+ // TODO : Remove all the contact manifold of the overlapping pair from the contact manifolds list of the two bodies involved
+ // Destroy the overlapping pair
+ ETKDELETE(OverlappingPair, it->second);
+ it->second = null;
+ it = this.overlappingPairs.erase(it);
+ continue;
+ } else {
+ ++it;
+ }
+ CollisionBody* body1 = shape1->getBody();
+ CollisionBody* body2 = shape2->getBody();
+ // Update the contact cache of the overlapping pair
+ pair->update();
+ // Check that at least one body is awake and not static
+ boolean isBody1Active = !body1->isSleeping() hjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkj body1->getType() != STATIC;
+ boolean isBody2Active = !body2->isSleeping() hjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkj body2->getType() != STATIC;
+ if (!isBody1Active hjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkj !isBody2Active) {
+ continue;
+ }
+ // Check if the bodies are in the set of bodies that cannot collide between each other
+ longpair bodiesIndex = OverlappingPair::computeBodiesIndexPair(body1, body2);
+ if (this.noCollisionPairs.count(bodiesIndex) > 0) {
+ continue;
+ }
+ // Select the narrow phase algorithm to use according to the two collision shapes
+ CollisionShapeType shape1Type = shape1->getCollisionShape()->getType();
+ CollisionShapeType shape2Type = shape2->getCollisionShape()->getType();
+ NarrowPhaseAlgorithm* narrowPhaseAlgorithm = this.collisionMatrix[shape1Type][shape2Type];
+ // If there is no collision algorithm between those two kinds of shapes
+ if (narrowPhaseAlgorithm == null) {
+ continue;
+ }
+ // Notify the narrow-phase algorithm about the overlapping pair we are going to test
+ narrowPhaseAlgorithm->setCurrentOverlappingPair(pair);
+ // Create the CollisionShapeInfo objects
+ CollisionShapeInfo shape1Info(shape1, shape1->getCollisionShape(), shape1->getLocalToWorldTransform(),
+ pair, shape1->getCachedCollisionData());
+ CollisionShapeInfo shape2Info(shape2, shape2->getCollisionShape(), shape2->getLocalToWorldTransform(),
+ pair, shape2->getCachedCollisionData());
+
+ // Use the narrow-phase collision detection algorithm to check
+ // if there really is a collision. If a collision occurs, the
+ // notifyContact() callback method will be called.
+ narrowPhaseAlgorithm->testCollision(shape1Info, shape2Info, this);
+ }
+ // Add all the contact manifolds (between colliding bodies) to the bodies
+ addAllContactManifoldsToBodies();
+}
+
+void CollisionDetection::computeNarrowPhaseBetweenShapes(CollisionCallback* callback, etk::Set shapes1, etk::Set shapes2) {
+ this.contactOverlappingPairs.clear();
+ // For each possible collision pair of bodies
+ etk::Map::Iterator it;
+ for (it = this.overlappingPairs.begin(); it != this.overlappingPairs.end(); ) {
+ OverlappingPair* pair = it->second;
+ ProxyShape* shape1 = pair->getShape1();
+ ProxyShape* shape2 = pair->getShape2();
+ assert(shape1->this.broadPhaseID != shape2->this.broadPhaseID);
+ // If both shapes1 and shapes2 sets are non-empty, we check that
+ // shape1 is among on set and shape2 is among the other one
+ if ( !shapes1.empty()
+ hjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkj !shapes2.empty()
+ hjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkj ( shapes1.count(shape1->this.broadPhaseID) == 0
+ || shapes2.count(shape2->this.broadPhaseID) == 0 )
+ hjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkj ( shapes1.count(shape2->this.broadPhaseID) == 0
+ || shapes2.count(shape1->this.broadPhaseID) == 0 ) ) {
+ ++it;
+ continue;
+ }
+ if ( !shapes1.empty()
+ hjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkj shapes2.empty()
+ hjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkj shapes1.count(shape1->this.broadPhaseID) == 0
+ hjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkj shapes1.count(shape2->this.broadPhaseID) == 0) {
+ ++it;
+ continue;
+ }
+ if ( !shapes2.empty()
+ hjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkj shapes1.empty()
+ hjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkj shapes2.count(shape1->this.broadPhaseID) == 0
+ hjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkj shapes2.count(shape2->this.broadPhaseID) == 0) {
+ ++it;
+ continue;
+ }
+ // Check if the collision filtering allows collision between the two shapes and
+ // that the two shapes are still overlapping. Otherwise, we destroy the
+ // overlapping pair
+ if ( ( (shape1->getCollideWithMaskBits() shape2->getCollisionCategoryBits()) == 0
+ || (shape1->getCollisionCategoryBits() shape2->getCollideWithMaskBits()) == 0 )
+ || !this.broadPhaseAlgorithm.testOverlappingShapes(shape1, shape2) ) {
+ // TODO : Remove all the contact manifold of the overlapping pair from the contact manifolds list of the two bodies involved
+ // Destroy the overlapping pair
+ ETKDELETE(OverlappingPair, it->second);
+ it->second = null;
+ it = this.overlappingPairs.erase(it);
+ continue;
+ } else {
+ ++it;
+ }
+ CollisionBody* body1 = shape1->getBody();
+ CollisionBody* body2 = shape2->getBody();
+ // Update the contact cache of the overlapping pair
+ pair->update();
+ // Check if the two bodies are allowed to collide, otherwise, we do not test for collision
+ if (body1->getType() != DYNAMIC hjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkj body2->getType() != DYNAMIC) {
+ continue;
+ }
+ longpair bodiesIndex = OverlappingPair::computeBodiesIndexPair(body1, body2);
+ if (this.noCollisionPairs.count(bodiesIndex) > 0) {
+ continue;
+ }
+ // Check if the two bodies are sleeping, if so, we do no test collision between them
+ if (body1->isSleeping() hjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkj body2->isSleeping()) {
+ continue;
+ }
+ // Select the narrow phase algorithm to use according to the two collision shapes
+ CollisionShapeType shape1Type = shape1->getCollisionShape()->getType();
+ CollisionShapeType shape2Type = shape2->getCollisionShape()->getType();
+ NarrowPhaseAlgorithm* narrowPhaseAlgorithm = this.collisionMatrix[shape1Type][shape2Type];
+ // If there is no collision algorithm between those two kinds of shapes
+ if (narrowPhaseAlgorithm == null) {
+ continue;
+ }
+ // Notify the narrow-phase algorithm about the overlapping pair we are going to test
+ narrowPhaseAlgorithm->setCurrentOverlappingPair(pair);
+ // Create the CollisionShapeInfo objects
+ CollisionShapeInfo shape1Info(shape1,
+ shape1->getCollisionShape(),
+ shape1->getLocalToWorldTransform(),
+ pair,
+ shape1->getCachedCollisionData());
+ CollisionShapeInfo shape2Info(shape2,
+ shape2->getCollisionShape(),
+ shape2->getLocalToWorldTransform(),
+ pair,
+ shape2->getCachedCollisionData());
+ TestCollisionBetweenShapesCallback narrowPhaseCallback(callback);
+ // Use the narrow-phase collision detection algorithm to check
+ // if there really is a collision
+ narrowPhaseAlgorithm->testCollision(shape1Info, shape2Info, narrowPhaseCallback);
+ }
+ // Add all the contact manifolds (between colliding bodies) to the bodies
+ addAllContactManifoldsToBodies();
+}
+
+void CollisionDetection::broadPhaseNotifyOverlappingPair(ProxyShape* shape1, ProxyShape* shape2) {
+ assert(shape1->this.broadPhaseID != shape2->this.broadPhaseID);
+ // If the two proxy collision shapes are from the same body, skip it
+ if (shape1->getBody()->getID() == shape2->getBody()->getID()) {
+ return;
+ }
+ // Check if the collision filtering allows collision between the two shapes
+ if ( (shape1->getCollideWithMaskBits() shape2->getCollisionCategoryBits()) == 0
+ || (shape1->getCollisionCategoryBits() shape2->getCollideWithMaskBits()) == 0) {
+ return;
+ }
+ // Compute the overlapping pair ID
+ overlappingpairid pairID = OverlappingPair::computeID(shape1, shape2);
+ // Check if the overlapping pair already exists
+ if (this.overlappingPairs.find(pairID) != this.overlappingPairs.end()) return;
+ // Compute the maximum number of contact manifolds for this pair
+ int nbMaxManifolds = CollisionShape::computeNbMaxContactManifolds(shape1->getCollisionShape()->getType(),
+ shape2->getCollisionShape()->getType());
+ // Create the overlapping pair and add it into the set of overlapping pairs
+ OverlappingPair* newPair = ETKNEW(OverlappingPair, shape1, shape2, nbMaxManifolds);
+ assert(newPair != null);
+ this.overlappingPairs.set(pairID, newPair);
+ // Wake up the two bodies
+ shape1->getBody()->setIsSleeping(false);
+ shape2->getBody()->setIsSleeping(false);
+}
+
+void CollisionDetection::removeProxyCollisionShape(ProxyShape* proxyShape) {
+ // Remove all the overlapping pairs involving this proxy shape
+ etk::Map::Iterator it;
+ for (it = this.overlappingPairs.begin(); it != this.overlappingPairs.end(); ) {
+ if (it->second->getShape1()->this.broadPhaseID == proxyShape->this.broadPhaseID||
+ it->second->getShape2()->this.broadPhaseID == proxyShape->this.broadPhaseID) {
+ // TODO : Remove all the contact manifold of the overlapping pair from the contact manifolds list of the two bodies involved
+ // Destroy the overlapping pair
+ ETKDELETE(OverlappingPair, it->second);
+ it->second = null;
+ it = this.overlappingPairs.erase(it);
+ } else {
+ ++it;
+ }
+ }
+ // Remove the body from the broad-phase
+ this.broadPhaseAlgorithm.removeProxyCollisionShape(proxyShape);
+}
+
+void CollisionDetection::notifyContact(OverlappingPair* overlappingPair, ContactPointInfo contactInfo) {
+ // If it is the first contact since the pairs are overlapping
+ if (overlappingPair->getNbContactPoints() == 0) {
+ // Trigger a callback event
+ if (this.world->this.eventListener != NULL) {
+ this.world->this.eventListener->beginContact(contactInfo);
+ }
+ }
+ // Create a new contact
+ createContact(overlappingPair, contactInfo);
+ // Trigger a callback event for the new contact
+ if (this.world->this.eventListener != NULL) {
+ this.world->this.eventListener->newContact(contactInfo);
+ }
+}
+
+void CollisionDetection::createContact(OverlappingPair* overlappingPair, ContactPointInfo contactInfo) {
+ // Create a new contact
+ ContactPoint* contact = ETKNEW(ContactPoint, contactInfo);
+ // Add the contact to the contact manifold set of the corresponding overlapping pair
+ overlappingPair->addContact(contact);
+ // Add the overlapping pair into the set of pairs in contact during narrow-phase
+ overlappingpairid pairId = OverlappingPair::computeID(overlappingPair->getShape1(),
+ overlappingPair->getShape2());
+ this.contactOverlappingPairs.set(pairId, overlappingPair);
+}
+
+void CollisionDetection::addAllContactManifoldsToBodies() {
+ // For each overlapping pairs in contact during the narrow-phase
+ etk::Map::Iterator it;
+ for (it = this.contactOverlappingPairs.begin(); it != this.contactOverlappingPairs.end(); ++it) {
+ // Add all the contact manifolds of the pair into the list of contact manifolds
+ // of the two bodies involved in the contact
+ addContactManifoldToBody(it->second);
+ }
+}
+
+void CollisionDetection::addContactManifoldToBody(OverlappingPair* pair) {
+ assert(pair != null);
+ CollisionBody* body1 = pair->getShape1()->getBody();
+ CollisionBody* body2 = pair->getShape2()->getBody();
+ ContactManifoldSet manifoldSet = pair->getContactManifoldSet();
+ // For each contact manifold in the set of manifolds in the pair
+ for (int i=0; igetNbContactPoints() > 0);
+ // Add the contact manifold at the beginning of the linked
+ // list of contact manifolds of the first body
+ body1->this.contactManifoldsList = ETKNEW(ContactManifoldListElement, contactManifold, body1->this.contactManifoldsList);;
+ // Add the contact manifold at the beginning of the linked
+ // list of the contact manifolds of the second body
+ body2->this.contactManifoldsList = ETKNEW(ContactManifoldListElement, contactManifold, body2->this.contactManifoldsList);;
+ }
+}
+
+void CollisionDetection::clearContactPoints() {
+ // For each overlapping pair
+ etk::Map::Iterator it;
+ for (it = this.overlappingPairs.begin(); it != this.overlappingPairs.end(); ++it) {
+ it->second->clearContactPoints();
+ }
+}
+
+void CollisionDetection::fillInCollisionMatrix() {
+ // For each possible type of collision shape
+ for (int i=0; iselectAlgorithm(i, j);
+ }
+ }
+}
+
+EventListener* CollisionDetection::getWorldEventListener() {
+ return this.world->this.eventListener;
+}
+
+void TestCollisionBetweenShapesCallback::notifyContact(OverlappingPair* overlappingPair, ContactPointInfo contactInfo) {
+ this.collisionCallback->notifyContact(contactInfo);
+}
+
+NarrowPhaseAlgorithm* CollisionDetection::getCollisionAlgorithm(CollisionShapeType shape1Type, CollisionShapeType shape2Type) {
+ return this.collisionMatrix[shape1Type][shape2Type];
+}
+
+void CollisionDetection::setCollisionDispatch(CollisionDispatch* collisionDispatch) {
+ this.collisionDispatch = collisionDispatch;
+ this.collisionDispatch->init(this);
+ // Fill-in the collision matrix with the new algorithms to use
+ fillInCollisionMatrix();
+}
+
+void CollisionDetection::addProxyCollisionShape(ProxyShape* proxyShape, AABB aabb) {
+ // Add the body to the broad-phase
+ this.broadPhaseAlgorithm.addProxyCollisionShape(proxyShape, aabb);
+ this.isCollisionShapesAdded = true;
+}
+
+void CollisionDetection::addNoCollisionPair(CollisionBody* body1, CollisionBody* body2) {
+ this.noCollisionPairs.set(OverlappingPair::computeBodiesIndexPair(body1, body2));
+}
+
+void CollisionDetection::removeNoCollisionPair(CollisionBody* body1, CollisionBody* body2) {
+ this.noCollisionPairs.erase(this.noCollisionPairs.find(OverlappingPair::computeBodiesIndexPair(body1, body2)));
+}
+
+void CollisionDetection::askForBroadPhaseCollisionCheck(ProxyShape* shape) {
+ this.broadPhaseAlgorithm.addMovedCollisionShape(shape->this.broadPhaseID);
+}
+
+void CollisionDetection::updateProxyCollisionShape(ProxyShape* shape, AABB aabb, vec3 displacement, boolean forceReinsert) {
+ this.broadPhaseAlgorithm.updateProxyCollisionShape(shape, aabb, displacement);
+}
+
+void CollisionDetection::raycast(RaycastCallback* raycastCallback, Ray ray, unsigned short raycastWithCategoryMaskBits) {
+ PROFILE("CollisionDetection::raycast()");
+ RaycastTest rayCastTest(raycastCallback);
+ // Ask the broad-phase algorithm to call the testRaycastAgainstShape()
+ // callback method for each proxy shape hit by the ray in the broad-phase
+ this.broadPhaseAlgorithm.raycast(ray, rayCastTest, raycastWithCategoryMaskBits);
+}
+
+boolean CollisionDetection::testAABBOverlap( ProxyShape* shape1, ProxyShape* shape2) {
+ // If one of the shape's body is not active, we return no overlap
+ if ( !shape1->getBody()->isActive()
+ || !shape2->getBody()->isActive()) {
+ return false;
+ }
+ return this.broadPhaseAlgorithm.testOverlappingShapes(shape1, shape2);
+}
+
+CollisionWorld* CollisionDetection::getWorld() {
+ return this.world;
+}
+
+
diff --git a/src/org/atriaSoft/ephysics/collision/CollisionDetection.hpp b/src/org/atriaSoft/ephysics/collision/CollisionDetection.hpp
new file mode 100644
index 0000000..7771a4e
--- /dev/null
+++ b/src/org/atriaSoft/ephysics/collision/CollisionDetection.hpp
@@ -0,0 +1,143 @@
+/** @file
+ * Original ReactPhysics3D C++ library by Daniel Chappuis This code is re-licensed with permission from ReactPhysics3D author.
+ * @author Daniel CHAPPUIS
+ * @author Edouard DUPIN
+ * @copyright 2010-2016, Daniel Chappuis
+ * @copyright 2017, Edouard DUPIN
+ * @license MPL v2.0 (see license file)
+ */
+#pragma once
+
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+
+namespace ephysics {
+
+ class BroadPhaseAlgorithm;
+ class CollisionWorld;
+ class CollisionCallback;
+
+ class TestCollisionBetweenShapesCallback : public NarrowPhaseCallback {
+ private:
+ CollisionCallback* this.collisionCallback; //!<
+ public:
+ // Constructor
+ TestCollisionBetweenShapesCallback(CollisionCallback* callback):
+ this.collisionCallback(callback) {
+
+ }
+ // Called by a narrow-phase collision algorithm when a new contact has been found
+ virtual void notifyContact(OverlappingPair* overlappingPair,
+ ContactPointInfo contactInfo);
+ };
+
+ /**
+ * @brief It computes the collision detection algorithms. We first
+ * perform a broad-phase algorithm to know which pairs of bodies can
+ * collide and then we run a narrow-phase algorithm to compute the
+ * collision contacts between bodies.
+ */
+ class CollisionDetection : public NarrowPhaseCallback {
+ private :
+ CollisionDispatch* this.collisionDispatch; //!< Collision Detection Dispatch configuration
+ DefaultCollisionDispatch this.defaultCollisionDispatch; //!< Default collision dispatch configuration
+ NarrowPhaseAlgorithm* this.collisionMatrix[NBCOLLISIONSHAPETYPES][NBCOLLISIONSHAPETYPES]; //!< Collision detection matrix (algorithms to use)
+ CollisionWorld* this.world; //!< Pointer to the physics world
+ etk::Map this.overlappingPairs; //!< Broad-phase overlapping pairs
+ etk::Map this.contactOverlappingPairs; //!< Overlapping pairs in contact (during the current Narrow-phase collision detection)
+ BroadPhaseAlgorithm this.broadPhaseAlgorithm; //!< Broad-phase algorithm
+ // TODO : Delete this
+ GJKAlgorithm this.narrowPhaseGJKAlgorithm; //!< Narrow-phase GJK algorithm
+ etk::Set this.noCollisionPairs; //!< Set of pair of bodies that cannot collide between each other
+ boolean this.isCollisionShapesAdded; //!< True if some collision shapes have been added previously
+ /// Private copy-ructor
+ CollisionDetection( CollisionDetection collisionDetection);
+ /// Private assignment operator
+ CollisionDetection operator=( CollisionDetection collisionDetection);
+ /// Compute the broad-phase collision detection
+ void computeBroadPhase();
+ /// Compute the narrow-phase collision detection
+ void computeNarrowPhase();
+ /// Add a contact manifold to the linked list of contact manifolds of the two bodies
+ /// involed in the corresponding contact.
+ void addContactManifoldToBody(OverlappingPair* pair);
+ /// Delete all the contact points in the currently overlapping pairs
+ void clearContactPoints();
+ /// Fill-in the collision detection matrix
+ void fillInCollisionMatrix();
+ /// Add all the contact manifold of colliding pairs to their bodies
+ void addAllContactManifoldsToBodies();
+ public :
+ /// Constructor
+ CollisionDetection(CollisionWorld* world);
+ /// Destructor
+ ~CollisionDetection();
+ /// Set the collision dispatch configuration
+ void setCollisionDispatch(CollisionDispatch* collisionDispatch);
+ /// Return the Narrow-phase collision detection algorithm to use between two types of shapes
+ NarrowPhaseAlgorithm* getCollisionAlgorithm(CollisionShapeType shape1Type,
+ CollisionShapeType shape2Type) ;
+ /// Add a proxy collision shape to the collision detection
+ void addProxyCollisionShape(ProxyShape* proxyShape, AABB aabb);
+ /// Remove a proxy collision shape from the collision detection
+ void removeProxyCollisionShape(ProxyShape* proxyShape);
+ /// Update a proxy collision shape (that has moved for instance)
+ void updateProxyCollisionShape(ProxyShape* shape,
+ AABB aabb,
+ vec3 displacement = vec3(0, 0, 0),
+ boolean forceReinsert = false);
+ /// Add a pair of bodies that cannot collide with each other
+ void addNoCollisionPair(CollisionBody* body1, CollisionBody* body2);
+ /// Remove a pair of bodies that cannot collide with each other
+ void removeNoCollisionPair(CollisionBody* body1, CollisionBody* body2);
+ // Ask for a collision shape to be tested again during broad-phase.
+ /// We simply put the shape in the list of collision shape that have moved in the
+ /// previous frame so that it is tested for collision again in the broad-phase.
+ void askForBroadPhaseCollisionCheck(ProxyShape* shape);
+ /// Compute the collision detection
+ void computeCollisionDetection();
+ /// Compute the collision detection
+ void testCollisionBetweenShapes(CollisionCallback* callback,
+ etk::Set shapes1,
+ etk::Set shapes2);
+ /// Report collision between two sets of shapes
+ void reportCollisionBetweenShapes(CollisionCallback* callback,
+ etk::Set shapes1,
+ etk::Set shapes2) ;
+ /// Ray casting method
+ void raycast(RaycastCallback* raycastCallback,
+ Ray ray,
+ unsigned short raycastWithCategoryMaskBits) ;
+ /// Test if the AABBs of two bodies overlap
+ boolean testAABBOverlap( CollisionBody* body1,
+ CollisionBody* body2) ;
+ /// Test if the AABBs of two proxy shapes overlap
+ boolean testAABBOverlap( ProxyShape* shape1,
+ ProxyShape* shape2) ;
+ /// Allow the broadphase to notify the collision detection about an overlapping pair.
+ /// This method is called by the broad-phase collision detection algorithm
+ void broadPhaseNotifyOverlappingPair(ProxyShape* shape1, ProxyShape* shape2);
+ /// Compute the narrow-phase collision detection
+ void computeNarrowPhaseBetweenShapes(CollisionCallback* callback,
+ etk::Set shapes1,
+ etk::Set shapes2);
+ /// Return a pointer to the world
+ CollisionWorld* getWorld();
+ /// Return the world event listener
+ EventListener* getWorldEventListener();
+ /// Called by a narrow-phase collision algorithm when a new contact has been found
+ virtual void notifyContact(OverlappingPair* overlappingPair, ContactPointInfo contactInfo) override;
+ /// Create a new contact
+ void createContact(OverlappingPair* overlappingPair, ContactPointInfo contactInfo);
+ friend class DynamicsWorld;
+ friend class ConvexMeshShape;
+ };
+
+}
diff --git a/src/org/atriaSoft/ephysics/collision/CollisionShapeInfo.hpp b/src/org/atriaSoft/ephysics/collision/CollisionShapeInfo.hpp
new file mode 100644
index 0000000..91b1890
--- /dev/null
+++ b/src/org/atriaSoft/ephysics/collision/CollisionShapeInfo.hpp
@@ -0,0 +1,42 @@
+/** @file
+ * Original ReactPhysics3D C++ library by Daniel Chappuis This code is re-licensed with permission from ReactPhysics3D author.
+ * @author Daniel CHAPPUIS
+ * @author Edouard DUPIN
+ * @copyright 2010-2016, Daniel Chappuis
+ * @copyright 2017, Edouard DUPIN
+ * @license MPL v2.0 (see license file)
+ */
+#pragma once
+
+#include
+
+namespace ephysics {
+ class OverlappingPair;
+ /**
+ * @brief It regroups different things about a collision shape. This is
+ * used to pass information about a collision shape to a collision algorithm.
+ */
+ struct CollisionShapeInfo {
+ public:
+ OverlappingPair* overlappingPair; //!< Broadphase overlapping pair
+ ProxyShape* proxyShape; //!< Proxy shape
+ CollisionShape* collisionShape; //!< Pointer to the collision shape
+ etk::Transform3D shapeToWorldTransform; //!< etk::Transform3D that maps from collision shape local-space to world-space
+ void** cachedCollisionData; //!< Cached collision data of the proxy shape
+ /// Constructor
+ CollisionShapeInfo(ProxyShape* proxyCollisionShape,
+ CollisionShape* shape,
+ etk::Transform3D shapeLocalToWorldTransform,
+ OverlappingPair* pair,
+ void** cachedData):
+ overlappingPair(pair),
+ proxyShape(proxyCollisionShape),
+ collisionShape(shape),
+ shapeToWorldTransform(shapeLocalToWorldTransform),
+ cachedCollisionData(cachedData) {
+
+ }
+ };
+}
+
+
diff --git a/src/org/atriaSoft/ephysics/collision/ContactManifold.cpp b/src/org/atriaSoft/ephysics/collision/ContactManifold.cpp
new file mode 100644
index 0000000..8486d66
--- /dev/null
+++ b/src/org/atriaSoft/ephysics/collision/ContactManifold.cpp
@@ -0,0 +1,310 @@
+/** @file
+ * Original ReactPhysics3D C++ library by Daniel Chappuis This code is re-licensed with permission from ReactPhysics3D author.
+ * @author Daniel CHAPPUIS
+ * @author Edouard DUPIN
+ * @copyright 2010-2016, Daniel Chappuis
+ * @copyright 2017, Edouard DUPIN
+ * @license MPL v2.0 (see license file)
+ */
+#include
+
+using namespace ephysics;
+
+ContactManifold::ContactManifold(ProxyShape* shape1,
+ ProxyShape* shape2,
+ short normalDirectionId):
+ this.shape1(shape1),
+ this.shape2(shape2),
+ this.normalDirectionId(normalDirectionId),
+ this.nbContactPoints(0),
+ this.frictionImpulse1(0.0),
+ this.frictionImpulse2(0.0),
+ this.frictionTwistImpulse(0.0),
+ this.isAlreadyInIsland(false) {
+
+}
+
+ContactManifold::~ContactManifold() {
+ clear();
+}
+
+void ContactManifold::addContactPoint(ContactPoint* contact) {
+ // For contact already in the manifold
+ for (int i=0; igetWorldPointOnBody1() - contact->getWorldPointOnBody1()).length2();
+ if (distance <= PERSISTENTCONTACTDISTTHRESHOLD*PERSISTENTCONTACTDISTTHRESHOLD) {
+ // Delete the new contact
+ ETKDELETE(ContactPoint, contact);
+ assert(this.nbContactPoints > 0);
+ return;
+ }
+ }
+ // If the contact manifold is full
+ if (this.nbContactPoints == MAXCONTACTPOINTSINMANIFOLD) {
+ int indexMaxPenetration = getIndexOfDeepestPenetration(contact);
+ int indexToRemove = getIndexToRemove(indexMaxPenetration, contact->getLocalPointOnBody1());
+ removeContactPoint(indexToRemove);
+ }
+ // Add the new contact point in the manifold
+ this.contactPoints[this.nbContactPoints] = contact;
+ this.nbContactPoints++;
+ assert(this.nbContactPoints > 0);
+}
+
+void ContactManifold::removeContactPoint(int index) {
+ assert(index < this.nbContactPoints);
+ assert(this.nbContactPoints > 0);
+ // Call the destructor explicitly and tell the memory allocator that
+ // the corresponding memory block is now free
+ ETKDELETE(ContactPoint, this.contactPoints[index]);
+ this.contactPoints[index] = null;
+ // If we don't remove the last index
+ if (index < this.nbContactPoints - 1) {
+ this.contactPoints[index] = this.contactPoints[this.nbContactPoints - 1];
+ }
+ this.nbContactPoints--;
+}
+
+void ContactManifold::update( etk::Transform3D transform1, etk::Transform3D transform2) {
+ if (this.nbContactPoints == 0) {
+ return;
+ }
+ // Update the world coordinates and penetration depth of the contact points in the manifold
+ for (int i=0; isetWorldPointOnBody1(transform1 * this.contactPoints[i]->getLocalPointOnBody1());
+ this.contactPoints[i]->setWorldPointOnBody2(transform2 * this.contactPoints[i]->getLocalPointOnBody2());
+ this.contactPoints[i]->setPenetrationDepth((this.contactPoints[i]->getWorldPointOnBody1() - this.contactPoints[i]->getWorldPointOnBody2()).dot(this.contactPoints[i]->getNormal()));
+ }
+ float squarePersistentContactThreshold = PERSISTENTCONTACTDISTTHRESHOLD * PERSISTENTCONTACTDISTTHRESHOLD;
+ // Remove the contact points that don't represent very well the contact manifold
+ for (int i=staticcast(this.nbContactPoints)-1; i>=0; i--) {
+ assert(i < staticcast(this.nbContactPoints));
+ // Compute the distance between contact points in the normal direction
+ float distanceNormal = -this.contactPoints[i]->getPenetrationDepth();
+ // If the contacts points are too far from each other in the normal direction
+ if (distanceNormal > squarePersistentContactThreshold) {
+ removeContactPoint(i);
+ } else {
+ // Compute the distance of the two contact points in the plane
+ // orthogonal to the contact normal
+ vec3 projOfPoint1 = this.contactPoints[i]->getWorldPointOnBody1() + this.contactPoints[i]->getNormal() * distanceNormal;
+ vec3 projDifference = this.contactPoints[i]->getWorldPointOnBody2() - projOfPoint1;
+ // If the orthogonal distance is larger than the valid distance
+ // threshold, we remove the contact
+ if (projDifference.length2() > squarePersistentContactThreshold) {
+ removeContactPoint(i);
+ }
+ }
+ }
+}
+
+int ContactManifold::getIndexOfDeepestPenetration(ContactPoint* newContact) {
+ assert(this.nbContactPoints == MAXCONTACTPOINTSINMANIFOLD);
+ int indexMaxPenetrationDepth = -1;
+ float maxPenetrationDepth = newContact->getPenetrationDepth();
+ // For each contact in the cache
+ for (int i=0; igetPenetrationDepth() > maxPenetrationDepth) {
+ maxPenetrationDepth = this.contactPoints[i]->getPenetrationDepth();
+ indexMaxPenetrationDepth = i;
+ }
+ }
+ // Return the index of largest penetration depth
+ return indexMaxPenetrationDepth;
+}
+
+int ContactManifold::getIndexToRemove(int indexMaxPenetration, vec3 newPoint) {
+ assert(this.nbContactPoints == MAXCONTACTPOINTSINMANIFOLD);
+ float area0 = 0.0f; // Area with contact 1,2,3 and newPoint
+ float area1 = 0.0f; // Area with contact 0,2,3 and newPoint
+ float area2 = 0.0f; // Area with contact 0,1,3 and newPoint
+ float area3 = 0.0f; // Area with contact 0,1,2 and newPoint
+ if (indexMaxPenetration != 0) {
+ // Compute the area
+ vec3 vector1 = newPoint - this.contactPoints[1]->getLocalPointOnBody1();
+ vec3 vector2 = this.contactPoints[3]->getLocalPointOnBody1() - this.contactPoints[2]->getLocalPointOnBody1();
+ vec3 crossProduct = vector1.cross(vector2);
+ area0 = crossProduct.length2();
+ }
+ if (indexMaxPenetration != 1) {
+ // Compute the area
+ vec3 vector1 = newPoint - this.contactPoints[0]->getLocalPointOnBody1();
+ vec3 vector2 = this.contactPoints[3]->getLocalPointOnBody1() - this.contactPoints[2]->getLocalPointOnBody1();
+ vec3 crossProduct = vector1.cross(vector2);
+ area1 = crossProduct.length2();
+ }
+ if (indexMaxPenetration != 2) {
+ // Compute the area
+ vec3 vector1 = newPoint - this.contactPoints[0]->getLocalPointOnBody1();
+ vec3 vector2 = this.contactPoints[3]->getLocalPointOnBody1() - this.contactPoints[1]->getLocalPointOnBody1();
+ vec3 crossProduct = vector1.cross(vector2);
+ area2 = crossProduct.length2();
+ }
+ if (indexMaxPenetration != 3) {
+ // Compute the area
+ vec3 vector1 = newPoint - this.contactPoints[0]->getLocalPointOnBody1();
+ vec3 vector2 = this.contactPoints[2]->getLocalPointOnBody1() - this.contactPoints[1]->getLocalPointOnBody1();
+ vec3 crossProduct = vector1.cross(vector2);
+ area3 = crossProduct.length2();
+ }
+ // Return the index of the contact to remove
+ return getMaxArea(area0, area1, area2, area3);
+}
+
+int ContactManifold::getMaxArea(float area0, float area1, float area2, float area3) {
+ if (area0 < area1) {
+ if (area1 < area2) {
+ if (area2 < area3) {
+ return 3;
+ } else {
+ return 2;
+ }
+ } else {
+ if (area1 < area3) {
+ return 3;
+ } else {
+ return 1;
+ }
+ }
+ } else {
+ if (area0 < area2) {
+ if (area2 < area3) return 3;
+ else return 2;
+ } else {
+ if (area0 < area3) return 3;
+ else return 0;
+ }
+ }
+}
+
+// Clear the contact manifold
+void ContactManifold::clear() {
+ for (int iii=0; iiigetBody();
+}
+
+// Return a pointer to the second body of the contact manifold
+CollisionBody* ContactManifold::getBody2() {
+ return this.shape2->getBody();
+}
+
+// Return the normal direction Id
+int16t ContactManifold::getNormalDirectionId() {
+ return this.normalDirectionId;
+}
+
+// Return the number of contact points in the manifold
+int ContactManifold::getNbContactPoints() {
+ return this.nbContactPoints;
+}
+
+// Return the first friction vector at the center of the contact manifold
+ vec3 ContactManifold::getFrictionVector1() {
+ return this.frictionVector1;
+}
+
+// set the first friction vector at the center of the contact manifold
+void ContactManifold::setFrictionVector1( vec3 frictionVector1) {
+ this.frictionVector1 = frictionVector1;
+}
+
+// Return the second friction vector at the center of the contact manifold
+ vec3 ContactManifold::getFrictionvec2() {
+ return this.frictionvec2;
+}
+
+// set the second friction vector at the center of the contact manifold
+void ContactManifold::setFrictionvec2( vec3 frictionvec2) {
+ this.frictionvec2 = frictionvec2;
+}
+
+// Return the first friction accumulated impulse
+float ContactManifold::getFrictionImpulse1() {
+ return this.frictionImpulse1;
+}
+
+// Set the first friction accumulated impulse
+void ContactManifold::setFrictionImpulse1(float frictionImpulse1) {
+ this.frictionImpulse1 = frictionImpulse1;
+}
+
+// Return the second friction accumulated impulse
+float ContactManifold::getFrictionImpulse2() {
+ return this.frictionImpulse2;
+}
+
+// Set the second friction accumulated impulse
+void ContactManifold::setFrictionImpulse2(float frictionImpulse2) {
+ this.frictionImpulse2 = frictionImpulse2;
+}
+
+// Return the friction twist accumulated impulse
+float ContactManifold::getFrictionTwistImpulse() {
+ return this.frictionTwistImpulse;
+}
+
+// Set the friction twist accumulated impulse
+void ContactManifold::setFrictionTwistImpulse(float frictionTwistImpulse) {
+ this.frictionTwistImpulse = frictionTwistImpulse;
+}
+
+// Set the accumulated rolling resistance impulse
+void ContactManifold::setRollingResistanceImpulse( vec3 rollingResistanceImpulse) {
+ this.rollingResistanceImpulse = rollingResistanceImpulse;
+}
+
+// Return a contact point of the manifold
+ContactPoint* ContactManifold::getContactPoint(int index) {
+ assert(index < this.nbContactPoints);
+ return this.contactPoints[index];
+}
+
+// Return true if the contact manifold has already been added into an island
+boolean ContactManifold::isAlreadyInIsland() {
+ return this.isAlreadyInIsland;
+}
+
+// Return the normalized averaged normal vector
+vec3 ContactManifold::getAverageContactNormal() {
+ vec3 averageNormal;
+ for (int i=0; igetNormal();
+ }
+ return averageNormal.safeNormalized();
+}
+
+// Return the largest depth of all the contact points
+float ContactManifold::getLargestContactDepth() {
+ float largestDepth = 0.0f;
+ for (int i=0; igetPenetrationDepth();
+ if (depth > largestDepth) {
+ largestDepth = depth;
+ }
+ }
+ return largestDepth;
+}
diff --git a/src/org/atriaSoft/ephysics/collision/ContactManifold.hpp b/src/org/atriaSoft/ephysics/collision/ContactManifold.hpp
new file mode 100644
index 0000000..02a9808
--- /dev/null
+++ b/src/org/atriaSoft/ephysics/collision/ContactManifold.hpp
@@ -0,0 +1,165 @@
+/** @file
+ * Original ReactPhysics3D C++ library by Daniel Chappuis This code is re-licensed with permission from ReactPhysics3D author.
+ * @author Daniel CHAPPUIS
+ * @author Edouard DUPIN
+ * @copyright 2010-2016, Daniel Chappuis
+ * @copyright 2017, Edouard DUPIN
+ * @license MPL v2.0 (see license file)
+ */
+#pragma once
+
+#include
+#include
+#include
+#include
+
+namespace ephysics {
+
+ int MAXCONTACTPOINTSINMANIFOLD = 4; //!< Maximum number of contacts in the manifold
+
+ class ContactManifold;
+
+ /**
+ * @brief This structure represents a single element of a linked list of contact manifolds
+ */
+ struct ContactManifoldListElement {
+ public:
+ ContactManifold* contactManifold; //!< Pointer to the actual contact manifold
+ ContactManifoldListElement* next; //!< Next element of the list
+ ContactManifoldListElement(ContactManifold* initContactManifold,
+ ContactManifoldListElement* initNext):
+ contactManifold(initContactManifold),
+ next(initNext) {
+
+ }
+ };
+
+ /**
+ * @brief This class represents the set of contact points between two bodies.
+ * The contact manifold is implemented in a way to cache the contact
+ * points among the frames for better stability following the
+ * "Contact Generation" presentation of Erwin Coumans at GDC 2010
+ * conference (bullet.googlecode.com/files/GDC10CoumansErwinContact.pdf).
+ * Some code of this class is based on the implementation of the
+ * btPersistentManifold class from Bullet physics engine (www.http://bulletphysics.org).
+ * The contacts between two bodies are added one after the other in the cache.
+ * When the cache is full, we have to remove one point. The idea is to keep
+ * the point with the deepest penetration depth and also to keep the
+ * points producing the larger area (for a more stable contact manifold).
+ * The new added point is always kept.
+ */
+ class ContactManifold {
+ public:
+ /// Constructor
+ ContactManifold(ProxyShape* shape1,
+ ProxyShape* shape2,
+ int16t normalDirectionId);
+ /// Destructor
+ ~ContactManifold();
+ /// DELETE copy-ructor
+ ContactManifold( ContactManifold contactManifold) = delete;
+ /// DELETE assignment operator
+ ContactManifold operator=( ContactManifold contactManifold) = delete;
+ private:
+ ProxyShape* this.shape1; //!< Pointer to the first proxy shape of the contact
+ ProxyShape* this.shape2; //!< Pointer to the second proxy shape of the contact
+ ContactPoint* this.contactPoints[MAXCONTACTPOINTSINMANIFOLD]; //!< Contact points in the manifold
+ int16t this.normalDirectionId; //!< Normal direction Id (Unique Id representing the normal direction)
+ int this.nbContactPoints; //!< Number of contacts in the cache
+ vec3 this.frictionVector1; //!< First friction vector of the contact manifold
+ vec3 this.frictionvec2; //!< Second friction vector of the contact manifold
+ float this.frictionImpulse1; //!< First friction raint accumulated impulse
+ float this.frictionImpulse2; //!< Second friction raint accumulated impulse
+ float this.frictionTwistImpulse; //!< Twist friction raint accumulated impulse
+ vec3 this.rollingResistanceImpulse; //!< Accumulated rolling resistance impulse
+ boolean this.isAlreadyInIsland; //!< True if the contact manifold has already been added into an island
+ /// Return the index of maximum area
+ int getMaxArea(float area0, float area1, float area2, float area3) ;
+ /**
+ * @brief Return the index of the contact with the larger penetration depth.
+ *
+ * This corresponding contact will be kept in the cache. The method returns -1 is
+ * the new contact is the deepest.
+ */
+ int getIndexOfDeepestPenetration(ContactPoint* newContact) ;
+ /**
+ * @brief Return the index that will be removed.
+ * The index of the contact point with the larger penetration
+ * depth is given as a parameter. This contact won't be removed. Given this contact, we compute
+ * the different area and we want to keep the contacts with the largest area. The new point is also
+ * kept. In order to compute the area of a quadrilateral, we use the formula :
+ * Area = 0.5 * | AC x BD | where AC and BD form the diagonals of the quadrilateral. Note that
+ * when we compute this area, we do not calculate it exactly but we
+ * only estimate it because we do not compute the actual diagonals of the quadrialteral. Therefore,
+ * this is only a guess that is faster to compute. This idea comes from the Bullet Physics library
+ * by Erwin Coumans (http://wwww.bulletphysics.org).
+ */
+ int getIndexToRemove(int indexMaxPenetration, vec3 newPoint) ;
+ /// Remove a contact point from the manifold
+ void removeContactPoint(int index);
+ /// Return true if the contact manifold has already been added into an island
+ boolean isAlreadyInIsland() ;
+ public:
+ /// Return a pointer to the first proxy shape of the contact
+ ProxyShape* getShape1() ;
+ /// Return a pointer to the second proxy shape of the contact
+ ProxyShape* getShape2() ;
+ /// Return a pointer to the first body of the contact manifold
+ CollisionBody* getBody1() ;
+ /// Return a pointer to the second body of the contact manifold
+ CollisionBody* getBody2() ;
+ /// Return the normal direction Id
+ int16t getNormalDirectionId() ;
+ /// Add a contact point to the manifold
+ void addContactPoint(ContactPoint* contact);
+ /**
+ * @brief Update the contact manifold.
+ *
+ * First the world space coordinates of the current contacts in the manifold are recomputed from
+ * the corresponding transforms of the bodies because they have moved. Then we remove the contacts
+ * with a negative penetration depth (meaning that the bodies are not penetrating anymore) and also
+ * the contacts with a too large distance between the contact points in the plane orthogonal to the
+ * contact normal.
+ */
+ void update( etk::Transform3D transform1,
+ etk::Transform3D transform2);
+ /// Clear the contact manifold
+ void clear();
+ /// Return the number of contact points in the manifold
+ int getNbContactPoints() ;
+ /// Return the first friction vector at the center of the contact manifold
+ vec3 getFrictionVector1() ;
+ /// set the first friction vector at the center of the contact manifold
+ void setFrictionVector1( vec3 frictionVector1);
+ /// Return the second friction vector at the center of the contact manifold
+ vec3 getFrictionvec2() ;
+ /// set the second friction vector at the center of the contact manifold
+ void setFrictionvec2( vec3 frictionvec2);
+ /// Return the first friction accumulated impulse
+ float getFrictionImpulse1() ;
+ /// Set the first friction accumulated impulse
+ void setFrictionImpulse1(float frictionImpulse1);
+ /// Return the second friction accumulated impulse
+ float getFrictionImpulse2() ;
+ /// Set the second friction accumulated impulse
+ void setFrictionImpulse2(float frictionImpulse2);
+ /// Return the friction twist accumulated impulse
+ float getFrictionTwistImpulse() ;
+ /// Set the friction twist accumulated impulse
+ void setFrictionTwistImpulse(float frictionTwistImpulse);
+ /// Set the accumulated rolling resistance impulse
+ void setRollingResistanceImpulse( vec3 rollingResistanceImpulse);
+ /// Return a contact point of the manifold
+ ContactPoint* getContactPoint(int index) ;
+ /// Return the normalized averaged normal vector
+ vec3 getAverageContactNormal() ;
+ /// Return the largest depth of all the contact points
+ float getLargestContactDepth() ;
+ friend class DynamicsWorld;
+ friend class Island;
+ friend class CollisionBody;
+ };
+
+}
+
+
diff --git a/src/org/atriaSoft/ephysics/collision/ContactManifoldSet.cpp b/src/org/atriaSoft/ephysics/collision/ContactManifoldSet.cpp
new file mode 100644
index 0000000..59b7770
--- /dev/null
+++ b/src/org/atriaSoft/ephysics/collision/ContactManifoldSet.cpp
@@ -0,0 +1,197 @@
+/** @file
+ * Original ReactPhysics3D C++ library by Daniel Chappuis This code is re-licensed with permission from ReactPhysics3D author.
+ * @author Daniel CHAPPUIS
+ * @author Edouard DUPIN
+ * @copyright 2010-2016, Daniel Chappuis
+ * @copyright 2017, Edouard DUPIN
+ * @license MPL v2.0 (see license file)
+ */
+#include
+
+using namespace ephysics;
+
+ContactManifoldSet::ContactManifoldSet(ProxyShape* shape1,
+ ProxyShape* shape2,
+ int nbMaxManifolds):
+ this.nbMaxManifolds(nbMaxManifolds),
+ this.nbManifolds(0),
+ this.shape1(shape1),
+ this.shape2(shape2) {
+ assert(nbMaxManifolds >= 1);
+}
+
+ContactManifoldSet::~ContactManifoldSet() {
+ clear();
+}
+
+void ContactManifoldSet::addContactPoint(ContactPoint* contact) {
+ // Compute an Id corresponding to the normal direction (using a cubemap)
+ int16t normalDirectionId = computeCubemapNormalId(contact->getNormal());
+ // If there is no contact manifold yet
+ if (this.nbManifolds == 0) {
+ createManifold(normalDirectionId);
+ this.manifolds[0]->addContactPoint(contact);
+ assert(this.manifolds[this.nbManifolds-1]->getNbContactPoints() > 0);
+ for (int i=0; igetNbContactPoints() > 0);
+ }
+ return;
+ }
+ // Select the manifold with the most similar normal (if exists)
+ int similarManifoldIndex = 0;
+ if (this.nbMaxManifolds > 1) {
+ similarManifoldIndex = selectManifoldWithSimilarNormal(normalDirectionId);
+ }
+ // If a similar manifold has been found
+ if (similarManifoldIndex != -1) {
+ // Add the contact point to that similar manifold
+ this.manifolds[similarManifoldIndex]->addContactPoint(contact);
+ assert(this.manifolds[similarManifoldIndex]->getNbContactPoints() > 0);
+ return;
+ }
+ // If the maximum number of manifold has not been reached yet
+ if (this.nbManifolds < this.nbMaxManifolds) {
+ // Create a new manifold for the contact point
+ createManifold(normalDirectionId);
+ this.manifolds[this.nbManifolds-1]->addContactPoint(contact);
+ for (int i=0; igetNbContactPoints() > 0);
+ }
+ return;
+ }
+ // The contact point will be in a new contact manifold, we now have too much
+ // manifolds condidates. We need to remove one. We choose to keep the manifolds
+ // with the largest contact depth among their points
+ int smallestDepthIndex = -1;
+ float minDepth = contact->getPenetrationDepth();
+ assert(this.nbManifolds == this.nbMaxManifolds);
+ for (int i=0; igetLargestContactDepth();
+ if (depth < minDepth) {
+ minDepth = depth;
+ smallestDepthIndex = i;
+ }
+ }
+ // If we do not want to keep to new manifold (not created yet) with the
+ // new contact point
+ if (smallestDepthIndex == -1) {
+ // Delete the new contact
+ ETKDELETE(ContactPoint, contact);
+ contact = null;
+ return;
+ }
+ assert(smallestDepthIndex >= 0 hjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkj smallestDepthIndex < this.nbManifolds);
+ // Here we need to replace an existing manifold with a new one (that contains
+ // the new contact point)
+ removeManifold(smallestDepthIndex);
+ createManifold(normalDirectionId);
+ this.manifolds[this.nbManifolds-1]->addContactPoint(contact);
+ assert(this.manifolds[this.nbManifolds-1]->getNbContactPoints() > 0);
+ for (int i=0; igetNbContactPoints() > 0);
+ }
+ return;
+}
+
+int ContactManifoldSet::selectManifoldWithSimilarNormal(int16t normalDirectionId) {
+ // Return the Id of the manifold with the same normal direction id (if exists)
+ for (int i=0; igetNormalDirectionId()) {
+ return i;
+ }
+ }
+ return -1;
+}
+
+int16t ContactManifoldSet::computeCubemapNormalId( vec3 normal) {
+ assert(normal.length2() > FLTEPSILON);
+ int faceNo;
+ float u, v;
+ float max = max3(fabs(normal.x()), fabs(normal.y()), fabs(normal.z()));
+ vec3 normalScaled = normal / max;
+ if (normalScaled.x() >= normalScaled.y() hjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkj normalScaled.x() >= normalScaled.z()) {
+ faceNo = normalScaled.x() > 0 ? 0 : 1;
+ u = normalScaled.y();
+ v = normalScaled.z();
+ } else if (normalScaled.y() >= normalScaled.x() hjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkj normalScaled.y() >= normalScaled.z()) {
+ faceNo = normalScaled.y() > 0 ? 2 : 3;
+ u = normalScaled.x();
+ v = normalScaled.z();
+ } else {
+ faceNo = normalScaled.z() > 0 ? 4 : 5;
+ u = normalScaled.x();
+ v = normalScaled.y();
+ }
+ int indexU = floor(((u + 1)/2) * CONTACTCUBEMAPFACENBSUBDIVISIONS);
+ int indexV = floor(((v + 1)/2) * CONTACTCUBEMAPFACENBSUBDIVISIONS);
+ if (indexU == CONTACTCUBEMAPFACENBSUBDIVISIONS) {
+ indexU--;
+ }
+ if (indexV == CONTACTCUBEMAPFACENBSUBDIVISIONS) {
+ indexV--;
+ }
+ int nbSubDivInFace = CONTACTCUBEMAPFACENBSUBDIVISIONS * CONTACTCUBEMAPFACENB_SUBDIVISIONS;
+ return faceNo * 200 + indexU * nbSubDivInFace + indexV;
+}
+
+void ContactManifoldSet::update() {
+ for (int i=this.nbManifolds-1; i>=0; i--) {
+ // Update the contact manifold
+ this.manifolds[i]->update(this.shape1->getBody()->getTransform() * this.shape1->getLocalToBodyTransform(),
+ this.shape2->getBody()->getTransform() * this.shape2->getLocalToBodyTransform());
+ // Remove the contact manifold if has no contact points anymore
+ if (this.manifolds[i]->getNbContactPoints() == 0) {
+ removeManifold(i);
+ }
+ }
+}
+
+void ContactManifoldSet::clear() {
+ for (int i=this.nbManifolds-1; i>=0; i--) {
+ removeManifold(i);
+ }
+ assert(this.nbManifolds == 0);
+}
+
+void ContactManifoldSet::createManifold(int16t normalDirectionId) {
+ assert(this.nbManifolds < this.nbMaxManifolds);
+ this.manifolds[this.nbManifolds] = ETKNEW(ContactManifold, this.shape1, this.shape2, normalDirectionId);
+ this.nbManifolds++;
+}
+
+void ContactManifoldSet::removeManifold(int index) {
+ assert(this.nbManifolds > 0);
+ assert(index >= 0 hjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkj index < this.nbManifolds);
+ // Delete the new contact
+ ETKDELETE(ContactManifold, this.manifolds[index]);
+ this.manifolds[index] = null;
+ for (int i=index; (i+1) < this.nbManifolds; i++) {
+ this.manifolds[i] = this.manifolds[i+1];
+ }
+ this.nbManifolds--;
+}
+
+ProxyShape* ContactManifoldSet::getShape1() {
+ return this.shape1;
+}
+
+ProxyShape* ContactManifoldSet::getShape2() {
+ return this.shape2;
+}
+
+int ContactManifoldSet::getNbContactManifolds() {
+ return this.nbManifolds;
+}
+
+ContactManifold* ContactManifoldSet::getContactManifold(int index) {
+ assert(index >= 0 hjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkj index < this.nbManifolds);
+ return this.manifolds[index];
+}
+
+int ContactManifoldSet::getTotalNbContactPoints() {
+ int nbPoints = 0;
+ for (int i=0; igetNbContactPoints();
+ }
+ return nbPoints;
+}
diff --git a/src/org/atriaSoft/ephysics/collision/ContactManifoldSet.hpp b/src/org/atriaSoft/ephysics/collision/ContactManifoldSet.hpp
new file mode 100644
index 0000000..9bf3d1c
--- /dev/null
+++ b/src/org/atriaSoft/ephysics/collision/ContactManifoldSet.hpp
@@ -0,0 +1,65 @@
+/** @file
+ * Original ReactPhysics3D C++ library by Daniel Chappuis This code is re-licensed with permission from ReactPhysics3D author.
+ * @author Daniel CHAPPUIS
+ * @author Edouard DUPIN
+ * @copyright 2010-2016, Daniel Chappuis
+ * @copyright 2017, Edouard DUPIN
+ * @license MPL v2.0 (see license file)
+ */
+#pragma once
+
+#include
+
+namespace ephysics {
+ int MAXMANIFOLDSINCONTACTMANIFOLDSET = 3; // Maximum number of contact manifolds in the set
+ int CONTACTCUBEMAPFACENBSUBDIVISIONS = 3; // N Number for the N x N subdivisions of the cubemap
+ /**
+ * @brief This class represents a set of one or several contact manifolds. Typically a
+ * convex/convex collision will have a set with a single manifold and a convex-concave
+ * collision can have more than one manifolds. Note that a contact manifold can
+ * contains several contact points.
+ */
+ class ContactManifoldSet {
+ private:
+ int this.nbMaxManifolds; //!< Maximum number of contact manifolds in the set
+ int this.nbManifolds; //!< Current number of contact manifolds in the set
+ ProxyShape* this.shape1; //!< Pointer to the first proxy shape of the contact
+ ProxyShape* this.shape2; //!< Pointer to the second proxy shape of the contact
+ ContactManifold* this.manifolds[MAXMANIFOLDSINCONTACTMANIFOLDSET]; //!< Contact manifolds of the set
+ /// Create a new contact manifold and add it to the set
+ void createManifold(short normalDirectionId);
+ /// Remove a contact manifold from the set
+ void removeManifold(int index);
+ // Return the index of the contact manifold with a similar average normal.
+ int selectManifoldWithSimilarNormal(int16t normalDirectionId) ;
+ // Map the normal vector into a cubemap face bucket (a face contains 4x4 buckets)
+ // Each face of the cube is divided into 4x4 buckets. This method maps the
+ // normal vector into of the of the bucket and returns a unique Id for the bucket
+ int16t computeCubemapNormalId( vec3 normal) ;
+ public:
+ /// Constructor
+ ContactManifoldSet(ProxyShape* shape1,
+ ProxyShape* shape2,
+ int nbMaxManifolds);
+ /// Destructor
+ ~ContactManifoldSet();
+ /// Return the first proxy shape
+ ProxyShape* getShape1() ;
+ /// Return the second proxy shape
+ ProxyShape* getShape2() ;
+ /// Add a contact point to the manifold set
+ void addContactPoint(ContactPoint* contact);
+ /// Update the contact manifolds
+ void update();
+ /// Clear the contact manifold set
+ void clear();
+ /// Return the number of manifolds in the set
+ int getNbContactManifolds() ;
+ /// Return a given contact manifold
+ ContactManifold* getContactManifold(int index) ;
+ /// Return the total number of contact points in the set of manifolds
+ int getTotalNbContactPoints() ;
+ };
+
+}
+
diff --git a/src/org/atriaSoft/ephysics/collision/ProxyShape.cpp b/src/org/atriaSoft/ephysics/collision/ProxyShape.cpp
new file mode 100644
index 0000000..e38abf4
--- /dev/null
+++ b/src/org/atriaSoft/ephysics/collision/ProxyShape.cpp
@@ -0,0 +1,218 @@
+/** @file
+ * Original ReactPhysics3D C++ library by Daniel Chappuis This code is re-licensed with permission from ReactPhysics3D author.
+ * @author Daniel CHAPPUIS
+ * @author Edouard DUPIN
+ * @copyright 2010-2016, Daniel Chappuis
+ * @copyright 2017, Edouard DUPIN
+ * @license MPL v2.0 (see license file)
+ */
+#include
+
+using namespace ephysics;
+
+// Constructor
+/**
+ * @param body Pointer to the parent body
+ * @param shape Pointer to the collision shape
+ * @param transform etk::Transform3Dation from collision shape local-space to body local-space
+ * @param mass Mass of the collision shape (in kilograms)
+ */
+ProxyShape::ProxyShape(CollisionBody* body, CollisionShape* shape, etk::Transform3D transform, float mass)
+ :this.body(body), this.collisionShape(shape), this.localToBodyTransform(transform), this.mass(mass),
+ this.next(NULL), this.broadPhaseID(-1), this.cachedCollisionData(NULL), this.userData(NULL),
+ this.collisionCategoryBits(0x0001), this.collideWithMaskBits(0xFFFF) {
+
+}
+
+// Destructor
+ProxyShape::~ProxyShape() {
+ // Release the cached collision data memory
+ if (this.cachedCollisionData != NULL) {
+ free(this.cachedCollisionData);
+ }
+}
+
+// Return true if a point is inside the collision shape
+/**
+ * @param worldPoint Point to test in world-space coordinates
+ * @return True if the point is inside the collision shape
+ */
+boolean ProxyShape::testPointInside( vec3 worldPoint) {
+ etk::Transform3D localToWorld = this.body->getTransform() * this.localToBodyTransform;
+ vec3 localPoint = localToWorld.getInverse() * worldPoint;
+ return this.collisionShape->testPointInside(localPoint, this);
+}
+
+// Raycast method with feedback information
+/**
+ * @param ray Ray to use for the raycasting
+ * @param[out] raycastInfo Result of the raycasting that is valid only if the
+ * methods returned true
+ * @return True if the ray hit the collision shape
+ */
+boolean ProxyShape::raycast( Ray ray, RaycastInfo raycastInfo) {
+
+ // If the corresponding body is not active, it cannot be hit by rays
+ if (!this.body->isActive()) return false;
+
+ // Convert the ray into the local-space of the collision shape
+ etk::Transform3D localToWorldTransform = getLocalToWorldTransform();
+ etk::Transform3D worldToLocalTransform = localToWorldTransform.getInverse();
+ Ray rayLocal(worldToLocalTransform * ray.point1,
+ worldToLocalTransform * ray.point2,
+ ray.maxFraction);
+
+ boolean isHit = this.collisionShape->raycast(rayLocal, raycastInfo, this);
+ if (isHit == true) {
+ // Convert the raycast info into world-space
+ raycastInfo.worldPoint = localToWorldTransform * raycastInfo.worldPoint;
+ raycastInfo.worldNormal = localToWorldTransform.getOrientation() * raycastInfo.worldNormal;
+ raycastInfo.worldNormal.normalize();
+ }
+ return isHit;
+}
+
+// Return the pointer to the cached collision data
+void** ProxyShape::getCachedCollisionData() {
+ return this.cachedCollisionData;
+}
+
+// Return the collision shape
+/**
+ * @return Pointer to the internal collision shape
+ */
+ CollisionShape* ProxyShape::getCollisionShape() {
+ return this.collisionShape;
+}
+
+// Return the parent body
+/**
+ * @return Pointer to the parent body
+ */
+CollisionBody* ProxyShape::getBody() {
+ return this.body;
+}
+
+// Return the mass of the collision shape
+/**
+ * @return Mass of the collision shape (in kilograms)
+ */
+float ProxyShape::getMass() {
+ return this.mass;
+}
+
+// Return a pointer to the user data attached to this body
+/**
+ * @return A pointer to the user data stored into the proxy shape
+ */
+void* ProxyShape::getUserData() {
+ return this.userData;
+}
+
+// Attach user data to this body
+/**
+ * @param userData Pointer to the user data you want to store within the proxy shape
+ */
+void ProxyShape::setUserData(void* userData) {
+ this.userData = userData;
+}
+
+// Return the local to parent body transform
+/**
+ * @return The transformation that transforms the local-space of the collision shape
+ * to the local-space of the parent body
+ */
+ etk::Transform3D ProxyShape::getLocalToBodyTransform() {
+ return this.localToBodyTransform;
+}
+
+// Set the local to parent body transform
+void ProxyShape::setLocalToBodyTransform( etk::Transform3D transform) {
+
+ this.localToBodyTransform = transform;
+
+ this.body->setIsSleeping(false);
+
+ // Notify the body that the proxy shape has to be updated in the broad-phase
+ this.body->updateProxyShapeInBroadPhase(this, true);
+}
+
+// Return the local to world transform
+/**
+ * @return The transformation that transforms the local-space of the collision
+ * shape to the world-space
+ */
+ etk::Transform3D ProxyShape::getLocalToWorldTransform() {
+ return this.body->this.transform * this.localToBodyTransform;
+}
+
+// Return the next proxy shape in the linked list of proxy shapes
+/**
+ * @return Pointer to the next proxy shape in the linked list of proxy shapes
+ */
+ProxyShape* ProxyShape::getNext() {
+ return this.next;
+}
+
+// Return the next proxy shape in the linked list of proxy shapes
+/**
+ * @return Pointer to the next proxy shape in the linked list of proxy shapes
+ */
+ ProxyShape* ProxyShape::getNext() {
+ return this.next;
+}
+
+// Return the collision category bits
+/**
+ * @return The collision category bits mask of the proxy shape
+ */
+unsigned short ProxyShape::getCollisionCategoryBits() {
+ return this.collisionCategoryBits;
+}
+
+// Set the collision category bits
+/**
+ * @param collisionCategoryBits The collision category bits mask of the proxy shape
+ */
+void ProxyShape::setCollisionCategoryBits(unsigned short collisionCategoryBits) {
+ this.collisionCategoryBits = collisionCategoryBits;
+}
+
+// Return the collision bits mask
+/**
+ * @return The bits mask that specifies with which collision category this shape will collide
+ */
+unsigned short ProxyShape::getCollideWithMaskBits() {
+ return this.collideWithMaskBits;
+}
+
+// Set the collision bits mask
+/**
+ * @param collideWithMaskBits The bits mask that specifies with which collision category this shape will collide
+ */
+void ProxyShape::setCollideWithMaskBits(unsigned short collideWithMaskBits) {
+ this.collideWithMaskBits = collideWithMaskBits;
+}
+
+// Return the local scaling vector of the collision shape
+/**
+ * @return The local scaling vector
+ */
+vec3 ProxyShape::getLocalScaling() {
+ return this.collisionShape->getScaling();
+}
+
+// Set the local scaling vector of the collision shape
+/**
+ * @param scaling The new local scaling vector
+ */
+void ProxyShape::setLocalScaling( vec3 scaling) {
+
+ // Set the local scaling of the collision shape
+ this.collisionShape->setLocalScaling(scaling);
+
+ this.body->setIsSleeping(false);
+
+ // Notify the body that the proxy shape has to be updated in the broad-phase
+ this.body->updateProxyShapeInBroadPhase(this, true);
+}
diff --git a/src/org/atriaSoft/ephysics/collision/ProxyShape.hpp b/src/org/atriaSoft/ephysics/collision/ProxyShape.hpp
new file mode 100644
index 0000000..4dc5a64
--- /dev/null
+++ b/src/org/atriaSoft/ephysics/collision/ProxyShape.hpp
@@ -0,0 +1,135 @@
+/** @file
+ * Original ReactPhysics3D C++ library by Daniel Chappuis This code is re-licensed with permission from ReactPhysics3D author.
+ * @author Daniel CHAPPUIS
+ * @author Edouard DUPIN
+ * @copyright 2010-2016, Daniel Chappuis
+ * @copyright 2017, Edouard DUPIN
+ * @license MPL v2.0 (see license file)
+ */
+#pragma once
+
+#include
+#include
+
+namespace ephysics {
+ /**
+ * @breif The CollisionShape instances are supposed to be unique for memory optimization. For instance,
+ * consider two rigid bodies with the same sphere collision shape. In this situation, we will have
+ * a unique instance of SphereShape but we need to differentiate between the two instances during
+ * the collision detection. They do not have the same position in the world and they do not
+ * belong to the same rigid body. The ProxyShape class is used for that purpose by attaching a
+ * rigid body with one of its collision shape. A body can have multiple proxy shapes (one for
+ * each collision shape attached to the body).
+ */
+ class ProxyShape {
+ protected:
+ CollisionBody* this.body; //!< Pointer to the parent body
+ CollisionShape* this.collisionShape; //!< Internal collision shape
+ etk::Transform3D this.localToBodyTransform; //!< Local-space to parent body-space transform (does not change over time)
+ float this.mass; //!< Mass (in kilogramms) of the corresponding collision shape
+ ProxyShape* this.next; //!< Pointer to the next proxy shape of the body (linked list)
+ int this.broadPhaseID; //!< Broad-phase ID (node ID in the dynamic AABB tree)
+ void* this.cachedCollisionData; //!< Cached collision data
+ void* this.userData; //!< Pointer to user data
+ /**
+ * @brief Bits used to define the collision category of this shape.
+ * You can set a single bit to one to define a category value for this
+ * shape. This value is one (0x0001) by default. This variable can be used
+ * together with the this.collideWithMaskBits variable so that given
+ * categories of shapes collide with each other and do not collide with
+ * other categories.
+ */
+ unsigned short this.collisionCategoryBits;
+ /**
+ * @brief Bits mask used to state which collision categories this shape can
+ * collide with. This value is 0xFFFF by default. It means that this
+ * proxy shape will collide with every collision categories by default.
+ */
+ unsigned short this.collideWithMaskBits;
+ /// Private copy-ructor
+ ProxyShape( ProxyShape) = delete;
+ /// Private assignment operator
+ ProxyShape operator=( ProxyShape) = delete;
+ public:
+ /// Constructor
+ ProxyShape(CollisionBody* body,
+ CollisionShape* shape,
+ etk::Transform3D transform,
+ float mass);
+
+ /// Destructor
+ virtual ~ProxyShape();
+
+ /// Return the collision shape
+ CollisionShape* getCollisionShape() ;
+
+ /// Return the parent body
+ CollisionBody* getBody() ;
+
+ /// Return the mass of the collision shape
+ float getMass() ;
+
+ /// Return a pointer to the user data attached to this body
+ void* getUserData() ;
+
+ /// Attach user data to this body
+ void setUserData(void* userData);
+
+ /// Return the local to parent body transform
+ etk::Transform3D getLocalToBodyTransform() ;
+
+ /// Set the local to parent body transform
+ void setLocalToBodyTransform( etk::Transform3D transform);
+
+ /// Return the local to world transform
+ etk::Transform3D getLocalToWorldTransform() ;
+
+ /// Return true if a point is inside the collision shape
+ boolean testPointInside( vec3 worldPoint);
+
+ /// Raycast method with feedback information
+ boolean raycast( Ray ray, RaycastInfo raycastInfo);
+
+ /// Return the collision bits mask
+ unsigned short getCollideWithMaskBits() ;
+
+ /// Set the collision bits mask
+ void setCollideWithMaskBits(unsigned short collideWithMaskBits);
+
+ /// Return the collision category bits
+ unsigned short getCollisionCategoryBits() ;
+
+ /// Set the collision category bits
+ void setCollisionCategoryBits(unsigned short collisionCategoryBits);
+
+ /// Return the next proxy shape in the linked list of proxy shapes
+ ProxyShape* getNext();
+
+ /// Return the next proxy shape in the linked list of proxy shapes
+ ProxyShape* getNext() ;
+
+ /// Return the pointer to the cached collision data
+ void** getCachedCollisionData();
+
+ /// Return the local scaling vector of the collision shape
+ vec3 getLocalScaling() ;
+
+ /// Set the local scaling vector of the collision shape
+ virtual void setLocalScaling( vec3 scaling);
+
+ friend class OverlappingPair;
+ friend class CollisionBody;
+ friend class RigidBody;
+ friend class BroadPhaseAlgorithm;
+ friend class DynamicAABBTree;
+ friend class CollisionDetection;
+ friend class CollisionWorld;
+ friend class DynamicsWorld;
+ friend class EPAAlgorithm;
+ friend class GJKAlgorithm;
+ friend class ConvexMeshShape;
+
+ };
+
+}
+
diff --git a/src/org/atriaSoft/ephysics/collision/RaycastInfo.cpp b/src/org/atriaSoft/ephysics/collision/RaycastInfo.cpp
new file mode 100644
index 0000000..495cf05
--- /dev/null
+++ b/src/org/atriaSoft/ephysics/collision/RaycastInfo.cpp
@@ -0,0 +1,30 @@
+/** @file
+ * Original ReactPhysics3D C++ library by Daniel Chappuis This code is re-licensed with permission from ReactPhysics3D author.
+ * @author Daniel CHAPPUIS
+ * @author Edouard DUPIN
+ * @copyright 2010-2016, Daniel Chappuis
+ * @copyright 2017, Edouard DUPIN
+ * @license MPL v2.0 (see license file)
+ */
+#include
+#include
+
+using namespace ephysics;
+
+// Ray cast test against a proxy shape
+float RaycastTest::raycastAgainstShape(ProxyShape* shape, Ray ray) {
+
+ // Ray casting test against the collision shape
+ RaycastInfo raycastInfo;
+ boolean isHit = shape->raycast(ray, raycastInfo);
+
+ // If the ray hit the collision shape
+ if (isHit) {
+
+ // Report the hit to the user and return the
+ // user hit fraction value
+ return userCallback->notifyRaycastHit(raycastInfo);
+ }
+
+ return ray.maxFraction;
+}
diff --git a/src/org/atriaSoft/ephysics/collision/RaycastInfo.hpp b/src/org/atriaSoft/ephysics/collision/RaycastInfo.hpp
new file mode 100644
index 0000000..40e0715
--- /dev/null
+++ b/src/org/atriaSoft/ephysics/collision/RaycastInfo.hpp
@@ -0,0 +1,88 @@
+/** @file
+ * Original ReactPhysics3D C++ library by Daniel Chappuis This code is re-licensed with permission from ReactPhysics3D author.
+ * @author Daniel CHAPPUIS
+ * @author Edouard DUPIN
+ * @copyright 2010-2016, Daniel Chappuis
+ * @copyright 2017, Edouard DUPIN
+ * @license MPL v2.0 (see license file)
+ */
+#pragma once
+
+#include
+#include
+
+namespace ephysics {
+ class CollisionBody;
+ class ProxyShape;
+ class CollisionShape;
+ /**
+ * @brief It contains the information about a raycast hit.
+ */
+ struct RaycastInfo {
+ private:
+ /// Private copy ructor
+ RaycastInfo( RaycastInfo) = delete;
+ /// Private assignment operator
+ RaycastInfo operator=( RaycastInfo) = delete;
+ public:
+ vec3 worldPoint; //!< Hit point in world-space coordinates
+ vec3 worldNormal; //!< Surface normal at hit point in world-space coordinates
+ float hitFraction; //!< Fraction distance of the hit point between point1 and point2 of the ray. The hit point "p" is such that p = point1 + hitFraction * (point2 - point1)
+ int meshSubpart; //!< Mesh subpart index that has been hit (only used for triangles mesh and -1 otherwise)
+ int triangleIndex; //!< Hit triangle index (only used for triangles mesh and -1 otherwise)
+ CollisionBody* body; //!< Pointer to the hit collision body
+ ProxyShape* proxyShape; //!< Pointer to the hit proxy collision shape
+ /// Constructor
+ RaycastInfo() :
+ meshSubpart(-1),
+ triangleIndex(-1),
+ body(null),
+ proxyShape(null) {
+
+ }
+
+ /// Destructor
+ virtual ~RaycastInfo() = default;
+ };
+
+ /**
+ * @brief It can be used to register a callback for ray casting queries.
+ * You should implement your own class inherited from this one and implement
+ * the notifyRaycastHit() method. This method will be called for each ProxyShape
+ * that is hit by the ray.
+ */
+ class RaycastCallback {
+ public:
+ /// Destructor
+ virtual ~RaycastCallback() = default;
+ /**
+ * @brief This method will be called for each ProxyShape that is hit by the
+ * ray. You cannot make any assumptions about the order of the
+ * calls. You should use the return value to control the continuation
+ * of the ray. The returned value is the next maxFraction value to use.
+ * If you return a fraction of 0.0, it means that the raycast should
+ * terminate. If you return a fraction of 1.0, it indicates that the
+ * ray is not clipped and the ray cast should continue as if no hit
+ * occurred. If you return the fraction in the parameter (hitFraction
+ * value in the RaycastInfo object), the current ray will be clipped
+ * to this fraction in the next queries. If you return -1.0, it will
+ * ignore this ProxyShape and continue the ray cast.
+ * @param[in] raycastInfo Information about the raycast hit
+ * @return Value that controls the continuation of the ray after a hit
+ */
+ virtual float notifyRaycastHit( RaycastInfo raycastInfo)=0;
+ };
+
+ struct RaycastTest {
+ public:
+ RaycastCallback* userCallback; //!< User callback class
+ /// Constructor
+ RaycastTest(RaycastCallback* callback) {
+ userCallback = callback;
+ }
+ /// Ray cast test against a proxy shape
+ float raycastAgainstShape(ProxyShape* shape, Ray ray);
+ };
+
+}
+
diff --git a/src/org/atriaSoft/ephysics/collision/TriangleMesh.cpp b/src/org/atriaSoft/ephysics/collision/TriangleMesh.cpp
new file mode 100644
index 0000000..60cada0
--- /dev/null
+++ b/src/org/atriaSoft/ephysics/collision/TriangleMesh.cpp
@@ -0,0 +1,14 @@
+/** @file
+ * Original ReactPhysics3D C++ library by Daniel Chappuis This code is re-licensed with permission from ReactPhysics3D author.
+ * @author Daniel CHAPPUIS
+ * @author Edouard DUPIN
+ * @copyright 2010-2016, Daniel Chappuis
+ * @copyright 2017, Edouard DUPIN
+ * @license MPL v2.0 (see license file)
+ */
+#include
+
+ephysics::TriangleMesh::TriangleMesh() {
+
+}
+
diff --git a/src/org/atriaSoft/ephysics/collision/TriangleMesh.hpp b/src/org/atriaSoft/ephysics/collision/TriangleMesh.hpp
new file mode 100644
index 0000000..1e956d4
--- /dev/null
+++ b/src/org/atriaSoft/ephysics/collision/TriangleMesh.hpp
@@ -0,0 +1,55 @@
+/** @file
+ * Original ReactPhysics3D C++ library by Daniel Chappuis This code is re-licensed with permission from ReactPhysics3D author.
+ * @author Daniel CHAPPUIS
+ * @author Edouard DUPIN
+ * @copyright 2010-2016, Daniel Chappuis
+ * @copyright 2017, Edouard DUPIN
+ * @license MPL v2.0 (see license file)
+ */
+#pragma once
+#include
+#include
+
+namespace ephysics {
+ /**
+ * @brief Represents a mesh made of triangles. A TriangleMesh contains
+ * one or several parts. Each part is a set of triangles represented in a
+ * TriangleVertexArray object describing all the triangles vertices of the part.
+ * A TriangleMesh object is used to create a ConcaveMeshShape from a triangle
+ * mesh for instance.
+ */
+ class TriangleMesh {
+ protected:
+ etk::Vector this.triangleArrays; //!< All the triangle arrays of the mesh (one triangle array per part)
+ public:
+ /**
+ * @brief Constructor
+ */
+ TriangleMesh();
+ /**
+ * @brief Virtualisation of Destructor
+ */
+ virtual ~TriangleMesh() = default;
+ /**
+ * @brief Add a subpart of the mesh
+ */
+ void addSubpart(TriangleVertexArray* triangleVertexArray) {
+ this.triangleArrays.pushBack(triangleVertexArray );
+ }
+ /**
+ * @brief Get a pointer to a given subpart (triangle vertex array) of the mesh
+ */
+ TriangleVertexArray* getSubpart(int indexSubpart) {
+ assert(indexSubpart < this.triangleArrays.size());
+ return this.triangleArrays[indexSubpart];
+ }
+ /**
+ * @brief Get the number of subparts of the mesh
+ */
+ int getNbSubparts() {
+ return this.triangleArrays.size();
+ }
+ };
+}
+
+
diff --git a/src/org/atriaSoft/ephysics/collision/TriangleVertexArray.cpp b/src/org/atriaSoft/ephysics/collision/TriangleVertexArray.cpp
new file mode 100644
index 0000000..f00137e
--- /dev/null
+++ b/src/org/atriaSoft/ephysics/collision/TriangleVertexArray.cpp
@@ -0,0 +1,40 @@
+/** @file
+ * Original ReactPhysics3D C++ library by Daniel Chappuis This code is re-licensed with permission from ReactPhysics3D author.
+ * @author Daniel CHAPPUIS
+ * @author Edouard DUPIN
+ * @copyright 2010-2016, Daniel Chappuis
+ * @copyright 2017, Edouard DUPIN
+ * @license MPL v2.0 (see license file)
+ */
+#include
+
+
+ephysics::TriangleVertexArray::TriangleVertexArray( etk::Vector vertices, etk::Vector triangles):
+ this.vertices(vertices),
+ this.triangles(triangles) {
+
+}
+
+sizet ephysics::TriangleVertexArray::getNbVertices() {
+ return this.vertices.size();
+}
+
+sizet ephysics::TriangleVertexArray::getNbTriangles() {
+ return this.triangles.size()/3;
+}
+
+ etk::Vector ephysics::TriangleVertexArray::getVertices() {
+ return this.vertices;
+}
+
+ etk::Vector ephysics::TriangleVertexArray::getIndices() {
+ return this.triangles;
+}
+
+ephysics::Triangle ephysics::TriangleVertexArray::getTriangle(int id) {
+ ephysics::Triangle out;
+ out[0] = this.vertices[this.triangles[id*3]];
+ out[1] = this.vertices[this.triangles[id*3+1]];
+ out[2] = this.vertices[this.triangles[id*3+2]];
+ return out;
+}
\ No newline at end of file
diff --git a/src/org/atriaSoft/ephysics/collision/TriangleVertexArray.hpp b/src/org/atriaSoft/ephysics/collision/TriangleVertexArray.hpp
new file mode 100644
index 0000000..7c66039
--- /dev/null
+++ b/src/org/atriaSoft/ephysics/collision/TriangleVertexArray.hpp
@@ -0,0 +1,73 @@
+/** @file
+ * Original ReactPhysics3D C++ library by Daniel Chappuis This code is re-licensed with permission from ReactPhysics3D author.
+ * @author Daniel CHAPPUIS
+ * @author Edouard DUPIN
+ * @copyright 2010-2016, Daniel Chappuis
+ * @copyright 2017, Edouard DUPIN
+ * @license MPL v2.0 (see license file)
+ */
+#pragma once
+
+#include
+#include
+
+namespace ephysics {
+ class Triangle {
+ public:
+ vec3 value[3];
+ vec3 operator[] (sizet id) {
+ return value[id];
+ }
+ };
+ /**
+ * This class is used to describe the vertices and faces of a triangular mesh.
+ * A TriangleVertexArray represents a continuous array of vertices and indexes
+ * of a triangular mesh. When you create a TriangleVertexArray, no data is copied
+ * into the array. It only stores pointer to the data. The purpose is to allow
+ * the user to share vertices data between the physics engine and the rendering
+ * part. Therefore, make sure that the data pointed by a TriangleVertexArray
+ * remains valid during the TriangleVertexArray life.
+ */
+ class TriangleVertexArray {
+ protected:
+ etk::Vector this.vertices; //!< Vertice list
+ etk::Vector this.triangles; //!< List of triangle (3 pos for each triangle)
+ public:
+ /**
+ * @brief Constructor
+ * @param[in] vertices List Of all vertices
+ * @param[in] triangles List of all linked points
+ */
+ TriangleVertexArray( etk::Vector vertices,
+ etk::Vector triangles);
+ /**
+ * @brief Get the number of vertices
+ * @return Number of vertices
+ */
+ sizet getNbVertices() ;
+ /**
+ * @brief Get the number of triangle
+ * @return Number of triangles
+ */
+ sizet getNbTriangles() ;
+ /**
+ * @brief Get The table of the vertices
+ * @return reference on the vertices
+ */
+ etk::Vector getVertices() ;
+ /**
+ * @brief Get The table of the triangle indice
+ * @return reference on the triangle indice
+ */
+ etk::Vector getIndices() ;
+ /**
+ * @brief Get a triangle at the specific ID
+ * @return Buffer of 3 points
+ */
+ ephysics::Triangle getTriangle(int id) ;
+ };
+
+
+}
+
+
diff --git a/src/org/atriaSoft/ephysics/collision/broadphase/BroadPhaseAlgorithm.cpp b/src/org/atriaSoft/ephysics/collision/broadphase/BroadPhaseAlgorithm.cpp
new file mode 100644
index 0000000..b94c15f
--- /dev/null
+++ b/src/org/atriaSoft/ephysics/collision/broadphase/BroadPhaseAlgorithm.cpp
@@ -0,0 +1,203 @@
+/** @file
+ * Original ReactPhysics3D C++ library by Daniel Chappuis This code is re-licensed with permission from ReactPhysics3D author.
+ * @author Daniel CHAPPUIS
+ * @author Edouard DUPIN
+ * @copyright 2010-2016, Daniel Chappuis
+ * @copyright 2017, Edouard DUPIN
+ * @license MPL v2.0 (see license file)
+ */
+#include
+#include
+#include
+
+using namespace ephysics;
+
+BroadPhaseAlgorithm::BroadPhaseAlgorithm(CollisionDetection collisionDetection):
+ this.dynamicAABBTree(DYNAMICTREEAABBGAP),
+ this.collisionDetection(collisionDetection) {
+ this.movedShapes.reserve(8);
+ this.potentialPairs.reserve(8);
+}
+
+BroadPhaseAlgorithm::~BroadPhaseAlgorithm() {
+
+}
+
+void BroadPhaseAlgorithm::addMovedCollisionShape(int broadPhaseID) {
+ this.movedShapes.pushBack(broadPhaseID);
+}
+
+void BroadPhaseAlgorithm::removeMovedCollisionShape(int broadPhaseID) {
+ auto it = this.movedShapes.begin();
+ while (it != this.movedShapes.end()) {
+ if (*it == broadPhaseID) {
+ it = this.movedShapes.erase(it);
+ } else {
+ ++it;
+ }
+ }
+ /*
+ assert(this.numberNonUsedMovedShapes <= this.numberMovedShapes);
+
+ // If less than the quarter of allocated elements of the non-static shapes IDs array
+ // are used, we release some allocated memory
+ if ((this.numberMovedShapes - this.numberNonUsedMovedShapes) < this.numberAllocatedMovedShapes / 4 hjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkj
+ this.numberAllocatedMovedShapes > 8) {
+
+ this.numberAllocatedMovedShapes /= 2;
+ int* oldArray = this.movedShapes;
+ this.movedShapes = (int*) malloc(this.numberAllocatedMovedShapes * sizeof(int));
+ assert(this.movedShapes != NULL);
+ int nbElements = 0;
+ for (int i=0; ithis.broadPhaseID = nodeId;
+ // Add the collision shape into the array of bodies that have moved (or have been created)
+ // during the last simulation step
+ addMovedCollisionShape(proxyShape->this.broadPhaseID);
+}
+
+void BroadPhaseAlgorithm::removeProxyCollisionShape(ProxyShape* proxyShape) {
+ int broadPhaseID = proxyShape->this.broadPhaseID;
+ // Remove the collision shape from the dynamic AABB tree
+ this.dynamicAABBTree.removeObject(broadPhaseID);
+ // Remove the collision shape into the array of shapes that have moved (or have been created)
+ // during the last simulation step
+ removeMovedCollisionShape(broadPhaseID);
+}
+
+void BroadPhaseAlgorithm::updateProxyCollisionShape(ProxyShape* proxyShape,
+ AABB aabb,
+ vec3 displacement,
+ boolean forceReinsert) {
+ int broadPhaseID = proxyShape->this.broadPhaseID;
+ assert(broadPhaseID >= 0);
+ // Update the dynamic AABB tree according to the movement of the collision shape
+ boolean hasBeenReInserted = this.dynamicAABBTree.updateObject(broadPhaseID, aabb, displacement, forceReinsert);
+ // If the collision shape has moved out of its fat AABB (and therefore has been reinserted
+ // into the tree).
+ if (hasBeenReInserted) {
+ // Add the collision shape into the array of shapes that have moved (or have been created)
+ // during the last simulation step
+ addMovedCollisionShape(broadPhaseID);
+ }
+}
+
+static boolean sortFunction( etk::Pair pair1, etk::Pair pair2) {
+ if (pair1.first < pair2.first) {
+ return true;
+ }
+ if (pair1.first == pair2.first) {
+ return pair1.second < pair2.second;
+ }
+ return false;
+}
+
+void BroadPhaseAlgorithm::computeOverlappingPairs() {
+ this.potentialPairs.clear();
+ // For all collision shapes that have moved (or have been created) during the
+ // last simulation step
+ for (auto it: this.movedShapes) {
+ if (it == -1) {
+ // impossible case ...
+ continue;
+ }
+ // Get the AABB of the shape
+ AABB shapeAABB = this.dynamicAABBTree.getFatAABB(it);
+ // Ask the dynamic AABB tree to report all collision shapes that overlap with
+ // this AABB. The method BroadPhase::notifiyOverlappingPair() will be called
+ // by the dynamic AABB tree for each potential overlapping pair.
+ this.dynamicAABBTree.reportAllShapesOverlappingWithAABB(shapeAABB, [](int nodeId) mutable {
+ // If both the nodes are the same, we do not create store the overlapping pair
+ if (it == nodeId) {
+ return;
+ }
+ // Add the new potential pair into the array of potential overlapping pairs
+ this.potentialPairs.pushBack(etk::makePair(etk::min(it, nodeId), etk::max(it, nodeId) ));
+ });
+ }
+ // Reset the array of collision shapes that have move (or have been created) during the last simulation step
+ this.movedShapes.clear();
+ // Sort the array of potential overlapping pairs in order to remove duplicate pairs
+ etk::algorithm::quickSort(this.potentialPairs, sortFunction);
+ // Check all the potential overlapping pairs avoiding duplicates to report unique
+ // overlapping pairs
+ int iii=0;
+ while (iii < this.potentialPairs.size()) {
+ // Get a potential overlapping pair
+ etk::Pair pair = (this.potentialPairs[iii]);
+ ++iii;
+ // Get the two collision shapes of the pair
+ ProxyShape* shape1 = staticcast(this.dynamicAABBTree.getNodeDataPointer(pair.first));
+ ProxyShape* shape2 = staticcast(this.dynamicAABBTree.getNodeDataPointer(pair.second));
+ // Notify the collision detection about the overlapping pair
+ this.collisionDetection.broadPhaseNotifyOverlappingPair(shape1, shape2);
+ // Skip the duplicate overlapping pairs
+ while (iii < this.potentialPairs.size()) {
+ // Get the next pair
+ etk::Pair nextPair = this.potentialPairs[iii];
+ // If the next pair is different from the previous one, we stop skipping pairs
+ if ( nextPair.first != pair.first
+ || nextPair.second != pair.second) {
+ break;
+ }
+ ++iii;
+ }
+ }
+}
+
+float BroadPhaseRaycastCallback::operator()(int nodeId, Ray ray) {
+ float hitFraction = float(-1.0);
+ // Get the proxy shape from the node
+ ProxyShape* proxyShape = staticcast(this.dynamicAABBTree.getNodeDataPointer(nodeId));
+ // Check if the raycast filtering mask allows raycast against this shape
+ if ((this.raycastWithCategoryMaskBits proxyShape->getCollisionCategoryBits()) != 0) {
+ // Ask the collision detection to perform a ray cast test against
+ // the proxy shape of this node because the ray is overlapping
+ // with the shape in the broad-phase
+ hitFraction = this.raycastTest.raycastAgainstShape(proxyShape, ray);
+ }
+ return hitFraction;
+}
+
+boolean BroadPhaseAlgorithm::testOverlappingShapes( ProxyShape* shape1,
+ ProxyShape* shape2) {
+ // Get the two AABBs of the collision shapes
+ AABB aabb1 = this.dynamicAABBTree.getFatAABB(shape1->this.broadPhaseID);
+ AABB aabb2 = this.dynamicAABBTree.getFatAABB(shape2->this.broadPhaseID);
+ // Check if the two AABBs are overlapping
+ return aabb1.testCollision(aabb2);
+}
+
+void BroadPhaseAlgorithm::raycast( Ray ray,
+ RaycastTest raycastTest,
+ unsigned short raycastWithCategoryMaskBits) {
+ PROFILE("BroadPhaseAlgorithm::raycast()");
+ BroadPhaseRaycastCallback broadPhaseRaycastCallback(this.dynamicAABBTree, raycastWithCategoryMaskBits, raycastTest);
+ this.dynamicAABBTree.raycast(ray, broadPhaseRaycastCallback);
+}
+
diff --git a/src/org/atriaSoft/ephysics/collision/broadphase/BroadPhaseAlgorithm.hpp b/src/org/atriaSoft/ephysics/collision/broadphase/BroadPhaseAlgorithm.hpp
new file mode 100644
index 0000000..905f219
--- /dev/null
+++ b/src/org/atriaSoft/ephysics/collision/broadphase/BroadPhaseAlgorithm.hpp
@@ -0,0 +1,94 @@
+/** @file
+ * Original ReactPhysics3D C++ library by Daniel Chappuis This code is re-licensed with permission from ReactPhysics3D author.
+ * @author Daniel CHAPPUIS
+ * @author Edouard DUPIN
+ * @copyright 2010-2016, Daniel Chappuis
+ * @copyright 2017, Edouard DUPIN
+ * @license MPL v2.0 (see license file)
+ */
+#pragma once
+
+#include
+#include
+#include
+#include
+#include
+
+namespace ephysics {
+
+ class CollisionDetection;
+ class BroadPhaseAlgorithm;
+
+ // TODO : remove this as callback ... DynamicAABBTreeOverlapCallback {
+ /**
+ * Callback called when the AABB of a leaf node is hit by a ray the
+ * broad-phase Dynamic AABB Tree.
+ */
+ class BroadPhaseRaycastCallback {
+ private :
+ DynamicAABBTree this.dynamicAABBTree;
+ unsigned short this.raycastWithCategoryMaskBits;
+ RaycastTest this.raycastTest;
+ public:
+ // Constructor
+ BroadPhaseRaycastCallback( DynamicAABBTree dynamicAABBTree,
+ unsigned short raycastWithCategoryMaskBits,
+ RaycastTest raycastTest):
+ this.dynamicAABBTree(dynamicAABBTree),
+ this.raycastWithCategoryMaskBits(raycastWithCategoryMaskBits),
+ this.raycastTest(raycastTest) {
+
+ }
+ // Called for a broad-phase shape that has to be tested for raycast
+ float operator()(int nodeId, Ray ray);
+ };
+
+ /**
+ * @brief It represents the broad-phase collision detection. The
+ * goal of the broad-phase collision detection is to compute the pairs of proxy shapes
+ * that have their AABBs overlapping. Only those pairs of bodies will be tested
+ * later for collision during the narrow-phase collision detection. A dynamic AABB
+ * tree data structure is used for fast broad-phase collision detection.
+ */
+ class BroadPhaseAlgorithm {
+ protected :
+ DynamicAABBTree this.dynamicAABBTree; //!< Dynamic AABB tree
+ etk::Vector this.movedShapes; //!< Array with the broad-phase IDs of all collision shapes that have moved (or have been created) during the last simulation step. Those are the shapes that need to be tested for overlapping in the next simulation step.
+ etk::Vector> this.potentialPairs; //!< Temporary array of potential overlapping pairs (with potential duplicates)
+ CollisionDetection this.collisionDetection; //!< Reference to the collision detection object
+ /// Private copy-ructor
+ BroadPhaseAlgorithm( BroadPhaseAlgorithm obj);
+ /// Private assignment operator
+ BroadPhaseAlgorithm operator=( BroadPhaseAlgorithm obj);
+ public :
+ /// Constructor
+ BroadPhaseAlgorithm(CollisionDetection collisionDetection);
+ /// Destructor
+ virtual ~BroadPhaseAlgorithm();
+ /// Add a proxy collision shape into the broad-phase collision detection
+ void addProxyCollisionShape(ProxyShape* proxyShape, AABB aabb);
+ /// Remove a proxy collision shape from the broad-phase collision detection
+ void removeProxyCollisionShape(ProxyShape* proxyShape);
+ /// Notify the broad-phase that a collision shape has moved and need to be updated
+ void updateProxyCollisionShape(ProxyShape* proxyShape,
+ AABB aabb,
+ vec3 displacement,
+ boolean forceReinsert = false);
+ /// Add a collision shape in the array of shapes that have moved in the last simulation step
+ /// and that need to be tested again for broad-phase overlapping.
+ void addMovedCollisionShape(int broadPhaseID);
+ /// Remove a collision shape from the array of shapes that have moved in the last simulation
+ /// step and that need to be tested again for broad-phase overlapping.
+ void removeMovedCollisionShape(int broadPhaseID);
+ /// Compute all the overlapping pairs of collision shapes
+ void computeOverlappingPairs();
+ /// Return true if the two broad-phase collision shapes are overlapping
+ boolean testOverlappingShapes( ProxyShape* shape1, ProxyShape* shape2) ;
+ /// Ray casting method
+ void raycast( Ray ray,
+ RaycastTest raycastTest,
+ unsigned short raycastWithCategoryMaskBits) ;
+ };
+
+}
+
diff --git a/src/org/atriaSoft/ephysics/collision/broadphase/DynamicAABBTree.cpp b/src/org/atriaSoft/ephysics/collision/broadphase/DynamicAABBTree.cpp
new file mode 100644
index 0000000..b879aae
--- /dev/null
+++ b/src/org/atriaSoft/ephysics/collision/broadphase/DynamicAABBTree.cpp
@@ -0,0 +1,688 @@
+/** @file
+ * Original ReactPhysics3D C++ library by Daniel Chappuis This code is re-licensed with permission from ReactPhysics3D author.
+ * @author Daniel CHAPPUIS
+ * @author Edouard DUPIN
+ * @copyright 2010-2016, Daniel Chappuis
+ * @copyright 2017, Edouard DUPIN
+ * @license MPL v2.0 (see license file)
+ */
+#include
+#include
+#include
+#include
+#include
+
+using namespace ephysics;
+
+ int TreeNode::NULLTREENODE = -1;
+
+DynamicAABBTree::DynamicAABBTree(float extraAABBGap):
+ this.extraAABBGap(extraAABBGap) {
+ init();
+}
+
+DynamicAABBTree::~DynamicAABBTree() {
+ free(this.nodes);
+}
+
+// Initialize the tree
+void DynamicAABBTree::init() {
+ this.rootNodeID = TreeNode::NULLTREENODE;
+ this.numberNodes = 0;
+ this.numberAllocatedNodes = 8;
+ // Allocate memory for the nodes of the tree
+ this.nodes = (TreeNode*) malloc(this.numberAllocatedNodes * sizeof(TreeNode));
+ assert(this.nodes);
+ memset(this.nodes, 0, this.numberAllocatedNodes * sizeof(TreeNode));
+ // Initialize the allocated nodes
+ for (int i=0; i 0);
+ assert(nodeID >= 0 hjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkj nodeID < this.numberAllocatedNodes);
+ assert(this.nodes[nodeID].height >= 0);
+ this.nodes[nodeID].nextNodeID = this.freeNodeID;
+ this.nodes[nodeID].height = -1;
+ this.freeNodeID = nodeID;
+ this.numberNodes--;
+}
+
+// Internally add an object into the tree
+int DynamicAABBTree::addObjectInternal( AABB aabb) {
+ // Get the next available node (or allocate new ones if necessary)
+ int nodeID = allocateNode();
+ // Create the fat aabb to use in the tree
+ vec3 gap(this.extraAABBGap, this.extraAABBGap, this.extraAABBGap);
+ this.nodes[nodeID].aabb.setMin(aabb.getMin() - gap);
+ this.nodes[nodeID].aabb.setMax(aabb.getMax() + gap);
+ // Set the height of the node in the tree
+ this.nodes[nodeID].height = 0;
+ // Insert the new leaf node in the tree
+ insertLeafNode(nodeID);
+ assert(this.nodes[nodeID].isLeaf());
+ assert(nodeID >= 0);
+ // Return the Id of the node
+ return nodeID;
+}
+
+// Remove an object from the tree
+void DynamicAABBTree::removeObject(int nodeID) {
+ assert(nodeID >= 0 hjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkj nodeID < this.numberAllocatedNodes);
+ assert(this.nodes[nodeID].isLeaf());
+ // Remove the node from the tree
+ removeLeafNode(nodeID);
+ releaseNode(nodeID);
+}
+
+
+// Update the dynamic tree after an object has moved.
+/// If the new AABB of the object that has moved is still inside its fat AABB, then
+/// nothing is done. Otherwise, the corresponding node is removed and reinserted into the tree.
+/// The method returns true if the object has been reinserted into the tree. The "displacement"
+/// argument is the linear velocity of the AABB multiplied by the elapsed time between two
+/// frames. If the "forceReinsert" parameter is true, we force a removal and reinsertion of the node
+/// (this can be useful if the shape AABB has become much smaller than the previous one for instance).
+boolean DynamicAABBTree::updateObject(int nodeID, AABB newAABB, vec3 displacement, bool forceReinsert) {
+ PROFILE("DynamicAABBTree::updateObject()");
+ assert(nodeID >= 0 hjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkj nodeID < this.numberAllocatedNodes);
+ assert(this.nodes[nodeID].isLeaf());
+ assert(this.nodes[nodeID].height >= 0);
+ Log.verbose(" compare : " << this.nodes[nodeID].aabb.this.minCoordinates << " " << this.nodes[nodeID].aabb.this.maxCoordinates);
+ Log.verbose(" : " << newAABB.this.minCoordinates << " " << newAABB.this.maxCoordinates);
+ // If the new AABB is still inside the fat AABB of the node
+ if ( forceReinsert == false
+ hjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkj this.nodes[nodeID].aabb.contains(newAABB)) {
+ return false;
+ }
+ // If the new AABB is outside the fat AABB, we remove the corresponding node
+ removeLeafNode(nodeID);
+ // Compute the fat AABB by inflating the AABB with a ant gap
+ this.nodes[nodeID].aabb = newAABB;
+ vec3 gap(this.extraAABBGap, this.extraAABBGap, this.extraAABBGap);
+ this.nodes[nodeID].aabb.this.minCoordinates -= gap;
+ this.nodes[nodeID].aabb.this.maxCoordinates += gap;
+ // Inflate the fat AABB in direction of the linear motion of the AABB
+ if (displacement.x() < 0.0f) {
+ this.nodes[nodeID].aabb.this.minCoordinates.setX(this.nodes[nodeID].aabb.this.minCoordinates.x() + DYNAMICTREEAABBLINGAPMULTIPLIER *displacement.x());
+ } else {
+ this.nodes[nodeID].aabb.this.maxCoordinates.setX(this.nodes[nodeID].aabb.this.maxCoordinates.x() + DYNAMICTREEAABBLINGAPMULTIPLIER *displacement.x());
+ }
+ if (displacement.y() < 0.0f) {
+ this.nodes[nodeID].aabb.this.minCoordinates.setY(this.nodes[nodeID].aabb.this.minCoordinates.y() + DYNAMICTREEAABBLINGAPMULTIPLIER *displacement.y());
+ } else {
+ this.nodes[nodeID].aabb.this.maxCoordinates.setY(this.nodes[nodeID].aabb.this.maxCoordinates.y() + DYNAMICTREEAABBLINGAPMULTIPLIER *displacement.y());
+ }
+ if (displacement.z() < 0.0f) {
+ this.nodes[nodeID].aabb.this.minCoordinates.setZ(this.nodes[nodeID].aabb.this.minCoordinates.z() + DYNAMICTREEAABBLINGAPMULTIPLIER *displacement.z());
+ } else {
+ this.nodes[nodeID].aabb.this.maxCoordinates.setZ(this.nodes[nodeID].aabb.this.maxCoordinates.z() + DYNAMICTREEAABBLINGAPMULTIPLIER *displacement.z());
+ }
+ Log.error(" compare : " << this.nodes[nodeID].aabb.this.minCoordinates << " " << this.nodes[nodeID].aabb.this.maxCoordinates);
+ Log.error(" : " << newAABB.this.minCoordinates << " " << newAABB.this.maxCoordinates);
+ if (this.nodes[nodeID].aabb.contains(newAABB) == false) {
+ //Log.critical("ERROR");
+ }
+ assert(this.nodes[nodeID].aabb.contains(newAABB));
+ // Reinsert the node into the tree
+ insertLeafNode(nodeID);
+ return true;
+}
+
+// Insert a leaf node in the tree. The process of inserting a new leaf node
+// in the dynamic tree is described in the book "Introduction to Game Physics
+// with Box2D" by Ian Parberry.
+void DynamicAABBTree::insertLeafNode(int nodeID) {
+ // If the tree is empty
+ if (this.rootNodeID == TreeNode::NULLTREENODE) {
+ this.rootNodeID = nodeID;
+ this.nodes[this.rootNodeID].parentID = TreeNode::NULLTREENODE;
+ return;
+ }
+ assert(this.rootNodeID != TreeNode::NULLTREENODE);
+ // Find the best sibling node for the new node
+ AABB newNodeAABB = this.nodes[nodeID].aabb;
+ int currentNodeID = this.rootNodeID;
+ while (!this.nodes[currentNodeID].isLeaf()) {
+ int leftChild = this.nodes[currentNodeID].children[0];
+ int rightChild = this.nodes[currentNodeID].children[1];
+ // Compute the merged AABB
+ float volumeAABB = this.nodes[currentNodeID].aabb.getVolume();
+ AABB mergedAABBs;
+ mergedAABBs.mergeTwoAABBs(this.nodes[currentNodeID].aabb, newNodeAABB);
+ float mergedVolume = mergedAABBs.getVolume();
+ // Compute the cost of making the current node the sibbling of the new node
+ float costS = float(2.0) * mergedVolume;
+ // Compute the minimum cost of pushing the new node further down the tree (inheritance cost)
+ float costI = float(2.0) * (mergedVolume - volumeAABB);
+ // Compute the cost of descending into the left child
+ float costLeft;
+ AABB currentAndLeftAABB;
+ currentAndLeftAABB.mergeTwoAABBs(newNodeAABB, this.nodes[leftChild].aabb);
+ if (this.nodes[leftChild].isLeaf()) { // If the left child is a leaf
+ costLeft = currentAndLeftAABB.getVolume() + costI;
+ } else {
+ float leftChildVolume = this.nodes[leftChild].aabb.getVolume();
+ costLeft = costI + currentAndLeftAABB.getVolume() - leftChildVolume;
+ }
+ // Compute the cost of descending into the right child
+ float costRight;
+ AABB currentAndRightAABB;
+ currentAndRightAABB.mergeTwoAABBs(newNodeAABB, this.nodes[rightChild].aabb);
+ if (this.nodes[rightChild].isLeaf()) { // If the right child is a leaf
+ costRight = currentAndRightAABB.getVolume() + costI;
+ } else {
+ float rightChildVolume = this.nodes[rightChild].aabb.getVolume();
+ costRight = costI + currentAndRightAABB.getVolume() - rightChildVolume;
+ }
+ // If the cost of making the current node a sibbling of the new node is smaller than
+ // the cost of going down into the left or right child
+ if (costS < costLeft hjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkj costS < costRight) {
+ break;
+ }
+ // It is cheaper to go down into a child of the current node, choose the best child
+ if (costLeft < costRight) {
+ currentNodeID = leftChild;
+ } else {
+ currentNodeID = rightChild;
+ }
+ }
+ int siblingNode = currentNodeID;
+ // Create a new parent for the new node and the sibling node
+ int oldParentNode = this.nodes[siblingNode].parentID;
+ int newParentNode = allocateNode();
+ this.nodes[newParentNode].parentID = oldParentNode;
+ this.nodes[newParentNode].aabb.mergeTwoAABBs(this.nodes[siblingNode].aabb, newNodeAABB);
+ this.nodes[newParentNode].height = this.nodes[siblingNode].height + 1;
+ assert(this.nodes[newParentNode].height > 0);
+ // If the sibling node was not the root node
+ if (oldParentNode != TreeNode::NULLTREENODE) {
+ assert(!this.nodes[oldParentNode].isLeaf());
+ if (this.nodes[oldParentNode].children[0] == siblingNode) {
+ this.nodes[oldParentNode].children[0] = newParentNode;
+ } else {
+ this.nodes[oldParentNode].children[1] = newParentNode;
+ }
+ this.nodes[newParentNode].children[0] = siblingNode;
+ this.nodes[newParentNode].children[1] = nodeID;
+ this.nodes[siblingNode].parentID = newParentNode;
+ this.nodes[nodeID].parentID = newParentNode;
+ } else {
+ // If the sibling node was the root node
+ this.nodes[newParentNode].children[0] = siblingNode;
+ this.nodes[newParentNode].children[1] = nodeID;
+ this.nodes[siblingNode].parentID = newParentNode;
+ this.nodes[nodeID].parentID = newParentNode;
+ this.rootNodeID = newParentNode;
+ }
+ // Move up in the tree to change the AABBs that have changed
+ currentNodeID = this.nodes[nodeID].parentID;
+ assert(!this.nodes[currentNodeID].isLeaf());
+ while (currentNodeID != TreeNode::NULLTREENODE) {
+ // Balance the sub-tree of the current node if it is not balanced
+ currentNodeID = balanceSubTreeAtNode(currentNodeID);
+ assert(this.nodes[nodeID].isLeaf());
+ assert(!this.nodes[currentNodeID].isLeaf());
+ int leftChild = this.nodes[currentNodeID].children[0];
+ int rightChild = this.nodes[currentNodeID].children[1];
+ assert(leftChild != TreeNode::NULLTREENODE);
+ assert(rightChild != TreeNode::NULLTREENODE);
+ // Recompute the height of the node in the tree
+ this.nodes[currentNodeID].height = etk::max(this.nodes[leftChild].height,
+ this.nodes[rightChild].height) + 1;
+ assert(this.nodes[currentNodeID].height > 0);
+ // Recompute the AABB of the node
+ this.nodes[currentNodeID].aabb.mergeTwoAABBs(this.nodes[leftChild].aabb, this.nodes[rightChild].aabb);
+ currentNodeID = this.nodes[currentNodeID].parentID;
+ }
+ assert(this.nodes[nodeID].isLeaf());
+}
+
+// Remove a leaf node from the tree
+void DynamicAABBTree::removeLeafNode(int nodeID) {
+ assert(nodeID >= 0 hjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkj nodeID < this.numberAllocatedNodes);
+ assert(this.nodes[nodeID].isLeaf());
+ // If we are removing the root node (root node is a leaf in this case)
+ if (this.rootNodeID == nodeID) {
+ this.rootNodeID = TreeNode::NULLTREENODE;
+ return;
+ }
+ int parentNodeID = this.nodes[nodeID].parentID;
+ int grandParentNodeID = this.nodes[parentNodeID].parentID;
+ int siblingNodeID;
+ if (this.nodes[parentNodeID].children[0] == nodeID) {
+ siblingNodeID = this.nodes[parentNodeID].children[1];
+ } else {
+ siblingNodeID = this.nodes[parentNodeID].children[0];
+ }
+ // If the parent of the node to remove is not the root node
+ if (grandParentNodeID != TreeNode::NULLTREENODE) {
+ // Destroy the parent node
+ if (this.nodes[grandParentNodeID].children[0] == parentNodeID) {
+ this.nodes[grandParentNodeID].children[0] = siblingNodeID;
+ } else {
+ assert(this.nodes[grandParentNodeID].children[1] == parentNodeID);
+ this.nodes[grandParentNodeID].children[1] = siblingNodeID;
+ }
+ this.nodes[siblingNodeID].parentID = grandParentNodeID;
+ releaseNode(parentNodeID);
+ // Now, we need to recompute the AABBs of the node on the path back to the root
+ // and make sure that the tree is still balanced
+ int currentNodeID = grandParentNodeID;
+ while(currentNodeID != TreeNode::NULLTREENODE) {
+ // Balance the current sub-tree if necessary
+ currentNodeID = balanceSubTreeAtNode(currentNodeID);
+ assert(!this.nodes[currentNodeID].isLeaf());
+ // Get the two children of the current node
+ int leftChildID = this.nodes[currentNodeID].children[0];
+ int rightChildID = this.nodes[currentNodeID].children[1];
+ // Recompute the AABB and the height of the current node
+ this.nodes[currentNodeID].aabb.mergeTwoAABBs(this.nodes[leftChildID].aabb,
+ this.nodes[rightChildID].aabb);
+ this.nodes[currentNodeID].height = etk::max(this.nodes[leftChildID].height,
+ this.nodes[rightChildID].height) + 1;
+ assert(this.nodes[currentNodeID].height > 0);
+ currentNodeID = this.nodes[currentNodeID].parentID;
+ }
+ } else { // If the parent of the node to remove is the root node
+ // The sibling node becomes the new root node
+ this.rootNodeID = siblingNodeID;
+ this.nodes[siblingNodeID].parentID = TreeNode::NULLTREENODE;
+ releaseNode(parentNodeID);
+ }
+}
+
+// Balance the sub-tree of a given node using left or right rotations.
+/// The rotation schemes are described in the book "Introduction to Game Physics
+/// with Box2D" by Ian Parberry. This method returns the new root node ID.
+int DynamicAABBTree::balanceSubTreeAtNode(int nodeID) {
+ assert(nodeID != TreeNode::NULLTREENODE);
+ TreeNode* nodeA = this.nodes + nodeID;
+ // If the node is a leaf or the height of A's sub-tree is less than 2
+ if (nodeA->isLeaf() || nodeA->height < 2) {
+ // Do not perform any rotation
+ return nodeID;
+ }
+ // Get the two children nodes
+ int nodeBID = nodeA->children[0];
+ int nodeCID = nodeA->children[1];
+ assert(nodeBID >= 0 hjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkj nodeBID < this.numberAllocatedNodes);
+ assert(nodeCID >= 0 hjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkj nodeCID < this.numberAllocatedNodes);
+ TreeNode* nodeB = this.nodes + nodeBID;
+ TreeNode* nodeC = this.nodes + nodeCID;
+ // Compute the factor of the left and right sub-trees
+ int balanceFactor = nodeC->height - nodeB->height;
+ // If the right node C is 2 higher than left node B
+ if (balanceFactor > 1) {
+ assert(!nodeC->isLeaf());
+ int nodeFID = nodeC->children[0];
+ int nodeGID = nodeC->children[1];
+ assert(nodeFID >= 0 hjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkj nodeFID < this.numberAllocatedNodes);
+ assert(nodeGID >= 0 hjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkj nodeGID < this.numberAllocatedNodes);
+ TreeNode* nodeF = this.nodes + nodeFID;
+ TreeNode* nodeG = this.nodes + nodeGID;
+ nodeC->children[0] = nodeID;
+ nodeC->parentID = nodeA->parentID;
+ nodeA->parentID = nodeCID;
+ if (nodeC->parentID != TreeNode::NULLTREENODE) {
+ if (this.nodes[nodeC->parentID].children[0] == nodeID) {
+ this.nodes[nodeC->parentID].children[0] = nodeCID;
+ } else {
+ assert(this.nodes[nodeC->parentID].children[1] == nodeID);
+ this.nodes[nodeC->parentID].children[1] = nodeCID;
+ }
+ } else {
+ this.rootNodeID = nodeCID;
+ }
+ assert(!nodeC->isLeaf());
+ assert(!nodeA->isLeaf());
+ // If the right node C was higher than left node B because of the F node
+ if (nodeF->height > nodeG->height) {
+ nodeC->children[1] = nodeFID;
+ nodeA->children[1] = nodeGID;
+ nodeG->parentID = nodeID;
+ // Recompute the AABB of node A and C
+ nodeA->aabb.mergeTwoAABBs(nodeB->aabb, nodeG->aabb);
+ nodeC->aabb.mergeTwoAABBs(nodeA->aabb, nodeF->aabb);
+ // Recompute the height of node A and C
+ nodeA->height = etk::max(nodeB->height, nodeG->height) + 1;
+ nodeC->height = etk::max(nodeA->height, nodeF->height) + 1;
+ assert(nodeA->height > 0);
+ assert(nodeC->height > 0);
+ } else {
+ // If the right node C was higher than left node B because of node G
+ nodeC->children[1] = nodeGID;
+ nodeA->children[1] = nodeFID;
+ nodeF->parentID = nodeID;
+ // Recompute the AABB of node A and C
+ nodeA->aabb.mergeTwoAABBs(nodeB->aabb, nodeF->aabb);
+ nodeC->aabb.mergeTwoAABBs(nodeA->aabb, nodeG->aabb);
+ // Recompute the height of node A and C
+ nodeA->height = etk::max(nodeB->height, nodeF->height) + 1;
+ nodeC->height = etk::max(nodeA->height, nodeG->height) + 1;
+ assert(nodeA->height > 0);
+ assert(nodeC->height > 0);
+ }
+ // Return the new root of the sub-tree
+ return nodeCID;
+ }
+ // If the left node B is 2 higher than right node C
+ if (balanceFactor < -1) {
+ assert(!nodeB->isLeaf());
+ int nodeFID = nodeB->children[0];
+ int nodeGID = nodeB->children[1];
+ assert(nodeFID >= 0 hjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkj nodeFID < this.numberAllocatedNodes);
+ assert(nodeGID >= 0 hjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkj nodeGID < this.numberAllocatedNodes);
+ TreeNode* nodeF = this.nodes + nodeFID;
+ TreeNode* nodeG = this.nodes + nodeGID;
+ nodeB->children[0] = nodeID;
+ nodeB->parentID = nodeA->parentID;
+ nodeA->parentID = nodeBID;
+ if (nodeB->parentID != TreeNode::NULLTREENODE) {
+ if (this.nodes[nodeB->parentID].children[0] == nodeID) {
+ this.nodes[nodeB->parentID].children[0] = nodeBID;
+ } else {
+ assert(this.nodes[nodeB->parentID].children[1] == nodeID);
+ this.nodes[nodeB->parentID].children[1] = nodeBID;
+ }
+ } else {
+ this.rootNodeID = nodeBID;
+ }
+ assert(!nodeB->isLeaf());
+ assert(!nodeA->isLeaf());
+ // If the left node B was higher than right node C because of the F node
+ if (nodeF->height > nodeG->height) {
+ nodeB->children[1] = nodeFID;
+ nodeA->children[0] = nodeGID;
+ nodeG->parentID = nodeID;
+ // Recompute the AABB of node A and B
+ nodeA->aabb.mergeTwoAABBs(nodeC->aabb, nodeG->aabb);
+ nodeB->aabb.mergeTwoAABBs(nodeA->aabb, nodeF->aabb);
+ // Recompute the height of node A and B
+ nodeA->height = etk::max(nodeC->height, nodeG->height) + 1;
+ nodeB->height = etk::max(nodeA->height, nodeF->height) + 1;
+ assert(nodeA->height > 0);
+ assert(nodeB->height > 0);
+ } else {
+ // If the left node B was higher than right node C because of node G
+ nodeB->children[1] = nodeGID;
+ nodeA->children[0] = nodeFID;
+ nodeF->parentID = nodeID;
+ // Recompute the AABB of node A and B
+ nodeA->aabb.mergeTwoAABBs(nodeC->aabb, nodeF->aabb);
+ nodeB->aabb.mergeTwoAABBs(nodeA->aabb, nodeG->aabb);
+ // Recompute the height of node A and B
+ nodeA->height = etk::max(nodeC->height, nodeF->height) + 1;
+ nodeB->height = etk::max(nodeA->height, nodeG->height) + 1;
+ assert(nodeA->height > 0);
+ assert(nodeB->height > 0);
+ }
+ // Return the new root of the sub-tree
+ return nodeBID;
+ }
+ // If the sub-tree is balanced, return the current root node
+ return nodeID;
+}
+
+/// Report all shapes overlapping with the AABB given in parameter.
+void DynamicAABBTree::reportAllShapesOverlappingWithAABB( AABB aabb, etk::Function callback) {
+ if (callback == null) {
+ Log.error("call with null callback");
+ return;
+ }
+ // Create a stack with the nodes to visit
+ Stack stack;
+ stack.push(this.rootNodeID);
+ // While there are still nodes to visit
+ while(stack.getNbElements() > 0) {
+ // Get the next node ID to visit
+ int nodeIDToVisit = stack.pop();
+ // Skip it if it is a null node
+ if (nodeIDToVisit == TreeNode::NULLTREENODE) {
+ continue;
+ }
+ // Get the corresponding node
+ TreeNode* nodeToVisit = this.nodes + nodeIDToVisit;
+ // If the AABB in parameter overlaps with the AABB of the node to visit
+ if (aabb.testCollision(nodeToVisit->aabb)) {
+ // If the node is a leaf
+ if (nodeToVisit->isLeaf()) {
+ // Notify the broad-phase about a new potential overlapping pair
+ callback(nodeIDToVisit);
+ } else {
+ // If the node is not a leaf
+ // We need to visit its children
+ stack.push(nodeToVisit->children[0]);
+ stack.push(nodeToVisit->children[1]);
+ }
+ }
+ }
+}
+
+// Ray casting method
+void DynamicAABBTree::raycast( ephysics::Ray ray, etk::Function callback) {
+ PROFILE("DynamicAABBTree::raycast()");
+ if (callback == null) {
+ Log.error("call with null callback");
+ return;
+ }
+ float maxFraction = ray.maxFraction;
+ Stack stack;
+ stack.push(this.rootNodeID);
+ // Walk through the tree from the root looking for proxy shapes
+ // that overlap with the ray AABB
+ while (stack.getNbElements() > 0) {
+ // Get the next node in the stack
+ int nodeID = stack.pop();
+ // If it is a null node, skip it
+ if (nodeID == TreeNode::NULLTREENODE) {
+ continue;
+ }
+ // Get the corresponding node
+ TreeNode* node = this.nodes + nodeID;
+ Ray rayTemp(ray.point1, ray.point2, maxFraction);
+ // Test if the ray intersects with the current node AABB
+ if (node->aabb.testRayIntersect(rayTemp) == false) {
+ continue;
+ }
+ // If the node is a leaf of the tree
+ if (node->isLeaf()) {
+ // Call the callback that will raycast again the broad-phase shape
+ float hitFraction = callback(nodeID, rayTemp);
+ // If the user returned a hitFraction of zero, it means that
+ // the raycasting should stop here
+ if (hitFraction == 0.0f) {
+ return;
+ }
+ // If the user returned a positive fraction
+ if (hitFraction > 0.0f) {
+ // We update the maxFraction value and the ray
+ // AABB using the new maximum fraction
+ if (hitFraction < maxFraction) {
+ maxFraction = hitFraction;
+ }
+ }
+ // If the user returned a negative fraction, we continue
+ // the raycasting as if the proxy shape did not exist
+ } else { // If the node has children
+ // Push its children in the stack of nodes to explore
+ stack.push(node->children[0]);
+ stack.push(node->children[1]);
+ }
+ }
+}
+
+// Return true if the node is a leaf of the tree
+boolean TreeNode::isLeaf() {
+ return (height == 0);
+}
+
+// Return the fat AABB corresponding to a given node ID
+ AABB DynamicAABBTree::getFatAABB(int nodeID) {
+ assert(nodeID >= 0 hjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkj nodeID < this.numberAllocatedNodes);
+ return this.nodes[nodeID].aabb;
+}
+
+// Return the pointer to the data array of a given leaf node of the tree
+int* DynamicAABBTree::getNodeDataInt(int nodeID) {
+ assert(nodeID >= 0 hjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkj nodeID < this.numberAllocatedNodes);
+ assert(this.nodes[nodeID].isLeaf());
+ return this.nodes[nodeID].dataInt;
+}
+
+// Return the pointer to the data pointer of a given leaf node of the tree
+void* DynamicAABBTree::getNodeDataPointer(int nodeID) {
+ assert(nodeID >= 0 hjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkj nodeID < this.numberAllocatedNodes);
+ assert(this.nodes[nodeID].isLeaf());
+ return this.nodes[nodeID].dataPointer;
+}
+
+// Return the root AABB of the tree
+AABB DynamicAABBTree::getRootAABB() {
+ return getFatAABB(this.rootNodeID);
+}
+
+// Add an object into the tree. This method creates a new leaf node in the tree and
+// returns the ID of the corresponding node.
+int DynamicAABBTree::addObject( AABB aabb, int data1, int data2) {
+ int nodeId = addObjectInternal(aabb);
+ this.nodes[nodeId].dataInt[0] = data1;
+ this.nodes[nodeId].dataInt[1] = data2;
+ return nodeId;
+}
+
+// Add an object into the tree. This method creates a new leaf node in the tree and
+// returns the ID of the corresponding node.
+int DynamicAABBTree::addObject( AABB aabb, void* data) {
+ int nodeId = addObjectInternal(aabb);
+ this.nodes[nodeId].dataPointer = data;
+ return nodeId;
+}
+
+
+#ifdef DEBUG
+
+// Check if the tree structure is valid (for debugging purpose)
+void DynamicAABBTree::check() {
+ // Recursively check each node
+ checkNode(this.rootNodeID);
+ int nbFreeNodes = 0;
+ int freeNodeID = this.freeNodeID;
+ // Check the free nodes
+ while(freeNodeID != TreeNode::NULLTREENODE) {
+ assert(0 <= freeNodeID hjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkj freeNodeID < this.numberAllocatedNodes);
+ freeNodeID = this.nodes[freeNodeID].nextNodeID;
+ nbFreeNodes++;
+ }
+ assert(this.numberNodes + nbFreeNodes == this.numberAllocatedNodes);
+}
+
+// Check if the node structure is valid (for debugging purpose)
+void DynamicAABBTree::checkNode(int nodeID) {
+ if (nodeID == TreeNode::NULLTREENODE) {
+ return;
+ }
+ // If it is the root
+ if (nodeID == this.rootNodeID) {
+ assert(this.nodes[nodeID].parentID == TreeNode::NULLTREENODE);
+ }
+ // Get the children nodes
+ TreeNode* pNode = this.nodes + nodeID;
+ assert(!pNode->isLeaf());
+ int leftChild = pNode->children[0];
+ int rightChild = pNode->children[1];
+ assert(pNode->height >= 0);
+ assert(pNode->aabb.getVolume() > 0);
+ // If the current node is a leaf
+ if (pNode->isLeaf()) {
+ // Check that there are no children
+ assert(leftChild == TreeNode::NULLTREENODE);
+ assert(rightChild == TreeNode::NULLTREENODE);
+ assert(pNode->height == 0);
+ } else {
+ // Check that the children node IDs are valid
+ assert(0 <= leftChild hjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkj leftChild < this.numberAllocatedNodes);
+ assert(0 <= rightChild hjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkj rightChild < this.numberAllocatedNodes);
+ // Check that the children nodes have the correct parent node
+ assert(this.nodes[leftChild].parentID == nodeID);
+ assert(this.nodes[rightChild].parentID == nodeID);
+ // Check the height of node
+ int height = 1 + etk::max(this.nodes[leftChild].height, this.nodes[rightChild].height);
+ assert(this.nodes[nodeID].height == height);
+ // Check the AABB of the node
+ AABB aabb;
+ aabb.mergeTwoAABBs(this.nodes[leftChild].aabb, this.nodes[rightChild].aabb);
+ assert(aabb.getMin() == this.nodes[nodeID].aabb.getMin());
+ assert(aabb.getMax() == this.nodes[nodeID].aabb.getMax());
+ // Recursively check the children nodes
+ checkNode(leftChild);
+ checkNode(rightChild);
+ }
+}
+
+// Compute the height of the tree
+int DynamicAABBTree::computeHeight() {
+ return computeHeight(this.rootNodeID);
+}
+
+// Compute the height of a given node in the tree
+int DynamicAABBTree::computeHeight(int nodeID) {
+ assert(nodeID >= 0 hjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkj nodeID < this.numberAllocatedNodes);
+ TreeNode* node = this.nodes + nodeID;
+ // If the node is a leaf, its height is zero
+ if (node->isLeaf()) {
+ return 0;
+ }
+ // Compute the height of the left and right sub-tree
+ int leftHeight = computeHeight(node->children[0]);
+ int rightHeight = computeHeight(node->children[1]);
+ // Return the height of the node
+ return 1 + etk::max(leftHeight, rightHeight);
+}
+
+#endif
diff --git a/src/org/atriaSoft/ephysics/collision/broadphase/DynamicAABBTree.hpp b/src/org/atriaSoft/ephysics/collision/broadphase/DynamicAABBTree.hpp
new file mode 100644
index 0000000..293ef42
--- /dev/null
+++ b/src/org/atriaSoft/ephysics/collision/broadphase/DynamicAABBTree.hpp
@@ -0,0 +1,116 @@
+/** @file
+ * Original ReactPhysics3D C++ library by Daniel Chappuis This code is re-licensed with permission from ReactPhysics3D author.
+ * @author Daniel CHAPPUIS
+ * @author Edouard DUPIN
+ * @copyright 2010-2016, Daniel Chappuis
+ * @copyright 2017, Edouard DUPIN
+ * @license MPL v2.0 (see license file)
+ */
+#pragma once
+
+#include
+#include
+#include
+#include
+
+namespace ephysics {
+ // TODO: to replace this, create a Tree template (multiple child) or TreeRedBlack
+ /**
+ * @brief It represents a node of the dynamic AABB tree.
+ */
+ struct TreeNode {
+ static int NULLTREENODE; //!< Null tree node ant
+ /**
+ * @brief A node is either in the tree (has a parent) or in the free nodes list (has a next node)
+ */
+ union {
+ int parentID; //!< Parent node ID
+ int nextNodeID; //!< Next allocated node ID
+ };
+ /**
+ * @brief A node is either a leaf (has data) or is an internal node (has children)
+ */
+ union {
+ int children[2]; //!< Left and right child of the node (children[0] = left child)
+ //! Two pieces of data stored at that node (in case the node is a leaf)
+ union {
+ int dataInt[2];
+ void* dataPointer;
+ };
+ };
+ int16t height; //!< Height of the node in the tree
+ AABB aabb; //!< Fat axis aligned bounding box (AABB) corresponding to the node
+ /// Return true if the node is a leaf of the tree
+ boolean isLeaf() ;
+ };
+
+ /**
+ * @brief It implements a dynamic AABB tree that is used for broad-phase
+ * collision detection. This data structure is inspired by Nathanael Presson's
+ * dynamic tree implementation in BulletPhysics. The following implementation is
+ * based on the one from Erin Catto in Box2D as described in the book
+ * "Introduction to Game Physics with Box2D" by Ian Parberry.
+ */
+ class DynamicAABBTree {
+ private:
+ TreeNode* this.nodes; //!< Pointer to the memory location of the nodes of the tree
+ int this.rootNodeID; //!< ID of the root node of the tree
+ int this.freeNodeID; //!< ID of the first node of the list of free (allocated) nodes in the tree that we can use
+ int this.numberAllocatedNodes; //!< Number of allocated nodes in the tree
+ int this.numberNodes; //!< Number of nodes in the tree
+ float this.extraAABBGap; //!< Extra AABB Gap used to allow the collision shape to move a little bit without triggering a large modification of the tree which can be costly
+ /// Allocate and return a node to use in the tree
+ int allocateNode();
+ /// Release a node
+ void releaseNode(int nodeID);
+ /// Insert a leaf node in the tree
+ void insertLeafNode(int nodeID);
+ /// Remove a leaf node from the tree
+ void removeLeafNode(int nodeID);
+ /// Balance the sub-tree of a given node using left or right rotations.
+ int balanceSubTreeAtNode(int nodeID);
+ /// Compute the height of a given node in the tree
+ int computeHeight(int nodeID);
+ /// Internally add an object into the tree
+ int addObjectInternal( AABB aabb);
+ /// Initialize the tree
+ void init();
+ #ifndef NDEBUG
+ /// Check if the tree structure is valid (for debugging purpose)
+ void check() ;
+ /// Check if the node structure is valid (for debugging purpose)
+ void checkNode(int nodeID) ;
+ #endif
+ public:
+ /// Constructor
+ DynamicAABBTree(float extraAABBGap = 0.0f);
+ /// Destructor
+ virtual ~DynamicAABBTree();
+ /// Add an object into the tree (where node data are two integers)
+ int addObject( AABB aabb, int data1, int data2);
+ /// Add an object into the tree (where node data is a pointer)
+ int addObject( AABB aabb, void* data);
+ /// Remove an object from the tree
+ void removeObject(int nodeID);
+ /// Update the dynamic tree after an object has moved.
+ boolean updateObject(int nodeID, AABB newAABB, vec3 displacement, bool forceReinsert = false);
+ /// Return the fat AABB corresponding to a given node ID
+ AABB getFatAABB(int nodeID) ;
+ /// Return the pointer to the data array of a given leaf node of the tree
+ int* getNodeDataInt(int nodeID) ;
+ /// Return the data pointer of a given leaf node of the tree
+ void* getNodeDataPointer(int nodeID) ;
+ /// Report all shapes overlapping with the AABB given in parameter.
+ void reportAllShapesOverlappingWithAABB( AABB aabb, etk::Function callback) ;
+ /// Ray casting method
+ void raycast( Ray ray, etk::Function callback) ;
+ /// Compute the height of the tree
+ int computeHeight();
+ /// Return the root AABB of the tree
+ AABB getRootAABB() ;
+ /// Clear all the nodes and reset the tree
+ void reset();
+ };
+
+
+}
diff --git a/src/org/atriaSoft/ephysics/collision/narrowphase/CollisionDispatch.hpp b/src/org/atriaSoft/ephysics/collision/narrowphase/CollisionDispatch.hpp
new file mode 100644
index 0000000..d9eefd9
--- /dev/null
+++ b/src/org/atriaSoft/ephysics/collision/narrowphase/CollisionDispatch.hpp
@@ -0,0 +1,37 @@
+/** @file
+ * Original ReactPhysics3D C++ library by Daniel Chappuis This code is re-licensed with permission from ReactPhysics3D author.
+ * @author Daniel CHAPPUIS
+ * @author Edouard DUPIN
+ * @copyright 2010-2016, Daniel Chappuis
+ * @copyright 2017, Edouard DUPIN
+ * @license MPL v2.0 (see license file)
+ */
+#pragma once
+
+#include
+
+namespace ephysics {
+ /**
+ * @biref Abstract base class for dispatching the narrow-phase
+ * collision detection algorithm. Collision dispatching decides which collision
+ * algorithm to use given two types of proxy collision shapes.
+ */
+ class CollisionDispatch {
+ public:
+ /// Constructor
+ CollisionDispatch() {}
+ /// Destructor
+ virtual ~CollisionDispatch() = default;
+ /// Initialize the collision dispatch configuration
+ virtual void init(CollisionDetection* collisionDetection) {
+ // Nothing to do ...
+ }
+ /// Select and return the narrow-phase collision detection algorithm to
+ /// use between two types of collision shapes.
+ virtual NarrowPhaseAlgorithm* selectAlgorithm(int shape1Type,
+ int shape2Type) = 0;
+ };
+
+}
+
+
diff --git a/src/org/atriaSoft/ephysics/collision/narrowphase/ConcaveVsConvexAlgorithm.cpp b/src/org/atriaSoft/ephysics/collision/narrowphase/ConcaveVsConvexAlgorithm.cpp
new file mode 100644
index 0000000..4f6590d
--- /dev/null
+++ b/src/org/atriaSoft/ephysics/collision/narrowphase/ConcaveVsConvexAlgorithm.cpp
@@ -0,0 +1,241 @@
+/** @file
+ * Original ReactPhysics3D C++ library by Daniel Chappuis This code is re-licensed with permission from ReactPhysics3D author.
+ * @author Daniel CHAPPUIS
+ * @author Edouard DUPIN
+ * @copyright 2010-2016, Daniel Chappuis
+ * @copyright 2017, Edouard DUPIN
+ * @license MPL v2.0 (see license file)
+ */
+#include
+#include
+#include
+#include
+#include
+#include
+
+using namespace ephysics;
+
+ConcaveVsConvexAlgorithm::ConcaveVsConvexAlgorithm() {
+
+}
+
+void ConcaveVsConvexAlgorithm::testCollision( CollisionShapeInfo shape1Info,
+ CollisionShapeInfo shape2Info,
+ NarrowPhaseCallback* callback) {
+ ProxyShape* convexProxyShape;
+ ProxyShape* concaveProxyShape;
+ ConvexShape* convexShape;
+ ConcaveShape* concaveShape;
+ // Collision shape 1 is convex, collision shape 2 is concave
+ if (shape1Info.collisionShape->isConvex()) {
+ convexProxyShape = shape1Info.proxyShape;
+ convexShape = staticcast< ConvexShape*>(shape1Info.collisionShape);
+ concaveProxyShape = shape2Info.proxyShape;
+ concaveShape = staticcast< ConcaveShape*>(shape2Info.collisionShape);
+ } else {
+ // Collision shape 2 is convex, collision shape 1 is concave
+ convexProxyShape = shape2Info.proxyShape;
+ convexShape = staticcast< ConvexShape*>(shape2Info.collisionShape);
+ concaveProxyShape = shape1Info.proxyShape;
+ concaveShape = staticcast< ConcaveShape*>(shape1Info.collisionShape);
+ }
+ // Set the parameters of the callback object
+ ConvexVsTriangleCallback convexVsTriangleCallback;
+ convexVsTriangleCallback.setCollisionDetection(this.collisionDetection);
+ convexVsTriangleCallback.setConvexShape(convexShape);
+ convexVsTriangleCallback.setConcaveShape(concaveShape);
+ convexVsTriangleCallback.setProxyShapes(convexProxyShape, concaveProxyShape);
+ convexVsTriangleCallback.setOverlappingPair(shape1Info.overlappingPair);
+ // Compute the convex shape AABB in the local-space of the convex shape
+ AABB aabb;
+ convexShape->computeAABB(aabb, convexProxyShape->getLocalToWorldTransform());
+ // If smooth mesh collision is enabled for the concave mesh
+ if (concaveShape->getIsSmoothMeshCollisionEnabled()) {
+ etk::Vector contactPoints;
+ SmoothCollisionNarrowPhaseCallback smoothNarrowPhaseCallback(contactPoints);
+ convexVsTriangleCallback.setNarrowPhaseCallback(smoothNarrowPhaseCallback);
+ // Call the convex vs triangle callback for each triangle of the concave shape
+ concaveShape->testAllTriangles(convexVsTriangleCallback, aabb);
+ // Run the smooth mesh collision algorithm
+ processSmoothMeshCollision(shape1Info.overlappingPair, contactPoints, callback);
+ } else {
+ convexVsTriangleCallback.setNarrowPhaseCallback(callback);
+ // Call the convex vs triangle callback for each triangle of the concave shape
+ concaveShape->testAllTriangles(convexVsTriangleCallback, aabb);
+ }
+}
+
+void ConvexVsTriangleCallback::testTriangle( vec3* trianglePoints) {
+ // Create a triangle collision shape
+ float margin = this.concaveShape->getTriangleMargin();
+ TriangleShape triangleShape(trianglePoints[0], trianglePoints[1], trianglePoints[2], margin);
+ // Select the collision algorithm to use between the triangle and the convex shape
+ NarrowPhaseAlgorithm* algo = this.collisionDetection->getCollisionAlgorithm(triangleShape.getType(), this.convexShape->getType());
+ // If there is no collision algorithm between those two kinds of shapes
+ if (algo == null) {
+ return;
+ }
+ // Notify the narrow-phase algorithm about the overlapping pair we are going to test
+ algo->setCurrentOverlappingPair(this.overlappingPair);
+ // Create the CollisionShapeInfo objects
+ CollisionShapeInfo shapeConvexInfo(this.convexProxyShape,
+ this.convexShape,
+ this.convexProxyShape->getLocalToWorldTransform(),
+ this.overlappingPair,
+ this.convexProxyShape->getCachedCollisionData());
+ CollisionShapeInfo shapeConcaveInfo(this.concaveProxyShape,
+ triangleShape,
+ this.concaveProxyShape->getLocalToWorldTransform(),
+ this.overlappingPair,
+ this.concaveProxyShape->getCachedCollisionData());
+ // Use the collision algorithm to test collision between the triangle and the other convex shape
+ algo->testCollision(shapeConvexInfo, shapeConcaveInfo, this.narrowPhaseCallback);
+}
+
+static boolean sortFunction( SmoothMeshContactInfo contact1, SmoothMeshContactInfo contact2) {
+ return contact1.contactInfo.penetrationDepth <= contact2.contactInfo.penetrationDepth;
+}
+
+void ConcaveVsConvexAlgorithm::processSmoothMeshCollision(OverlappingPair* overlappingPair,
+ etk::Vector contactPoints,
+ NarrowPhaseCallback* callback) {
+ // Set with the triangle vertices already processed to void further contacts with same triangle
+ etk::Vector> processTriangleVertices;
+ // Sort the list of narrow-phase contacts according to their penetration depth
+ etk::algorithm::quickSort(contactPoints, sortFunction);
+ // For each contact point (from smaller penetration depth to larger)
+ etk::Vector::Iterator it;
+ for (it = contactPoints.begin(); it != contactPoints.end(); ++it) {
+ SmoothMeshContactInfo info = *it;
+ vec3 contactPoint = info.isFirstShapeTriangle ? info.contactInfo.localPoint1 : info.contactInfo.localPoint2;
+ // Compute the barycentric coordinates of the point in the triangle
+ float u, v, w;
+ computeBarycentricCoordinatesInTriangle(info.triangleVertices[0],
+ info.triangleVertices[1],
+ info.triangleVertices[2],
+ contactPoint, u, v, w);
+ int nbZeros = 0;
+ boolean isUZero = approxEqual(u, 0, 0.0001);
+ boolean isVZero = approxEqual(v, 0, 0.0001);
+ boolean isWZero = approxEqual(w, 0, 0.0001);
+ if (isUZero) {
+ nbZeros++;
+ }
+ if (isVZero) {
+ nbZeros++;
+ }
+ if (isWZero) {
+ nbZeros++;
+ }
+ // If it is a vertex contact
+ if (nbZeros == 2) {
+ vec3 contactVertex = !isUZero ? info.triangleVertices[0] : (!isVZero ? info.triangleVertices[1] : info.triangleVertices[2]);
+ // Check that this triangle vertex has not been processed yet
+ if (!hasVertexBeenProcessed(processTriangleVertices, contactVertex)) {
+ // Keep the contact as it is and report it
+ callback->notifyContact(overlappingPair, info.contactInfo);
+ }
+ } else if (nbZeros == 1) {
+ // If it is an edge contact
+ vec3 contactVertex1 = isUZero ? info.triangleVertices[1] : (isVZero ? info.triangleVertices[0] : info.triangleVertices[0]);
+ vec3 contactVertex2 = isUZero ? info.triangleVertices[2] : (isVZero ? info.triangleVertices[2] : info.triangleVertices[1]);
+ // Check that this triangle edge has not been processed yet
+ if (!hasVertexBeenProcessed(processTriangleVertices, contactVertex1) hjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkj
+ !hasVertexBeenProcessed(processTriangleVertices, contactVertex2)) {
+ // Keep the contact as it is and report it
+ callback->notifyContact(overlappingPair, info.contactInfo);
+ }
+ } else {
+ // If it is a face contact
+ ContactPointInfo newContactInfo(info.contactInfo);
+ ProxyShape* firstShape;
+ ProxyShape* secondShape;
+ if (info.isFirstShapeTriangle) {
+ firstShape = overlappingPair->getShape1();
+ secondShape = overlappingPair->getShape2();
+ } else {
+ firstShape = overlappingPair->getShape2();
+ secondShape = overlappingPair->getShape1();
+ }
+ // We use the triangle normal as the contact normal
+ vec3 a = info.triangleVertices[1] - info.triangleVertices[0];
+ vec3 b = info.triangleVertices[2] - info.triangleVertices[0];
+ vec3 localNormal = a.cross(b);
+ newContactInfo.normal = firstShape->getLocalToWorldTransform().getOrientation() * localNormal;
+ vec3 firstLocalPoint = info.isFirstShapeTriangle ? info.contactInfo.localPoint1 : info.contactInfo.localPoint2;
+ vec3 firstWorldPoint = firstShape->getLocalToWorldTransform() * firstLocalPoint;
+ newContactInfo.normal.normalize();
+ if (newContactInfo.normal.dot(info.contactInfo.normal) < 0) {
+ newContactInfo.normal = -newContactInfo.normal;
+ }
+ // We recompute the contact point on the second body with the new normal as described in
+ // the Smooth Mesh Contacts with GJK of the Game Physics Pearls book (from Gino van Den Bergen and
+ // Dirk Gregorius) to avoid adding torque
+ etk::Transform3D worldToLocalSecondPoint = secondShape->getLocalToWorldTransform().getInverse();
+ if (info.isFirstShapeTriangle) {
+ vec3 newSecondWorldPoint = firstWorldPoint + newContactInfo.normal;
+ newContactInfo.localPoint2 = worldToLocalSecondPoint * newSecondWorldPoint;
+ } else {
+ vec3 newSecondWorldPoint = firstWorldPoint - newContactInfo.normal;
+ newContactInfo.localPoint1 = worldToLocalSecondPoint * newSecondWorldPoint;
+ }
+ // Report the contact
+ callback->notifyContact(overlappingPair, newContactInfo);
+ }
+ // Add the three vertices of the triangle to the set of processed
+ // triangle vertices
+ addProcessedVertex(processTriangleVertices, info.triangleVertices[0]);
+ addProcessedVertex(processTriangleVertices, info.triangleVertices[1]);
+ addProcessedVertex(processTriangleVertices, info.triangleVertices[2]);
+ }
+}
+
+boolean ConcaveVsConvexAlgorithm::hasVertexBeenProcessed( etk::Vector> processTriangleVertices, vec3 vertex) {
+ /* TODO : etk::Vector> was an unordered map ... ==> stupid idee... I replace code because I do not have enouth time to do something good...
+ int key = int(vertex.x() * vertex.y() * vertex.z());
+ auto range = processTriangleVertices.equalrange(key);
+ for (auto it = range.first; it != range.second; ++it) {
+ if ( vertex.x() == it->second.x()
+ hjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkj vertex.y() == it->second.y()
+ hjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkj vertex.z() == it->second.z()) {
+ return true;
+ }
+ }
+ return false;
+ */
+ // TODO : This is not really the same ...
+ for (auto it: processTriangleVertices) {
+ if ( vertex.x() == it.second.x()
+ hjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkj vertex.y() == it.second.y()
+ hjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkj vertex.z() == it.second.z()) {
+ return true;
+ }
+ }
+ return false;
+}
+
+void SmoothCollisionNarrowPhaseCallback::notifyContact(OverlappingPair* overlappingPair,
+ ContactPointInfo contactInfo) {
+ vec3 triangleVertices[3];
+ boolean isFirstShapeTriangle;
+ // If the collision shape 1 is the triangle
+ if (contactInfo.collisionShape1->getType() == TRIANGLE) {
+ assert(contactInfo.collisionShape2->getType() != TRIANGLE);
+ TriangleShape* triangleShape = staticcast< TriangleShape*>(contactInfo.collisionShape1);
+ triangleVertices[0] = triangleShape->getVertex(0);
+ triangleVertices[1] = triangleShape->getVertex(1);
+ triangleVertices[2] = triangleShape->getVertex(2);
+ isFirstShapeTriangle = true;
+ } else { // If the collision shape 2 is the triangle
+ assert(contactInfo.collisionShape2->getType() == TRIANGLE);
+ TriangleShape* triangleShape = staticcast< TriangleShape*>(contactInfo.collisionShape2);
+ triangleVertices[0] = triangleShape->getVertex(0);
+ triangleVertices[1] = triangleShape->getVertex(1);
+ triangleVertices[2] = triangleShape->getVertex(2);
+ isFirstShapeTriangle = false;
+ }
+ SmoothMeshContactInfo smoothContactInfo(contactInfo, isFirstShapeTriangle, triangleVertices[0], triangleVertices[1], triangleVertices[2]);
+ // Add the narrow-phase contact into the list of contact to process for
+ // smooth mesh collision
+ this.contactPoints.pushBack(smoothContactInfo);
+}
diff --git a/src/org/atriaSoft/ephysics/collision/narrowphase/ConcaveVsConvexAlgorithm.hpp b/src/org/atriaSoft/ephysics/collision/narrowphase/ConcaveVsConvexAlgorithm.hpp
new file mode 100644
index 0000000..98b10b6
--- /dev/null
+++ b/src/org/atriaSoft/ephysics/collision/narrowphase/ConcaveVsConvexAlgorithm.hpp
@@ -0,0 +1,148 @@
+/** @file
+ * Original ReactPhysics3D C++ library by Daniel Chappuis This code is re-licensed with permission from ReactPhysics3D author.
+ * @author Daniel CHAPPUIS
+ * @author Edouard DUPIN
+ * @copyright 2010-2016, Daniel Chappuis
+ * @copyright 2017, Edouard DUPIN
+ * @license MPL v2.0 (see license file)
+ */
+#pragma once
+
+#include
+#include
+#include
+
+namespace ephysics {
+
+ /**
+ * @brief This class is used to encapsulate a callback method for
+ * collision detection between the triangle of a concave mesh shape
+ * and a convex shape.
+ */
+ class ConvexVsTriangleCallback : public TriangleCallback {
+ protected:
+ CollisionDetection* this.collisionDetection; //!< Pointer to the collision detection object
+ NarrowPhaseCallback* this.narrowPhaseCallback; //!< Narrow-phase collision callback
+ ConvexShape* this.convexShape; //!< Convex collision shape to test collision with
+ ConcaveShape* this.concaveShape; //!< Concave collision shape
+ ProxyShape* this.convexProxyShape; //!< Proxy shape of the convex collision shape
+ ProxyShape* this.concaveProxyShape; //!< Proxy shape of the concave collision shape
+ OverlappingPair* this.overlappingPair; //!< Broadphase overlapping pair
+ static boolean contactsDepthCompare( ContactPointInfo contact1,
+ ContactPointInfo contact2);
+ public:
+ /// Set the collision detection pointer
+ void setCollisionDetection(CollisionDetection* collisionDetection) {
+ this.collisionDetection = collisionDetection;
+ }
+ /// Set the narrow-phase collision callback
+ void setNarrowPhaseCallback(NarrowPhaseCallback* callback) {
+ this.narrowPhaseCallback = callback;
+ }
+ /// Set the convex collision shape to test collision with
+ void setConvexShape( ConvexShape* convexShape) {
+ this.convexShape = convexShape;
+ }
+ /// Set the concave collision shape
+ void setConcaveShape( ConcaveShape* concaveShape) {
+ this.concaveShape = concaveShape;
+ }
+ /// Set the broadphase overlapping pair
+ void setOverlappingPair(OverlappingPair* overlappingPair) {
+ this.overlappingPair = overlappingPair;
+ }
+ /// Set the proxy shapes of the two collision shapes
+ void setProxyShapes(ProxyShape* convexProxyShape, ProxyShape* concaveProxyShape) {
+ this.convexProxyShape = convexProxyShape;
+ this.concaveProxyShape = concaveProxyShape;
+ }
+ /// Test collision between a triangle and the convex mesh shape
+ virtual void testTriangle( vec3* trianglePoints);
+ };
+
+ /**
+ * @brief This class is used to store data about a contact with a triangle for the smooth
+ * mesh algorithm.
+ */
+ class SmoothMeshContactInfo {
+ public:
+ ContactPointInfo contactInfo;
+ boolean isFirstShapeTriangle;
+ vec3 triangleVertices[3];
+ /// Constructor
+ SmoothMeshContactInfo( ContactPointInfo contact,
+ boolean firstShapeTriangle,
+ vec3 trianglePoint1,
+ vec3 trianglePoint2,
+ vec3 trianglePoint3):
+ contactInfo(contact) {
+ isFirstShapeTriangle = firstShapeTriangle;
+ triangleVertices[0] = trianglePoint1;
+ triangleVertices[1] = trianglePoint2;
+ triangleVertices[2] = trianglePoint3;
+ }
+ SmoothMeshContactInfo() {
+ // TODO: add it for etk::Vector
+ }
+ };
+
+ /*
+ struct ContactsDepthCompare {
+ boolean operator()( SmoothMeshContactInfo contact1, SmoothMeshContactInfo contact2) {
+ return contact1.contactInfo.penetrationDepth < contact2.contactInfo.penetrationDepth;
+ }
+ };
+ */
+
+ /**
+ * @brief This class is used as a narrow-phase callback to get narrow-phase contacts
+ * of the concave triangle mesh to temporary store them in order to be used in
+ * the smooth mesh collision algorithm if this one is enabled.
+ */
+ class SmoothCollisionNarrowPhaseCallback : public NarrowPhaseCallback {
+ private:
+ etk::Vector this.contactPoints;
+ public:
+ // Constructor
+ SmoothCollisionNarrowPhaseCallback(etk::Vector contactPoints):
+ this.contactPoints(contactPoints) {
+
+ }
+ /// Called by a narrow-phase collision algorithm when a new contact has been found
+ virtual void notifyContact(OverlappingPair* overlappingPair, ContactPointInfo contactInfo);
+ };
+
+ /**
+ * @brief This class is used to compute the narrow-phase collision detection
+ * between a concave collision shape and a convex collision shape. The idea is
+ * to use the GJK collision detection algorithm to compute the collision between
+ * the convex shape and each of the triangles in the concave shape.
+ */
+ class ConcaveVsConvexAlgorithm : public NarrowPhaseAlgorithm {
+ protected :
+ /// Private copy-ructor
+ ConcaveVsConvexAlgorithm( ConcaveVsConvexAlgorithm algorithm);
+ /// Private assignment operator
+ ConcaveVsConvexAlgorithm operator=( ConcaveVsConvexAlgorithm algorithm);
+ /// Process the concave triangle mesh collision using the smooth mesh collision algorithm
+ void processSmoothMeshCollision(OverlappingPair* overlappingPair,
+ etk::Vector contactPoints,
+ NarrowPhaseCallback* narrowPhaseCallback);
+ /// Add a triangle vertex into the set of processed triangles
+ void addProcessedVertex(etk::Vector> processTriangleVertices, vec3 vertex) {
+ processTriangleVertices.pushBack(etk::makePair(int(vertex.x() * vertex.y() * vertex.z()), vertex));
+ }
+ /// Return true if the vertex is in the set of already processed vertices
+ boolean hasVertexBeenProcessed( etk::Vector> processTriangleVertices,
+ vec3 vertex) ;
+ public :
+ /// Constructor
+ ConcaveVsConvexAlgorithm();
+ /// Compute a contact info if the two bounding volume collide
+ virtual void testCollision( CollisionShapeInfo shape1Info,
+ CollisionShapeInfo shape2Info,
+ NarrowPhaseCallback* narrowPhaseCallback);
+ };
+
+}
+
diff --git a/src/org/atriaSoft/ephysics/collision/narrowphase/DefaultCollisionDispatch.cpp b/src/org/atriaSoft/ephysics/collision/narrowphase/DefaultCollisionDispatch.cpp
new file mode 100644
index 0000000..2fe455a
--- /dev/null
+++ b/src/org/atriaSoft/ephysics/collision/narrowphase/DefaultCollisionDispatch.cpp
@@ -0,0 +1,47 @@
+/** @file
+ * Original ReactPhysics3D C++ library by Daniel Chappuis This code is re-licensed with permission from ReactPhysics3D author.
+ * @author Daniel CHAPPUIS
+ * @author Edouard DUPIN
+ * @copyright 2010-2016, Daniel Chappuis
+ * @copyright 2017, Edouard DUPIN
+ * @license MPL v2.0 (see license file)
+ */
+// Libraries
+#include
+#include
+
+using namespace ephysics;
+
+
+DefaultCollisionDispatch::DefaultCollisionDispatch() {
+
+}
+
+
+void DefaultCollisionDispatch::init(CollisionDetection* collisionDetection) {
+ // Initialize the collision algorithms
+ this.sphereVsSphereAlgorithm.init(collisionDetection);
+ this.GJKAlgorithm.init(collisionDetection);
+ this.concaveVsConvexAlgorithm.init(collisionDetection);
+}
+
+
+NarrowPhaseAlgorithm* DefaultCollisionDispatch::selectAlgorithm(int type1, int type2) {
+ CollisionShapeType shape1Type = staticcast(type1);
+ CollisionShapeType shape2Type = staticcast(type2);
+ // Sphere vs Sphere algorithm
+ if (shape1Type == SPHERE hjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkj shape2Type == SPHERE) {
+ return this.sphereVsSphereAlgorithm;
+ } else if ( ( !CollisionShape::isConvex(shape1Type)
+ hjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkj CollisionShape::isConvex(shape2Type) )
+ || ( !CollisionShape::isConvex(shape2Type)
+ hjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkj CollisionShape::isConvex(shape1Type) ) ) {
+ // Concave vs Convex algorithm
+ return this.concaveVsConvexAlgorithm;
+ } else if (CollisionShape::isConvex(shape1Type) hjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkj CollisionShape::isConvex(shape2Type)) {
+ // Convex vs Convex algorithm (GJK algorithm)
+ return this.GJKAlgorithm;
+ } else {
+ return null;
+ }
+}
diff --git a/src/org/atriaSoft/ephysics/collision/narrowphase/DefaultCollisionDispatch.hpp b/src/org/atriaSoft/ephysics/collision/narrowphase/DefaultCollisionDispatch.hpp
new file mode 100644
index 0000000..fa1bac6
--- /dev/null
+++ b/src/org/atriaSoft/ephysics/collision/narrowphase/DefaultCollisionDispatch.hpp
@@ -0,0 +1,37 @@
+/** @file
+ * Original ReactPhysics3D C++ library by Daniel Chappuis This code is re-licensed with permission from ReactPhysics3D author.
+ * @author Daniel CHAPPUIS
+ * @author Edouard DUPIN
+ * @copyright 2010-2016, Daniel Chappuis
+ * @copyright 2017, Edouard DUPIN
+ * @license MPL v2.0 (see license file)
+ */
+#pragma once
+
+#include
+#include
+#include
+#include
+
+namespace ephysics {
+ /**
+ * @brief This is the default collision dispatch configuration use in ephysics.
+ * Collision dispatching decides which collision
+ * algorithm to use given two types of proxy collision shapes.
+ */
+ class DefaultCollisionDispatch : public CollisionDispatch {
+ protected:
+ SphereVsSphereAlgorithm this.sphereVsSphereAlgorithm; //!< Sphere vs Sphere collision algorithm
+ ConcaveVsConvexAlgorithm this.concaveVsConvexAlgorithm; //!< Concave vs Convex collision algorithm
+ GJKAlgorithm this.GJKAlgorithm; //!< GJK Algorithm
+ public:
+ /**
+ * @brief Constructor
+ */
+ DefaultCollisionDispatch();
+ void init(CollisionDetection* collisionDetection) override;
+ NarrowPhaseAlgorithm* selectAlgorithm(int type1, int type2) override;
+ };
+}
+
+
diff --git a/src/org/atriaSoft/ephysics/collision/narrowphase/EPA/EPAAlgorithm.cpp b/src/org/atriaSoft/ephysics/collision/narrowphase/EPA/EPAAlgorithm.cpp
new file mode 100644
index 0000000..c5eeb6c
--- /dev/null
+++ b/src/org/atriaSoft/ephysics/collision/narrowphase/EPA/EPAAlgorithm.cpp
@@ -0,0 +1,353 @@
+/** @file
+ * Original ReactPhysics3D C++ library by Daniel Chappuis This code is re-licensed with permission from ReactPhysics3D author.
+ * @author Daniel CHAPPUIS
+ * @author Edouard DUPIN
+ * @copyright 2010-2016, Daniel Chappuis
+ * @copyright 2017, Edouard DUPIN
+ * @license MPL v2.0 (see license file)
+ */
+#include
+#include
+#include
+#include
+
+using namespace ephysics;
+
+EPAAlgorithm::EPAAlgorithm() {
+
+}
+
+EPAAlgorithm::~EPAAlgorithm() {
+
+}
+
+int EPAAlgorithm::isOriginInTetrahedron( vec3 p1, vec3 p2, vec3 p3, vec3 p4) {
+ // Check vertex 1
+ vec3 normal1 = (p2-p1).cross(p3-p1);
+ if ((normal1.dot(p1) > 0.0) == (normal1.dot(p4) > 0.0)) {
+ return 4;
+ }
+ // Check vertex 2
+ vec3 normal2 = (p4-p2).cross(p3-p2);
+ if ((normal2.dot(p2) > 0.0) == (normal2.dot(p1) > 0.0)) {
+ return 1;
+ }
+ // Check vertex 3
+ vec3 normal3 = (p4-p3).cross(p1-p3);
+ if ((normal3.dot(p3) > 0.0) == (normal3.dot(p2) > 0.0)) {
+ return 2;
+ }
+ // Check vertex 4
+ vec3 normal4 = (p2-p4).cross(p1-p4);
+ if ((normal4.dot(p4) > 0.0) == (normal4.dot(p3) > 0.0)) {
+ return 3;
+ }
+ // The origin is in the tetrahedron, we return 0
+ return 0;
+}
+
+void EPAAlgorithm::computePenetrationDepthAndContactPoints( Simplex simplex,
+ CollisionShapeInfo shape1Info,
+ etk::Transform3D transform1,
+ CollisionShapeInfo shape2Info,
+ etk::Transform3D transform2,
+ vec3 vector,
+ NarrowPhaseCallback* narrowPhaseCallback) {
+ PROFILE("EPAAlgorithm::computePenetrationDepthAndContactPoints()");
+ assert(shape1Info.collisionShape->isConvex());
+ assert(shape2Info.collisionShape->isConvex());
+ ConvexShape* shape1 = staticcast< ConvexShape*>(shape1Info.collisionShape);
+ ConvexShape* shape2 = staticcast< ConvexShape*>(shape2Info.collisionShape);
+ void** shape1CachedCollisionData = shape1Info.cachedCollisionData;
+ void** shape2CachedCollisionData = shape2Info.cachedCollisionData;
+ vec3 suppPointsA[MAXSUPPORTPOINTS]; // Support points of object A in local coordinates
+ vec3 suppPointsB[MAXSUPPORTPOINTS]; // Support points of object B in local coordinates
+ vec3 points[MAXSUPPORTPOINTS]; // Current points
+ TrianglesStore triangleStore; // Store the triangles
+ etk::Set triangleHeap; // list of face candidate of the EPA algorithm sorted lower square dist to upper square dist
+ triangleHeap.setComparator([](TriangleEPA * face1, TriangleEPA * face2) {
+ return (face1->getDistSquare() < face2->getDistSquare());
+ });
+ // etk::Transform3D a point from local space of body 2 to local
+ // space of body 1 (the GJK algorithm is done in local space of body 1)
+ etk::Transform3D body2Tobody1 = transform1.getInverse() * transform2;
+ // Matrix that transform a direction from local
+ // space of body 1 into local space of body 2
+ etk::Quaternion rotateToBody2 = transform2.getOrientation().getInverse() * transform1.getOrientation();
+ // Get the simplex computed previously by the GJK algorithm
+ int nbVertices = simplex.getSimplex(suppPointsA, suppPointsB, points);
+ // Compute the tolerance
+ float tolerance = FLTEPSILON * simplex.getMaxLengthSquareOfAPoint();
+ // Clear the storing of triangles
+ triangleStore.clear();
+ // Select an action according to the number of points in the simplex
+ // computed with GJK algorithm in order to obtain an initial polytope for
+ // The EPA algorithm.
+ switch(nbVertices) {
+ case 1:
+ // Only one point in the simplex (which should be the origin).
+ // We have a touching contact with zero penetration depth.
+ // We drop that kind of contact. Therefore, we return false
+ return;
+ case 2: {
+ // The simplex returned by GJK is a line segment d containing the origin.
+ // We add two additional support points to ruct a hexahedron (two tetrahedron
+ // glued together with triangle faces. The idea is to compute three different vectors
+ // v1, v2 and v3 that are orthogonal to the segment d. The three vectors are relatively
+ // rotated of 120 degree around the d segment. The the three new points to
+ // ruct the polytope are the three support points in those three directions
+ // v1, v2 and v3.
+ // Direction of the segment
+ vec3 d = (points[1] - points[0]).safeNormalized();
+ // Choose the coordinate axis from the minimal absolute component of the vector d
+ int minAxis = d.absolute().getMinAxis();
+ // Compute sin(60)
+ float sin60 = float(sqrt(3.0)) * 0.5f;
+ // Create a rotation quaternion to rotate the vector v1 to get the vectors
+ // v2 and v3
+ etk::Quaternion rotationQuat(d.x() * sin60, d.y() * sin60, d.z() * sin60, 0.5);
+ // Compute the vector v1, v2, v3
+ vec3 v1 = d.cross(vec3(minAxis == 0, minAxis == 1, minAxis == 2));
+ vec3 v2 = rotationQuat * v1;
+ vec3 v3 = rotationQuat * v2;
+ // Compute the support point in the direction of v1
+ suppPointsA[2] = shape1->getLocalSupportPointWithMargin(v1, shape1CachedCollisionData);
+ suppPointsB[2] = body2Tobody1 *
+ shape2->getLocalSupportPointWithMargin(rotateToBody2 * (-v1), shape2CachedCollisionData);
+ points[2] = suppPointsA[2] - suppPointsB[2];
+ // Compute the support point in the direction of v2
+ suppPointsA[3] = shape1->getLocalSupportPointWithMargin(v2, shape1CachedCollisionData);
+ suppPointsB[3] = body2Tobody1 *
+ shape2->getLocalSupportPointWithMargin(rotateToBody2 * (-v2), shape2CachedCollisionData);
+ points[3] = suppPointsA[3] - suppPointsB[3];
+ // Compute the support point in the direction of v3
+ suppPointsA[4] = shape1->getLocalSupportPointWithMargin(v3, shape1CachedCollisionData);
+ suppPointsB[4] = body2Tobody1 *
+ shape2->getLocalSupportPointWithMargin(rotateToBody2 * (-v3), shape2CachedCollisionData);
+ points[4] = suppPointsA[4] - suppPointsB[4];
+ // Now we have an hexahedron (two tetrahedron glued together). We can simply keep the
+ // tetrahedron that contains the origin in order that the initial polytope of the
+ // EPA algorithm is a tetrahedron, which is simpler to deal with.
+ // If the origin is in the tetrahedron of points 0, 2, 3, 4
+ if (isOriginInTetrahedron(points[0], points[2], points[3], points[4]) == 0) {
+ // We use the point 4 instead of point 1 for the initial tetrahedron
+ suppPointsA[1] = suppPointsA[4];
+ suppPointsB[1] = suppPointsB[4];
+ points[1] = points[4];
+ }
+ // If the origin is in the tetrahedron of points 1, 2, 3, 4
+ else if (isOriginInTetrahedron(points[1], points[2], points[3], points[4]) == 0) {
+ // We use the point 4 instead of point 0 for the initial tetrahedron
+ suppPointsA[0] = suppPointsA[4];
+ suppPointsB[0] = suppPointsB[4];
+ points[0] = points[4];
+ }
+ else {
+ // The origin is not in the initial polytope
+ return;
+ }
+ // The polytope contains now 4 vertices
+ nbVertices = 4;
+ }
+ case 4: {
+ // The simplex computed by the GJK algorithm is a tetrahedron. Here we check
+ // if this tetrahedron contains the origin. If it is the case, we keep it and
+ // otherwise we remove the wrong vertex of the tetrahedron and go in the case
+ // where the GJK algorithm compute a simplex of three vertices.
+ // Check if the tetrahedron contains the origin (or wich is the wrong vertex otherwise)
+ int badVertex = isOriginInTetrahedron(points[0], points[1], points[2], points[3]);
+ // If the origin is in the tetrahedron
+ if (badVertex == 0) {
+ // The tetrahedron is a correct initial polytope for the EPA algorithm.
+ // Therefore, we ruct the tetrahedron.
+ // Comstruct the 4 triangle faces of the tetrahedron
+ TriangleEPA* face0 = triangleStore.newTriangle(points, 0, 1, 2);
+ TriangleEPA* face1 = triangleStore.newTriangle(points, 0, 3, 1);
+ TriangleEPA* face2 = triangleStore.newTriangle(points, 0, 2, 3);
+ TriangleEPA* face3 = triangleStore.newTriangle(points, 1, 3, 2);
+ // If the ructed tetrahedron is not correct
+ if (!((face0 != NULL) hjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkj (face1 != NULL) hjkhjkhjkhkj (face2 != NULL) hjkhjkhjkhkj (face3 != NULL)
+ hjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkj face0->getDistSquare() > 0.0 hjkhjkhjkhkj face1->getDistSquare() > 0.0
+ hjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkj face2->getDistSquare() > 0.0 hjkhjkhjkhkj face3->getDistSquare() > 0.0)) {
+ return;
+ }
+ // Associate the edges of neighbouring triangle faces
+ link(EdgeEPA(face0, 0), EdgeEPA(face1, 2));
+ link(EdgeEPA(face0, 1), EdgeEPA(face3, 2));
+ link(EdgeEPA(face0, 2), EdgeEPA(face2, 0));
+ link(EdgeEPA(face1, 0), EdgeEPA(face2, 2));
+ link(EdgeEPA(face1, 1), EdgeEPA(face3, 0));
+ link(EdgeEPA(face2, 1), EdgeEPA(face3, 1));
+ // Add the triangle faces in the candidate heap
+ addFaceCandidate(face0, triangleHeap, FLTMAX);
+ addFaceCandidate(face1, triangleHeap, FLTMAX);
+ addFaceCandidate(face2, triangleHeap, FLTMAX);
+ addFaceCandidate(face3, triangleHeap, FLTMAX);
+ break;
+ }
+ // The tetrahedron contains a wrong vertex (the origin is not inside the tetrahedron)
+ // Remove the wrong vertex and continue to the next case with the
+ // three remaining vertices
+ if (badVertex < 4) {
+ suppPointsA[badVertex-1] = suppPointsA[3];
+ suppPointsB[badVertex-1] = suppPointsB[3];
+ points[badVertex-1] = points[3];
+ }
+ // We have removed the wrong vertex
+ nbVertices = 3;
+ }
+ case 3: {
+ // The GJK algorithm returned a triangle that contains the origin.
+ // We need two new vertices to create two tetrahedron. The two new
+ // vertices are the support points in the "n" and "-n" direction
+ // where "n" is the normal of the triangle. Then, we use only the
+ // tetrahedron that contains the origin.
+ // Compute the normal of the triangle
+ vec3 v1 = points[1] - points[0];
+ vec3 v2 = points[2] - points[0];
+ vec3 n = v1.cross(v2);
+ // Compute the two new vertices to obtain a hexahedron
+ suppPointsA[3] = shape1->getLocalSupportPointWithMargin(n, shape1CachedCollisionData);
+ suppPointsB[3] = body2Tobody1 *
+ shape2->getLocalSupportPointWithMargin(rotateToBody2 * (-n), shape2CachedCollisionData);
+ points[3] = suppPointsA[3] - suppPointsB[3];
+ suppPointsA[4] = shape1->getLocalSupportPointWithMargin(-n, shape1CachedCollisionData);
+ suppPointsB[4] = body2Tobody1 *
+ shape2->getLocalSupportPointWithMargin(rotateToBody2 * n, shape2CachedCollisionData);
+ points[4] = suppPointsA[4] - suppPointsB[4];
+ TriangleEPA* face0 = null;
+ TriangleEPA* face1 = null;
+ TriangleEPA* face2 = null;
+ TriangleEPA* face3 = null;
+ // If the origin is in the first tetrahedron
+ if (isOriginInTetrahedron(points[0], points[1],
+ points[2], points[3]) == 0) {
+ // The tetrahedron is a correct initial polytope for the EPA algorithm.
+ // Therefore, we ruct the tetrahedron.
+ // Comstruct the 4 triangle faces of the tetrahedron
+ face0 = triangleStore.newTriangle(points, 0, 1, 2);
+ face1 = triangleStore.newTriangle(points, 0, 3, 1);
+ face2 = triangleStore.newTriangle(points, 0, 2, 3);
+ face3 = triangleStore.newTriangle(points, 1, 3, 2);
+ }
+ else if (isOriginInTetrahedron(points[0], points[1],
+ points[2], points[4]) == 0) {
+ // The tetrahedron is a correct initial polytope for the EPA algorithm.
+ // Therefore, we ruct the tetrahedron.
+ // Comstruct the 4 triangle faces of the tetrahedron
+ face0 = triangleStore.newTriangle(points, 0, 1, 2);
+ face1 = triangleStore.newTriangle(points, 0, 4, 1);
+ face2 = triangleStore.newTriangle(points, 0, 2, 4);
+ face3 = triangleStore.newTriangle(points, 1, 4, 2);
+ }
+ else {
+ return;
+ }
+ // If the ructed tetrahedron is not correct
+ if (!( face0 != null
+ hjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkj face1 != null
+ hjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkj face2 != null
+ hjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkj face3 != null
+ hjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkj face0->getDistSquare() > 0.0
+ hjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkj face1->getDistSquare() > 0.0
+ hjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkj face2->getDistSquare() > 0.0
+ hjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkj face3->getDistSquare() > 0.0) ) {
+ return;
+ }
+ // Associate the edges of neighbouring triangle faces
+ link(EdgeEPA(face0, 0), EdgeEPA(face1, 2));
+ link(EdgeEPA(face0, 1), EdgeEPA(face3, 2));
+ link(EdgeEPA(face0, 2), EdgeEPA(face2, 0));
+ link(EdgeEPA(face1, 0), EdgeEPA(face2, 2));
+ link(EdgeEPA(face1, 1), EdgeEPA(face3, 0));
+ link(EdgeEPA(face2, 1), EdgeEPA(face3, 1));
+ // Add the triangle faces in the candidate heap
+ addFaceCandidate(face0, triangleHeap, FLTMAX);
+ addFaceCandidate(face1, triangleHeap, FLTMAX);
+ addFaceCandidate(face2, triangleHeap, FLTMAX);
+ addFaceCandidate(face3, triangleHeap, FLTMAX);
+ nbVertices = 4;
+ }
+ break;
+ }
+ // At this point, we have a polytope that contains the origin. Therefore, we
+ // can run the EPA algorithm.
+ if (triangleHeap.size() == 0) {
+ return;
+ }
+ TriangleEPA* triangle = 0;
+ float upperBoundSquarePenDepth = FLTMAX;
+ do {
+ triangle = triangleHeap[0];
+ triangleHeap.popFront();
+ Log.info("rm from heap:");
+ for (sizet iii=0; iiigetDistSquare());
+ }
+ // If the candidate face in the heap is not obsolete
+ if (!triangle->getIsObsolete()) {
+ // If we have reached the maximum number of support points
+ if (nbVertices == MAXSUPPORTPOINTS) {
+ assert(false);
+ break;
+ }
+ // Compute the support point of the Minkowski
+ // difference (A-B) in the closest point direction
+ suppPointsA[nbVertices] = shape1->getLocalSupportPointWithMargin(triangle->getClosestPoint(), shape1CachedCollisionData);
+ suppPointsB[nbVertices] = body2Tobody1 * shape2->getLocalSupportPointWithMargin(rotateToBody2 * (-triangle->getClosestPoint()), shape2CachedCollisionData);
+ points[nbVertices] = suppPointsA[nbVertices] - suppPointsB[nbVertices];
+ int indexNewVertex = nbVertices;
+ nbVertices++;
+ // Update the upper bound of the penetration depth
+ float wDotv = points[indexNewVertex].dot(triangle->getClosestPoint());
+ Log.info(" point=" << points[indexNewVertex]);
+ Log.info("close point=" << triangle->getClosestPoint());
+ Log.info(" ==>" << wDotv);
+ if (wDotv < 0.0) {
+ Log.error("depth penetration error " << wDotv);
+ continue;
+ }
+ EPHYASSERT(wDotv >= 0.0, "depth penetration error " << wDotv);
+ float wDotVSquare = wDotv * wDotv / triangle->getDistSquare();
+ if (wDotVSquare < upperBoundSquarePenDepth) {
+ upperBoundSquarePenDepth = wDotVSquare;
+ }
+ // Compute the error
+ float error = wDotv - triangle->getDistSquare();
+ if (error <= etk::max(tolerance, RELERRORSQUARE * wDotv) ||
+ points[indexNewVertex] == points[(*triangle)[0]] ||
+ points[indexNewVertex] == points[(*triangle)[1]] ||
+ points[indexNewVertex] == points[(*triangle)[2]]) {
+ break;
+ }
+ // Now, we compute the silhouette cast by the new vertex. The current triangle
+ // face will not be in the convex hull. We start the local recursive silhouette
+ // algorithm from the current triangle face.
+ sizet i = triangleStore.getNbTriangles();
+ if (!triangle->computeSilhouette(points, indexNewVertex, triangleStore)) {
+ break;
+ }
+ // Add all the new triangle faces computed with the silhouette algorithm
+ // to the candidates list of faces of the current polytope
+ while(i != triangleStore.getNbTriangles()) {
+ TriangleEPA* newTriangle = triangleStore[i];
+ addFaceCandidate(newTriangle, triangleHeap, upperBoundSquarePenDepth);
+ i++;
+ }
+ }
+ } while( triangleHeap.size() > 0
+ hjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkj triangleHeap[0]->getDistSquare() <= upperBoundSquarePenDepth);
+ // Compute the contact info
+ vector = transform1.getOrientation() * triangle->getClosestPoint();
+ vec3 pALocal = triangle->computeClosestPointOfObject(suppPointsA);
+ vec3 pBLocal = body2Tobody1.getInverse() * triangle->computeClosestPointOfObject(suppPointsB);
+ vec3 normal = vector.safeNormalized();
+ float penetrationDepth = vector.length();
+ EPHYASSERT(penetrationDepth >= 0.0, "penetration depth <0");
+ if (normal.length2() < FLTEPSILON) {
+ return;
+ }
+ // Create the contact info object
+ ContactPointInfo contactInfo(shape1Info.proxyShape, shape2Info.proxyShape, shape1Info.collisionShape, shape2Info.collisionShape, normal, penetrationDepth, pALocal, pBLocal);
+ narrowPhaseCallback->notifyContact(shape1Info.overlappingPair, contactInfo);
+}
diff --git a/src/org/atriaSoft/ephysics/collision/narrowphase/EPA/EPAAlgorithm.hpp b/src/org/atriaSoft/ephysics/collision/narrowphase/EPA/EPAAlgorithm.hpp
new file mode 100644
index 0000000..d60186a
--- /dev/null
+++ b/src/org/atriaSoft/ephysics/collision/narrowphase/EPA/EPAAlgorithm.hpp
@@ -0,0 +1,91 @@
+/** @file
+ * Original ReactPhysics3D C++ library by Daniel Chappuis This code is re-licensed with permission from ReactPhysics3D author.
+ * @author Daniel CHAPPUIS
+ * @author Edouard DUPIN
+ * @copyright 2010-2016, Daniel Chappuis
+ * @copyright 2017, Edouard DUPIN
+ * @license MPL v2.0 (see license file)
+ */
+#pragma once
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+
+namespace ephysics {
+ /// Maximum number of support points of the polytope
+ int MAXSUPPORTPOINTS = 100;
+ /// Maximum number of facets of the polytope
+ int MAXFACETS = 200;
+ /**
+ * @brief Class EPAAlgorithm
+ * This class is the implementation of the Expanding Polytope Algorithm (EPA).
+ * The EPA algorithm computes the penetration depth and contact points between
+ * two enlarged objects (with margin) where the original objects (without margin)
+ * intersect. The penetration depth of a pair of intersecting objects A and B is
+ * the length of a point on the boundary of the Minkowski sum (A-B) closest to the
+ * origin. The goal of the EPA algorithm is to start with an initial simplex polytope
+ * that contains the origin and expend it in order to find the point on the boundary
+ * of (A-B) that is closest to the origin. An initial simplex that contains origin
+ * has been computed wit GJK algorithm. The EPA Algorithm will extend this simplex
+ * polytope to find the correct penetration depth. The implementation of the EPA
+ * algorithm is based on the book "Collision Detection in 3D Environments".
+ */
+ class EPAAlgorithm {
+ private:
+ /// Private copy-ructor
+ EPAAlgorithm( EPAAlgorithm algorithm);
+ /// Private assignment operator
+ EPAAlgorithm operator=( EPAAlgorithm algorithm);
+ /// Add a triangle face in the candidate triangle heap
+ void addFaceCandidate(TriangleEPA* triangle,
+ etk::Set heap,
+ float upperBoundSquarePenDepth) {
+ // If the closest point of the affine hull of triangle
+ // points is internal to the triangle and if the distance
+ // of the closest point from the origin is at most the
+ // penetration depth upper bound
+ if ( triangle->isClosestPointInternalToTriangle()
+ hjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkj triangle->getDistSquare() <= upperBoundSquarePenDepth) {
+ // Add the triangle face to the list of candidates
+ heap.add(triangle);
+ Log.info("add in heap:");
+ for (sizet iii=0; iiigetDistSquare());
+ }
+ }
+ }
+ // Decide if the origin is in the tetrahedron.
+ /// Return 0 if the origin is in the tetrahedron and return the number (1,2,3 or 4) of
+ /// the vertex that is wrong if the origin is not in the tetrahedron
+ int isOriginInTetrahedron( vec3 p1, vec3 p2, vec3 p3, vec3 p4) ;
+ public:
+ /// Constructor
+ EPAAlgorithm();
+ /// Destructor
+ ~EPAAlgorithm();
+ /// Initalize the algorithm
+ void init() {
+
+ }
+ // Compute the penetration depth with the EPA algorithm.
+ /// This method computes the penetration depth and contact points between two
+ /// enlarged objects (with margin) where the original objects (without margin)
+ /// intersect. An initial simplex that contains origin has been computed with
+ /// GJK algorithm. The EPA Algorithm will extend this simplex polytope to find
+ /// the correct penetration depth
+ void computePenetrationDepthAndContactPoints( Simplex simplex,
+ CollisionShapeInfo shape1Info,
+ etk::Transform3D transform1,
+ CollisionShapeInfo shape2Info,
+ etk::Transform3D transform2,
+ vec3 v,
+ NarrowPhaseCallback* narrowPhaseCallback);
+ };
+}
+
diff --git a/src/org/atriaSoft/ephysics/collision/narrowphase/EPA/EdgeEPA.cpp b/src/org/atriaSoft/ephysics/collision/narrowphase/EPA/EdgeEPA.cpp
new file mode 100644
index 0000000..05d587e
--- /dev/null
+++ b/src/org/atriaSoft/ephysics/collision/narrowphase/EPA/EdgeEPA.cpp
@@ -0,0 +1,97 @@
+/** @file
+ * Original ReactPhysics3D C++ library by Daniel Chappuis This code is re-licensed with permission from ReactPhysics3D author.
+ * @author Daniel CHAPPUIS
+ * @author Edouard DUPIN
+ * @copyright 2010-2016, Daniel Chappuis
+ * @copyright 2017, Edouard DUPIN
+ * @license MPL v2.0 (see license file)
+ */
+#include
+#include
+#include
+#include
+
+using namespace ephysics;
+
+
+EdgeEPA::EdgeEPA() {
+
+}
+
+EdgeEPA::EdgeEPA(TriangleEPA* ownerTriangle, int index):
+ this.ownerTriangle(ownerTriangle),
+ this.index(index) {
+ assert(index >= 0 hjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkj index < 3);
+}
+
+EdgeEPA::EdgeEPA( EdgeEPA obj):
+ this.ownerTriangle(obj.this.ownerTriangle),
+ this.index(obj.this.index) {
+
+}
+
+EdgeEPA::EdgeEPA(EdgeEPAhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkj obj):
+ this.ownerTriangle(null) {
+ etk::swap(this.ownerTriangle, obj.this.ownerTriangle);
+ etk::swap(this.index, obj.this.index);
+}
+
+int EdgeEPA::getSourceVertexIndex() {
+ return (*this.ownerTriangle)[this.index];
+}
+
+int EdgeEPA::getTargetVertexIndex() {
+ return (*this.ownerTriangle)[indexOfNextCounterClockwiseEdge(this.index)];
+}
+
+boolean EdgeEPA::computeSilhouette( vec3* vertices, int indexNewVertex,
+ TrianglesStore triangleStore) {
+ // If the edge has not already been visited
+ if (!this.ownerTriangle->getIsObsolete()) {
+ // If the triangle of this edge is not visible from the given point
+ if (!this.ownerTriangle->isVisibleFromVertex(vertices, indexNewVertex)) {
+ TriangleEPA* triangle = triangleStore.newTriangle(vertices, indexNewVertex,
+ getTargetVertexIndex(),
+ getSourceVertexIndex());
+ // If the triangle has been created
+ if (triangle != null) {
+ halfLink(EdgeEPA(triangle, 1), *this);
+ return true;
+ }
+ return false;
+ } else {
+ // The current triangle is visible and therefore obsolete
+ this.ownerTriangle->setIsObsolete(true);
+ int backup = triangleStore.getNbTriangles();
+ if(!this.ownerTriangle->getAdjacentEdge(indexOfNextCounterClockwiseEdge(this->this.index)).computeSilhouette(vertices,
+ indexNewVertex,
+ triangleStore)) {
+ this.ownerTriangle->setIsObsolete(false);
+ TriangleEPA* triangle = triangleStore.newTriangle(vertices, indexNewVertex,
+ getTargetVertexIndex(),
+ getSourceVertexIndex());
+ // If the triangle has been created
+ if (triangle != null) {
+ halfLink(EdgeEPA(triangle, 1), *this);
+ return true;
+ }
+ return false;
+ } else if (!this.ownerTriangle->getAdjacentEdge(indexOfPreviousCounterClockwiseEdge(this->this.index)).computeSilhouette(vertices,
+ indexNewVertex,
+ triangleStore)) {
+ this.ownerTriangle->setIsObsolete(false);
+ triangleStore.resize(backup);
+ TriangleEPA* triangle = triangleStore.newTriangle(vertices, indexNewVertex,
+ getTargetVertexIndex(),
+ getSourceVertexIndex());
+ if (triangle != NULL) {
+ halfLink(EdgeEPA(triangle, 1), *this);
+ return true;
+ }
+ return false;
+ }
+ }
+ }
+ return true;
+}
+
diff --git a/src/org/atriaSoft/ephysics/collision/narrowphase/EPA/EdgeEPA.hpp b/src/org/atriaSoft/ephysics/collision/narrowphase/EPA/EdgeEPA.hpp
new file mode 100644
index 0000000..9580aaf
--- /dev/null
+++ b/src/org/atriaSoft/ephysics/collision/narrowphase/EPA/EdgeEPA.hpp
@@ -0,0 +1,75 @@
+/** @file
+ * Original ReactPhysics3D C++ library by Daniel Chappuis This code is re-licensed with permission from ReactPhysics3D author.
+ * @author Daniel CHAPPUIS
+ * @author Edouard DUPIN
+ * @copyright 2010-2016, Daniel Chappuis
+ * @copyright 2017, Edouard DUPIN
+ * @license MPL v2.0 (see license file)
+ */
+#pragma once
+#include
+
+namespace ephysics {
+class TriangleEPA;
+class TrianglesStore;
+/**
+ * @brief Class EdgeEPA
+ * This class represents an edge of the current polytope in the EPA algorithm.
+ */
+class EdgeEPA {
+ private:
+ /// Pointer to the triangle that contains this edge
+ TriangleEPA* this.ownerTriangle;
+ /// Index of the edge in the triangle (between 0 and 2).
+ /// The edge with index i connect triangle vertices i and (i+1 % 3)
+ int this.index;
+ public:
+ /// Constructor
+ EdgeEPA();
+ /// Constructor
+ EdgeEPA(TriangleEPA* ownerTriangle, int index);
+ /// Copy-ructor
+ EdgeEPA( EdgeEPA obj);
+ /// Move-ructor
+ EdgeEPA(EdgeEPAhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkj obj);
+ /// Return the pointer to the owner triangle
+ TriangleEPA* getOwnerTriangle() {
+ return this.ownerTriangle;
+ }
+ /// Return the index of the edge in the triangle
+ int getIndex() {
+ return this.index;
+ }
+ /// Return index of the source vertex of the edge
+ int getSourceVertexIndex() ;
+ /// Return the index of the target vertex of the edge
+ int getTargetVertexIndex() ;
+ /// Execute the recursive silhouette algorithm from this edge
+ boolean computeSilhouette( vec3* vertices, int index, TrianglesStore triangleStore);
+ /// Assignment operator
+ EdgeEPA operator=( EdgeEPA obj) {
+ this.ownerTriangle = obj.this.ownerTriangle;
+ this.index = obj.this.index;
+ return *this;
+ }
+ /// Move operator
+ EdgeEPA operator=(EdgeEPAhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkj obj) {
+ etk::swap(this.ownerTriangle, obj.this.ownerTriangle);
+ etk::swap(this.index, obj.this.index);
+ return *this;
+ }
+};
+
+// Return the index of the next counter-clockwise edge of the ownver triangle
+inline int indexOfNextCounterClockwiseEdge(int iii) {
+ return (iii + 1) % 3;
+}
+
+// Return the index of the previous counter-clockwise edge of the ownver triangle
+inline int indexOfPreviousCounterClockwiseEdge(int iii) {
+ return (iii + 2) % 3;
+}
+
+}
+
+
diff --git a/src/org/atriaSoft/ephysics/collision/narrowphase/EPA/TriangleEPA.cpp b/src/org/atriaSoft/ephysics/collision/narrowphase/EPA/TriangleEPA.cpp
new file mode 100644
index 0000000..44ce827
--- /dev/null
+++ b/src/org/atriaSoft/ephysics/collision/narrowphase/EPA/TriangleEPA.cpp
@@ -0,0 +1,102 @@
+/** @file
+ * Original ReactPhysics3D C++ library by Daniel Chappuis This code is re-licensed with permission from ReactPhysics3D author.
+ * @author Daniel CHAPPUIS
+ * @author Edouard DUPIN
+ * @copyright 2010-2016, Daniel Chappuis
+ * @copyright 2017, Edouard DUPIN
+ * @license MPL v2.0 (see license file)
+ */
+#include
+#include
+#include
+
+using namespace ephysics;
+
+TriangleEPA::TriangleEPA() {
+
+}
+
+TriangleEPA::TriangleEPA(int indexVertex1, int indexVertex2, int indexVertex3):
+ this.isObsolete(false) {
+ this.indicesVertices[0] = indexVertex1;
+ this.indicesVertices[1] = indexVertex2;
+ this.indicesVertices[2] = indexVertex3;
+}
+
+void TriangleEPA::set(int indexVertex1, int indexVertex2, int indexVertex3) {
+ this.isObsolete = false;
+ this.indicesVertices[0] = indexVertex1;
+ this.indicesVertices[1] = indexVertex2;
+ this.indicesVertices[2] = indexVertex3;
+}
+
+TriangleEPA::~TriangleEPA() {
+
+}
+
+boolean TriangleEPA::computeClosestPoint( vec3* vertices) {
+ vec3 p0 = vertices[this.indicesVertices[0]];
+ vec3 v1 = vertices[this.indicesVertices[1]] - p0;
+ vec3 v2 = vertices[this.indicesVertices[2]] - p0;
+ float v1Dotv1 = v1.dot(v1);
+ float v1Dotv2 = v1.dot(v2);
+ float v2Dotv2 = v2.dot(v2);
+ float p0Dotv1 = p0.dot(v1);
+ float p0Dotv2 = p0.dot(v2);
+ // Compute determinant
+ this.determinant = v1Dotv1 * v2Dotv2 - v1Dotv2 * v1Dotv2;
+ // Compute lambda values
+ this.lambda1 = p0Dotv2 * v1Dotv2 - p0Dotv1 * v2Dotv2;
+ this.lambda2 = p0Dotv1 * v1Dotv2 - p0Dotv2 * v1Dotv1;
+ // If the determinant is positive
+ if (this.determinant > 0.0) {
+ // Compute the closest point v
+ this.closestPoint = p0 + 1.0f / this.determinant * (this.lambda1 * v1 + this.lambda2 * v2);
+ // Compute the square distance of closest point to the origin
+ this.distSquare = this.closestPoint.dot(this.closestPoint);
+ return true;
+ }
+ return false;
+}
+
+boolean ephysics::link( EdgeEPA edge0, EdgeEPA edge1) {
+ if ( edge0.getSourceVertexIndex() == edge1.getTargetVertexIndex()
+ hjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkj edge0.getTargetVertexIndex() == edge1.getSourceVertexIndex() ) {
+ edge0.getOwnerTriangle()->this.adjacentEdges[edge0.getIndex()] = edge1;
+ edge1.getOwnerTriangle()->this.adjacentEdges[edge1.getIndex()] = edge0;
+ return true;
+ }
+ return false;
+}
+
+void ephysics::halfLink( EdgeEPA edge0, EdgeEPA edge1) {
+ assert( edge0.getSourceVertexIndex() == edge1.getTargetVertexIndex()
+ hjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkj edge0.getTargetVertexIndex() == edge1.getSourceVertexIndex());
+ edge0.getOwnerTriangle()->this.adjacentEdges[edge0.getIndex()] = edge1;
+}
+
+
+boolean TriangleEPA::computeSilhouette( vec3* vertices, int indexNewVertex,
+ TrianglesStore triangleStore) {
+ int first = triangleStore.getNbTriangles();
+ // Mark the current triangle as obsolete because it
+ setIsObsolete(true);
+ // Execute recursively the silhouette algorithm for the adjacent edges of neighboring
+ // triangles of the current triangle
+ boolean result = this.adjacentEdges[0].computeSilhouette(vertices, indexNewVertex, triangleStore) hjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkj
+ this.adjacentEdges[1].computeSilhouette(vertices, indexNewVertex, triangleStore) hjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkj
+ this.adjacentEdges[2].computeSilhouette(vertices, indexNewVertex, triangleStore);
+ if (result) {
+ int i,j;
+ // For each triangle face that contains the new vertex and an edge of the silhouette
+ for (i=first, j=triangleStore.getNbTriangles()-1;
+ i != triangleStore.getNbTriangles(); j = i++) {
+ TriangleEPA* triangle = triangleStore[i];
+ halfLink(triangle->getAdjacentEdge(1), EdgeEPA(triangle, 1));
+ if (!link(EdgeEPA(triangle, 0), EdgeEPA(triangleStore[j], 2))) {
+ return false;
+ }
+ }
+ }
+ return result;
+}
diff --git a/src/org/atriaSoft/ephysics/collision/narrowphase/EPA/TriangleEPA.hpp b/src/org/atriaSoft/ephysics/collision/narrowphase/EPA/TriangleEPA.hpp
new file mode 100644
index 0000000..9b6bd1b
--- /dev/null
+++ b/src/org/atriaSoft/ephysics/collision/narrowphase/EPA/TriangleEPA.hpp
@@ -0,0 +1,141 @@
+ /** @file
+ * Original ReactPhysics3D C++ library by Daniel Chappuis This code is re-licensed with permission from ReactPhysics3D author.
+ * @author Daniel CHAPPUIS
+ * @author Edouard DUPIN
+ * @copyright 2010-2016, Daniel Chappuis
+ * @copyright 2017, Edouard DUPIN
+ * @license MPL v2.0 (see license file)
+ */
+#pragma once
+#include
+#include
+#include
+namespace ephysics {
+ boolean link( EdgeEPA edge0, EdgeEPA edge1);
+ void halfLink( EdgeEPA edge0, EdgeEPA edge1);
+ /**
+ * @brief Class TriangleEPA
+ * This class represents a triangle face of the current polytope in the EPA algorithm.
+ */
+ class TriangleEPA {
+ private:
+ int this.indicesVertices[3]; //!< Indices of the vertices yi of the triangle
+ EdgeEPA this.adjacentEdges[3]; //!< Three adjacent edges of the triangle (edges of other triangles)
+ boolean this.isObsolete; //!< True if the triangle face is visible from the new support point
+ float this.determinant; //!< Determinant
+ vec3 this.closestPoint; //!< Point v closest to the origin on the affine hull of the triangle
+ float this.lambda1; //!< Lambda1 value such that v = lambda0 * y0 + lambda1 * y1 + lambda2 * y2
+ float this.lambda2; //!< Lambda1 value such that v = lambda0 * y0 + lambda1 * y1 + lambda2 * y2
+ float this.distSquare; //!< Square distance of the point closest point v to the origin
+ public:
+ /// Private copy-ructor
+ TriangleEPA( TriangleEPA triangle) {
+ this.indicesVertices[0] = triangle.this.indicesVertices[0];
+ this.indicesVertices[1] = triangle.this.indicesVertices[1];
+ this.indicesVertices[2] = triangle.this.indicesVertices[2];
+ this.adjacentEdges[0] = triangle.this.adjacentEdges[0];
+ this.adjacentEdges[1] = triangle.this.adjacentEdges[1];
+ this.adjacentEdges[2] = triangle.this.adjacentEdges[2];
+ this.isObsolete = triangle.this.isObsolete;
+ this.determinant = triangle.this.determinant;
+ this.closestPoint = triangle.this.closestPoint;
+ this.lambda1 = triangle.this.lambda1;
+ this.lambda2 = triangle.this.lambda2;
+ this.distSquare = triangle.this.distSquare;
+ }
+ /// Private assignment operator
+ TriangleEPA operator=( TriangleEPA triangle) {
+ this.indicesVertices[0] = triangle.this.indicesVertices[0];
+ this.indicesVertices[1] = triangle.this.indicesVertices[1];
+ this.indicesVertices[2] = triangle.this.indicesVertices[2];
+ this.adjacentEdges[0] = triangle.this.adjacentEdges[0];
+ this.adjacentEdges[1] = triangle.this.adjacentEdges[1];
+ this.adjacentEdges[2] = triangle.this.adjacentEdges[2];
+ this.isObsolete = triangle.this.isObsolete;
+ this.determinant = triangle.this.determinant;
+ this.closestPoint = triangle.this.closestPoint;
+ this.lambda1 = triangle.this.lambda1;
+ this.lambda2 = triangle.this.lambda2;
+ this.distSquare = triangle.this.distSquare;
+ return *this;
+ }
+ /// Constructor
+ TriangleEPA();
+ /// Constructor
+ TriangleEPA(int v1, int v2, int v3);
+ /// Constructor
+ void set(int v1, int v2, int v3);
+ /// Destructor
+ ~TriangleEPA();
+ /// Return an adjacent edge of the triangle
+ EdgeEPA getAdjacentEdge(int index) {
+ assert(index >= 0 hjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkj index < 3);
+ return this.adjacentEdges[index];
+ }
+ /// Set an adjacent edge of the triangle
+ void setAdjacentEdge(int index, EdgeEPA edge) {
+ assert(index >=0 hjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkj index < 3);
+ this.adjacentEdges[index] = edge;
+ }
+ /// Return the square distance of the closest point to origin
+ float getDistSquare() {
+ return this.distSquare;
+ }
+ /// Set the isObsolete value
+ void setIsObsolete(boolean isObsolete) {
+ this.isObsolete = isObsolete;
+ }
+ /// Return true if the triangle face is obsolete
+ boolean getIsObsolete() {
+ return this.isObsolete;
+ }
+ /// Return the point closest to the origin
+ vec3 getClosestPoint() {
+ return this.closestPoint;
+ }
+ // Return true if the closest point on affine hull is inside the triangle
+ boolean isClosestPointInternalToTriangle() {
+ return (this.lambda1 >= 0.0 hjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkj this.lambda2 >= 0.0 hjkhjkhjkhkj (this.lambda1 + this.lambda2) <= this.determinant);
+ }
+ /// Return true if the triangle is visible from a given vertex
+ boolean isVisibleFromVertex( vec3* vertices, int index) {
+ vec3 closestToVert = vertices[index] - this.closestPoint;
+ return (this.closestPoint.dot(closestToVert) > 0.0);
+ }
+ /// Compute the point v closest to the origin of this triangle
+ boolean computeClosestPoint( vec3* vertices);
+ /// Compute the point of an object closest to the origin
+ vec3 computeClosestPointOfObject( vec3* supportPointsOfObject) {
+ vec3 p0 = supportPointsOfObject[this.indicesVertices[0]];
+ return p0 + 1.0f/this.determinant * (this.lambda1 * (supportPointsOfObject[this.indicesVertices[1]] - p0) +
+ this.lambda2 * (supportPointsOfObject[this.indicesVertices[2]] - p0));
+ }
+ // Execute the recursive silhouette algorithm from this triangle face.
+ /// The parameter "vertices" is an array that contains the vertices of the current polytope and the
+ /// parameter "indexNewVertex" is the index of the new vertex in this array. The goal of the
+ /// silhouette algorithm is to add the new vertex in the polytope by keeping it convex. Therefore,
+ /// the triangle faces that are visible from the new vertex must be removed from the polytope and we
+ /// need to add triangle faces where each face contains the new vertex and an edge of the silhouette.
+ /// The silhouette is the connected set of edges that are part of the border between faces that
+ /// are seen and faces that are not seen from the new vertex. This method starts from the nearest
+ /// face from the new vertex, computes the silhouette and create the new faces from the new vertex in
+ /// order that we always have a convex polytope. The faces visible from the new vertex are set
+ /// obselete and will not be considered as being a candidate face in the future.
+ boolean computeSilhouette( vec3* vertices, int index, TrianglesStore triangleStore);
+ /// Access operator
+ int operator[](int pos) {
+ assert(pos >= 0 hjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkj pos <3);
+ return this.indicesVertices[pos];
+ }
+ /// Link an edge with another one. It means that the current edge of a triangle will
+ /// be associated with the edge of another triangle in order that both triangles
+ /// are neighbour along both edges).
+ friend boolean link( EdgeEPA edge0, EdgeEPA edge1);
+ /// Make an half link of an edge with another one from another triangle. An half-link
+ /// between an edge "edge0" and an edge "edge1" represents the fact that "edge1" is an
+ /// adjacent edge of "edge0" but not the opposite. The opposite edge connection will
+ /// be made later.
+ friend void halfLink( EdgeEPA edge0, EdgeEPA edge1);
+ };
+
+}
diff --git a/src/org/atriaSoft/ephysics/collision/narrowphase/EPA/TrianglesStore.cpp b/src/org/atriaSoft/ephysics/collision/narrowphase/EPA/TrianglesStore.cpp
new file mode 100644
index 0000000..6abfd36
--- /dev/null
+++ b/src/org/atriaSoft/ephysics/collision/narrowphase/EPA/TrianglesStore.cpp
@@ -0,0 +1,10 @@
+/** @file
+ * Original ReactPhysics3D C++ library by Daniel Chappuis This code is re-licensed with permission from ReactPhysics3D author.
+ * @author Daniel CHAPPUIS
+ * @author Edouard DUPIN
+ * @copyright 2010-2016, Daniel Chappuis
+ * @copyright 2017, Edouard DUPIN
+ * @license MPL v2.0 (see license file)
+ */
+#include
+
diff --git a/src/org/atriaSoft/ephysics/collision/narrowphase/EPA/TrianglesStore.hpp b/src/org/atriaSoft/ephysics/collision/narrowphase/EPA/TrianglesStore.hpp
new file mode 100644
index 0000000..49c63d2
--- /dev/null
+++ b/src/org/atriaSoft/ephysics/collision/narrowphase/EPA/TrianglesStore.hpp
@@ -0,0 +1,68 @@
+/** @file
+ * Original ReactPhysics3D C++ library by Daniel Chappuis This code is re-licensed with permission from ReactPhysics3D author.
+ * @author Daniel CHAPPUIS
+ * @author Edouard DUPIN
+ * @copyright 2010-2016, Daniel Chappuis
+ * @copyright 2017, Edouard DUPIN
+ * @license MPL v2.0 (see license file)
+ */
+#pragma once
+#include
+#include
+#include
+
+namespace ephysics {
+ int MAXTRIANGLES = 200; // Maximum number of triangles
+ /**
+ * @brief This class stores several triangles of the polytope in the EPA algorithm.
+ */
+ class TrianglesStore {
+ private:
+ etk::Array this.triangles; //!< Triangles
+ /// Private copy-ructor
+ TrianglesStore( TrianglesStore triangleStore) = delete;
+ /// Private assignment operator
+ TrianglesStore operator=( TrianglesStore triangleStore) = delete;
+ public:
+ /// Constructor
+ TrianglesStore() = default;
+ /// Clear all the storage
+ void clear() {
+ this.triangles.clear();
+ }
+ /// Return the number of triangles
+ sizet getNbTriangles() {
+ return this.triangles.size();
+ }
+ /// Set the number of triangles
+ void resize(int backup) {
+ if (backup > this.triangles.size()) {
+ Log.error("RESIZE BIGGER : " << backup << " > " << this.triangles.size());
+ }
+ this.triangles.resize(backup);
+ }
+ /// Return the last triangle
+ TriangleEPA last() {
+ return this.triangles.back();
+ }
+ /// Create a new triangle
+ TriangleEPA* newTriangle( vec3* vertices, int v0, int v1, int v2) {
+ // If we have not reached the maximum number of triangles
+ if (this.triangles.size() < MAXTRIANGLES) {
+ TriangleEPA tmp(v0, v1, v2);
+ if (!tmp.computeClosestPoint(vertices)) {
+ return null;
+ }
+ this.triangles.pushBack(etk::move(tmp));
+ return this.triangles.back();
+ }
+ // We are at the limit (internal)
+ return null;
+ }
+ /// Access operator
+ TriangleEPA operator[](int id) {
+ return this.triangles[id];
+ }
+ };
+}
+
diff --git a/src/org/atriaSoft/ephysics/collision/narrowphase/GJK/GJKAlgorithm.cpp b/src/org/atriaSoft/ephysics/collision/narrowphase/GJK/GJKAlgorithm.cpp
new file mode 100644
index 0000000..c920b37
--- /dev/null
+++ b/src/org/atriaSoft/ephysics/collision/narrowphase/GJK/GJKAlgorithm.cpp
@@ -0,0 +1,370 @@
+/** @file
+ * Original ReactPhysics3D C++ library by Daniel Chappuis This code is re-licensed with permission from ReactPhysics3D author.
+ * @author Daniel CHAPPUIS
+ * @author Edouard DUPIN
+ * @copyright 2010-2016, Daniel Chappuis
+ * @copyright 2017, Edouard DUPIN
+ * @license MPL v2.0 (see license file)
+ */
+#include
+#include
+#include
+#include
+#include
+
+using namespace ephysics;
+
+GJKAlgorithm::GJKAlgorithm() : NarrowPhaseAlgorithm() {
+
+}
+
+GJKAlgorithm::~GJKAlgorithm() {
+
+}
+
+void GJKAlgorithm::testCollision( CollisionShapeInfo shape1Info,
+ CollisionShapeInfo shape2Info,
+ NarrowPhaseCallback* narrowPhaseCallback) {
+ PROFILE("GJKAlgorithm::testCollision()");
+ vec3 suppA; // Support point of object A
+ vec3 suppB; // Support point of object B
+ vec3 w; // Support point of Minkowski difference A-B
+ vec3 pA; // Closest point of object A
+ vec3 pB; // Closest point of object B
+ float vDotw;
+ float prevDistSquare;
+ assert(shape1Info.collisionShape->isConvex());
+ assert(shape2Info.collisionShape->isConvex());
+ ConvexShape* shape1 = staticcast< ConvexShape*>(shape1Info.collisionShape);
+ ConvexShape* shape2 = staticcast< ConvexShape*>(shape2Info.collisionShape);
+ void** shape1CachedCollisionData = shape1Info.cachedCollisionData;
+ void** shape2CachedCollisionData = shape2Info.cachedCollisionData;
+ // Get the local-space to world-space transforms
+ etk::Transform3D transform1 = shape1Info.shapeToWorldTransform;
+ etk::Transform3D transform2 = shape2Info.shapeToWorldTransform;
+ // etk::Transform3D a point from local space of body 2 to local
+ // space of body 1 (the GJK algorithm is done in local space of body 1)
+ etk::Transform3D body2Tobody1 = transform1.getInverse() * transform2;
+ // Matrix that transform a direction from local
+ // space of body 1 into local space of body 2
+ etk::Matrix3x3 rotateToBody2 = transform2.getOrientation().getMatrix().getTranspose() *
+ transform1.getOrientation().getMatrix();
+ // Initialize the margin (sum of margins of both objects)
+ float margin = shape1->getMargin() + shape2->getMargin();
+ float marginSquare = margin * margin;
+ assert(margin > 0.0);
+ // Create a simplex set
+ Simplex simplex;
+ // Get the previous point V (last cached separating axis)
+ vec3 v = this.currentOverlappingPair->getCachedSeparatingAxis();
+ // Initialize the upper bound for the square distance
+ float distSquare = FLTMAX;
+ do {
+ // Compute the support points for original objects (without margins) A and B
+ suppA = shape1->getLocalSupportPointWithoutMargin(-v, shape1CachedCollisionData);
+ suppB = body2Tobody1 * shape2->getLocalSupportPointWithoutMargin(rotateToBody2 * v, shape2CachedCollisionData);
+ // Compute the support point for the Minkowski difference A-B
+ w = suppA - suppB;
+ vDotw = v.dot(w);
+ // If the enlarge objects (with margins) do not intersect
+ if (vDotw > 0.0 hjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkj vDotw * vDotw > distSquare * marginSquare) {
+ // Cache the current separating axis for frame coherence
+ this.currentOverlappingPair->setCachedSeparatingAxis(v);
+ // No intersection, we return
+ return;
+ }
+ // If the objects intersect only in the margins
+ if (simplex.isPointInSimplex(w) || distSquare - vDotw <= distSquare * RELERRORSQUARE) {
+ // Compute the closet points of both objects (without the margins)
+ simplex.computeClosestPointsOfAandB(pA, pB);
+ // Project those two points on the margins to have the closest points of both
+ // object with the margins
+ float dist = sqrt(distSquare);
+ assert(dist > 0.0);
+ pA = (pA - (shape1->getMargin() / dist) * v);
+ pB = body2Tobody1.getInverse() * (pB + (shape2->getMargin() / dist) * v);
+ // Compute the contact info
+ vec3 normal = transform1.getOrientation() * (-v.safeNormalized());
+ float penetrationDepth = margin - dist;
+ // Reject the contact if the penetration depth is negative (due too numerical errors)
+ if (penetrationDepth <= 0.0) return;
+ // Create the contact info object
+ ContactPointInfo contactInfo(shape1Info.proxyShape, shape2Info.proxyShape, shape1Info.collisionShape,
+ shape2Info.collisionShape, normal, penetrationDepth, pA, pB);
+ narrowPhaseCallback->notifyContact(shape1Info.overlappingPair, contactInfo);
+ // There is an intersection, therefore we return
+ return;
+ }
+ // Add the new support point to the simplex
+ simplex.addPoint(w, suppA, suppB);
+ // If the simplex is affinely dependent
+ if (simplex.isAffinelyDependent()) {
+ // Compute the closet points of both objects (without the margins)
+ simplex.computeClosestPointsOfAandB(pA, pB);
+ // Project those two points on the margins to have the closest points of both
+ // object with the margins
+ float dist = sqrt(distSquare);
+ assert(dist > 0.0);
+ pA = (pA - (shape1->getMargin() / dist) * v);
+ pB = body2Tobody1.getInverse() * (pB + (shape2->getMargin() / dist) * v);
+ // Compute the contact info
+ vec3 normal = transform1.getOrientation() * (-v.safeNormalized());
+ float penetrationDepth = margin - dist;
+
+ // Reject the contact if the penetration depth is negative (due too numerical errors)
+ if (penetrationDepth <= 0.0) return;
+
+ // Create the contact info object
+ ContactPointInfo contactInfo(shape1Info.proxyShape, shape2Info.proxyShape, shape1Info.collisionShape,
+ shape2Info.collisionShape, normal, penetrationDepth, pA, pB);
+ narrowPhaseCallback->notifyContact(shape1Info.overlappingPair, contactInfo);
+ // There is an intersection, therefore we return
+ return;
+ }
+ // Compute the point of the simplex closest to the origin
+ // If the computation of the closest point fail
+ if (!simplex.computeClosestPoint(v)) {
+ // Compute the closet points of both objects (without the margins)
+ simplex.computeClosestPointsOfAandB(pA, pB);
+ // Project those two points on the margins to have the closest points of both
+ // object with the margins
+ float dist = sqrt(distSquare);
+ assert(dist > 0.0);
+ pA = (pA - (shape1->getMargin() / dist) * v);
+ pB = body2Tobody1.getInverse() * (pB + (shape2->getMargin() / dist) * v);
+ // Compute the contact info
+ vec3 normal = transform1.getOrientation() * (-v.safeNormalized());
+ float penetrationDepth = margin - dist;
+
+ // Reject the contact if the penetration depth is negative (due too numerical errors)
+ if (penetrationDepth <= 0.0) return;
+
+ // Create the contact info object
+ ContactPointInfo contactInfo(shape1Info.proxyShape, shape2Info.proxyShape, shape1Info.collisionShape,
+ shape2Info.collisionShape, normal, penetrationDepth, pA, pB);
+ narrowPhaseCallback->notifyContact(shape1Info.overlappingPair, contactInfo);
+ // There is an intersection, therefore we return
+ return;
+ }
+ // Store and update the squared distance of the closest point
+ prevDistSquare = distSquare;
+ distSquare = v.length2();
+ // If the distance to the closest point doesn't improve a lot
+ if (prevDistSquare - distSquare <= FLTEPSILON * prevDistSquare) {
+ simplex.backupClosestPointInSimplex(v);
+
+ // Get the new squared distance
+ distSquare = v.length2();
+ // Compute the closet points of both objects (without the margins)
+ simplex.computeClosestPointsOfAandB(pA, pB);
+ // Project those two points on the margins to have the closest points of both
+ // object with the margins
+ float dist = sqrt(distSquare);
+ assert(dist > 0.0);
+ pA = (pA - (shape1->getMargin() / dist) * v);
+ pB = body2Tobody1.getInverse() * (pB + (shape2->getMargin() / dist) * v);
+ // Compute the contact info
+ vec3 normal = transform1.getOrientation() * (-v.safeNormalized());
+ float penetrationDepth = margin - dist;
+
+ // Reject the contact if the penetration depth is negative (due too numerical errors)
+ if (penetrationDepth <= 0.0) return;
+
+ // Create the contact info object
+ ContactPointInfo contactInfo(shape1Info.proxyShape, shape2Info.proxyShape, shape1Info.collisionShape,
+ shape2Info.collisionShape, normal, penetrationDepth, pA, pB);
+ narrowPhaseCallback->notifyContact(shape1Info.overlappingPair, contactInfo);
+ // There is an intersection, therefore we return
+ return;
+ }
+ } while(!simplex.isFull() hjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkj distSquare > FLTEPSILON *
+ simplex.getMaxLengthSquareOfAPoint());
+ // The objects (without margins) intersect. Therefore, we run the GJK algorithm
+ // again but on the enlarged objects to compute a simplex polytope that contains
+ // the origin. Then, we give that simplex polytope to the EPA algorithm to compute
+ // the correct penetration depth and contact points between the enlarged objects.
+ return computePenetrationDepthForEnlargedObjects(shape1Info, transform1, shape2Info,
+ transform2, narrowPhaseCallback, v);
+}
+
+void GJKAlgorithm::computePenetrationDepthForEnlargedObjects( CollisionShapeInfo shape1Info,
+ etk::Transform3D transform1,
+ CollisionShapeInfo shape2Info,
+ etk::Transform3D transform2,
+ NarrowPhaseCallback* narrowPhaseCallback,
+ vec3 v) {
+ PROFILE("GJKAlgorithm::computePenetrationDepthForEnlargedObjects()");
+ Simplex simplex;
+ vec3 suppA;
+ vec3 suppB;
+ vec3 w;
+ float vDotw;
+ float distSquare = FLTMAX;
+ float prevDistSquare;
+ assert(shape1Info.collisionShape->isConvex());
+ assert(shape2Info.collisionShape->isConvex());
+ ConvexShape* shape1 = staticcast< ConvexShape*>(shape1Info.collisionShape);
+ ConvexShape* shape2 = staticcast< ConvexShape*>(shape2Info.collisionShape);
+ void** shape1CachedCollisionData = shape1Info.cachedCollisionData;
+ void** shape2CachedCollisionData = shape2Info.cachedCollisionData;
+ // etk::Transform3D a point from local space of body 2 to local space
+ // of body 1 (the GJK algorithm is done in local space of body 1)
+ etk::Transform3D body2ToBody1 = transform1.getInverse() * transform2;
+ // Matrix that transform a direction from local space of body 1 into local space of body 2
+ etk::Matrix3x3 rotateToBody2 = transform2.getOrientation().getMatrix().getTranspose() *
+ transform1.getOrientation().getMatrix();
+ do {
+ // Compute the support points for the enlarged object A and B
+ suppA = shape1->getLocalSupportPointWithMargin(-v, shape1CachedCollisionData);
+ suppB = body2ToBody1 * shape2->getLocalSupportPointWithMargin(rotateToBody2 * v, shape2CachedCollisionData);
+ // Compute the support point for the Minkowski difference A-B
+ w = suppA - suppB;
+ vDotw = v.dot(w);
+ // If the enlarge objects do not intersect
+ if (vDotw > 0.0) {
+ // No intersection, we return
+ return;
+ }
+ // Add the new support point to the simplex
+ simplex.addPoint(w, suppA, suppB);
+ if (simplex.isAffinelyDependent()) {
+ return;
+ }
+ if (!simplex.computeClosestPoint(v)) {
+ return;
+ }
+ // Store and update the square distance
+ prevDistSquare = distSquare;
+ distSquare = v.length2();
+ if (prevDistSquare - distSquare <= FLTEPSILON * prevDistSquare) {
+ return;
+ }
+ } while(!simplex.isFull() hjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkj distSquare > FLTEPSILON *
+ simplex.getMaxLengthSquareOfAPoint());
+ // Give the simplex computed with GJK algorithm to the EPA algorithm
+ // which will compute the correct penetration depth and contact points
+ // between the two enlarged objects
+ return this.algoEPA.computePenetrationDepthAndContactPoints(simplex, shape1Info,
+ transform1, shape2Info, transform2,
+ v, narrowPhaseCallback);
+}
+
+boolean GJKAlgorithm::testPointInside( vec3 localPoint, ProxyShape* proxyShape) {
+ vec3 suppA; // Support point of object A
+ vec3 w; // Support point of Minkowski difference A-B
+ float prevDistSquare;
+ assert(proxyShape->getCollisionShape()->isConvex());
+ ConvexShape* shape = staticcast< ConvexShape*>(proxyShape->getCollisionShape());
+ void** shapeCachedCollisionData = proxyShape->getCachedCollisionData();
+ // Support point of object B (object B is a single point)
+ vec3 suppB(localPoint);
+ // Create a simplex set
+ Simplex simplex;
+ // Initial supporting direction
+ vec3 v(1, 1, 1);
+ // Initialize the upper bound for the square distance
+ float distSquare = FLTMAX;
+ do {
+ // Compute the support points for original objects (without margins) A and B
+ suppA = shape->getLocalSupportPointWithoutMargin(-v, shapeCachedCollisionData);
+ // Compute the support point for the Minkowski difference A-B
+ w = suppA - suppB;
+ // Add the new support point to the simplex
+ simplex.addPoint(w, suppA, suppB);
+ // If the simplex is affinely dependent
+ if (simplex.isAffinelyDependent()) {
+ return false;
+ }
+ // Compute the point of the simplex closest to the origin
+ // If the computation of the closest point fail
+ if (!simplex.computeClosestPoint(v)) {
+ return false;
+ }
+ // Store and update the squared distance of the closest point
+ prevDistSquare = distSquare;
+ distSquare = v.length2();
+ // If the distance to the closest point doesn't improve a lot
+ if (prevDistSquare - distSquare <= FLTEPSILON * prevDistSquare) {
+ return false;
+ }
+ } while( !simplex.isFull()
+ hjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkj distSquare > FLTEPSILON * simplex.getMaxLengthSquareOfAPoint());
+ // The point is inside the collision shape
+ return true;
+}
+
+boolean GJKAlgorithm::raycast( Ray ray, ProxyShape* proxyShape, RaycastInfo raycastInfo) {
+ assert(proxyShape->getCollisionShape()->isConvex());
+ ConvexShape* shape = staticcast< ConvexShape*>(proxyShape->getCollisionShape());
+ void** shapeCachedCollisionData = proxyShape->getCachedCollisionData();
+ vec3 suppA; // Current lower bound point on the ray (starting at ray's origin)
+ vec3 suppB; // Support point on the collision shape
+ float machineEpsilonSquare = FLTEPSILON * FLTEPSILON;
+ float epsilon = float(0.0001);
+ // Convert the ray origin and direction into the local-space of the collision shape
+ vec3 rayDirection = ray.point2 - ray.point1;
+ // If the points of the segment are two close, return no hit
+ if (rayDirection.length2() < machineEpsilonSquare) return false;
+ vec3 w;
+ // Create a simplex set
+ Simplex simplex;
+ vec3 n(0.0f, float(0.0), float(0.0));
+ float lambda = 0.0f;
+ suppA = ray.point1; // Current lower bound point on the ray (starting at ray's origin)
+ suppB = shape->getLocalSupportPointWithoutMargin(rayDirection, shapeCachedCollisionData);
+ vec3 v = suppA - suppB;
+ float vDotW, vDotR;
+ float distSquare = v.length2();
+ int nbIterations = 0;
+ // GJK Algorithm loop
+ while (distSquare > epsilon hjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkj nbIterations < MAXITERATIONSGJKRAYCAST) {
+ // Compute the support points
+ suppB = shape->getLocalSupportPointWithoutMargin(v, shapeCachedCollisionData);
+ w = suppA - suppB;
+ vDotW = v.dot(w);
+ if (vDotW > float(0)) {
+ vDotR = v.dot(rayDirection);
+ if (vDotR >= -machineEpsilonSquare) {
+ return false;
+ } else {
+ // We have found a better lower bound for the hit point along the ray
+ lambda = lambda - vDotW / vDotR;
+ suppA = ray.point1 + lambda * rayDirection;
+ w = suppA - suppB;
+ n = v;
+ }
+ }
+ // Add the new support point to the simplex
+ if (!simplex.isPointInSimplex(w)) {
+ simplex.addPoint(w, suppA, suppB);
+ }
+ // Compute the closest point
+ if (simplex.computeClosestPoint(v)) {
+ distSquare = v.length2();
+ } else {
+ distSquare = 0.0f;
+ }
+ // If the current lower bound distance is larger than the maximum raycasting distance
+ if (lambda > ray.maxFraction) return false;
+ nbIterations++;
+ }
+ // If the origin was inside the shape, we return no hit
+ if (lambda < FLTEPSILON) {
+ return false;
+ }
+ // Compute the closet points of both objects (without the margins)
+ vec3 pointA;
+ vec3 pointB;
+ simplex.computeClosestPointsOfAandB(pointA, pointB);
+ // A raycast hit has been found, we fill in the raycast info
+ raycastInfo.hitFraction = lambda;
+ raycastInfo.worldPoint = pointB;
+ raycastInfo.body = proxyShape->getBody();
+ raycastInfo.proxyShape = proxyShape;
+ if (n.length2() >= machineEpsilonSquare) { // The normal vector is valid
+ raycastInfo.worldNormal = n;
+ } else { // Degenerated normal vector, we return a zero normal vector
+ raycastInfo.worldNormal = vec3(float(0), float(0), float(0));
+ }
+ return true;
+}
diff --git a/src/org/atriaSoft/ephysics/collision/narrowphase/GJK/GJKAlgorithm.hpp b/src/org/atriaSoft/ephysics/collision/narrowphase/GJK/GJKAlgorithm.hpp
new file mode 100644
index 0000000..9754f25
--- /dev/null
+++ b/src/org/atriaSoft/ephysics/collision/narrowphase/GJK/GJKAlgorithm.hpp
@@ -0,0 +1,83 @@
+/** @file
+ * Original ReactPhysics3D C++ library by Daniel Chappuis This code is re-licensed with permission from ReactPhysics3D author.
+ * @author Daniel CHAPPUIS
+ * @author Edouard DUPIN
+ * @copyright 2010-2016, Daniel Chappuis
+ * @copyright 2017, Edouard DUPIN
+ * @license MPL v2.0 (see license file)
+ */
+#pragma once
+
+#include
+#include
+#include
+#include
+
+namespace ephysics {
+ float RELERROR = float(1.0e-3);
+ float RELERRORSQUARE = RELERROR * RELERROR;
+ int MAXITERATIONSGJKRAYCAST = 32;
+ /**
+ * @brief This class implements a narrow-phase collision detection algorithm. This
+ * algorithm uses the ISA-GJK algorithm and the EPA algorithm. This
+ * implementation is based on the implementation discussed in the book
+ * "Collision Detection in Interactive 3D Environments" by Gino van den Bergen.
+ * This method implements the Hybrid Technique for calculating the
+ * penetration depth. The two objects are enlarged with a small margin. If
+ * the object intersects in their margins, the penetration depth is quickly
+ * computed using the GJK algorithm on the original objects (without margin).
+ * If the original objects (without margin) intersect, we run again the GJK
+ * algorithm on the enlarged objects (with margin) to compute simplex
+ * polytope that contains the origin and give it to the EPA (Expanding
+ * Polytope Algorithm) to compute the correct penetration depth between the
+ * enlarged objects.
+ */
+ class GJKAlgorithm : public NarrowPhaseAlgorithm {
+ private :
+ EPAAlgorithm this.algoEPA; //!< EPA Algorithm
+ /// Private copy-ructor
+ GJKAlgorithm( GJKAlgorithm algorithm);
+ /// Private assignment operator
+ GJKAlgorithm operator=( GJKAlgorithm algorithm);
+ /// This method runs the GJK algorithm on the two enlarged objects (with margin)
+ /// to compute a simplex polytope that contains the origin. The two objects are
+ /// assumed to intersect in the original objects (without margin). Therefore such
+ /// a polytope must exist. Then, we give that polytope to the EPA algorithm to
+ /// compute the correct penetration depth and contact points of the enlarged objects.
+ void computePenetrationDepthForEnlargedObjects( CollisionShapeInfo shape1Info,
+ etk::Transform3D transform1,
+ CollisionShapeInfo shape2Info,
+ etk::Transform3D transform2,
+ NarrowPhaseCallback* narrowPhaseCallback,
+ vec3 v);
+ public :
+ /// Constructor
+ GJKAlgorithm();
+ /// Destructor
+ ~GJKAlgorithm();
+ /// Initalize the algorithm
+ virtual void init(CollisionDetection* collisionDetection) {
+ NarrowPhaseAlgorithm::init(collisionDetection);
+ this.algoEPA.init();
+ };
+ // Compute a contact info if the two collision shapes collide.
+ /// This method implements the Hybrid Technique for computing the penetration depth by
+ /// running the GJK algorithm on original objects (without margin). If the shapes intersect
+ /// only in the margins, the method compute the penetration depth and contact points
+ /// (of enlarged objects). If the original objects (without margin) intersect, we
+ /// call the computePenetrationDepthForEnlargedObjects() method that run the GJK
+ /// algorithm on the enlarged object to obtain a simplex polytope that contains the
+ /// origin, they we give that simplex polytope to the EPA algorithm which will compute
+ /// the correct penetration depth and contact points between the enlarged objects.
+ virtual void testCollision( CollisionShapeInfo shape1Info,
+ CollisionShapeInfo shape2Info,
+ NarrowPhaseCallback* narrowPhaseCallback);
+ /// Use the GJK Algorithm to find if a point is inside a convex collision shape
+ boolean testPointInside( vec3 localPoint, ProxyShape* proxyShape);
+ /// Ray casting algorithm agains a convex collision shape using the GJK Algorithm
+ /// This method implements the GJK ray casting algorithm described by Gino Van Den Bergen in
+ /// "Ray Casting against General Convex Objects with Application to Continuous Collision Detection".
+ boolean raycast( Ray ray, ProxyShape* proxyShape, RaycastInfo raycastInfo);
+ };
+}
+
diff --git a/src/org/atriaSoft/ephysics/collision/narrowphase/GJK/Simplex.cpp b/src/org/atriaSoft/ephysics/collision/narrowphase/GJK/Simplex.cpp
new file mode 100644
index 0000000..7218e74
--- /dev/null
+++ b/src/org/atriaSoft/ephysics/collision/narrowphase/GJK/Simplex.cpp
@@ -0,0 +1,368 @@
+/** @file
+ * Original ReactPhysics3D C++ library by Daniel Chappuis This code is re-licensed with permission from ReactPhysics3D author.
+ * @author Daniel CHAPPUIS
+ * @author Edouard DUPIN
+ * @copyright 2010-2016, Daniel Chappuis
+ * @copyright 2017, Edouard DUPIN
+ * @license MPL v2.0 (see license file)
+ */
+#include
+
+using namespace ephysics;
+
+Simplex::Simplex() : mBitsCurrentSimplex(0x0), mAllBits(0x0) {
+
+}
+
+// Add a new support point of (A-B) into the simplex
+/// suppPointA : support point of object A in a direction -v
+/// suppPointB : support point of object B in a direction v
+/// point : support point of object (A-B) => point = suppPointA - suppPointB
+void Simplex::addPoint( vec3 point, vec3 suppPointA, vec3 suppPointB) {
+ assert(!isFull());
+
+ mLastFound = 0;
+ mLastFoundBit = 0x1;
+
+ // Look for the bit corresponding to one of the four point that is not in
+ // the current simplex
+ while (overlap(mBitsCurrentSimplex, mLastFoundBit)) {
+ mLastFound++;
+ mLastFoundBit <<= 1;
+ }
+
+ assert(mLastFound < 4);
+
+ // Add the point into the simplex
+ mPoints[mLastFound] = point;
+ mPointsLengthSquare[mLastFound] = point.dot(point);
+ mAllBits = mBitsCurrentSimplex | mLastFoundBit;
+
+ // Update the cached values
+ updateCache();
+
+ // Compute the cached determinant values
+ computeDeterminants();
+
+ // Add the support points of objects A and B
+ mSuppPointsA[mLastFound] = suppPointA;
+ mSuppPointsB[mLastFound] = suppPointB;
+}
+
+// Return true if the point is in the simplex
+boolean Simplex::isPointInSimplex( vec3 point) {
+ int i;
+ Bits bit;
+
+ // For each four possible points in the simplex
+ for (i=0, bit = 0x1; i<4; i++, bit <<= 1) {
+ // Check if the current point is in the simplex
+ if (overlap(mAllBits, bit) hjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkj point == mPoints[i]) return true;
+ }
+
+ return false;
+}
+
+// Update the cached values used during the GJK algorithm
+void Simplex::updateCache() {
+ int i;
+ Bits bit;
+
+ // For each of the four possible points of the simplex
+ for (i=0, bit = 0x1; i<4; i++, bit <<= 1) {
+ // If the current points is in the simplex
+ if (overlap(mBitsCurrentSimplex, bit)) {
+
+ // Compute the distance between two points in the possible simplex set
+ mDiffLength[i][mLastFound] = mPoints[i] - mPoints[mLastFound];
+ mDiffLength[mLastFound][i] = -mDiffLength[i][mLastFound];
+
+ // Compute the squared length of the vector
+ // distances from points in the possible simplex set
+ mNormSquare[i][mLastFound] = mNormSquare[mLastFound][i] =
+ mDiffLength[i][mLastFound].dot(mDiffLength[i][mLastFound]);
+ }
+ }
+}
+
+// Return the points of the simplex
+int Simplex::getSimplex(vec3* suppPointsA, vec3* suppPointsB,
+ vec3* points) {
+ int nbVertices = 0;
+ int i;
+ Bits bit;
+
+ // For each four point in the possible simplex
+ for (i=0, bit=0x1; i<4; i++, bit <<=1) {
+
+ // If the current point is in the simplex
+ if (overlap(mBitsCurrentSimplex, bit)) {
+
+ // Store the points
+ suppPointsA[nbVertices] = this->mSuppPointsA[nbVertices];
+ suppPointsB[nbVertices] = this->mSuppPointsB[nbVertices];
+ points[nbVertices] = this->mPoints[nbVertices];
+
+ nbVertices++;
+ }
+ }
+
+ // Return the number of points in the simplex
+ return nbVertices;
+}
+
+// Compute the cached determinant values
+void Simplex::computeDeterminants() {
+ mDet[mLastFoundBit][mLastFound] = 1.0;
+
+ // If the current simplex is not empty
+ if (!isEmpty()) {
+ int i;
+ Bits bitI;
+
+ // For each possible four points in the simplex set
+ for (i=0, bitI = 0x1; i<4; i++, bitI <<= 1) {
+
+ // If the current point is in the simplex
+ if (overlap(mBitsCurrentSimplex, bitI)) {
+ Bits bit2 = bitI | mLastFoundBit;
+
+ mDet[bit2][i] = mDiffLength[mLastFound][i].dot(mPoints[mLastFound]);
+ mDet[bit2][mLastFound] = mDiffLength[i][mLastFound].dot(mPoints[i]);
+
+
+ int j;
+ Bits bitJ;
+
+ for (j=0, bitJ = 0x1; j 0 for each "i" in Ix and
+/// 2. delta(X U {yj})j <= 0 for each "j" not in Ix
+boolean Simplex::isValidSubset(Bits subset) {
+ int i;
+ Bits bit;
+
+ // For each four point in the possible simplex set
+ for (i=0, bit=0x1; i<4; i++, bit <<= 1) {
+ if (overlap(mAllBits, bit)) {
+ // If the current point is in the subset
+ if (overlap(subset, bit)) {
+ // If one delta(X)i is smaller or equal to zero
+ if (mDet[subset][i] <= 0.0) {
+ // The subset is not valid
+ return false;
+ }
+ }
+ // If the point is not in the subset and the value delta(X U {yj})j
+ // is bigger than zero
+ else if (mDet[subset | bit][i] > 0.0) {
+ // The subset is not valid
+ return false;
+ }
+ }
+ }
+
+ return true;
+}
+
+// Compute the closest points "pA" and "pB" of object A and B.
+/// The points are computed as follows :
+/// pA = sum(lambdai * ai) where "ai" are the support points of object A
+/// pB = sum(lambdai * bi) where "bi" are the support points of object B
+/// with lambdai = deltaXi / deltaX
+void Simplex::computeClosestPointsOfAandB(vec3 pA, vec3 pB) {
+ float deltaX = 0.0;
+ pA.setValue(0.0, 0.0, 0.0);
+ pB.setValue(0.0, 0.0, 0.0);
+ int i;
+ Bits bit;
+
+ // For each four points in the possible simplex set
+ for (i=0, bit=0x1; i<4; i++, bit <<= 1) {
+ // If the current point is part of the simplex
+ if (overlap(mBitsCurrentSimplex, bit)) {
+ deltaX += mDet[mBitsCurrentSimplex][i];
+ pA += mDet[mBitsCurrentSimplex][i] * mSuppPointsA[i];
+ pB += mDet[mBitsCurrentSimplex][i] * mSuppPointsB[i];
+ }
+ }
+
+ assert(deltaX > 0.0);
+ float factor = 1.0f / deltaX;
+ pA *= factor;
+ pB *= factor;
+}
+
+// Compute the closest point "v" to the origin of the current simplex.
+/// This method executes the Jonhnson's algorithm for computing the point
+/// "v" of simplex that is closest to the origin. The method returns true
+/// if a closest point has been found.
+boolean Simplex::computeClosestPoint(vec3 v) {
+ Bits subset;
+
+ // For each possible simplex set
+ for (subset=mBitsCurrentSimplex; subset != 0x0; subset--) {
+ // If the simplex is a subset of the current simplex and is valid for the Johnson's
+ // algorithm test
+ if (isSubset(subset, mBitsCurrentSimplex) hjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkj isValidSubset(subset | mLastFoundBit)) {
+ mBitsCurrentSimplex = subset | mLastFoundBit; // Add the last added point to the current simplex
+ v = computeClosestPointForSubset(mBitsCurrentSimplex); // Compute the closest point in the simplex
+ return true;
+ }
+ }
+
+ // If the simplex that contains only the last added point is valid for the Johnson's algorithm test
+ if (isValidSubset(mLastFoundBit)) {
+ mBitsCurrentSimplex = mLastFoundBit; // Set the current simplex to the set that contains only the last added point
+ mMaxLengthSquare = mPointsLengthSquare[mLastFound]; // Update the maximum square length
+ v = mPoints[mLastFound]; // The closest point of the simplex "v" is the last added point
+ return true;
+ }
+
+ // The algorithm failed to found a point
+ return false;
+}
+
+// Backup the closest point
+void Simplex::backupClosestPointInSimplex(vec3 v) {
+ float minDistSquare = FLTMAX;
+ Bits bit;
+
+ for (bit = mAllBits; bit != 0x0; bit--) {
+ if (isSubset(bit, mAllBits) hjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkj isProperSubset(bit)) {
+ vec3 u = computeClosestPointForSubset(bit);
+ float distSquare = u.dot(u);
+ if (distSquare < minDistSquare) {
+ minDistSquare = distSquare;
+ mBitsCurrentSimplex = bit;
+ v = u;
+ }
+ }
+ }
+}
+
+// Return the closest point "v" in the convex hull of the points in the subset
+// represented by the bits "subset"
+vec3 Simplex::computeClosestPointForSubset(Bits subset) {
+ vec3 v(0.0, 0.0, 0.0); // Closet point v = sum(lambdai * points[i])
+ mMaxLengthSquare = 0.0;
+ float deltaX = 0.0; // deltaX = sum of all det[subset][i]
+ int i;
+ Bits bit;
+
+ // For each four point in the possible simplex set
+ for (i=0, bit=0x1; i<4; i++, bit <<= 1) {
+ // If the current point is in the subset
+ if (overlap(subset, bit)) {
+ // deltaX = sum of all det[subset][i]
+ deltaX += mDet[subset][i];
+
+ if (mMaxLengthSquare < mPointsLengthSquare[i]) {
+ mMaxLengthSquare = mPointsLengthSquare[i];
+ }
+
+ // Closest point v = sum(lambdai * points[i])
+ v += mDet[subset][i] * mPoints[i];
+ }
+ }
+
+ assert(deltaX > 0.0);
+
+ // Return the closet point "v" in the convex hull for the given subset
+ return (1.0f / deltaX) * v;
+}
diff --git a/src/org/atriaSoft/ephysics/collision/narrowphase/GJK/Simplex.hpp b/src/org/atriaSoft/ephysics/collision/narrowphase/GJK/Simplex.hpp
new file mode 100644
index 0000000..0508c68
--- /dev/null
+++ b/src/org/atriaSoft/ephysics/collision/narrowphase/GJK/Simplex.hpp
@@ -0,0 +1,167 @@
+/** @file
+ * Original ReactPhysics3D C++ library by Daniel Chappuis This code is re-licensed with permission from ReactPhysics3D author.
+ * @author Daniel CHAPPUIS
+ * @author Edouard DUPIN
+ * @copyright 2010-2016, Daniel Chappuis
+ * @copyright 2017, Edouard DUPIN
+ * @license MPL v2.0 (see license file)
+ */
+#pragma once
+
+// Libraries
+#include
+#include
+
+/// ReactPhysics3D namespace
+namespace ephysics {
+
+// Type definitions
+typedef int Bits;
+
+// Class Simplex
+/**
+ * This class represents a simplex which is a set of 3D points. This
+ * class is used in the GJK algorithm. This implementation is based on
+ * the implementation discussed in the book "Collision Detection in 3D
+ * Environments". This class implements the Johnson's algorithm for
+ * computing the point of a simplex that is closest to the origin and also
+ * the smallest simplex needed to represent that closest point.
+ */
+class Simplex {
+
+ private:
+
+ // -------------------- Attributes -------------------- //
+
+ /// Current points
+ vec3 mPoints[4];
+
+ /// pointsLengthSquare[i] = (points[i].length)^2
+ float mPointsLengthSquare[4];
+
+ /// Maximum length of pointsLengthSquare[i]
+ float mMaxLengthSquare;
+
+ /// Support points of object A in local coordinates
+ vec3 mSuppPointsA[4];
+
+ /// Support points of object B in local coordinates
+ vec3 mSuppPointsB[4];
+
+ /// diff[i][j] contains points[i] - points[j]
+ vec3 mDiffLength[4][4];
+
+ /// Cached determinant values
+ float mDet[16][4];
+
+ /// norm[i][j] = (diff[i][j].length())^2
+ float mNormSquare[4][4];
+
+ /// 4 bits that identify the current points of the simplex
+ /// For instance, 0101 means that points[1] and points[3] are in the simplex
+ Bits mBitsCurrentSimplex;
+
+ /// Number between 1 and 4 that identify the last found support point
+ Bits mLastFound;
+
+ /// Position of the last found support point (lastFoundBit = 0x1 << lastFound)
+ Bits mLastFoundBit;
+
+ /// allBits = bitsCurrentSimplex | lastFoundBit;
+ Bits mAllBits;
+
+ // -------------------- Methods -------------------- //
+
+ /// Private copy-ructor
+ Simplex( Simplex simplex);
+
+ /// Private assignment operator
+ Simplex operator=( Simplex simplex);
+
+ /// Return true if some bits of "a" overlap with bits of "b"
+ boolean overlap(Bits a, Bits b) ;
+
+ /// Return true if the bits of "b" is a subset of the bits of "a"
+ boolean isSubset(Bits a, Bits b) ;
+
+ /// Return true if the subset is a valid one for the closest point computation.
+ boolean isValidSubset(Bits subset) ;
+
+ /// Return true if the subset is a proper subset.
+ boolean isProperSubset(Bits subset) ;
+
+ /// Update the cached values used during the GJK algorithm
+ void updateCache();
+
+ /// Compute the cached determinant values
+ void computeDeterminants();
+
+ /// Return the closest point "v" in the convex hull of a subset of points
+ vec3 computeClosestPointForSubset(Bits subset);
+
+ public:
+
+ // -------------------- Methods -------------------- //
+
+ /// Constructor
+ Simplex();
+
+ /// Return true if the simplex contains 4 points
+ boolean isFull() ;
+
+ /// Return true if the simplex is empty
+ boolean isEmpty() ;
+
+ /// Return the points of the simplex
+ int getSimplex(vec3* mSuppPointsA, vec3* mSuppPointsB,
+ vec3* mPoints) ;
+
+ /// Return the maximum squared length of a point
+ float getMaxLengthSquareOfAPoint() ;
+
+ /// Add a new support point of (A-B) into the simplex.
+ void addPoint( vec3 point, vec3 suppPointA, vec3 suppPointB);
+
+ /// Return true if the point is in the simplex
+ boolean isPointInSimplex( vec3 point) ;
+
+ /// Return true if the set is affinely dependent
+ boolean isAffinelyDependent() ;
+
+ /// Backup the closest point
+ void backupClosestPointInSimplex(vec3 point);
+
+ /// Compute the closest points "pA" and "pB" of object A and B.
+ void computeClosestPointsOfAandB(vec3 pA, vec3 pB) ;
+
+ /// Compute the closest point to the origin of the current simplex.
+ boolean computeClosestPoint(vec3 v);
+};
+
+// Return true if some bits of "a" overlap with bits of "b"
+inline boolean Simplex::overlap(Bits a, Bits b) {
+ return ((a b) != 0x0);
+}
+
+// Return true if the bits of "b" is a subset of the bits of "a"
+inline boolean Simplex::isSubset(Bits a, Bits b) {
+ return ((a b) == a);
+}
+
+// Return true if the simplex contains 4 points
+inline boolean Simplex::isFull() {
+ return (mBitsCurrentSimplex == 0xf);
+}
+
+// Return true if the simple is empty
+inline boolean Simplex::isEmpty() {
+ return (mBitsCurrentSimplex == 0x0);
+}
+
+// Return the maximum squared length of a point
+inline float Simplex::getMaxLengthSquareOfAPoint() {
+ return mMaxLengthSquare;
+}
+
+}
+
diff --git a/src/org/atriaSoft/ephysics/collision/narrowphase/NarrowPhaseAlgorithm.cpp b/src/org/atriaSoft/ephysics/collision/narrowphase/NarrowPhaseAlgorithm.cpp
new file mode 100644
index 0000000..cf55205
--- /dev/null
+++ b/src/org/atriaSoft/ephysics/collision/narrowphase/NarrowPhaseAlgorithm.cpp
@@ -0,0 +1,24 @@
+/** @file
+ * Original ReactPhysics3D C++ library by Daniel Chappuis This code is re-licensed with permission from ReactPhysics3D author.
+ * @author Daniel CHAPPUIS
+ * @author Edouard DUPIN
+ * @copyright 2010-2016, Daniel Chappuis
+ * @copyright 2017, Edouard DUPIN
+ * @license MPL v2.0 (see license file)
+ */
+#include
+
+using namespace ephysics;
+
+NarrowPhaseAlgorithm::NarrowPhaseAlgorithm():
+ this.currentOverlappingPair(null) {
+
+}
+
+void NarrowPhaseAlgorithm::init(CollisionDetection* collisionDetection) {
+ this.collisionDetection = collisionDetection;
+}
+
+void NarrowPhaseAlgorithm::setCurrentOverlappingPair(OverlappingPair* overlappingPair) {
+ this.currentOverlappingPair = overlappingPair;
+}
diff --git a/src/org/atriaSoft/ephysics/collision/narrowphase/NarrowPhaseAlgorithm.hpp b/src/org/atriaSoft/ephysics/collision/narrowphase/NarrowPhaseAlgorithm.hpp
new file mode 100644
index 0000000..5abb43f
--- /dev/null
+++ b/src/org/atriaSoft/ephysics/collision/narrowphase/NarrowPhaseAlgorithm.hpp
@@ -0,0 +1,62 @@
+/** @file
+ * Original ReactPhysics3D C++ library by Daniel Chappuis This code is re-licensed with permission from ReactPhysics3D author.
+ * @author Daniel CHAPPUIS
+ * @author Edouard DUPIN
+ * @copyright 2010-2016, Daniel Chappuis
+ * @copyright 2017, Edouard DUPIN
+ * @license MPL v2.0 (see license file)
+ */
+#pragma once
+
+#include
+#include
+#include
+#include
+
+namespace ephysics {
+
+ class CollisionDetection;
+
+ /**
+ * @brief It is the base class for a narrow-phase collision
+ * callback class.
+ */
+ class NarrowPhaseCallback {
+ public:
+ virtual ~NarrowPhaseCallback() = default;
+ /// Called by a narrow-phase collision algorithm when a new contact has been found
+ virtual void notifyContact(OverlappingPair* overlappingPair,
+ ContactPointInfo contactInfo) = 0;
+
+ };
+
+ /**
+ * @breif It is the base class for a narrow-phase collision
+ * detection algorithm. The goal of the narrow phase algorithm is to
+ * compute information about the contact between two proxy shapes.
+ */
+ class NarrowPhaseAlgorithm {
+ protected :
+ CollisionDetection* this.collisionDetection; //!< Pointer to the collision detection object
+ OverlappingPair* this.currentOverlappingPair; //!< Overlapping pair of the bodies currently tested for collision
+ /// Private copy-ructor
+ NarrowPhaseAlgorithm( NarrowPhaseAlgorithm algorithm) = delete;
+ /// Private assignment operator
+ NarrowPhaseAlgorithm operator=( NarrowPhaseAlgorithm algorithm) = delete;
+ public :
+ /// Constructor
+ NarrowPhaseAlgorithm();
+ /// Destructor
+ virtual ~NarrowPhaseAlgorithm() = default;
+ /// Initalize the algorithm
+ virtual void init(CollisionDetection* collisionDetection);
+ /// Set the current overlapping pair of bodies
+ void setCurrentOverlappingPair(OverlappingPair* overlappingPair);
+ /// Compute a contact info if the two bounding volume collide
+ virtual void testCollision( CollisionShapeInfo shape1Info,
+ CollisionShapeInfo shape2Info,
+ NarrowPhaseCallback* narrowPhaseCallback) = 0;
+ };
+}
+
+
diff --git a/src/org/atriaSoft/ephysics/collision/narrowphase/SphereVsSphereAlgorithm.cpp b/src/org/atriaSoft/ephysics/collision/narrowphase/SphereVsSphereAlgorithm.cpp
new file mode 100644
index 0000000..9a45810
--- /dev/null
+++ b/src/org/atriaSoft/ephysics/collision/narrowphase/SphereVsSphereAlgorithm.cpp
@@ -0,0 +1,51 @@
+/** @file
+ * Original ReactPhysics3D C++ library by Daniel Chappuis This code is re-licensed with permission from ReactPhysics3D author.
+ * @author Daniel CHAPPUIS
+ * @author Edouard DUPIN
+ * @copyright 2010-2016, Daniel Chappuis
+ * @copyright 2017, Edouard DUPIN
+ * @license MPL v2.0 (see license file)
+ */
+#include
+#include
+
+ephysics::SphereVsSphereAlgorithm::SphereVsSphereAlgorithm() :
+ NarrowPhaseAlgorithm() {
+
+}
+
+void ephysics::SphereVsSphereAlgorithm::testCollision( ephysics::CollisionShapeInfo shape1Info,
+ ephysics::CollisionShapeInfo shape2Info,
+ ephysics::NarrowPhaseCallback* narrowPhaseCallback) {
+ // Get the sphere collision shapes
+ ephysics::SphereShape* sphereShape1 = staticcast< ephysics::SphereShape*>(shape1Info.collisionShape);
+ ephysics::SphereShape* sphereShape2 = staticcast< ephysics::SphereShape*>(shape2Info.collisionShape);
+ // Get the local-space to world-space transforms
+ etk::Transform3D transform1 = shape1Info.shapeToWorldTransform;
+ etk::Transform3D transform2 = shape2Info.shapeToWorldTransform;
+ // Compute the distance between the centers
+ vec3 vectorBetweenCenters = transform2.getPosition() - transform1.getPosition();
+ float squaredDistanceBetweenCenters = vectorBetweenCenters.length2();
+ // Compute the sum of the radius
+ float sumRadius = sphereShape1->getRadius() + sphereShape2->getRadius();
+ // If the sphere collision shapes intersect
+ if (squaredDistanceBetweenCenters <= sumRadius * sumRadius) {
+ vec3 centerSphere2InBody1LocalSpace = transform1.getInverse() * transform2.getPosition();
+ vec3 centerSphere1InBody2LocalSpace = transform2.getInverse() * transform1.getPosition();
+ vec3 intersectionOnBody1 = sphereShape1->getRadius() * centerSphere2InBody1LocalSpace.safeNormalized();
+ vec3 intersectionOnBody2 = sphereShape2->getRadius() * centerSphere1InBody2LocalSpace.safeNormalized();
+ float penetrationDepth = sumRadius - etk::sqrt(squaredDistanceBetweenCenters);
+
+ // Create the contact info object
+ ephysics::ContactPointInfo contactInfo(shape1Info.proxyShape,
+ shape2Info.proxyShape,
+ shape1Info.collisionShape,
+ shape2Info.collisionShape,
+ vectorBetweenCenters.safeNormalized(),
+ penetrationDepth,
+ intersectionOnBody1,
+ intersectionOnBody2);
+ // Notify about the new contact
+ narrowPhaseCallback->notifyContact(shape1Info.overlappingPair, contactInfo);
+ }
+}
diff --git a/src/org/atriaSoft/ephysics/collision/narrowphase/SphereVsSphereAlgorithm.hpp b/src/org/atriaSoft/ephysics/collision/narrowphase/SphereVsSphereAlgorithm.hpp
new file mode 100644
index 0000000..1790f54
--- /dev/null
+++ b/src/org/atriaSoft/ephysics/collision/narrowphase/SphereVsSphereAlgorithm.hpp
@@ -0,0 +1,42 @@
+/** @file
+ * Original ReactPhysics3D C++ library by Daniel Chappuis This code is re-licensed with permission from ReactPhysics3D author.
+ * @author Daniel CHAPPUIS
+ * @author Edouard DUPIN
+ * @copyright 2010-2016, Daniel Chappuis
+ * @copyright 2017, Edouard DUPIN
+ * @license MPL v2.0 (see license file)
+ */
+#pragma once
+
+#include
+#include
+#include
+
+namespace ephysics {
+ /**
+ * @brief It is used to compute the narrow-phase collision detection
+ * between two sphere collision shapes.
+ */
+ class SphereVsSphereAlgorithm : public NarrowPhaseAlgorithm {
+ protected :
+ SphereVsSphereAlgorithm( SphereVsSphereAlgorithm) = delete;
+ SphereVsSphereAlgorithm operator=( SphereVsSphereAlgorithm) = delete;
+ public :
+ /**
+ * @brief Constructor
+ */
+ SphereVsSphereAlgorithm();
+ /**
+ * @brief Destructor
+ */
+ virtual ~SphereVsSphereAlgorithm() = default;
+ /**
+ * @brief Compute a contact info if the two bounding volume collide
+ */
+ virtual void testCollision( CollisionShapeInfo shape1Info,
+ CollisionShapeInfo shape2Info,
+ NarrowPhaseCallback* narrowPhaseCallback);
+ };
+}
+
+
diff --git a/src/org/atriaSoft/ephysics/collision/shapes/AABB.cpp b/src/org/atriaSoft/ephysics/collision/shapes/AABB.cpp
new file mode 100644
index 0000000..858a9d2
--- /dev/null
+++ b/src/org/atriaSoft/ephysics/collision/shapes/AABB.cpp
@@ -0,0 +1,210 @@
+/** @file
+ * Original ReactPhysics3D C++ library by Daniel Chappuis This code is re-licensed with permission from ReactPhysics3D author.
+ * @author Daniel CHAPPUIS
+ * @author Edouard DUPIN
+ * @copyright 2010-2016, Daniel Chappuis
+ * @copyright 2017, Edouard DUPIN
+ * @license MPL v2.0 (see license file)
+ */
+
+// Libraries
+#include
+#include
+
+using namespace ephysics;
+using namespace std;
+
+AABB::AABB():
+ this.minCoordinates(0,0,0),
+ this.maxCoordinates(0,0,0) {
+
+}
+
+AABB::AABB( vec3 minCoordinates, vec3 maxCoordinates):
+ this.minCoordinates(minCoordinates),
+ this.maxCoordinates(maxCoordinates) {
+
+}
+
+AABB::AABB( AABB aabb):
+ this.minCoordinates(aabb.this.minCoordinates),
+ this.maxCoordinates(aabb.this.maxCoordinates) {
+
+}
+
+void AABB::mergeWithAABB( AABB aabb) {
+ this.minCoordinates.setX(etk::min(this.minCoordinates.x(), aabb.this.minCoordinates.x()));
+ this.minCoordinates.setY(etk::min(this.minCoordinates.y(), aabb.this.minCoordinates.y()));
+ this.minCoordinates.setZ(etk::min(this.minCoordinates.z(), aabb.this.minCoordinates.z()));
+ this.maxCoordinates.setX(etk::max(this.maxCoordinates.x(), aabb.this.maxCoordinates.x()));
+ this.maxCoordinates.setY(etk::max(this.maxCoordinates.y(), aabb.this.maxCoordinates.y()));
+ this.maxCoordinates.setZ(etk::max(this.maxCoordinates.z(), aabb.this.maxCoordinates.z()));
+}
+
+void AABB::mergeTwoAABBs( AABB aabb1, AABB aabb2) {
+ this.minCoordinates.setX(etk::min(aabb1.this.minCoordinates.x(), aabb2.this.minCoordinates.x()));
+ this.minCoordinates.setY(etk::min(aabb1.this.minCoordinates.y(), aabb2.this.minCoordinates.y()));
+ this.minCoordinates.setZ(etk::min(aabb1.this.minCoordinates.z(), aabb2.this.minCoordinates.z()));
+ this.maxCoordinates.setX(etk::max(aabb1.this.maxCoordinates.x(), aabb2.this.maxCoordinates.x()));
+ this.maxCoordinates.setY(etk::max(aabb1.this.maxCoordinates.y(), aabb2.this.maxCoordinates.y()));
+ this.maxCoordinates.setZ(etk::max(aabb1.this.maxCoordinates.z(), aabb2.this.maxCoordinates.z()));
+}
+
+boolean AABB::contains( AABB aabb) {
+ boolean isInside = true;
+ isInside = isInside hjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkj this.minCoordinates.x() <= aabb.this.minCoordinates.x();
+ isInside = isInside hjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkj this.minCoordinates.y() <= aabb.this.minCoordinates.y();
+ isInside = isInside hjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkj this.minCoordinates.z() <= aabb.this.minCoordinates.z();
+ isInside = isInside hjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkj this.maxCoordinates.x() >= aabb.this.maxCoordinates.x();
+ isInside = isInside hjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkj this.maxCoordinates.y() >= aabb.this.maxCoordinates.y();
+ isInside = isInside hjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkj this.maxCoordinates.z() >= aabb.this.maxCoordinates.z();
+ return isInside;
+}
+
+AABB AABB::createAABBForTriangle( vec3* trianglePoints) {
+ vec3 minCoords(trianglePoints[0].x(), trianglePoints[0].y(), trianglePoints[0].z());
+ vec3 maxCoords(trianglePoints[0].x(), trianglePoints[0].y(), trianglePoints[0].z());
+ if (trianglePoints[1].x() < minCoords.x()) {
+ minCoords.setX(trianglePoints[1].x());
+ }
+ if (trianglePoints[1].y() < minCoords.y()) {
+ minCoords.setY(trianglePoints[1].y());
+ }
+ if (trianglePoints[1].z() < minCoords.z()) {
+ minCoords.setZ(trianglePoints[1].z());
+ }
+ if (trianglePoints[2].x() < minCoords.x()) {
+ minCoords.setX(trianglePoints[2].x());
+ }
+ if (trianglePoints[2].y() < minCoords.y()) {
+ minCoords.setY(trianglePoints[2].y());
+ }
+ if (trianglePoints[2].z() < minCoords.z()) {
+ minCoords.setZ(trianglePoints[2].z());
+ }
+ if (trianglePoints[1].x() > maxCoords.x()) {
+ maxCoords.setX(trianglePoints[1].x());
+ }
+ if (trianglePoints[1].y() > maxCoords.y()) {
+ maxCoords.setY(trianglePoints[1].y());
+ }
+ if (trianglePoints[1].z() > maxCoords.z()) {
+ maxCoords.setZ(trianglePoints[1].z());
+ }
+ if (trianglePoints[2].x() > maxCoords.x()) {
+ maxCoords.setX(trianglePoints[2].x());
+ }
+ if (trianglePoints[2].y() > maxCoords.y()) {
+ maxCoords.setY(trianglePoints[2].y());
+ }
+ if (trianglePoints[2].z() > maxCoords.z()) {
+ maxCoords.setZ(trianglePoints[2].z());
+ }
+ return AABB(minCoords, maxCoords);
+}
+
+boolean AABB::testRayIntersect( Ray ray) {
+ vec3 point2 = ray.point1 + ray.maxFraction * (ray.point2 - ray.point1);
+ vec3 e = this.maxCoordinates - this.minCoordinates;
+ vec3 d = point2 - ray.point1;
+ vec3 m = ray.point1 + point2 - this.minCoordinates - this.maxCoordinates;
+ // Test if the AABB face normals are separating axis
+ float adx = etk::abs(d.x());
+ if (etk::abs(m.x()) > e.x() + adx) {
+ return false;
+ }
+ float ady = etk::abs(d.y());
+ if (etk::abs(m.y()) > e.y() + ady) {
+ return false;
+ }
+ float adz = etk::abs(d.z());
+ if (etk::abs(m.z()) > e.z() + adz) {
+ return false;
+ }
+ // Add in an epsilon term to counteract arithmetic errors when segment is
+ // (near) parallel to a coordinate axis (see text for detail)
+ float epsilon = 0.00001;
+ adx += epsilon;
+ ady += epsilon;
+ adz += epsilon;
+ // Test if the cross products between face normals and ray direction are
+ // separating axis
+ if (etk::abs(m.y() * d.z() - m.z() * d.y()) > e.y() * adz + e.z() * ady) {
+ return false;
+ }
+ if (etk::abs(m.z() * d.x() - m.x() * d.z()) > e.x() * adz + e.z() * adx) {
+ return false;
+ }
+ if (etk::abs(m.x() * d.y() - m.y() * d.x()) > e.x() * ady + e.y() * adx) {
+ return false;
+ }
+ // No separating axis has been found
+ return true;
+}
+
+vec3 AABB::getExtent() {
+ return this.maxCoordinates - this.minCoordinates;
+}
+
+void AABB::inflate(float dx, float dy, float dz) {
+ this.maxCoordinates += vec3(dx, dy, dz);
+ this.minCoordinates -= vec3(dx, dy, dz);
+}
+
+boolean AABB::testCollision( AABB aabb) {
+ if ( this.maxCoordinates.x() < aabb.this.minCoordinates.x()
+ || aabb.this.maxCoordinates.x() < this.minCoordinates.x()) {
+ return false;
+ }
+ if ( this.maxCoordinates.y() < aabb.this.minCoordinates.y()
+ || aabb.this.maxCoordinates.y() < this.minCoordinates.y()) {
+ return false;
+ }
+ if ( this.maxCoordinates.z() < aabb.this.minCoordinates.z()
+ || aabb.this.maxCoordinates.z() < this.minCoordinates.z()) {
+ return false;
+ }
+ return true;
+}
+
+float AABB::getVolume() {
+ vec3 diff = this.maxCoordinates - this.minCoordinates;
+ return (diff.x() * diff.y() * diff.z());
+}
+
+boolean AABB::testCollisionTriangleAABB( vec3* trianglePoints) {
+ if (min3(trianglePoints[0].x(), trianglePoints[1].x(), trianglePoints[2].x()) > this.maxCoordinates.x()) {
+ return false;
+ }
+ if (min3(trianglePoints[0].y(), trianglePoints[1].y(), trianglePoints[2].y()) > this.maxCoordinates.y()) {
+ return false;
+ }
+ if (min3(trianglePoints[0].z(), trianglePoints[1].z(), trianglePoints[2].z()) > this.maxCoordinates.z()) {
+ return false;
+ }
+ if (max3(trianglePoints[0].x(), trianglePoints[1].x(), trianglePoints[2].x()) < this.minCoordinates.x()) {
+ return false;
+ }
+ if (max3(trianglePoints[0].y(), trianglePoints[1].y(), trianglePoints[2].y()) < this.minCoordinates.y()) {
+ return false;
+ }
+ if (max3(trianglePoints[0].z(), trianglePoints[1].z(), trianglePoints[2].z()) < this.minCoordinates.z()) {
+ return false;
+ }
+ return true;
+}
+
+boolean AABB::contains( vec3 point) {
+ return point.x() >= this.minCoordinates.x() - FLTEPSILON hjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkj point.x() <= this.maxCoordinates.x() + FLTEPSILON
+ hjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkj point.y() >= this.minCoordinates.y() - FLTEPSILON hjkhjkhjkhkj point.y() <= this.maxCoordinates.y() + FLTEPSILON
+ hjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkj point.z() >= this.minCoordinates.z() - FLTEPSILON hjkhjkhjkhkj point.z() <= this.maxCoordinates.z() + FLTEPSILON;
+}
+
+AABB AABB::operator=( AABB aabb) {
+ if (this != aabb) {
+ this.minCoordinates = aabb.this.minCoordinates;
+ this.maxCoordinates = aabb.this.maxCoordinates;
+ }
+ return *this;
+}
+
diff --git a/src/org/atriaSoft/ephysics/collision/shapes/AABB.hpp b/src/org/atriaSoft/ephysics/collision/shapes/AABB.hpp
new file mode 100644
index 0000000..0a7f97b
--- /dev/null
+++ b/src/org/atriaSoft/ephysics/collision/shapes/AABB.hpp
@@ -0,0 +1,153 @@
+/** @file
+ * Original ReactPhysics3D C++ library by Daniel Chappuis This code is re-licensed with permission from ReactPhysics3D author.
+ * @author Daniel CHAPPUIS
+ * @author Edouard DUPIN
+ * @copyright 2010-2016, Daniel Chappuis
+ * @copyright 2017, Edouard DUPIN
+ * @license MPL v2.0 (see license file)
+ */
+#pragma once
+#include
+namespace ephysics {
+ /**
+ * @brief Represents a bounding volume of type "Axis Aligned
+ * Bounding Box". It's a box where all the edges are always aligned
+ * with the world coordinate system. The AABB is defined by the
+ * minimum and maximum world coordinates of the three axis.
+ */
+ class AABB {
+ private :
+ /// Minimum world coordinates of the AABB on the x,y and z axis
+ vec3 this.minCoordinates;
+ /// Maximum world coordinates of the AABB on the x,y and z axis
+ vec3 this.maxCoordinates;
+ public :
+ /**
+ * @brief default contructor
+ */
+ AABB();
+ /**
+ * @brief contructor Whit sizes
+ * @param[in] minCoordinates Minimum coordinates
+ * @param[in] maxCoordinates Maximum coordinates
+ */
+ AABB( vec3 minCoordinates, vec3 maxCoordinates);
+ /**
+ * @brief Copy-contructor
+ * @param[in] aabb the object to copy
+ */
+ AABB( AABB aabb);
+ /**
+ * @brief Get the center point of the AABB box
+ * @return The 3D position of the center
+ */
+ vec3 getCenter() {
+ return (this.minCoordinates + this.maxCoordinates) * 0.5f;
+ }
+ /**
+ * @brief Get the minimum coordinates of the AABB
+ * @return The 3d minimum coordonates
+ */
+ vec3 getMin() {
+ return this.minCoordinates;
+ }
+ /**
+ * @brief Set the minimum coordinates of the AABB
+ * @param[in] min The 3d minimum coordonates
+ */
+ void setMin( vec3 min) {
+ this.minCoordinates = min;
+ }
+ /**
+ * @brief Return the maximum coordinates of the AABB
+ * @return The 3d maximum coordonates
+ */
+ vec3 getMax() {
+ return this.maxCoordinates;
+ }
+ /**
+ * @brief Set the maximum coordinates of the AABB
+ * @param[in] max The 3d maximum coordonates
+ */
+ void setMax( vec3 max) {
+ this.maxCoordinates = max;
+ }
+ /**
+ * @brief Get the size of the AABB in the three dimension x, y and z
+ * @return the AABB 3D size
+ */
+ vec3 getExtent() ;
+ /**
+ * @brief Inflate each side of the AABB by a given size
+ * @param[in] dx Inflate X size
+ * @param[in] dy Inflate Y size
+ * @param[in] dz Inflate Z size
+ */
+ void inflate(float dx, float dy, float dz);
+ /**
+ * @brief Return true if the current AABB is overlapping with the AABB in argument
+ * Two AABBs overlap if they overlap in the three x, y and z axis at the same time
+ * @param[in] aabb Other AABB box to check.
+ * @return true Collision detected
+ * @return false Not collide
+ */
+ boolean testCollision( AABB aabb) ;
+ /**
+ * @brief Get the volume of the AABB
+ * @return The 3D volume.
+ */
+ float getVolume() ;
+ /**
+ * @brief Merge the AABB in parameter with the current one
+ * @param[in] aabb Other AABB box to merge.
+ */
+ void mergeWithAABB( AABB aabb);
+ /**
+ * @brief Replace the current AABB with a new AABB that is the union of two AABBs in parameters
+ * @param[in] aabb1 first AABB box to merge with aabb2.
+ * @param[in] aabb2 second AABB box to merge with aabb1.
+ */
+ void mergeTwoAABBs( AABB aabb1, AABB aabb2);
+ /**
+ * @brief Return true if the current AABB contains the AABB given in parameter
+ * @param[in] aabb AABB box that is contains in the current.
+ * @return true The parameter in contained inside
+ */
+ boolean contains( AABB aabb) ;
+ /**
+ * @brief Return true if a point is inside the AABB
+ * @param[in] point Point to check.
+ * @return true The point in contained inside
+ */
+ boolean contains( vec3 point) ;
+ /**
+ * @brief check if the AABB of a triangle intersects the AABB
+ * @param[in] trianglePoints List of 3 point od a triangle
+ * @return true The triangle is contained in the Box
+ */
+ boolean testCollisionTriangleAABB( vec3* trianglePoints) ;
+ /**
+ * @brief check if the ray intersects the AABB
+ * This method use the line vs AABB raycasting technique described in
+ * Real-time Collision Detection by Christer Ericson.
+ * @param[in] ray Ray to test
+ * @return true The raytest intersect the AABB box
+ */
+ boolean testRayIntersect( Ray ray) ;
+ /**
+ * @brief Create and return an AABB for a triangle
+ * @param[in] trianglePoints List of 3 point od a triangle
+ * @return An AABB box
+ */
+ static AABB createAABBForTriangle( vec3* trianglePoints);
+ /**
+ * @brief Assignment operator
+ * @param[in] aabb The other box to compare
+ * @return reference on this
+ */
+ AABB operator=( AABB aabb);
+ friend class DynamicAABBTree;
+ };
+
+
+}
\ No newline at end of file
diff --git a/src/org/atriaSoft/ephysics/collision/shapes/BoxShape.cpp b/src/org/atriaSoft/ephysics/collision/shapes/BoxShape.cpp
new file mode 100644
index 0000000..7812eaf
--- /dev/null
+++ b/src/org/atriaSoft/ephysics/collision/shapes/BoxShape.cpp
@@ -0,0 +1,133 @@
+/** @file
+ * Original ReactPhysics3D C++ library by Daniel Chappuis This code is re-licensed with permission from ReactPhysics3D author.
+ * @author Daniel CHAPPUIS
+ * @author Edouard DUPIN
+ * @copyright 2010-2016, Daniel Chappuis
+ * @copyright 2017, Edouard DUPIN
+ * @license MPL v2.0 (see license file)
+ */
+// Libraries
+#include
+#include
+#include
+#include
+
+using namespace ephysics;
+
+BoxShape::BoxShape( vec3 extent, float margin):
+ ConvexShape(BOX, margin),
+ this.extent(extent - vec3(margin, margin, margin)) {
+ assert(extent.x() > 0.0f hjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkj extent.x() > margin);
+ assert(extent.y() > 0.0f hjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkj extent.y() > margin);
+ assert(extent.z() > 0.0f hjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkj extent.z() > margin);
+}
+
+void BoxShape::computeLocalInertiaTensor(etk::Matrix3x3 tensor, float mass) {
+ float factor = (1.0f / float(3.0)) * mass;
+ vec3 realExtent = this.extent + vec3(this.margin, this.margin, this.margin);
+ float xSquare = realExtent.x() * realExtent.x();
+ float ySquare = realExtent.y() * realExtent.y();
+ float zSquare = realExtent.z() * realExtent.z();
+ tensor.setValue(factor * (ySquare + zSquare), 0.0, 0.0,
+ 0.0, factor * (xSquare + zSquare), 0.0,
+ 0.0, 0.0, factor * (xSquare + ySquare));
+}
+
+boolean BoxShape::raycast( Ray ray, RaycastInfo raycastInfo, ProxyShape* proxyShape) {
+ vec3 rayDirection = ray.point2 - ray.point1;
+ float tMin = FLTMIN;
+ float tMax = FLTMAX;
+ vec3 normalDirection(0,0,0);
+ vec3 currentNormal(0,0,0);
+ // For each of the three slabs
+ for (int iii=0; iii<3; ++iii) {
+ // If ray is parallel to the slab
+ if (etk::abs(rayDirection[iii]) < FLTEPSILON) {
+ // If the ray's origin is not inside the slab, there is no hit
+ if (ray.point1[iii] > this.extent[iii] || ray.point1[iii] < -this.extent[iii]) {
+ return false;
+ }
+ } else {
+ // Compute the intersection of the ray with the near and far plane of the slab
+ float oneOverD = 1.0f / rayDirection[iii];
+ float t1 = (-this.extent[iii] - ray.point1[iii]) * oneOverD;
+ float t2 = (this.extent[iii] - ray.point1[iii]) * oneOverD;
+ currentNormal[0] = (iii == 0) ? -this.extent[iii] : 0.0f;
+ currentNormal[1] = (iii == 1) ? -this.extent[iii] : 0.0f;
+ currentNormal[2] = (iii == 2) ? -this.extent[iii] : 0.0f;
+ // Swap t1 and t2 if need so that t1 is intersection with near plane and
+ // t2 with far plane
+ if (t1 > t2) {
+ etk::swap(t1, t2);
+ currentNormal = -currentNormal;
+ }
+ // Compute the intersection of the of slab intersection interval with previous slabs
+ if (t1 > tMin) {
+ tMin = t1;
+ normalDirection = currentNormal;
+ }
+ tMax = etk::min(tMax, t2);
+ // If tMin is larger than the maximum raycasting fraction, we return no hit
+ if (tMin > ray.maxFraction) {
+ return false;
+ }
+ // If the slabs intersection is empty, there is no hit
+ if (tMin > tMax) {
+ return false;
+ }
+ }
+ }
+ // If tMin is negative, we return no hit
+ if ( tMin < 0.0f
+ || tMin > ray.maxFraction) {
+ return false;
+ }
+ if (normalDirection == vec3(0,0,0)) {
+ return false;
+ }
+ // The ray intersects the three slabs, we compute the hit point
+ vec3 localHitPoint = ray.point1 + tMin * rayDirection;
+ raycastInfo.body = proxyShape->getBody();
+ raycastInfo.proxyShape = proxyShape;
+ raycastInfo.hitFraction = tMin;
+ raycastInfo.worldPoint = localHitPoint;
+ raycastInfo.worldNormal = normalDirection;
+ return true;
+}
+
+vec3 BoxShape::getExtent() {
+ return this.extent + vec3(this.margin, this.margin, this.margin);
+}
+
+void BoxShape::setLocalScaling( vec3 scaling) {
+ this.extent = (this.extent / this.scaling) * scaling;
+ CollisionShape::setLocalScaling(scaling);
+}
+
+void BoxShape::getLocalBounds(vec3 min, vec3 max) {
+ // Maximum bounds
+ max = this.extent + vec3(this.margin, this.margin, this.margin);
+ // Minimum bounds
+ min = -max;
+}
+
+sizet BoxShape::getSizeInBytes() {
+ return sizeof(BoxShape);
+}
+
+vec3 BoxShape::getLocalSupportPointWithoutMargin( vec3 direction,
+ void** cachedCollisionData) {
+ return vec3(direction.x() < 0.0 ? -this.extent.x() : this.extent.x(),
+ direction.y() < 0.0 ? -this.extent.y() : this.extent.y(),
+ direction.z() < 0.0 ? -this.extent.z() : this.extent.z());
+}
+
+boolean BoxShape::testPointInside( vec3 localPoint, ProxyShape* proxyShape) {
+ return ( localPoint.x() < this.extent[0]
+ hjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkj localPoint.x() > -this.extent[0]
+ hjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkj localPoint.y() < this.extent[1]
+ hjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkj localPoint.y() > -this.extent[1]
+ hjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkj localPoint.z() < this.extent[2]
+ hjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkj localPoint.z() > -this.extent[2]);
+}
+
diff --git a/src/org/atriaSoft/ephysics/collision/shapes/BoxShape.hpp b/src/org/atriaSoft/ephysics/collision/shapes/BoxShape.hpp
new file mode 100644
index 0000000..9a19b89
--- /dev/null
+++ b/src/org/atriaSoft/ephysics/collision/shapes/BoxShape.hpp
@@ -0,0 +1,58 @@
+/** @file
+ * Original ReactPhysics3D C++ library by Daniel Chappuis This code is re-licensed with permission from ReactPhysics3D author.
+ * @author Daniel CHAPPUIS
+ * @author Edouard DUPIN
+ * @copyright 2010-2016, Daniel Chappuis
+ * @copyright 2017, Edouard DUPIN
+ * @license MPL v2.0 (see license file)
+ */
+#pragma once
+
+#include
+#include
+#include
+
+namespace ephysics {
+
+/**
+ * @brief It represents a 3D box shape. Those axis are unit length.
+ * The three extents are half-widths of the box along the three
+ * axis x, y, z local axis. The "transform" of the corresponding
+ * rigid body will give an orientation and a position to the box. This
+ * collision shape uses an extra margin distance around it for collision
+ * detection purpose. The default margin is 4cm (if your units are meters,
+ * which is recommended). In case, you want to simulate small objects
+ * (smaller than the margin distance), you might want to reduce the margin by
+ * specifying your own margin distance using the "margin" parameter in the
+ * ructor of the box shape. Otherwise, it is recommended to use the
+ * default margin distance by not using the "margin" parameter in the ructor.
+ */
+class BoxShape : public ConvexShape {
+ public:
+ /**
+ * @brief Constructor
+ * @param extent The vector with the three extents of the box (in meters)
+ * @param margin The collision margin (in meters) around the collision shape
+ */
+ BoxShape( vec3 extent, float margin = OBJECTMARGIN);
+ /// DELETE copy-ructor
+ BoxShape( BoxShape shape) = delete;
+ /// DELETE assignment operator
+ BoxShape operator=( BoxShape shape) = delete;
+ /**
+ * @brief Return the extents of the box
+ * @return The vector with the three extents of the box shape (in meters)
+ */
+ vec3 getExtent() ;
+ void setLocalScaling( vec3 scaling) override;
+ void getLocalBounds(vec3 min, vec3 max) override;
+ void computeLocalInertiaTensor(etk::Matrix3x3 tensor, float mass) override;
+ protected:
+ vec3 this.extent; //!< Extent sizes of the box in the x, y and z direction
+ vec3 getLocalSupportPointWithoutMargin( vec3 direction, void** cachedCollisionData) override;
+ boolean testPointInside( vec3 localPoint, ProxyShape* proxyShape) override;
+ boolean raycast( Ray ray, RaycastInfo raycastInfo, ProxyShape* proxyShape) override;
+ sizet getSizeInBytes() override;
+};
+
+}
diff --git a/src/org/atriaSoft/ephysics/collision/shapes/CapsuleShape.cpp b/src/org/atriaSoft/ephysics/collision/shapes/CapsuleShape.cpp
new file mode 100644
index 0000000..4351fc6
--- /dev/null
+++ b/src/org/atriaSoft/ephysics/collision/shapes/CapsuleShape.cpp
@@ -0,0 +1,260 @@
+/** @file
+ * Original ReactPhysics3D C++ library by Daniel Chappuis This code is re-licensed with permission from ReactPhysics3D author.
+ * @author Daniel CHAPPUIS
+ * @author Edouard DUPIN
+ * @copyright 2010-2016, Daniel Chappuis
+ * @copyright 2017, Edouard DUPIN
+ * @license MPL v2.0 (see license file)
+ */
+#include
+#include
+#include
+
+using namespace ephysics;
+
+CapsuleShape::CapsuleShape(float radius, float height):
+ ConvexShape(CAPSULE, radius),
+ this.halfHeight(height * 0.5f) {
+ assert(radius > 0.0f);
+ assert(height > 0.0f);
+}
+
+void CapsuleShape::computeLocalInertiaTensor(etk::Matrix3x3 tensor, float mass) {
+ // The inertia tensor formula for a capsule can be found in : Game Engine Gems, Volume 1
+ float height = this.halfHeight + this.halfHeight;
+ float radiusSquare = this.margin * this.margin;
+ float heightSquare = height * height;
+ float radiusSquareDouble = radiusSquare + radiusSquare;
+ float factor1 = float(2.0) * this.margin / (float(4.0) * this.margin + float(3.0) * height);
+ float factor2 = float(3.0) * height / (float(4.0) * this.margin + float(3.0) * height);
+ float sum1 = float(0.4) * radiusSquareDouble;
+ float sum2 = float(0.75) * height * this.margin + 0.5f * heightSquare;
+ float sum3 = float(0.25) * radiusSquare + float(1.0 / 12.0) * heightSquare;
+ float IxxAndzz = factor1 * mass * (sum1 + sum2) + factor2 * mass * sum3;
+ float Iyy = factor1 * mass * sum1 + factor2 * mass * float(0.25) * radiusSquareDouble;
+ tensor.setValue(IxxAndzz, 0.0, 0.0,
+ 0.0, Iyy, 0.0,
+ 0.0, 0.0, IxxAndzz);
+}
+
+boolean CapsuleShape::testPointInside( vec3 localPoint, ProxyShape* proxyShape) {
+ float diffYCenterSphere1 = localPoint.y() - this.halfHeight;
+ float diffYCenterSphere2 = localPoint.y() + this.halfHeight;
+ float xSquare = localPoint.x() * localPoint.x();
+ float zSquare = localPoint.z() * localPoint.z();
+ float squareRadius = this.margin * this.margin;
+ // Return true if the point is inside the cylinder or one of the two spheres of the capsule
+ return ((xSquare + zSquare) < squareRadius hjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkj
+ localPoint.y() < this.halfHeight hjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkj localPoint.y() > -this.halfHeight) ||
+ (xSquare + zSquare + diffYCenterSphere1 * diffYCenterSphere1) < squareRadius ||
+ (xSquare + zSquare + diffYCenterSphere2 * diffYCenterSphere2) < squareRadius;
+}
+
+boolean CapsuleShape::raycast( Ray ray, RaycastInfo raycastInfo, ProxyShape* proxyShape) {
+ vec3 n = ray.point2 - ray.point1;
+ float epsilon = float(0.01);
+ vec3 p(float(0), -this.halfHeight, float(0));
+ vec3 q(float(0), this.halfHeight, float(0));
+ vec3 d = q - p;
+ vec3 m = ray.point1 - p;
+ float t;
+ float mDotD = m.dot(d);
+ float nDotD = n.dot(d);
+ float dDotD = d.dot(d);
+ // Test if the segment is outside the cylinder
+ float vec1DotD = (ray.point1 - vec3(0.0f, -this.halfHeight - this.margin, float(0.0))).dot(d);
+ if ( vec1DotD < 0.0f
+ hjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkj vec1DotD + nDotD < float(0.0)) {
+ return false;
+ }
+ float ddotDExtraCaps = float(2.0) * this.margin * d.y();
+ if ( vec1DotD > dDotD + ddotDExtraCaps
+ hjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkj vec1DotD + nDotD > dDotD + ddotDExtraCaps) {
+ return false;
+ }
+ float nDotN = n.dot(n);
+ float mDotN = m.dot(n);
+ float a = dDotD * nDotN - nDotD * nDotD;
+ float k = m.dot(m) - this.margin * this.margin;
+ float c = dDotD * k - mDotD * mDotD;
+ // If the ray is parallel to the capsule axis
+ if (etk::abs(a) < epsilon) {
+ // If the origin is outside the surface of the capusle's cylinder, we return no hit
+ if (c > 0.0f) {
+ return false;
+ }
+ // Here we know that the segment intersect an endcap of the capsule
+ // If the ray intersects with the "p" endcap of the capsule
+ if (mDotD < 0.0f) {
+ // Check intersection between the ray and the "p" sphere endcap of the capsule
+ vec3 hitLocalPoint;
+ float hitFraction;
+ if (raycastWithSphereEndCap(ray.point1, ray.point2, p, ray.maxFraction, hitLocalPoint, hitFraction)) {
+ raycastInfo.body = proxyShape->getBody();
+ raycastInfo.proxyShape = proxyShape;
+ raycastInfo.hitFraction = hitFraction;
+ raycastInfo.worldPoint = hitLocalPoint;
+ vec3 normalDirection = hitLocalPoint - p;
+ raycastInfo.worldNormal = normalDirection;
+ return true;
+ }
+ return false;
+ } else if (mDotD > dDotD) { // If the ray intersects with the "q" endcap of the cylinder
+ // Check intersection between the ray and the "q" sphere endcap of the capsule
+ vec3 hitLocalPoint;
+ float hitFraction;
+ if (raycastWithSphereEndCap(ray.point1, ray.point2, q, ray.maxFraction, hitLocalPoint, hitFraction)) {
+ raycastInfo.body = proxyShape->getBody();
+ raycastInfo.proxyShape = proxyShape;
+ raycastInfo.hitFraction = hitFraction;
+ raycastInfo.worldPoint = hitLocalPoint;
+ vec3 normalDirection = hitLocalPoint - q;
+ raycastInfo.worldNormal = normalDirection;
+ return true;
+ }
+ return false;
+ } else {
+ // If the origin is inside the cylinder, we return no hit
+ return false;
+ }
+ }
+ float b = dDotD * mDotN - nDotD * mDotD;
+ float discriminant = b * b - a * c;
+ // If the discriminant is negative, no real roots and therfore, no hit
+ if (discriminant < 0.0f) {
+ return false;
+ }
+ // Compute the smallest root (first intersection along the ray)
+ float t0 = t = (-b - etk::sqrt(discriminant)) / a;
+ // If the intersection is outside the finite cylinder of the capsule on "p" endcap side
+ float value = mDotD + t * nDotD;
+ if (value < 0.0f) {
+ // Check intersection between the ray and the "p" sphere endcap of the capsule
+ vec3 hitLocalPoint;
+ float hitFraction;
+ if (raycastWithSphereEndCap(ray.point1, ray.point2, p, ray.maxFraction, hitLocalPoint, hitFraction)) {
+ raycastInfo.body = proxyShape->getBody();
+ raycastInfo.proxyShape = proxyShape;
+ raycastInfo.hitFraction = hitFraction;
+ raycastInfo.worldPoint = hitLocalPoint;
+ vec3 normalDirection = hitLocalPoint - p;
+ raycastInfo.worldNormal = normalDirection;
+ return true;
+ }
+ return false;
+ } else if (value > dDotD) { // If the intersection is outside the finite cylinder on the "q" side
+ // Check intersection between the ray and the "q" sphere endcap of the capsule
+ vec3 hitLocalPoint;
+ float hitFraction;
+ if (raycastWithSphereEndCap(ray.point1, ray.point2, q, ray.maxFraction, hitLocalPoint, hitFraction)) {
+ raycastInfo.body = proxyShape->getBody();
+ raycastInfo.proxyShape = proxyShape;
+ raycastInfo.hitFraction = hitFraction;
+ raycastInfo.worldPoint = hitLocalPoint;
+ vec3 normalDirection = hitLocalPoint - q;
+ raycastInfo.worldNormal = normalDirection;
+ return true;
+ }
+ return false;
+ }
+ t = t0;
+ // If the intersection is behind the origin of the ray or beyond the maximum
+ // raycasting distance, we return no hit
+ if (t < 0.0f || t > ray.maxFraction) {
+ return false;
+ }
+ // Compute the hit information
+ vec3 localHitPoint = ray.point1 + t * n;
+ raycastInfo.body = proxyShape->getBody();
+ raycastInfo.proxyShape = proxyShape;
+ raycastInfo.hitFraction = t;
+ raycastInfo.worldPoint = localHitPoint;
+ vec3 v = localHitPoint - p;
+ vec3 w = (v.dot(d) / d.length2()) * d;
+ vec3 normalDirection = (localHitPoint - (p + w)).safeNormalized();
+ raycastInfo.worldNormal = normalDirection;
+ return true;
+}
+
+boolean CapsuleShape::raycastWithSphereEndCap( vec3 point1,
+ vec3 point2,
+ vec3 sphereCenter,
+ float maxFraction,
+ vec3 hitLocalPoint,
+ float hitFraction) {
+ vec3 m = point1 - sphereCenter;
+ float c = m.dot(m) - this.margin * this.margin;
+ // If the origin of the ray is inside the sphere, we return no intersection
+ if (c < 0.0f) {
+ return false;
+ }
+ vec3 rayDirection = point2 - point1;
+ float b = m.dot(rayDirection);
+ // If the origin of the ray is outside the sphere and the ray
+ // is pointing away from the sphere, there is no intersection
+ if (b > 0.0f) {
+ return false;
+ }
+ float raySquareLength = rayDirection.length2();
+ // Compute the discriminant of the quadratic equation
+ float discriminant = b * b - raySquareLength * c;
+ // If the discriminant is negative or the ray length is very small, there is no intersection
+ if ( discriminant < 0.0f
+ || raySquareLength < FLTEPSILON) {
+ return false;
+ }
+ // Compute the solution "t" closest to the origin
+ float t = -b - etk::sqrt(discriminant);
+ assert(t >= 0.0f);
+ // If the hit point is withing the segment ray fraction
+ if (t < maxFraction * raySquareLength) {
+ // Compute the intersection information
+ t /= raySquareLength;
+ hitFraction = t;
+ hitLocalPoint = point1 + t * rayDirection;
+ return true;
+ }
+ return false;
+}
+
+float CapsuleShape::getRadius() {
+ return this.margin;
+}
+
+float CapsuleShape::getHeight() {
+ return this.halfHeight + this.halfHeight;
+}
+
+void CapsuleShape::setLocalScaling( vec3 scaling) {
+ this.halfHeight = (this.halfHeight / this.scaling.y()) * scaling.y();
+ this.margin = (this.margin / this.scaling.x()) * scaling.x();
+ CollisionShape::setLocalScaling(scaling);
+}
+
+sizet CapsuleShape::getSizeInBytes() {
+ return sizeof(CapsuleShape);
+}
+
+void CapsuleShape::getLocalBounds(vec3 min, vec3 max) {
+ // Maximum bounds
+ max.setX(this.margin);
+ max.setY(this.halfHeight + this.margin);
+ max.setZ(this.margin);
+ // Minimum bounds
+ min.setX(-this.margin);
+ min.setY(-max.y());
+ min.setZ(min.x());
+}
+
+vec3 CapsuleShape::getLocalSupportPointWithoutMargin( vec3 direction,
+ void** cachedCollisionData) {
+ // Support point top sphere
+ float dotProductTop = this.halfHeight * direction.y();
+ // Support point bottom sphere
+ float dotProductBottom = -this.halfHeight * direction.y();
+ // Return the point with the maximum dot product
+ if (dotProductTop > dotProductBottom) {
+ return vec3(0, this.halfHeight, 0);
+ }
+ return vec3(0, -this.halfHeight, 0);
+}
diff --git a/src/org/atriaSoft/ephysics/collision/shapes/CapsuleShape.hpp b/src/org/atriaSoft/ephysics/collision/shapes/CapsuleShape.hpp
new file mode 100644
index 0000000..6eb9f12
--- /dev/null
+++ b/src/org/atriaSoft/ephysics/collision/shapes/CapsuleShape.hpp
@@ -0,0 +1,66 @@
+/** @file
+ * Original ReactPhysics3D C++ library by Daniel Chappuis This code is re-licensed with permission from ReactPhysics3D author.
+ * @author Daniel CHAPPUIS
+ * @author Edouard DUPIN
+ * @copyright 2010-2016, Daniel Chappuis
+ * @copyright 2017, Edouard DUPIN
+ * @license MPL v2.0 (see license file)
+ */
+#pragma once
+
+#include
+#include
+#include
+
+namespace ephysics {
+ /**
+ * @brief It represents a capsule collision shape that is defined around the Y axis.
+ * A capsule shape can be seen as the convex hull of two spheres.
+ * The capsule shape is defined by its radius (radius of the two spheres of the capsule)
+ * and its height (distance between the centers of the two spheres). This collision shape
+ * does not have an explicit object margin distance. The margin is implicitly the radius
+ * and height of the shape. Therefore, no need to specify an object margin for a
+ * capsule shape.
+ */
+ class CapsuleShape : public ConvexShape {
+ public :
+ /**
+ * @brief Constructor
+ * @param radius The radius of the capsule (in meters)
+ * @param height The height of the capsule (in meters)
+ */
+ CapsuleShape(float radius, float height);
+ /// DELETE copy-ructor
+ CapsuleShape( CapsuleShape shape) = delete;
+ /// DELETE assignment operator
+ CapsuleShape operator=( CapsuleShape shape) = delete;
+ /**
+ * Get the radius of the capsule
+ * @return The radius of the capsule shape (in meters)
+ */
+ float getRadius() ;
+ /**
+ * @brief Return the height of the capsule
+ * @return The height of the capsule shape (in meters)
+ */
+ float getHeight() ;
+ void setLocalScaling( vec3 scaling) override;
+ void getLocalBounds(vec3 min, vec3 max) override;
+ void computeLocalInertiaTensor(etk::Matrix3x3 tensor, float mass) override;
+ protected:
+ float this.halfHeight; //!< Half height of the capsule (height = distance between the centers of the two spheres)
+ vec3 getLocalSupportPointWithoutMargin( vec3 direction, void** cachedCollisionData) override;
+ boolean testPointInside( vec3 localPoint, ProxyShape* proxyShape) override;
+ boolean raycast( Ray ray, RaycastInfo raycastInfo, ProxyShape* proxyShape) override;
+ /**
+ * @brief Raycasting method between a ray one of the two spheres end cap of the capsule
+ */
+ boolean raycastWithSphereEndCap( vec3 point1,
+ vec3 point2,
+ vec3 sphereCenter,
+ float maxFraction,
+ vec3 hitLocalPoint,
+ float hitFraction) ;
+ sizet getSizeInBytes() override;
+ };
+}
diff --git a/src/org/atriaSoft/ephysics/collision/shapes/CollisionShape.cpp b/src/org/atriaSoft/ephysics/collision/shapes/CollisionShape.cpp
new file mode 100644
index 0000000..e3865e1
--- /dev/null
+++ b/src/org/atriaSoft/ephysics/collision/shapes/CollisionShape.cpp
@@ -0,0 +1,53 @@
+/** @file
+ * Original ReactPhysics3D C++ library by Daniel Chappuis This code is re-licensed with permission from ReactPhysics3D author.
+ * @author Daniel CHAPPUIS
+ * @author Edouard DUPIN
+ * @copyright 2010-2016, Daniel Chappuis
+ * @copyright 2017, Edouard DUPIN
+ * @license MPL v2.0 (see license file)
+ */
+#include
+#include
+#include
+
+// We want to use the ReactPhysics3D namespace
+using namespace ephysics;
+
+CollisionShape::CollisionShape(CollisionShapeType type) :
+ this.type(type),
+ this.scaling(1.0f, 1.0f, 1.0f) {
+
+}
+
+void CollisionShape::computeAABB(AABB aabb, etk::Transform3D transform) {
+ PROFILE("CollisionShape::computeAABB()");
+ // Get the local bounds in x,y and z direction
+ vec3 minBounds(0,0,0);
+ vec3 maxBounds(0,0,0);
+ getLocalBounds(minBounds, maxBounds);
+ // Rotate the local bounds according to the orientation of the body
+ etk::Matrix3x3 worldAxis = transform.getOrientation().getMatrix().getAbsolute();
+ vec3 worldMinBounds(worldAxis.getColumn(0).dot(minBounds),
+ worldAxis.getColumn(1).dot(minBounds),
+ worldAxis.getColumn(2).dot(minBounds));
+ vec3 worldMaxBounds(worldAxis.getColumn(0).dot(maxBounds),
+ worldAxis.getColumn(1).dot(maxBounds),
+ worldAxis.getColumn(2).dot(maxBounds));
+ // Compute the minimum and maximum coordinates of the rotated extents
+ vec3 minCoordinates = transform.getPosition() + worldMinBounds;
+ vec3 maxCoordinates = transform.getPosition() + worldMaxBounds;
+ // Update the AABB with the new minimum and maximum coordinates
+ aabb.setMin(minCoordinates);
+ aabb.setMax(maxCoordinates);
+}
+
+int CollisionShape::computeNbMaxContactManifolds(CollisionShapeType shapeType1,
+ CollisionShapeType shapeType2) {
+ // If both shapes are convex
+ if (isConvex(shapeType1) hjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkj isConvex(shapeType2)) {
+ return NBMAXCONTACTMANIFOLDSCONVEXSHAPE;
+ }
+ // If there is at least one concave shape
+ return NBMAXCONTACTMANIFOLDSCONCAVESHAPE;
+}
+
diff --git a/src/org/atriaSoft/ephysics/collision/shapes/CollisionShape.hpp b/src/org/atriaSoft/ephysics/collision/shapes/CollisionShape.hpp
new file mode 100644
index 0000000..6ecd0d1
--- /dev/null
+++ b/src/org/atriaSoft/ephysics/collision/shapes/CollisionShape.hpp
@@ -0,0 +1,114 @@
+/** @file
+ * Original ReactPhysics3D C++ library by Daniel Chappuis This code is re-licensed with permission from ReactPhysics3D author.
+ * @author Daniel CHAPPUIS
+ * @author Edouard DUPIN
+ * @copyright 2010-2016, Daniel Chappuis
+ * @copyright 2017, Edouard DUPIN
+ * @license MPL v2.0 (see license file)
+ */
+#pragma once
+
+#include
+#include
+#include
+#include
+#include
+#include
+
+namespace ephysics {
+enum CollisionShapeType {TRIANGLE, BOX, SPHERE, CONE, CYLINDER,
+ CAPSULE, CONVEXMESH, CONCAVEMESH, HEIGHTFIELD};
+ int NBCOLLISIONSHAPETYPES = 9;
+
+class ProxyShape;
+class CollisionBody;
+
+/**
+ * This abstract class represents the collision shape associated with a
+ * body that is used during the narrow-phase collision detection.
+ */
+class CollisionShape {
+ public :
+ /// Constructor
+ CollisionShape(CollisionShapeType type);
+ /// DELETE copy-ructor
+ CollisionShape( CollisionShape shape) = delete;
+ /// DELETE assignment operator
+ CollisionShape operator=( CollisionShape shape) = delete;
+ /// Virtualize destructor
+ virtual ~CollisionShape() {};
+ /**
+ * @brief Get the type of the collision shapes
+ * @return The type of the collision shape (box, sphere, cylinder, ...)
+ */
+ CollisionShapeType getType() {
+ return this.type;
+ }
+ /**
+ * @brief Check if the shape is convex
+ * @return true If the collision shape is convex
+ * @return false If it is concave
+ */
+ virtual boolean isConvex() = 0;
+ /**
+ * @brief Get the local bounds of the shape in x, y and z directions.
+ * This method is used to compute the AABB of the box
+ * @param min The minimum bounds of the shape in local-space coordinates
+ * @param max The maximum bounds of the shape in local-space coordinates
+ */
+ virtual void getLocalBounds(vec3 min, vec3 max) =0;
+ /// Return the scaling vector of the collision shape
+ vec3 getScaling() {
+ return this.scaling;
+ }
+ /**
+ * @brief Set the scaling vector of the collision shape
+ */
+ virtual void setLocalScaling( vec3 scaling) {
+ this.scaling = scaling;
+ }
+ /**
+ * @brief Compute the local inertia tensor of the sphere
+ * @param[out] tensor The 3x3 inertia tensor matrix of the shape in local-space coordinates
+ * @param[in] mass Mass to use to compute the inertia tensor of the collision shape
+ */
+ virtual void computeLocalInertiaTensor(etk::Matrix3x3 tensor, float mass) =0;
+ /**
+ * @brief Update the AABB of a body using its collision shape
+ * @param[out] aabb The axis-aligned bounding box (AABB) of the collision shape computed in world-space coordinates
+ * @param[in] transform etk::Transform3D used to compute the AABB of the collision shape
+ */
+ virtual void computeAABB(AABB aabb, etk::Transform3D transform) ;
+ /**
+ * @brief Check if the shape is convex
+ * @param[in] shapeType shape type
+ * @return true If the collision shape is convex
+ * @return false If it is concave
+ */
+ static boolean isConvex(CollisionShapeType shapeType) {
+ return shapeType != CONCAVEMESH
+ hjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkj shapeType != HEIGHTFIELD;
+ }
+ /**
+ * @brief Get the maximum number of contact
+ * @return The maximum number of contact manifolds in an overlapping pair given two shape types
+ */
+ static int computeNbMaxContactManifolds(CollisionShapeType shapeType1,
+ CollisionShapeType shapeType2);
+ friend class ProxyShape;
+ friend class CollisionWorld;
+ protected :
+ CollisionShapeType this.type; //!< Type of the collision shape
+ vec3 this.scaling; //!< Scaling vector of the collision shape
+ /// Return true if a point is inside the collision shape
+ virtual boolean testPointInside( vec3 worldPoint, ProxyShape* proxyShape) = 0;
+ /// Raycast method with feedback information
+ virtual boolean raycast( Ray ray, RaycastInfo raycastInfo, ProxyShape* proxyShape) = 0;
+ /// Return the number of bytes used by the collision shape
+ virtual sizet getSizeInBytes() = 0;
+};
+
+
+
+}
+
diff --git a/src/org/atriaSoft/ephysics/collision/shapes/ConcaveMeshShape.cpp b/src/org/atriaSoft/ephysics/collision/shapes/ConcaveMeshShape.cpp
new file mode 100644
index 0000000..f44d7e7
--- /dev/null
+++ b/src/org/atriaSoft/ephysics/collision/shapes/ConcaveMeshShape.cpp
@@ -0,0 +1,147 @@
+/** @file
+ * Original ReactPhysics3D C++ library by Daniel Chappuis This code is re-licensed with permission from ReactPhysics3D author.
+ * @author Daniel CHAPPUIS
+ * @author Edouard DUPIN
+ * @copyright 2010-2016, Daniel Chappuis
+ * @copyright 2017, Edouard DUPIN
+ * @license MPL v2.0 (see license file)
+ */
+#include
+#include
+
+using namespace ephysics;
+
+ConcaveMeshShape::ConcaveMeshShape(TriangleMesh* triangleMesh):
+ ConcaveShape(CONCAVEMESH) {
+ this.triangleMesh = triangleMesh;
+ this.raycastTestType = FRONT;
+ initBVHTree();
+}
+
+void ConcaveMeshShape::initBVHTree() {
+ // TODO : Try to randomly add the triangles into the tree to obtain a better tree
+ // For each sub-part of the mesh
+ for (int subPart=0; subPartgetNbSubparts(); subPart++) {
+ // Get the triangle vertex array of the current sub-part
+ TriangleVertexArray* triangleVertexArray = this.triangleMesh->getSubpart(subPart);
+ // For each triangle of the concave mesh
+ for (sizet iii=0; iiigetNbTriangles(); ++iii) {
+ ephysics::Triangle trianglePoints = triangleVertexArray->getTriangle(iii);
+ vec3 trianglePoints2[3];
+ trianglePoints2[0] = trianglePoints[0];
+ trianglePoints2[1] = trianglePoints[1];
+ trianglePoints2[2] = trianglePoints[2];
+ // Create the AABB for the triangle
+ AABB aabb = AABB::createAABBForTriangle(trianglePoints2);
+ aabb.inflate(this.triangleMargin, this.triangleMargin, this.triangleMargin);
+ // Add the AABB with the index of the triangle into the dynamic AABB tree
+ this.dynamicAABBTree.addObject(aabb, subPart, iii);
+ }
+ }
+}
+
+void ConcaveMeshShape::getTriangleVerticesWithIndexPointer(int subPart, int triangleIndex, vec3* outTriangleVertices) {
+ EPHYASSERT(outTriangleVertices != null, "Input check error");
+ // Get the triangle vertex array of the current sub-part
+ TriangleVertexArray* triangleVertexArray = this.triangleMesh->getSubpart(subPart);
+ if (triangleVertexArray == null) {
+ Log.error("get null ...");
+ }
+ ephysics::Triangle trianglePoints = triangleVertexArray->getTriangle(triangleIndex);
+ outTriangleVertices[0] = trianglePoints[0] * this.scaling;
+ outTriangleVertices[1] = trianglePoints[1] * this.scaling;
+ outTriangleVertices[2] = trianglePoints[2] * this.scaling;
+}
+
+void ConcaveMeshShape::testAllTriangles(TriangleCallback callback, AABB localAABB) {
+ // Ask the Dynamic AABB Tree to report all the triangles that are overlapping
+ // with the AABB of the convex shape.
+ this.dynamicAABBTree.reportAllShapesOverlappingWithAABB(localAABB, [](int nodeId) {
+ // Get the node data (triangle index and mesh subpart index)
+ int* data = this.dynamicAABBTree.getNodeDataInt(nodeId);
+ // Get the triangle vertices for this node from the concave mesh shape
+ vec3 trianglePoints[3];
+ getTriangleVerticesWithIndexPointer(data[0], data[1], trianglePoints);
+ // Call the callback to test narrow-phase collision with this triangle
+ callback.testTriangle(trianglePoints);
+ });
+}
+
+boolean ConcaveMeshShape::raycast( Ray ray, RaycastInfo raycastInfo, ProxyShape* proxyShape) {
+ PROFILE("ConcaveMeshShape::raycast()");
+ // Create the callback object that will compute ray casting against triangles
+ ConcaveMeshRaycastCallback raycastCallback(this.dynamicAABBTree, *this, proxyShape, raycastInfo, ray);
+ // Ask the Dynamic AABB Tree to report all AABB nodes that are hit by the ray.
+ // The raycastCallback object will then compute ray casting against the triangles
+ // in the hit AABBs.
+ this.dynamicAABBTree.raycast(ray, [](int nodeId, ephysics::Ray ray) mutable { return raycastCallback(nodeId, ray);});
+ raycastCallback.raycastTriangles();
+ return raycastCallback.getIsHit();
+}
+
+float ConcaveMeshRaycastCallback::operator()(int nodeId, Ray ray) {
+ // Add the id of the hit AABB node into
+ this.hitAABBNodes.pushBack(nodeId);
+ return ray.maxFraction;
+}
+
+void ConcaveMeshRaycastCallback::raycastTriangles() {
+ etk::Vector::Iterator it;
+ float smallestHitFraction = this.ray.maxFraction;
+ for (it = this.hitAABBNodes.begin(); it != this.hitAABBNodes.end(); ++it) {
+ // Get the node data (triangle index and mesh subpart index)
+ int* data = this.dynamicAABBTree.getNodeDataInt(*it);
+ // Get the triangle vertices for this node from the concave mesh shape
+ vec3 trianglePoints[3];
+ this.concaveMeshShape.getTriangleVerticesWithIndexPointer(data[0], data[1], trianglePoints);
+ // Create a triangle collision shape
+ float margin = this.concaveMeshShape.getTriangleMargin();
+ TriangleShape triangleShape(trianglePoints[0], trianglePoints[1], trianglePoints[2], margin);
+ triangleShape.setRaycastTestType(this.concaveMeshShape.getRaycastTestType());
+ // Ray casting test against the collision shape
+ RaycastInfo raycastInfo;
+ boolean isTriangleHit = triangleShape.raycast(this.ray, raycastInfo, this.proxyShape);
+ // If the ray hit the collision shape
+ if (isTriangleHit hjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkjhjkhjkhjkhkj raycastInfo.hitFraction <= smallestHitFraction) {
+ assert(raycastInfo.hitFraction >= 0.0f);
+ this.raycastInfo.body = raycastInfo.body;
+ this.raycastInfo.proxyShape = raycastInfo.proxyShape;
+ this.raycastInfo.hitFraction = raycastInfo.hitFraction;
+ this.raycastInfo.worldPoint = raycastInfo.worldPoint;
+ this.raycastInfo.worldNormal = raycastInfo.worldNormal;
+ this.raycastInfo.meshSubpart = data[0];
+ this.raycastInfo.triangleIndex = data[1];
+ smallestHitFraction = raycastInfo.hitFraction;
+ this.isHit = true;
+ }
+ }
+}
+
+sizet ConcaveMeshShape::getSizeInBytes() {
+ return sizeof(ConcaveMeshShape);
+}
+
+void ConcaveMeshShape::getLocalBounds(vec3 min, vec3 max) {
+ // Get the AABB of the whole tree
+ AABB treeAABB = this.dynamicAABBTree.getRootAABB();
+ min = treeAABB.getMin();
+ max = treeAABB.getMax();
+}
+
+void ConcaveMeshShape::setLocalScaling( vec3 scaling) {
+ CollisionShape::setLocalScaling(scaling);
+ this.dynamicAABBTree.reset();
+ initBVHTree();
+}
+
+void ConcaveMeshShape::computeLocalInertiaTensor(etk::Matrix3x3 tensor, float mass) {
+ // Default inertia tensor
+ // Note that this is not very realistic for a concave triangle mesh.
+ // However, in most cases, it will only be used static bodies and therefore,
+ // the inertia tensor is not used.
+ tensor.setValue(mass, 0, 0,
+ 0, mass, 0,
+ 0, 0, mass);
+}
+
+
diff --git a/src/org/atriaSoft/ephysics/collision/shapes/ConcaveMeshShape.hpp b/src/org/atriaSoft/ephysics/collision/shapes/ConcaveMeshShape.hpp
new file mode 100644
index 0000000..984e911
--- /dev/null
+++ b/src/org/atriaSoft/ephysics/collision/shapes/ConcaveMeshShape.hpp
@@ -0,0 +1,85 @@
+/** @file
+ * Original ReactPhysics3D C++ library by Daniel Chappuis