From 096b4638c461cba2e97d336553225e3001da438f Mon Sep 17 00:00:00 2001 From: Daniel Genrich Date: Wed, 3 Sep 2008 11:11:11 +0000 Subject: [PATCH 1/9] Revert rev16344 on trunk, bullet work is done in sim_physics branch as discussed on sunday meeting --- extern/bullet2/src/Bullet-C-Api.h | 136 +- .../BroadphaseCollision/btAxisSweep3.cpp | 636 +++- .../BroadphaseCollision/btAxisSweep3.h | 865 +----- .../btBroadphaseInterface.h | 28 +- .../BroadphaseCollision/btBroadphaseProxy.h | 55 +- .../btCollisionAlgorithm.cpp | 2 +- .../btCollisionAlgorithm.h | 11 +- .../BroadphaseCollision/btDbvt.cpp | 1320 --------- .../BroadphaseCollision/btDbvt.h | 1101 ------- .../BroadphaseCollision/btDbvtBroadphase.cpp | 344 --- .../BroadphaseCollision/btDbvtBroadphase.h | 103 - .../BroadphaseCollision/btDispatcher.h | 22 +- .../btMultiSapBroadphase.cpp | 466 --- .../btMultiSapBroadphase.h | 144 - .../btOverlappingPairCache.cpp | 515 +--- .../btOverlappingPairCache.h | 351 +-- .../btOverlappingPairCallback.h | 40 - .../BroadphaseCollision/btQuantizedBvh.cpp | 1025 ------- .../BroadphaseCollision/btQuantizedBvh.h | 486 ---- .../btSimpleBroadphase.cpp | 246 +- .../BroadphaseCollision/btSimpleBroadphase.h | 101 +- .../SphereTriangleDetector.cpp | 15 +- .../SphereTriangleDetector.h | 6 +- .../btBoxBoxCollisionAlgorithm.cpp | 85 - .../btBoxBoxCollisionAlgorithm.h | 66 - .../CollisionDispatch/btBoxBoxDetector.cpp | 683 ----- .../CollisionDispatch/btBoxBoxDetector.h | 44 - .../btCollisionConfiguration.h | 47 - .../CollisionDispatch/btCollisionCreateFunc.h | 2 +- .../btCollisionDispatcher.cpp | 237 +- .../CollisionDispatch/btCollisionDispatcher.h | 62 +- .../CollisionDispatch/btCollisionObject.cpp | 10 +- .../CollisionDispatch/btCollisionObject.h | 71 +- .../CollisionDispatch/btCollisionWorld.cpp | 633 ++-- .../CollisionDispatch/btCollisionWorld.h | 210 +- .../btCompoundCollisionAlgorithm.cpp | 36 +- .../btCompoundCollisionAlgorithm.h | 28 +- .../btConvexConcaveCollisionAlgorithm.cpp | 27 +- .../btConvexConcaveCollisionAlgorithm.h | 24 +- .../btConvexConvexAlgorithm.cpp | 20 +- .../btConvexConvexAlgorithm.h | 25 +- .../btConvexPlaneCollisionAlgorithm.cpp | 108 - .../btConvexPlaneCollisionAlgorithm.h | 71 - .../btDefaultCollisionConfiguration.cpp | 281 -- .../btDefaultCollisionConfiguration.h | 112 - .../btEmptyCollisionAlgorithm.h | 10 +- .../CollisionDispatch/btManifoldResult.cpp | 30 +- .../CollisionDispatch/btManifoldResult.h | 29 +- .../btSimulationIslandManager.cpp | 129 +- .../btSimulationIslandManager.h | 14 +- .../btSphereBoxCollisionAlgorithm.cpp | 19 +- .../btSphereBoxCollisionAlgorithm.h | 23 +- .../btSphereSphereCollisionAlgorithm.cpp | 19 +- .../btSphereSphereCollisionAlgorithm.h | 18 +- .../btSphereTriangleCollisionAlgorithm.cpp | 18 +- .../btSphereTriangleCollisionAlgorithm.h | 18 +- .../CollisionDispatch/btUnionFind.cpp | 4 +- .../CollisionDispatch/btUnionFind.h | 6 +- .../CollisionShapes/btBoxShape.cpp | 11 +- .../CollisionShapes/btBoxShape.h | 104 +- .../btBvhTriangleMeshShape.cpp | 223 +- .../CollisionShapes/btBvhTriangleMeshShape.h | 40 +- .../CollisionShapes/btCapsuleShape.cpp | 36 +- .../CollisionShapes/btCapsuleShape.h | 77 +- .../CollisionShapes/btCollisionShape.cpp | 9 +- .../CollisionShapes/btCollisionShape.h | 45 +- .../CollisionShapes/btCompoundShape.cpp | 61 +- .../CollisionShapes/btCompoundShape.h | 75 +- .../CollisionShapes/btConcaveShape.h | 6 +- .../CollisionShapes/btConeShape.h | 12 +- .../CollisionShapes/btConvexHullShape.h | 20 +- .../CollisionShapes/btConvexInternalShape.cpp | 78 - .../CollisionShapes/btConvexInternalShape.h | 98 - .../CollisionShapes/btConvexShape.cpp | 59 + .../CollisionShapes/btConvexShape.h | 93 +- .../btConvexTriangleMeshShape.cpp | 5 +- .../btConvexTriangleMeshShape.h | 17 +- .../CollisionShapes/btCylinderShape.cpp | 14 +- .../CollisionShapes/btCylinderShape.h | 20 +- .../CollisionShapes/btEmptyShape.cpp | 2 +- .../CollisionShapes/btEmptyShape.h | 14 +- .../btHeightfieldTerrainShape.cpp | 107 +- .../btHeightfieldTerrainShape.h | 17 +- .../CollisionShapes/btMaterial.h | 34 - .../CollisionShapes/btMinkowskiSumShape.cpp | 6 +- .../CollisionShapes/btMinkowskiSumShape.h | 12 +- .../CollisionShapes/btMultiSphereShape.cpp | 4 +- .../CollisionShapes/btMultiSphereShape.h | 13 +- .../btMultimaterialTriangleMeshShape.cpp | 45 - .../btMultimaterialTriangleMeshShape.h | 124 - .../CollisionShapes/btOptimizedBvh.cpp | 659 ++++- .../CollisionShapes/btOptimizedBvh.h | 297 +- .../btPolyhedralConvexShape.cpp | 42 +- .../CollisionShapes/btPolyhedralConvexShape.h | 14 +- .../CollisionShapes/btShapeHull.cpp | 164 -- .../CollisionShapes/btShapeHull.h | 56 - .../CollisionShapes/btSphereShape.cpp | 2 +- .../CollisionShapes/btSphereShape.h | 20 +- .../CollisionShapes/btStaticPlaneShape.cpp | 5 +- .../CollisionShapes/btStaticPlaneShape.h | 16 +- .../btStridingMeshInterface.cpp | 6 +- .../CollisionShapes/btStridingMeshInterface.h | 12 +- .../CollisionShapes/btTetrahedronShape.h | 6 +- .../CollisionShapes/btTriangleBuffer.cpp | 9 +- .../CollisionShapes/btTriangleBuffer.h | 10 +- .../CollisionShapes/btTriangleCallback.h | 4 +- .../btTriangleIndexVertexArray.cpp | 45 +- .../btTriangleIndexVertexArray.h | 40 +- .../btTriangleIndexVertexMaterialArray.cpp | 86 - .../btTriangleIndexVertexMaterialArray.h | 84 - .../CollisionShapes/btTriangleMesh.cpp | 117 +- .../CollisionShapes/btTriangleMesh.h | 62 +- .../CollisionShapes/btTriangleMeshShape.cpp | 14 +- .../CollisionShapes/btTriangleMeshShape.h | 17 +- .../CollisionShapes/btTriangleShape.h | 18 +- .../CollisionShapes/btUniformScalingShape.cpp | 114 - .../CollisionShapes/btUniformScalingShape.h | 88 - .../btContinuousConvexCollision.cpp | 41 +- .../btContinuousConvexCollision.h | 6 +- .../NarrowPhaseCollision/btConvexCast.h | 18 +- .../btConvexPenetrationDepthSolver.h | 4 +- .../btDiscreteCollisionDetectorInterface.h | 6 +- .../NarrowPhaseCollision/btGjkConvexCast.cpp | 162 +- .../NarrowPhaseCollision/btGjkConvexCast.h | 10 +- .../NarrowPhaseCollision/btGjkEpa.cpp | 10 +- .../NarrowPhaseCollision/btGjkEpa.h | 8 +- .../NarrowPhaseCollision/btGjkEpa2.cpp | 943 ------ .../NarrowPhaseCollision/btGjkEpa2.h | 71 - .../btGjkEpaPenetrationDepthSolver.cpp | 13 +- .../btGjkEpaPenetrationDepthSolver.h | 2 +- .../btGjkPairDetector.cpp | 11 +- .../NarrowPhaseCollision/btGjkPairDetector.h | 12 +- .../NarrowPhaseCollision/btManifoldPoint.h | 26 +- .../btMinkowskiPenetrationDepthSolver.cpp | 7 +- .../btMinkowskiPenetrationDepthSolver.h | 2 +- .../btPersistentManifold.cpp | 38 +- .../btPersistentManifold.h | 62 +- .../btRaycastCallback.cpp | 72 +- .../NarrowPhaseCollision/btRaycastCallback.h | 27 +- .../btSimplexSolverInterface.h | 4 +- .../btSubSimplexConvexCast.cpp | 80 +- .../btVoronoiSimplexSolver.cpp | 2 +- .../btConeTwistConstraint.cpp | 27 +- .../ConstraintSolver/btConeTwistConstraint.h | 3 - .../ConstraintSolver/btConstraintSolver.h | 13 +- .../ConstraintSolver/btContactConstraint.cpp | 32 +- .../ConstraintSolver/btContactConstraint.h | 4 +- .../ConstraintSolver/btContactSolverInfo.h | 56 +- .../btGeneric6DofConstraint.cpp | 821 +++--- .../btGeneric6DofConstraint.h | 463 +-- .../ConstraintSolver/btHingeConstraint.cpp | 269 +- .../ConstraintSolver/btHingeConstraint.h | 97 +- .../ConstraintSolver/btJacobianEntry.h | 4 +- .../btPoint2PointConstraint.cpp | 15 +- .../btPoint2PointConstraint.h | 18 +- .../btSequentialImpulseConstraintSolver.cpp | 840 ++---- .../btSequentialImpulseConstraintSolver.h | 48 +- .../ConstraintSolver/btSliderConstraint.cpp | 414 --- .../ConstraintSolver/btSliderConstraint.h | 215 -- .../btSolve2LinearConstraint.h | 4 +- .../ConstraintSolver/btSolverBody.h | 64 +- .../ConstraintSolver/btSolverConstraint.h | 21 +- .../ConstraintSolver/btTypedConstraint.cpp | 15 +- .../ConstraintSolver/btTypedConstraint.h | 38 +- .../BulletDynamics/Dynamics/Bullet-C-API.cpp | 366 +-- .../Dynamics/btContinuousDynamicsWorld.cpp | 193 -- .../Dynamics/btContinuousDynamicsWorld.h | 46 - .../Dynamics/btDiscreteDynamicsWorld.cpp | 463 ++- .../Dynamics/btDiscreteDynamicsWorld.h | 42 +- .../BulletDynamics/Dynamics/btDynamicsWorld.h | 86 +- .../BulletDynamics/Dynamics/btRigidBody.cpp | 222 +- .../src/BulletDynamics/Dynamics/btRigidBody.h | 189 +- .../Dynamics/btSimpleDynamicsWorld.cpp | 52 +- .../Dynamics/btSimpleDynamicsWorld.h | 32 +- .../Vehicle/btRaycastVehicle.cpp | 72 +- .../BulletDynamics/Vehicle/btRaycastVehicle.h | 14 +- .../Vehicle/btVehicleRaycaster.h | 2 +- .../src/BulletDynamics/Vehicle/btWheelInfo.h | 4 +- .../bullet2/src/BulletSoftBody/CMakeLists.txt | 21 - .../bullet2/src/BulletSoftBody/btSoftBody.cpp | 2590 ----------------- .../bullet2/src/BulletSoftBody/btSoftBody.h | 810 ------ .../btSoftBodyConcaveCollisionAlgorithm.cpp | 410 --- .../btSoftBodyConcaveCollisionAlgorithm.h | 118 - .../src/BulletSoftBody/btSoftBodyHelpers.cpp | 656 ----- .../src/BulletSoftBody/btSoftBodyHelpers.h | 107 - .../src/BulletSoftBody/btSoftBodyInternals.h | 895 ------ ...oftBodyRigidBodyCollisionConfiguration.cpp | 108 - ...tSoftBodyRigidBodyCollisionConfiguration.h | 48 - .../btSoftRigidCollisionAlgorithm.cpp | 79 - .../btSoftRigidCollisionAlgorithm.h | 75 - .../btSoftRigidDynamicsWorld.cpp | 126 - .../BulletSoftBody/btSoftRigidDynamicsWorld.h | 73 - .../btSoftSoftCollisionAlgorithm.cpp | 46 - .../btSoftSoftCollisionAlgorithm.h | 69 - .../bullet2/src/BulletSoftBody/btSparseSDF.h | 306 -- extern/bullet2/src/LinearMath/btAabbUtil2.h | 49 +- .../src/LinearMath/btAlignedAllocator.cpp | 185 +- .../src/LinearMath/btAlignedAllocator.h | 28 +- .../src/LinearMath/btAlignedObjectArray.h | 69 +- .../src/LinearMath/btDefaultMotionState.h | 2 +- .../bullet2/src/LinearMath/btGeometryUtil.cpp | 9 +- .../bullet2/src/LinearMath/btGeometryUtil.h | 1 - extern/bullet2/src/LinearMath/btIDebugDraw.h | 16 - extern/bullet2/src/LinearMath/btMatrix3x3.h | 11 +- extern/bullet2/src/LinearMath/btMinMax.h | 12 +- extern/bullet2/src/LinearMath/btMotionState.h | 2 +- extern/bullet2/src/LinearMath/btQuadWord.h | 71 +- extern/bullet2/src/LinearMath/btQuaternion.h | 10 +- extern/bullet2/src/LinearMath/btQuickprof.cpp | 302 +- extern/bullet2/src/LinearMath/btQuickprof.h | 864 ++++-- extern/bullet2/src/LinearMath/btScalar.h | 253 +- extern/bullet2/src/LinearMath/btStackAlloc.h | 19 +- extern/bullet2/src/LinearMath/btTransform.h | 19 +- .../bullet2/src/LinearMath/btTransformUtil.h | 12 +- extern/bullet2/src/LinearMath/btVector3.h | 51 - extern/bullet2/src/btBulletCollisionCommon.h | 7 +- extern/bullet2/src/btBulletDynamicsCommon.h | 8 +- .../Converter/KX_BlenderSceneConverter.cpp | 5 - .../Physics/Bullet/CcdPhysicsController.cpp | 15 +- .../Physics/Bullet/CcdPhysicsEnvironment.cpp | 61 +- .../Physics/Bullet/CcdPhysicsEnvironment.h | 4 - 221 files changed, 5266 insertions(+), 24982 deletions(-) delete mode 100644 extern/bullet2/src/BulletCollision/BroadphaseCollision/btDbvt.cpp delete mode 100644 extern/bullet2/src/BulletCollision/BroadphaseCollision/btDbvt.h delete mode 100644 extern/bullet2/src/BulletCollision/BroadphaseCollision/btDbvtBroadphase.cpp delete mode 100644 extern/bullet2/src/BulletCollision/BroadphaseCollision/btDbvtBroadphase.h delete mode 100644 extern/bullet2/src/BulletCollision/BroadphaseCollision/btMultiSapBroadphase.cpp delete mode 100644 extern/bullet2/src/BulletCollision/BroadphaseCollision/btMultiSapBroadphase.h delete mode 100644 extern/bullet2/src/BulletCollision/BroadphaseCollision/btOverlappingPairCallback.h delete mode 100644 extern/bullet2/src/BulletCollision/BroadphaseCollision/btQuantizedBvh.cpp delete mode 100644 extern/bullet2/src/BulletCollision/BroadphaseCollision/btQuantizedBvh.h delete mode 100644 extern/bullet2/src/BulletCollision/CollisionDispatch/btBoxBoxCollisionAlgorithm.cpp delete mode 100644 extern/bullet2/src/BulletCollision/CollisionDispatch/btBoxBoxCollisionAlgorithm.h delete mode 100644 extern/bullet2/src/BulletCollision/CollisionDispatch/btBoxBoxDetector.cpp delete mode 100644 extern/bullet2/src/BulletCollision/CollisionDispatch/btBoxBoxDetector.h delete mode 100644 extern/bullet2/src/BulletCollision/CollisionDispatch/btCollisionConfiguration.h delete mode 100644 extern/bullet2/src/BulletCollision/CollisionDispatch/btConvexPlaneCollisionAlgorithm.cpp delete mode 100644 extern/bullet2/src/BulletCollision/CollisionDispatch/btConvexPlaneCollisionAlgorithm.h delete mode 100644 extern/bullet2/src/BulletCollision/CollisionDispatch/btDefaultCollisionConfiguration.cpp delete mode 100644 extern/bullet2/src/BulletCollision/CollisionDispatch/btDefaultCollisionConfiguration.h delete mode 100644 extern/bullet2/src/BulletCollision/CollisionShapes/btConvexInternalShape.cpp delete mode 100644 extern/bullet2/src/BulletCollision/CollisionShapes/btConvexInternalShape.h delete mode 100644 extern/bullet2/src/BulletCollision/CollisionShapes/btMaterial.h delete mode 100644 extern/bullet2/src/BulletCollision/CollisionShapes/btMultimaterialTriangleMeshShape.cpp delete mode 100644 extern/bullet2/src/BulletCollision/CollisionShapes/btMultimaterialTriangleMeshShape.h delete mode 100644 extern/bullet2/src/BulletCollision/CollisionShapes/btShapeHull.cpp delete mode 100644 extern/bullet2/src/BulletCollision/CollisionShapes/btShapeHull.h delete mode 100644 extern/bullet2/src/BulletCollision/CollisionShapes/btTriangleIndexVertexMaterialArray.cpp delete mode 100644 extern/bullet2/src/BulletCollision/CollisionShapes/btTriangleIndexVertexMaterialArray.h delete mode 100644 extern/bullet2/src/BulletCollision/CollisionShapes/btUniformScalingShape.cpp delete mode 100644 extern/bullet2/src/BulletCollision/CollisionShapes/btUniformScalingShape.h delete mode 100644 extern/bullet2/src/BulletCollision/NarrowPhaseCollision/btGjkEpa2.cpp delete mode 100644 extern/bullet2/src/BulletCollision/NarrowPhaseCollision/btGjkEpa2.h delete mode 100644 extern/bullet2/src/BulletDynamics/ConstraintSolver/btSliderConstraint.cpp delete mode 100644 extern/bullet2/src/BulletDynamics/ConstraintSolver/btSliderConstraint.h delete mode 100644 extern/bullet2/src/BulletDynamics/Dynamics/btContinuousDynamicsWorld.cpp delete mode 100644 extern/bullet2/src/BulletDynamics/Dynamics/btContinuousDynamicsWorld.h delete mode 100644 extern/bullet2/src/BulletSoftBody/CMakeLists.txt delete mode 100644 extern/bullet2/src/BulletSoftBody/btSoftBody.cpp delete mode 100644 extern/bullet2/src/BulletSoftBody/btSoftBody.h delete mode 100644 extern/bullet2/src/BulletSoftBody/btSoftBodyConcaveCollisionAlgorithm.cpp delete mode 100644 extern/bullet2/src/BulletSoftBody/btSoftBodyConcaveCollisionAlgorithm.h delete mode 100644 extern/bullet2/src/BulletSoftBody/btSoftBodyHelpers.cpp delete mode 100644 extern/bullet2/src/BulletSoftBody/btSoftBodyHelpers.h delete mode 100644 extern/bullet2/src/BulletSoftBody/btSoftBodyInternals.h delete mode 100644 extern/bullet2/src/BulletSoftBody/btSoftBodyRigidBodyCollisionConfiguration.cpp delete mode 100644 extern/bullet2/src/BulletSoftBody/btSoftBodyRigidBodyCollisionConfiguration.h delete mode 100644 extern/bullet2/src/BulletSoftBody/btSoftRigidCollisionAlgorithm.cpp delete mode 100644 extern/bullet2/src/BulletSoftBody/btSoftRigidCollisionAlgorithm.h delete mode 100644 extern/bullet2/src/BulletSoftBody/btSoftRigidDynamicsWorld.cpp delete mode 100644 extern/bullet2/src/BulletSoftBody/btSoftRigidDynamicsWorld.h delete mode 100644 extern/bullet2/src/BulletSoftBody/btSoftSoftCollisionAlgorithm.cpp delete mode 100644 extern/bullet2/src/BulletSoftBody/btSoftSoftCollisionAlgorithm.h delete mode 100644 extern/bullet2/src/BulletSoftBody/btSparseSDF.h diff --git a/extern/bullet2/src/Bullet-C-Api.h b/extern/bullet2/src/Bullet-C-Api.h index a196f6417bc..078dcae63bb 100644 --- a/extern/bullet2/src/Bullet-C-Api.h +++ b/extern/bullet2/src/Bullet-C-Api.h @@ -23,145 +23,11 @@ subject to the following restrictions: #ifndef BULLET_C_API_H #define BULLET_C_API_H -#define PL_DECLARE_HANDLE(name) typedef struct name##__ { int unused; } *name - -#ifdef BT_USE_DOUBLE_PRECISION -typedef double plReal; -#else -typedef float plReal; -#endif - -typedef plReal plVector3[3]; -typedef plReal plQuaternion[4]; - #ifdef __cplusplus extern "C" { #endif -/* Particular physics SDK */ - PL_DECLARE_HANDLE(plPhysicsSdkHandle); - -/* Dynamics world, belonging to some physics SDK */ - PL_DECLARE_HANDLE(plDynamicsWorldHandle); - -/* Rigid Body that can be part of a Dynamics World */ - PL_DECLARE_HANDLE(plRigidBodyHandle); - -/* Collision Shape/Geometry, property of a Rigid Body */ - PL_DECLARE_HANDLE(plCollisionShapeHandle); - -/* Constraint for Rigid Bodies */ - PL_DECLARE_HANDLE(plConstraintHandle); - -/* Triangle Mesh interface */ - PL_DECLARE_HANDLE(plMeshInterfaceHandle); - -/* Broadphase Scene/Proxy Handles */ - PL_DECLARE_HANDLE(plCollisionBroadphaseHandle); - PL_DECLARE_HANDLE(plBroadphaseProxyHandle); - PL_DECLARE_HANDLE(plCollisionWorldHandle); - -/* - Create and Delete a Physics SDK -*/ - - extern plPhysicsSdkHandle plNewBulletSdk(); //this could be also another sdk, like ODE, PhysX etc. - extern void plDeletePhysicsSdk(plPhysicsSdkHandle physicsSdk); - -/* Collision World, not strictly necessary, you can also just create a Dynamics World with Rigid Bodies which internally manages the Collision World with Collision Objects */ - - typedef void(*btBroadphaseCallback)(void* clientData, void* object1,void* object2); - - extern plCollisionBroadphaseHandle plCreateSapBroadphase(btBroadphaseCallback beginCallback,btBroadphaseCallback endCallback); - - extern void plDestroyBroadphase(plCollisionBroadphaseHandle bp); - - extern plBroadphaseProxyHandle plCreateProxy(plCollisionBroadphaseHandle bp, void* clientData, plReal minX,plReal minY,plReal minZ, plReal maxX,plReal maxY, plReal maxZ); - - extern void plDestroyProxy(plCollisionBroadphaseHandle bp, plBroadphaseProxyHandle proxyHandle); - - extern void plSetBoundingBox(plBroadphaseProxyHandle proxyHandle, plReal minX,plReal minY,plReal minZ, plReal maxX,plReal maxY, plReal maxZ); - -/* todo: add pair cache support with queries like add/remove/find pair */ - - extern plCollisionWorldHandle plCreateCollisionWorld(plPhysicsSdkHandle physicsSdk); - -/* todo: add/remove objects */ - - -/* Dynamics World */ - - extern plDynamicsWorldHandle plCreateDynamicsWorld(plPhysicsSdkHandle physicsSdk); - - extern void plDeleteDynamicsWorld(plDynamicsWorldHandle world); - - extern void plStepSimulation(plDynamicsWorldHandle, plReal timeStep); - - extern void plAddRigidBody(plDynamicsWorldHandle world, plRigidBodyHandle object); - - extern void plRemoveRigidBody(plDynamicsWorldHandle world, plRigidBodyHandle object); - - -/* Rigid Body */ - - extern plRigidBodyHandle plCreateRigidBody( void* user_data, float mass, plCollisionShapeHandle cshape ); - - extern void plDeleteRigidBody(plRigidBodyHandle body); - - -/* Collision Shape definition */ - - extern plCollisionShapeHandle plNewSphereShape(plReal radius); - extern plCollisionShapeHandle plNewBoxShape(plReal x, plReal y, plReal z); - extern plCollisionShapeHandle plNewCapsuleShape(plReal radius, plReal height); - extern plCollisionShapeHandle plNewConeShape(plReal radius, plReal height); - extern plCollisionShapeHandle plNewCylinderShape(plReal radius, plReal height); - extern plCollisionShapeHandle plNewCompoundShape(); - extern void plAddChildShape(plCollisionShapeHandle compoundShape,plCollisionShapeHandle childShape, plVector3 childPos,plQuaternion childOrn); - - extern void plDeleteShape(plCollisionShapeHandle shape); - - /* Convex Meshes */ - extern plCollisionShapeHandle plNewConvexHullShape(); - extern void plAddVertex(plCollisionShapeHandle convexHull, plReal x,plReal y,plReal z); -/* Concave static triangle meshes */ - extern plMeshInterfaceHandle plNewMeshInterface(); - extern void plAddTriangle(plMeshInterfaceHandle meshHandle, plVector3 v0,plVector3 v1,plVector3 v2); - extern plCollisionShapeHandle plNewStaticTriangleMeshShape(plMeshInterfaceHandle); - - extern void plSetScaling(plCollisionShapeHandle shape, plVector3 scaling); - -/* SOLID has Response Callback/Table/Management */ -/* PhysX has Triggers, User Callbacks and filtering */ -/* ODE has the typedef void dNearCallback (void *data, dGeomID o1, dGeomID o2); */ - -/* typedef void plUpdatedPositionCallback(void* userData, plRigidBodyHandle rbHandle, plVector3 pos); */ -/* typedef void plUpdatedOrientationCallback(void* userData, plRigidBodyHandle rbHandle, plQuaternion orientation); */ - - /* get world transform */ - extern void plGetOpenGLMatrix(plRigidBodyHandle object, plReal* matrix); - extern void plGetPosition(plRigidBodyHandle object,plVector3 position); - extern void plGetOrientation(plRigidBodyHandle object,plQuaternion orientation); - - /* set world transform (position/orientation) */ - extern void plSetPosition(plRigidBodyHandle object, const plVector3 position); - extern void plSetOrientation(plRigidBodyHandle object, const plQuaternion orientation); - extern void plSetEuler(plReal yaw,plReal pitch,plReal roll, plQuaternion orient); - - typedef struct plRayCastResult { - plRigidBodyHandle m_body; - plCollisionShapeHandle m_shape; - plVector3 m_positionWorld; - plVector3 m_normalWorld; - } plRayCastResult; - - extern int plRayCast(plDynamicsWorldHandle world, const plVector3 rayStart, const plVector3 rayEnd, plRayCastResult res); - - /* Sweep API */ - - /* extern plRigidBodyHandle plObjectCast(plDynamicsWorldHandle world, const plVector3 rayStart, const plVector3 rayEnd, plVector3 hitpoint, plVector3 normal); */ - - /* Continuous Collision Detection API */ +double plNearestPoints(float p1[3], float p2[3], float p3[3], float q1[3], float q2[3], float q3[3], float *pa, float *pb, float normal[3]); #ifdef __cplusplus } diff --git a/extern/bullet2/src/BulletCollision/BroadphaseCollision/btAxisSweep3.cpp b/extern/bullet2/src/BulletCollision/BroadphaseCollision/btAxisSweep3.cpp index d7eea33ea41..be4a11506df 100644 --- a/extern/bullet2/src/BulletCollision/BroadphaseCollision/btAxisSweep3.cpp +++ b/extern/bullet2/src/BulletCollision/BroadphaseCollision/btAxisSweep3.cpp @@ -21,18 +21,640 @@ #include -btAxisSweep3::btAxisSweep3(const btPoint3& worldAabbMin,const btPoint3& worldAabbMax, unsigned short int maxHandles, btOverlappingPairCache* pairCache) -:btAxisSweep3Internal(worldAabbMin,worldAabbMax,0xfffe,0xffff,maxHandles,pairCache) +#ifdef DEBUG_BROADPHASE +#include +void btAxisSweep3::debugPrintAxis(int axis, bool checkCardinality) { - // 1 handle is reserved as sentinel - btAssert(maxHandles > 1 && maxHandles < 32767); + int numEdges = m_pHandles[0].m_maxEdges[axis]; + printf("SAP Axis %d, numEdges=%d\n",axis,numEdges); + + int i; + for (i=0;im_handle); + int handleIndex = pEdge->IsMax()? pHandlePrev->m_maxEdges[axis] : pHandlePrev->m_minEdges[axis]; + char beginOrEnd; + beginOrEnd=pEdge->IsMax()?'E':'B'; + printf(" [%c,h=%d,p=%x,i=%d]\n",beginOrEnd,pEdge->m_handle,pEdge->m_pos,handleIndex); + } + + if (checkCardinality) + assert(numEdges == m_numHandles*2+1); +} +#endif //DEBUG_BROADPHASE + + +btBroadphaseProxy* btAxisSweep3::createProxy( const btVector3& min, const btVector3& max,int shapeType,void* userPtr,short int collisionFilterGroup,short int collisionFilterMask) +{ + (void)shapeType; + BP_FP_INT_TYPE handleId = addHandle(min,max, userPtr,collisionFilterGroup,collisionFilterMask); + + Handle* handle = getHandle(handleId); + + return handle; +} + +void btAxisSweep3::destroyProxy(btBroadphaseProxy* proxy) +{ + Handle* handle = static_cast(proxy); + removeHandle(handle->m_handleId); +} + +void btAxisSweep3::setAabb(btBroadphaseProxy* proxy,const btVector3& aabbMin,const btVector3& aabbMax) +{ + Handle* handle = static_cast(proxy); + updateHandle(handle->m_handleId,aabbMin,aabbMax); } -bt32BitAxisSweep3::bt32BitAxisSweep3(const btPoint3& worldAabbMin,const btPoint3& worldAabbMax, unsigned int maxHandles , btOverlappingPairCache* pairCache ) -:btAxisSweep3Internal(worldAabbMin,worldAabbMax,0xfffffffe,0x7fffffff,maxHandles,pairCache) + + + + +btAxisSweep3::btAxisSweep3(const btPoint3& worldAabbMin,const btPoint3& worldAabbMax, int maxHandles) +:btOverlappingPairCache() { + m_invalidPair = 0; + //assert(bounds.HasVolume()); + // 1 handle is reserved as sentinel - btAssert(maxHandles > 1 && maxHandles < 2147483647); + btAssert(maxHandles > 1 && maxHandles < BP_MAX_HANDLES); + + // init bounds + m_worldAabbMin = worldAabbMin; + m_worldAabbMax = worldAabbMax; + + btVector3 aabbSize = m_worldAabbMax - m_worldAabbMin; + + BP_FP_INT_TYPE maxInt = BP_HANDLE_SENTINEL; + + m_quantize = btVector3(btScalar(maxInt),btScalar(maxInt),btScalar(maxInt)) / aabbSize; + + // allocate handles buffer and put all handles on free list + m_pHandles = new Handle[maxHandles]; + m_maxHandles = maxHandles; + m_numHandles = 0; + + // handle 0 is reserved as the null index, and is also used as the sentinel + m_firstFreeHandle = 1; + { + for (BP_FP_INT_TYPE i = m_firstFreeHandle; i < maxHandles; i++) + m_pHandles[i].SetNextFree(i + 1); + m_pHandles[maxHandles - 1].SetNextFree(0); + } + + { + // allocate edge buffers + for (int i = 0; i < 3; i++) + m_pEdges[i] = new Edge[maxHandles * 2]; + } + //removed overlap management + + // make boundary sentinels + + m_pHandles[0].m_clientObject = 0; + + for (int axis = 0; axis < 3; axis++) + { + m_pHandles[0].m_minEdges[axis] = 0; + m_pHandles[0].m_maxEdges[axis] = 1; + + m_pEdges[axis][0].m_pos = 0; + m_pEdges[axis][0].m_handle = 0; + m_pEdges[axis][1].m_pos = BP_HANDLE_SENTINEL; + m_pEdges[axis][1].m_handle = 0; +#ifdef DEBUG_BROADPHASE + debugPrintAxis(axis); +#endif //DEBUG_BROADPHASE + + } + +} + +btAxisSweep3::~btAxisSweep3() +{ + + for (int i = 2; i >= 0; i--) + delete[] m_pEdges[i]; + delete[] m_pHandles; +} + +void btAxisSweep3::quantize(BP_FP_INT_TYPE* out, const btPoint3& point, int isMax) const +{ + btPoint3 clampedPoint(point); + + + + clampedPoint.setMax(m_worldAabbMin); + clampedPoint.setMin(m_worldAabbMax); + + btVector3 v = (clampedPoint - m_worldAabbMin) * m_quantize; + out[0] = (BP_FP_INT_TYPE)(((BP_FP_INT_TYPE)v.getX() & BP_HANDLE_MASK) | isMax); + out[1] = (BP_FP_INT_TYPE)(((BP_FP_INT_TYPE)v.getY() & BP_HANDLE_MASK) | isMax); + out[2] = (BP_FP_INT_TYPE)(((BP_FP_INT_TYPE)v.getZ() & BP_HANDLE_MASK) | isMax); + +} + + + +BP_FP_INT_TYPE btAxisSweep3::allocHandle() +{ + assert(m_firstFreeHandle); + + BP_FP_INT_TYPE handle = m_firstFreeHandle; + m_firstFreeHandle = getHandle(handle)->GetNextFree(); + m_numHandles++; + + return handle; +} + +void btAxisSweep3::freeHandle(BP_FP_INT_TYPE handle) +{ + assert(handle > 0 && handle < m_maxHandles); + + getHandle(handle)->SetNextFree(m_firstFreeHandle); + m_firstFreeHandle = handle; + + m_numHandles--; +} + + + +BP_FP_INT_TYPE btAxisSweep3::addHandle(const btPoint3& aabbMin,const btPoint3& aabbMax, void* pOwner,short int collisionFilterGroup,short int collisionFilterMask) +{ + // quantize the bounds + BP_FP_INT_TYPE min[3], max[3]; + quantize(min, aabbMin, 0); + quantize(max, aabbMax, 1); + + // allocate a handle + BP_FP_INT_TYPE handle = allocHandle(); + assert(handle!= 0xcdcd); + + Handle* pHandle = getHandle(handle); + + pHandle->m_handleId = handle; + //pHandle->m_pOverlaps = 0; + pHandle->m_clientObject = pOwner; + pHandle->m_collisionFilterGroup = collisionFilterGroup; + pHandle->m_collisionFilterMask = collisionFilterMask; + + // compute current limit of edge arrays + BP_FP_INT_TYPE limit = m_numHandles * 2; + + + // insert new edges just inside the max boundary edge + for (BP_FP_INT_TYPE axis = 0; axis < 3; axis++) + { + + m_pHandles[0].m_maxEdges[axis] += 2; + + m_pEdges[axis][limit + 1] = m_pEdges[axis][limit - 1]; + + m_pEdges[axis][limit - 1].m_pos = min[axis]; + m_pEdges[axis][limit - 1].m_handle = handle; + + m_pEdges[axis][limit].m_pos = max[axis]; + m_pEdges[axis][limit].m_handle = handle; + + pHandle->m_minEdges[axis] = limit - 1; + pHandle->m_maxEdges[axis] = limit; + } + + // now sort the new edges to their correct position + sortMinDown(0, pHandle->m_minEdges[0], false); + sortMaxDown(0, pHandle->m_maxEdges[0], false); + sortMinDown(1, pHandle->m_minEdges[1], false); + sortMaxDown(1, pHandle->m_maxEdges[1], false); + sortMinDown(2, pHandle->m_minEdges[2], true); + sortMaxDown(2, pHandle->m_maxEdges[2], true); + + + return handle; +} + + +void btAxisSweep3::removeHandle(BP_FP_INT_TYPE handle) +{ + + Handle* pHandle = getHandle(handle); + + //explicitly remove the pairs containing the proxy + //we could do it also in the sortMinUp (passing true) + //todo: compare performance + removeOverlappingPairsContainingProxy(pHandle); + + + // compute current limit of edge arrays + int limit = m_numHandles * 2; + + int axis; + + for (axis = 0;axis<3;axis++) + { + m_pHandles[0].m_maxEdges[axis] -= 2; + } + + // remove the edges by sorting them up to the end of the list + for ( axis = 0; axis < 3; axis++) + { + Edge* pEdges = m_pEdges[axis]; + BP_FP_INT_TYPE max = pHandle->m_maxEdges[axis]; + pEdges[max].m_pos = BP_HANDLE_SENTINEL; + + sortMaxUp(axis,max,false); + + + BP_FP_INT_TYPE i = pHandle->m_minEdges[axis]; + pEdges[i].m_pos = BP_HANDLE_SENTINEL; + + + sortMinUp(axis,i,false); + + pEdges[limit-1].m_handle = 0; + pEdges[limit-1].m_pos = BP_HANDLE_SENTINEL; + +#ifdef DEBUG_BROADPHASE + debugPrintAxis(axis,false); +#endif //DEBUG_BROADPHASE + + + } + + + // free the handle + freeHandle(handle); + + +} + +extern int gOverlappingPairs; + + +void btAxisSweep3::refreshOverlappingPairs() +{ + +} +void btAxisSweep3::processAllOverlappingPairs(btOverlapCallback* callback) +{ + + //perform a sort, to find duplicates and to sort 'invalid' pairs to the end + m_overlappingPairArray.heapSort(btBroadphasePairSortPredicate()); + + //remove the 'invalid' ones +#ifdef USE_POPBACK_REMOVAL + while (m_invalidPair>0) + { + m_invalidPair--; + m_overlappingPairArray.pop_back(); + } +#else + m_overlappingPairArray.resize(m_overlappingPairArray.size() - m_invalidPair); + m_invalidPair = 0; +#endif + + + int i; + + btBroadphasePair previousPair; + previousPair.m_pProxy0 = 0; + previousPair.m_pProxy1 = 0; + previousPair.m_algorithm = 0; + + + for (i=0;iprocessOverlap(pair); + } else + { + needsRemoval = true; + } + } else + { + //remove duplicate + needsRemoval = true; + //should have no algorithm + btAssert(!pair.m_algorithm); + } + + if (needsRemoval) + { + cleanOverlappingPair(pair); + + // m_overlappingPairArray.swap(i,m_overlappingPairArray.size()-1); + // m_overlappingPairArray.pop_back(); + pair.m_pProxy0 = 0; + pair.m_pProxy1 = 0; + m_invalidPair++; + gOverlappingPairs--; + } + + } +} + + +bool btAxisSweep3::testOverlap(btBroadphaseProxy* proxy0,btBroadphaseProxy* proxy1) +{ + const Handle* pHandleA = static_cast(proxy0); + const Handle* pHandleB = static_cast(proxy1); + + //optimization 1: check the array index (memory address), instead of the m_pos + + for (int axis = 0; axis < 3; axis++) + { + if (pHandleA->m_maxEdges[axis] < pHandleB->m_minEdges[axis] || + pHandleB->m_maxEdges[axis] < pHandleA->m_minEdges[axis]) + { + return false; + } + } + return true; +} + +bool btAxisSweep3::testOverlap(int ignoreAxis,const Handle* pHandleA, const Handle* pHandleB) +{ + //optimization 1: check the array index (memory address), instead of the m_pos + + for (int axis = 0; axis < 3; axis++) + { + if (axis != ignoreAxis) + { + if (pHandleA->m_maxEdges[axis] < pHandleB->m_minEdges[axis] || + pHandleB->m_maxEdges[axis] < pHandleA->m_minEdges[axis]) + { + return false; + } + } + } + + //optimization 2: only 2 axis need to be tested (conflicts with 'delayed removal' optimization) + + /*for (int axis = 0; axis < 3; axis++) + { + if (m_pEdges[axis][pHandleA->m_maxEdges[axis]].m_pos < m_pEdges[axis][pHandleB->m_minEdges[axis]].m_pos || + m_pEdges[axis][pHandleB->m_maxEdges[axis]].m_pos < m_pEdges[axis][pHandleA->m_minEdges[axis]].m_pos) + { + return false; + } + } + */ + + return true; +} + +void btAxisSweep3::updateHandle(BP_FP_INT_TYPE handle, const btPoint3& aabbMin,const btPoint3& aabbMax) +{ +// assert(bounds.IsFinite()); + //assert(bounds.HasVolume()); + + Handle* pHandle = getHandle(handle); + + // quantize the new bounds + BP_FP_INT_TYPE min[3], max[3]; + quantize(min, aabbMin, 0); + quantize(max, aabbMax, 1); + + // update changed edges + for (int axis = 0; axis < 3; axis++) + { + BP_FP_INT_TYPE emin = pHandle->m_minEdges[axis]; + BP_FP_INT_TYPE emax = pHandle->m_maxEdges[axis]; + + int dmin = (int)min[axis] - (int)m_pEdges[axis][emin].m_pos; + int dmax = (int)max[axis] - (int)m_pEdges[axis][emax].m_pos; + + m_pEdges[axis][emin].m_pos = min[axis]; + m_pEdges[axis][emax].m_pos = max[axis]; + + // expand (only adds overlaps) + if (dmin < 0) + sortMinDown(axis, emin); + + if (dmax > 0) + sortMaxUp(axis, emax); + + // shrink (only removes overlaps) + if (dmin > 0) + sortMinUp(axis, emin); + + if (dmax < 0) + sortMaxDown(axis, emax); + +#ifdef DEBUG_BROADPHASE + debugPrintAxis(axis); +#endif //DEBUG_BROADPHASE + } + + +} + + + + +// sorting a min edge downwards can only ever *add* overlaps +void btAxisSweep3::sortMinDown(int axis, BP_FP_INT_TYPE edge, bool updateOverlaps) +{ + + Edge* pEdge = m_pEdges[axis] + edge; + Edge* pPrev = pEdge - 1; + Handle* pHandleEdge = getHandle(pEdge->m_handle); + + while (pEdge->m_pos < pPrev->m_pos) + { + Handle* pHandlePrev = getHandle(pPrev->m_handle); + + if (pPrev->IsMax()) + { + // if previous edge is a maximum check the bounds and add an overlap if necessary + if (updateOverlaps && testOverlap(axis,pHandleEdge, pHandlePrev)) + { + addOverlappingPair(pHandleEdge,pHandlePrev); + + //AddOverlap(pEdge->m_handle, pPrev->m_handle); + + } + + // update edge reference in other handle + pHandlePrev->m_maxEdges[axis]++; + } + else + pHandlePrev->m_minEdges[axis]++; + + pHandleEdge->m_minEdges[axis]--; + + // swap the edges + Edge swap = *pEdge; + *pEdge = *pPrev; + *pPrev = swap; + + // decrement + pEdge--; + pPrev--; + } + +#ifdef DEBUG_BROADPHASE + debugPrintAxis(axis); +#endif //DEBUG_BROADPHASE + +} + +// sorting a min edge upwards can only ever *remove* overlaps +void btAxisSweep3::sortMinUp(int axis, BP_FP_INT_TYPE edge, bool updateOverlaps) +{ + Edge* pEdge = m_pEdges[axis] + edge; + Edge* pNext = pEdge + 1; + Handle* pHandleEdge = getHandle(pEdge->m_handle); + + while (pNext->m_handle && (pEdge->m_pos >= pNext->m_pos)) + { + Handle* pHandleNext = getHandle(pNext->m_handle); + + if (pNext->IsMax()) + { + // if next edge is maximum remove any overlap between the two handles + if (updateOverlaps) + { + /* + Handle* handle0 = getHandle(pEdge->m_handle); + Handle* handle1 = getHandle(pNext->m_handle); + btBroadphasePair tmpPair(*handle0,*handle1); + removeOverlappingPair(tmpPair); + */ + + } + + // update edge reference in other handle + pHandleNext->m_maxEdges[axis]--; + } + else + pHandleNext->m_minEdges[axis]--; + + pHandleEdge->m_minEdges[axis]++; + + // swap the edges + Edge swap = *pEdge; + *pEdge = *pNext; + *pNext = swap; + + // increment + pEdge++; + pNext++; + } + + +} + +// sorting a max edge downwards can only ever *remove* overlaps +void btAxisSweep3::sortMaxDown(int axis, BP_FP_INT_TYPE edge, bool updateOverlaps) +{ + + Edge* pEdge = m_pEdges[axis] + edge; + Edge* pPrev = pEdge - 1; + Handle* pHandleEdge = getHandle(pEdge->m_handle); + + while (pEdge->m_pos < pPrev->m_pos) + { + Handle* pHandlePrev = getHandle(pPrev->m_handle); + + if (!pPrev->IsMax()) + { + // if previous edge was a minimum remove any overlap between the two handles + if (updateOverlaps) + { + //this is done during the overlappingpairarray iteration/narrowphase collision + /* + Handle* handle0 = getHandle(pEdge->m_handle); + Handle* handle1 = getHandle(pPrev->m_handle); + btBroadphasePair* pair = findPair(handle0,handle1); + //assert(pair); + + if (pair) + { + removeOverlappingPair(*pair); + } + */ + + } + + // update edge reference in other handle + pHandlePrev->m_minEdges[axis]++;; + } + else + pHandlePrev->m_maxEdges[axis]++; + + pHandleEdge->m_maxEdges[axis]--; + + // swap the edges + Edge swap = *pEdge; + *pEdge = *pPrev; + *pPrev = swap; + + // decrement + pEdge--; + pPrev--; + } + + +#ifdef DEBUG_BROADPHASE + debugPrintAxis(axis); +#endif //DEBUG_BROADPHASE + +} + +// sorting a max edge upwards can only ever *add* overlaps +void btAxisSweep3::sortMaxUp(int axis, BP_FP_INT_TYPE edge, bool updateOverlaps) +{ + Edge* pEdge = m_pEdges[axis] + edge; + Edge* pNext = pEdge + 1; + Handle* pHandleEdge = getHandle(pEdge->m_handle); + + while (pNext->m_handle && (pEdge->m_pos >= pNext->m_pos)) + { + Handle* pHandleNext = getHandle(pNext->m_handle); + + if (!pNext->IsMax()) + { + // if next edge is a minimum check the bounds and add an overlap if necessary + if (updateOverlaps && testOverlap(axis, pHandleEdge, pHandleNext)) + { + Handle* handle0 = getHandle(pEdge->m_handle); + Handle* handle1 = getHandle(pNext->m_handle); + addOverlappingPair(handle0,handle1); + } + + // update edge reference in other handle + pHandleNext->m_minEdges[axis]--; + } + else + pHandleNext->m_maxEdges[axis]--; + + pHandleEdge->m_maxEdges[axis]++; + + // swap the edges + Edge swap = *pEdge; + *pEdge = *pNext; + *pNext = swap; + + // increment + pEdge++; + pNext++; + } + } diff --git a/extern/bullet2/src/BulletCollision/BroadphaseCollision/btAxisSweep3.h b/extern/bullet2/src/BulletCollision/BroadphaseCollision/btAxisSweep3.h index e7c5fb5b6cf..57bbb368672 100644 --- a/extern/bullet2/src/BulletCollision/BroadphaseCollision/btAxisSweep3.h +++ b/extern/bullet2/src/BulletCollision/BroadphaseCollision/btAxisSweep3.h @@ -19,25 +19,34 @@ #ifndef AXIS_SWEEP_3_H #define AXIS_SWEEP_3_H -#include "LinearMath/btPoint3.h" -#include "LinearMath/btVector3.h" +#include "../../LinearMath/btPoint3.h" +#include "../../LinearMath/btVector3.h" #include "btOverlappingPairCache.h" -#include "btBroadphaseInterface.h" #include "btBroadphaseProxy.h" -#include "btOverlappingPairCallback.h" + + +//Enable BP_USE_FIXEDPOINT_INT_32 if you need more then 32767 objects +//#define BP_USE_FIXEDPOINT_INT_32 1 + +#ifdef BP_USE_FIXEDPOINT_INT_32 + #define BP_FP_INT_TYPE unsigned int + #define BP_MAX_HANDLES 1500000 //arbitrary maximum number of handles + #define BP_HANDLE_SENTINEL 0x7fffffff + #define BP_HANDLE_MASK 0xfffffffe +#else + #define BP_FP_INT_TYPE unsigned short int + #define BP_MAX_HANDLES 32767 + #define BP_HANDLE_SENTINEL 0xffff + #define BP_HANDLE_MASK 0xfffe +#endif //BP_USE_FIXEDPOINT_INT_32 //#define DEBUG_BROADPHASE 1 -/// The internal templace class btAxisSweep3Internal implements the sweep and prune broadphase. -/// It uses quantized integers to represent the begin and end points for each of the 3 axis. -/// Dont use this class directly, use btAxisSweep3 or bt32BitAxisSweep3 instead. -template -class btAxisSweep3Internal : public btBroadphaseInterface +/// btAxisSweep3 is an efficient implementation of the 3d axis sweep and prune broadphase. +/// It uses arrays rather then lists for storage of the 3 axis. Also it operates using integer coordinates instead of floats. +/// The testOverlap check is optimized to check the array index, rather then the actual AABB coordinates/pos +class btAxisSweep3 : public btOverlappingPairCache { -protected: - - BP_FP_INT_TYPE m_bpHandleMask; - BP_FP_INT_TYPE m_handleSentinel; public: @@ -48,52 +57,40 @@ public: BP_FP_INT_TYPE m_pos; // low bit is min/max BP_FP_INT_TYPE m_handle; - BP_FP_INT_TYPE IsMax() const {return static_cast(m_pos & 1);} + BP_FP_INT_TYPE IsMax() const {return m_pos & 1;} }; public: - //This breaks the Intel compiler, see http://softwarecommunity.intel.com/isn/Community/en-US/forums/thread/30253577.aspx class Handle : public btBroadphaseProxy - //ATTRIBUTE_ALIGNED16(class) Handle : public btBroadphaseProxy { public: - BT_DECLARE_ALIGNED_ALLOCATOR(); - + // indexes into the edge arrays BP_FP_INT_TYPE m_minEdges[3], m_maxEdges[3]; // 6 * 2 = 12 -// BP_FP_INT_TYPE m_uniqueId; + BP_FP_INT_TYPE m_handleId; BP_FP_INT_TYPE m_pad; //void* m_pOwner; this is now in btBroadphaseProxy.m_clientObject - SIMD_FORCE_INLINE void SetNextFree(BP_FP_INT_TYPE next) {m_minEdges[0] = next;} - SIMD_FORCE_INLINE BP_FP_INT_TYPE GetNextFree() const {return m_minEdges[0];} + inline void SetNextFree(BP_FP_INT_TYPE next) {m_minEdges[0] = next;} + inline BP_FP_INT_TYPE GetNextFree() const {return m_minEdges[0];} }; // 24 bytes + 24 for Edge structures = 44 bytes total per entry -protected: +private: btPoint3 m_worldAabbMin; // overall system bounds btPoint3 m_worldAabbMax; // overall system bounds btVector3 m_quantize; // scaling factor for quantization BP_FP_INT_TYPE m_numHandles; // number of active handles - BP_FP_INT_TYPE m_maxHandles; // max number of handles + int m_maxHandles; // max number of handles Handle* m_pHandles; // handles pool - void* m_pHandlesRawPtr; BP_FP_INT_TYPE m_firstFreeHandle; // free handles list Edge* m_pEdges[3]; // edge arrays for the 3 axes (each array has m_maxHandles * 2 + 2 sentinel entries) - void* m_pEdgesRawPtr[3]; - btOverlappingPairCache* m_pairCache; - - ///btOverlappingPairCallback is an additional optional user callback for adding/removing overlapping pairs, similar interface to btOverlappingPairCache. - btOverlappingPairCallback* m_userPairCallback; - - bool m_ownsPairCache; - - int m_invalidPair; + int m_invalidPair; // allocation/deallocation BP_FP_INT_TYPE allocHandle(); @@ -111,801 +108,29 @@ protected: void quantize(BP_FP_INT_TYPE* out, const btPoint3& point, int isMax) const; - void sortMinDown(int axis, BP_FP_INT_TYPE edge, btDispatcher* dispatcher, bool updateOverlaps ); - void sortMinUp(int axis, BP_FP_INT_TYPE edge, btDispatcher* dispatcher, bool updateOverlaps ); - void sortMaxDown(int axis, BP_FP_INT_TYPE edge, btDispatcher* dispatcher, bool updateOverlaps ); - void sortMaxUp(int axis, BP_FP_INT_TYPE edge, btDispatcher* dispatcher, bool updateOverlaps ); + void sortMinDown(int axis, BP_FP_INT_TYPE edge, bool updateOverlaps = true); + void sortMinUp(int axis, BP_FP_INT_TYPE edge, bool updateOverlaps = true); + void sortMaxDown(int axis, BP_FP_INT_TYPE edge, bool updateOverlaps = true); + void sortMaxUp(int axis, BP_FP_INT_TYPE edge, bool updateOverlaps = true); public: + btAxisSweep3(const btPoint3& worldAabbMin,const btPoint3& worldAabbMax, int maxHandles = 16384); + virtual ~btAxisSweep3(); - btAxisSweep3Internal(const btPoint3& worldAabbMin,const btPoint3& worldAabbMax, BP_FP_INT_TYPE handleMask, BP_FP_INT_TYPE handleSentinel, BP_FP_INT_TYPE maxHandles = 16384, btOverlappingPairCache* pairCache=0); - - virtual ~btAxisSweep3Internal(); - - BP_FP_INT_TYPE getNumHandles() const - { - return m_numHandles; - } - - virtual void calculateOverlappingPairs(btDispatcher* dispatcher); + virtual void refreshOverlappingPairs(); - BP_FP_INT_TYPE addHandle(const btPoint3& aabbMin,const btPoint3& aabbMax, void* pOwner,short int collisionFilterGroup,short int collisionFilterMask,btDispatcher* dispatcher,void* multiSapProxy); - void removeHandle(BP_FP_INT_TYPE handle,btDispatcher* dispatcher); - void updateHandle(BP_FP_INT_TYPE handle, const btPoint3& aabbMin,const btPoint3& aabbMax,btDispatcher* dispatcher); - SIMD_FORCE_INLINE Handle* getHandle(BP_FP_INT_TYPE index) const {return m_pHandles + index;} + BP_FP_INT_TYPE addHandle(const btPoint3& aabbMin,const btPoint3& aabbMax, void* pOwner,short int collisionFilterGroup,short int collisionFilterMask); + void removeHandle(BP_FP_INT_TYPE handle); + void updateHandle(BP_FP_INT_TYPE handle, const btPoint3& aabbMin,const btPoint3& aabbMax); + inline Handle* getHandle(BP_FP_INT_TYPE index) const {return m_pHandles + index;} void processAllOverlappingPairs(btOverlapCallback* callback); //Broadphase Interface - virtual btBroadphaseProxy* createProxy( const btVector3& aabbMin, const btVector3& aabbMax,int shapeType,void* userPtr ,short int collisionFilterGroup,short int collisionFilterMask,btDispatcher* dispatcher,void* multiSapProxy); - virtual void destroyProxy(btBroadphaseProxy* proxy,btDispatcher* dispatcher); - virtual void setAabb(btBroadphaseProxy* proxy,const btVector3& aabbMin,const btVector3& aabbMax,btDispatcher* dispatcher); - - bool testAabbOverlap(btBroadphaseProxy* proxy0,btBroadphaseProxy* proxy1); - - btOverlappingPairCache* getOverlappingPairCache() - { - return m_pairCache; - } - const btOverlappingPairCache* getOverlappingPairCache() const - { - return m_pairCache; - } - - void setOverlappingPairUserCallback(btOverlappingPairCallback* pairCallback) - { - m_userPairCallback = pairCallback; - } - const btOverlappingPairCallback* getOverlappingPairUserCallback() const - { - return m_userPairCallback; - } - - ///getAabb returns the axis aligned bounding box in the 'global' coordinate frame - ///will add some transform later - virtual void getBroadphaseAabb(btVector3& aabbMin,btVector3& aabbMax) const - { - aabbMin = m_worldAabbMin; - aabbMax = m_worldAabbMax; - } - - virtual void printStats() - { -/* printf("btAxisSweep3.h\n"); - printf("numHandles = %d, maxHandles = %d\n",m_numHandles,m_maxHandles); - printf("aabbMin=%f,%f,%f,aabbMax=%f,%f,%f\n",m_worldAabbMin.getX(),m_worldAabbMin.getY(),m_worldAabbMin.getZ(), - m_worldAabbMax.getX(),m_worldAabbMax.getY(),m_worldAabbMax.getZ()); - */ - - } - -}; - -//////////////////////////////////////////////////////////////////// - - - - -#ifdef DEBUG_BROADPHASE -#include - -template -void btAxisSweep3::debugPrintAxis(int axis, bool checkCardinality) -{ - int numEdges = m_pHandles[0].m_maxEdges[axis]; - printf("SAP Axis %d, numEdges=%d\n",axis,numEdges); - - int i; - for (i=0;im_handle); - int handleIndex = pEdge->IsMax()? pHandlePrev->m_maxEdges[axis] : pHandlePrev->m_minEdges[axis]; - char beginOrEnd; - beginOrEnd=pEdge->IsMax()?'E':'B'; - printf(" [%c,h=%d,p=%x,i=%d]\n",beginOrEnd,pEdge->m_handle,pEdge->m_pos,handleIndex); - } - - if (checkCardinality) - assert(numEdges == m_numHandles*2+1); -} -#endif //DEBUG_BROADPHASE - -template -btBroadphaseProxy* btAxisSweep3Internal::createProxy( const btVector3& aabbMin, const btVector3& aabbMax,int shapeType,void* userPtr,short int collisionFilterGroup,short int collisionFilterMask,btDispatcher* dispatcher,void* multiSapProxy) -{ - (void)shapeType; - BP_FP_INT_TYPE handleId = addHandle(aabbMin,aabbMax, userPtr,collisionFilterGroup,collisionFilterMask,dispatcher,multiSapProxy); - - Handle* handle = getHandle(handleId); - - return handle; -} - - - -template -void btAxisSweep3Internal::destroyProxy(btBroadphaseProxy* proxy,btDispatcher* dispatcher) -{ - Handle* handle = static_cast(proxy); - removeHandle(static_cast(handle->m_uniqueId), dispatcher); -} - -template -void btAxisSweep3Internal::setAabb(btBroadphaseProxy* proxy,const btVector3& aabbMin,const btVector3& aabbMax,btDispatcher* dispatcher) -{ - Handle* handle = static_cast(proxy); - updateHandle(static_cast(handle->m_uniqueId), aabbMin, aabbMax,dispatcher); - -} - - - - - -template -btAxisSweep3Internal::btAxisSweep3Internal(const btPoint3& worldAabbMin,const btPoint3& worldAabbMax, BP_FP_INT_TYPE handleMask, BP_FP_INT_TYPE handleSentinel,BP_FP_INT_TYPE userMaxHandles, btOverlappingPairCache* pairCache ) -:m_bpHandleMask(handleMask), -m_handleSentinel(handleSentinel), -m_pairCache(pairCache), -m_userPairCallback(0), -m_ownsPairCache(false), -m_invalidPair(0) -{ - BP_FP_INT_TYPE maxHandles = static_cast(userMaxHandles+1);//need to add one sentinel handle - - if (!m_pairCache) - { - void* ptr = btAlignedAlloc(sizeof(btHashedOverlappingPairCache),16); - m_pairCache = new(ptr) btHashedOverlappingPairCache(); - m_ownsPairCache = true; - } - - //assert(bounds.HasVolume()); - - // init bounds - m_worldAabbMin = worldAabbMin; - m_worldAabbMax = worldAabbMax; - - btVector3 aabbSize = m_worldAabbMax - m_worldAabbMin; - - BP_FP_INT_TYPE maxInt = m_handleSentinel; - - m_quantize = btVector3(btScalar(maxInt),btScalar(maxInt),btScalar(maxInt)) / aabbSize; - - // allocate handles buffer and put all handles on free list - m_pHandlesRawPtr = btAlignedAlloc(sizeof(Handle)*maxHandles,16); - m_pHandles = new(m_pHandlesRawPtr) Handle[maxHandles]; - - m_maxHandles = maxHandles; - m_numHandles = 0; - - // handle 0 is reserved as the null index, and is also used as the sentinel - m_firstFreeHandle = 1; - { - for (BP_FP_INT_TYPE i = m_firstFreeHandle; i < maxHandles; i++) - m_pHandles[i].SetNextFree(static_cast(i + 1)); - m_pHandles[maxHandles - 1].SetNextFree(0); - } - - { - // allocate edge buffers - for (int i = 0; i < 3; i++) - { - m_pEdgesRawPtr[i] = btAlignedAlloc(sizeof(Edge)*maxHandles*2,16); - m_pEdges[i] = new(m_pEdgesRawPtr[i]) Edge[maxHandles * 2]; - } - } - //removed overlap management - - // make boundary sentinels - - m_pHandles[0].m_clientObject = 0; - - for (int axis = 0; axis < 3; axis++) - { - m_pHandles[0].m_minEdges[axis] = 0; - m_pHandles[0].m_maxEdges[axis] = 1; - - m_pEdges[axis][0].m_pos = 0; - m_pEdges[axis][0].m_handle = 0; - m_pEdges[axis][1].m_pos = m_handleSentinel; - m_pEdges[axis][1].m_handle = 0; -#ifdef DEBUG_BROADPHASE - debugPrintAxis(axis); -#endif //DEBUG_BROADPHASE - - } - -} - -template -btAxisSweep3Internal::~btAxisSweep3Internal() -{ - - for (int i = 2; i >= 0; i--) - { - btAlignedFree(m_pEdgesRawPtr[i]); - } - btAlignedFree(m_pHandlesRawPtr); - - if (m_ownsPairCache) - { - m_pairCache->~btOverlappingPairCache(); - btAlignedFree(m_pairCache); - } -} - -template -void btAxisSweep3Internal::quantize(BP_FP_INT_TYPE* out, const btPoint3& point, int isMax) const -{ - btPoint3 clampedPoint(point); - - - - clampedPoint.setMax(m_worldAabbMin); - clampedPoint.setMin(m_worldAabbMax); - - btVector3 v = (clampedPoint - m_worldAabbMin) * m_quantize; - out[0] = (BP_FP_INT_TYPE)(((BP_FP_INT_TYPE)v.getX() & m_bpHandleMask) | isMax); - out[1] = (BP_FP_INT_TYPE)(((BP_FP_INT_TYPE)v.getY() & m_bpHandleMask) | isMax); - out[2] = (BP_FP_INT_TYPE)(((BP_FP_INT_TYPE)v.getZ() & m_bpHandleMask) | isMax); - -} - - -template -BP_FP_INT_TYPE btAxisSweep3Internal::allocHandle() -{ - assert(m_firstFreeHandle); - - BP_FP_INT_TYPE handle = m_firstFreeHandle; - m_firstFreeHandle = getHandle(handle)->GetNextFree(); - m_numHandles++; - - return handle; -} - -template -void btAxisSweep3Internal::freeHandle(BP_FP_INT_TYPE handle) -{ - assert(handle > 0 && handle < m_maxHandles); - - getHandle(handle)->SetNextFree(m_firstFreeHandle); - m_firstFreeHandle = handle; - - m_numHandles--; -} - - -template -BP_FP_INT_TYPE btAxisSweep3Internal::addHandle(const btPoint3& aabbMin,const btPoint3& aabbMax, void* pOwner,short int collisionFilterGroup,short int collisionFilterMask,btDispatcher* dispatcher,void* multiSapProxy) -{ - // quantize the bounds - BP_FP_INT_TYPE min[3], max[3]; - quantize(min, aabbMin, 0); - quantize(max, aabbMax, 1); - - // allocate a handle - BP_FP_INT_TYPE handle = allocHandle(); - - - Handle* pHandle = getHandle(handle); - - pHandle->m_uniqueId = static_cast(handle); - //pHandle->m_pOverlaps = 0; - pHandle->m_clientObject = pOwner; - pHandle->m_collisionFilterGroup = collisionFilterGroup; - pHandle->m_collisionFilterMask = collisionFilterMask; - pHandle->m_multiSapParentProxy = multiSapProxy; - - // compute current limit of edge arrays - BP_FP_INT_TYPE limit = static_cast(m_numHandles * 2); - - - // insert new edges just inside the max boundary edge - for (BP_FP_INT_TYPE axis = 0; axis < 3; axis++) - { - - m_pHandles[0].m_maxEdges[axis] += 2; - - m_pEdges[axis][limit + 1] = m_pEdges[axis][limit - 1]; - - m_pEdges[axis][limit - 1].m_pos = min[axis]; - m_pEdges[axis][limit - 1].m_handle = handle; - - m_pEdges[axis][limit].m_pos = max[axis]; - m_pEdges[axis][limit].m_handle = handle; - - pHandle->m_minEdges[axis] = static_cast(limit - 1); - pHandle->m_maxEdges[axis] = limit; - } - - // now sort the new edges to their correct position - sortMinDown(0, pHandle->m_minEdges[0], dispatcher,false); - sortMaxDown(0, pHandle->m_maxEdges[0], dispatcher,false); - sortMinDown(1, pHandle->m_minEdges[1], dispatcher,false); - sortMaxDown(1, pHandle->m_maxEdges[1], dispatcher,false); - sortMinDown(2, pHandle->m_minEdges[2], dispatcher,true); - sortMaxDown(2, pHandle->m_maxEdges[2], dispatcher,true); - - - return handle; -} - - -template -void btAxisSweep3Internal::removeHandle(BP_FP_INT_TYPE handle,btDispatcher* dispatcher) -{ - - Handle* pHandle = getHandle(handle); - - //explicitly remove the pairs containing the proxy - //we could do it also in the sortMinUp (passing true) - //todo: compare performance - if (!m_pairCache->hasDeferredRemoval()) - { - m_pairCache->removeOverlappingPairsContainingProxy(pHandle,dispatcher); - } - - // compute current limit of edge arrays - int limit = static_cast(m_numHandles * 2); - - int axis; - - for (axis = 0;axis<3;axis++) - { - m_pHandles[0].m_maxEdges[axis] -= 2; - } - - // remove the edges by sorting them up to the end of the list - for ( axis = 0; axis < 3; axis++) - { - Edge* pEdges = m_pEdges[axis]; - BP_FP_INT_TYPE max = pHandle->m_maxEdges[axis]; - pEdges[max].m_pos = m_handleSentinel; - - sortMaxUp(axis,max,dispatcher,false); - - - BP_FP_INT_TYPE i = pHandle->m_minEdges[axis]; - pEdges[i].m_pos = m_handleSentinel; - - - sortMinUp(axis,i,dispatcher,false); - - pEdges[limit-1].m_handle = 0; - pEdges[limit-1].m_pos = m_handleSentinel; - -#ifdef DEBUG_BROADPHASE - debugPrintAxis(axis,false); -#endif //DEBUG_BROADPHASE - - - } - - - // free the handle - freeHandle(handle); - - -} - -extern int gOverlappingPairs; -//#include - -template -void btAxisSweep3Internal::calculateOverlappingPairs(btDispatcher* dispatcher) -{ - - if (m_pairCache->hasDeferredRemoval()) - { - - btBroadphasePairArray& overlappingPairArray = m_pairCache->getOverlappingPairArray(); - - //perform a sort, to find duplicates and to sort 'invalid' pairs to the end - overlappingPairArray.quickSort(btBroadphasePairSortPredicate()); - - overlappingPairArray.resize(overlappingPairArray.size() - m_invalidPair); - m_invalidPair = 0; - - - int i; - - btBroadphasePair previousPair; - previousPair.m_pProxy0 = 0; - previousPair.m_pProxy1 = 0; - previousPair.m_algorithm = 0; - - - for (i=0;iprocessOverlap(pair); - } else - { - needsRemoval = true; - } - } else - { - //remove duplicate - needsRemoval = true; - //should have no algorithm - btAssert(!pair.m_algorithm); - } - - if (needsRemoval) - { - m_pairCache->cleanOverlappingPair(pair,dispatcher); - - // m_overlappingPairArray.swap(i,m_overlappingPairArray.size()-1); - // m_overlappingPairArray.pop_back(); - pair.m_pProxy0 = 0; - pair.m_pProxy1 = 0; - m_invalidPair++; - gOverlappingPairs--; - } - - } - - ///if you don't like to skip the invalid pairs in the array, execute following code: - #define CLEAN_INVALID_PAIRS 1 - #ifdef CLEAN_INVALID_PAIRS - - //perform a sort, to sort 'invalid' pairs to the end - overlappingPairArray.quickSort(btBroadphasePairSortPredicate()); - - overlappingPairArray.resize(overlappingPairArray.size() - m_invalidPair); - m_invalidPair = 0; - #endif//CLEAN_INVALID_PAIRS - - //printf("overlappingPairArray.size()=%d\n",overlappingPairArray.size()); - } - - - - - -} - - -template -bool btAxisSweep3Internal::testAabbOverlap(btBroadphaseProxy* proxy0,btBroadphaseProxy* proxy1) -{ - const Handle* pHandleA = static_cast(proxy0); - const Handle* pHandleB = static_cast(proxy1); - - //optimization 1: check the array index (memory address), instead of the m_pos - - for (int axis = 0; axis < 3; axis++) - { - if (pHandleA->m_maxEdges[axis] < pHandleB->m_minEdges[axis] || - pHandleB->m_maxEdges[axis] < pHandleA->m_minEdges[axis]) - { - return false; - } - } - return true; -} - -template -bool btAxisSweep3Internal::testOverlap(int ignoreAxis,const Handle* pHandleA, const Handle* pHandleB) -{ - //optimization 1: check the array index (memory address), instead of the m_pos - - for (int axis = 0; axis < 3; axis++) - { - if (axis != ignoreAxis) - { - if (pHandleA->m_maxEdges[axis] < pHandleB->m_minEdges[axis] || - pHandleB->m_maxEdges[axis] < pHandleA->m_minEdges[axis]) - { - return false; - } - } - } - - //optimization 2: only 2 axis need to be tested (conflicts with 'delayed removal' optimization) - - /*for (int axis = 0; axis < 3; axis++) - { - if (m_pEdges[axis][pHandleA->m_maxEdges[axis]].m_pos < m_pEdges[axis][pHandleB->m_minEdges[axis]].m_pos || - m_pEdges[axis][pHandleB->m_maxEdges[axis]].m_pos < m_pEdges[axis][pHandleA->m_minEdges[axis]].m_pos) - { - return false; - } - } - */ - - return true; -} - -template -void btAxisSweep3Internal::updateHandle(BP_FP_INT_TYPE handle, const btPoint3& aabbMin,const btPoint3& aabbMax,btDispatcher* dispatcher) -{ -// assert(bounds.IsFinite()); - //assert(bounds.HasVolume()); - - Handle* pHandle = getHandle(handle); - - // quantize the new bounds - BP_FP_INT_TYPE min[3], max[3]; - quantize(min, aabbMin, 0); - quantize(max, aabbMax, 1); - - // update changed edges - for (int axis = 0; axis < 3; axis++) - { - BP_FP_INT_TYPE emin = pHandle->m_minEdges[axis]; - BP_FP_INT_TYPE emax = pHandle->m_maxEdges[axis]; - - int dmin = (int)min[axis] - (int)m_pEdges[axis][emin].m_pos; - int dmax = (int)max[axis] - (int)m_pEdges[axis][emax].m_pos; - - m_pEdges[axis][emin].m_pos = min[axis]; - m_pEdges[axis][emax].m_pos = max[axis]; - - // expand (only adds overlaps) - if (dmin < 0) - sortMinDown(axis, emin,dispatcher,true); - - if (dmax > 0) - sortMaxUp(axis, emax,dispatcher,true); - - // shrink (only removes overlaps) - if (dmin > 0) - sortMinUp(axis, emin,dispatcher,true); - - if (dmax < 0) - sortMaxDown(axis, emax,dispatcher,true); - -#ifdef DEBUG_BROADPHASE - debugPrintAxis(axis); -#endif //DEBUG_BROADPHASE - } - - -} - - - - -// sorting a min edge downwards can only ever *add* overlaps -template -void btAxisSweep3Internal::sortMinDown(int axis, BP_FP_INT_TYPE edge, btDispatcher* /* dispatcher */, bool updateOverlaps) -{ - - Edge* pEdge = m_pEdges[axis] + edge; - Edge* pPrev = pEdge - 1; - Handle* pHandleEdge = getHandle(pEdge->m_handle); - - while (pEdge->m_pos < pPrev->m_pos) - { - Handle* pHandlePrev = getHandle(pPrev->m_handle); - - if (pPrev->IsMax()) - { - // if previous edge is a maximum check the bounds and add an overlap if necessary - if (updateOverlaps && testOverlap(axis,pHandleEdge, pHandlePrev)) - { - m_pairCache->addOverlappingPair(pHandleEdge,pHandlePrev); - if (m_userPairCallback) - m_userPairCallback->addOverlappingPair(pHandleEdge,pHandlePrev); - - //AddOverlap(pEdge->m_handle, pPrev->m_handle); - - } - - // update edge reference in other handle - pHandlePrev->m_maxEdges[axis]++; - } - else - pHandlePrev->m_minEdges[axis]++; - - pHandleEdge->m_minEdges[axis]--; - - // swap the edges - Edge swap = *pEdge; - *pEdge = *pPrev; - *pPrev = swap; - - // decrement - pEdge--; - pPrev--; - } - -#ifdef DEBUG_BROADPHASE - debugPrintAxis(axis); -#endif //DEBUG_BROADPHASE - -} - -// sorting a min edge upwards can only ever *remove* overlaps -template -void btAxisSweep3Internal::sortMinUp(int axis, BP_FP_INT_TYPE edge, btDispatcher* dispatcher, bool updateOverlaps) -{ - Edge* pEdge = m_pEdges[axis] + edge; - Edge* pNext = pEdge + 1; - Handle* pHandleEdge = getHandle(pEdge->m_handle); - - while (pNext->m_handle && (pEdge->m_pos >= pNext->m_pos)) - { - Handle* pHandleNext = getHandle(pNext->m_handle); - - if (pNext->IsMax()) - { - - // if next edge is maximum remove any overlap between the two handles - if (updateOverlaps) - { - Handle* handle0 = getHandle(pEdge->m_handle); - Handle* handle1 = getHandle(pNext->m_handle); - - m_pairCache->removeOverlappingPair(handle0,handle1,dispatcher); - if (m_userPairCallback) - m_userPairCallback->removeOverlappingPair(handle0,handle1,dispatcher); - - } - - - // update edge reference in other handle - pHandleNext->m_maxEdges[axis]--; - } - else - pHandleNext->m_minEdges[axis]--; - - pHandleEdge->m_minEdges[axis]++; - - // swap the edges - Edge swap = *pEdge; - *pEdge = *pNext; - *pNext = swap; - - // increment - pEdge++; - pNext++; - } - - -} - -// sorting a max edge downwards can only ever *remove* overlaps -template -void btAxisSweep3Internal::sortMaxDown(int axis, BP_FP_INT_TYPE edge, btDispatcher* dispatcher, bool updateOverlaps) -{ - - Edge* pEdge = m_pEdges[axis] + edge; - Edge* pPrev = pEdge - 1; - Handle* pHandleEdge = getHandle(pEdge->m_handle); - - while (pEdge->m_pos < pPrev->m_pos) - { - Handle* pHandlePrev = getHandle(pPrev->m_handle); - - if (!pPrev->IsMax()) - { - // if previous edge was a minimum remove any overlap between the two handles - if (updateOverlaps) - { - //this is done during the overlappingpairarray iteration/narrowphase collision - - Handle* handle0 = getHandle(pEdge->m_handle); - Handle* handle1 = getHandle(pPrev->m_handle); - m_pairCache->removeOverlappingPair(handle0,handle1,dispatcher); - if (m_userPairCallback) - m_userPairCallback->removeOverlappingPair(handle0,handle1,dispatcher); - - - - } - - // update edge reference in other handle - pHandlePrev->m_minEdges[axis]++;; - } - else - pHandlePrev->m_maxEdges[axis]++; - - pHandleEdge->m_maxEdges[axis]--; - - // swap the edges - Edge swap = *pEdge; - *pEdge = *pPrev; - *pPrev = swap; - - // decrement - pEdge--; - pPrev--; - } - - -#ifdef DEBUG_BROADPHASE - debugPrintAxis(axis); -#endif //DEBUG_BROADPHASE - -} - -// sorting a max edge upwards can only ever *add* overlaps -template -void btAxisSweep3Internal::sortMaxUp(int axis, BP_FP_INT_TYPE edge, btDispatcher* /* dispatcher */, bool updateOverlaps) -{ - Edge* pEdge = m_pEdges[axis] + edge; - Edge* pNext = pEdge + 1; - Handle* pHandleEdge = getHandle(pEdge->m_handle); - - while (pNext->m_handle && (pEdge->m_pos >= pNext->m_pos)) - { - Handle* pHandleNext = getHandle(pNext->m_handle); - - if (!pNext->IsMax()) - { - // if next edge is a minimum check the bounds and add an overlap if necessary - if (updateOverlaps && testOverlap(axis, pHandleEdge, pHandleNext)) - { - Handle* handle0 = getHandle(pEdge->m_handle); - Handle* handle1 = getHandle(pNext->m_handle); - m_pairCache->addOverlappingPair(handle0,handle1); - if (m_userPairCallback) - m_userPairCallback->addOverlappingPair(handle0,handle1); - } - - // update edge reference in other handle - pHandleNext->m_minEdges[axis]--; - } - else - pHandleNext->m_maxEdges[axis]--; - - pHandleEdge->m_maxEdges[axis]++; - - // swap the edges - Edge swap = *pEdge; - *pEdge = *pNext; - *pNext = swap; - - // increment - pEdge++; - pNext++; - } - -} - - - -//////////////////////////////////////////////////////////////////// - - -/// The btAxisSweep3 is an efficient implementation of the 3d axis sweep and prune broadphase. -/// It uses arrays rather then lists for storage of the 3 axis. Also it operates using 16 bit integer coordinates instead of floats. -/// For large worlds and many objects, use bt32BitAxisSweep3 or btDbvtBroadphase instead. bt32BitAxisSweep3 has higher precision and allows more then 16384 objects at the cost of more memory and bit of performance. -class btAxisSweep3 : public btAxisSweep3Internal -{ -public: - - btAxisSweep3(const btPoint3& worldAabbMin,const btPoint3& worldAabbMax, unsigned short int maxHandles = 16384, btOverlappingPairCache* pairCache = 0); - -}; - -/// The bt32BitAxisSweep3 allows higher precision quantization and more objects compared to the btAxisSweep3 sweep and prune. -/// This comes at the cost of more memory per handle, and a bit slower performance. -/// It uses arrays rather then lists for storage of the 3 axis. -class bt32BitAxisSweep3 : public btAxisSweep3Internal -{ -public: - - bt32BitAxisSweep3(const btPoint3& worldAabbMin,const btPoint3& worldAabbMax, unsigned int maxHandles = 1500000, btOverlappingPairCache* pairCache = 0); + virtual btBroadphaseProxy* createProxy( const btVector3& min, const btVector3& max,int shapeType,void* userPtr ,short int collisionFilterGroup,short int collisionFilterMask); + virtual void destroyProxy(btBroadphaseProxy* proxy); + virtual void setAabb(btBroadphaseProxy* proxy,const btVector3& aabbMin,const btVector3& aabbMax); + bool testOverlap(btBroadphaseProxy* proxy0,btBroadphaseProxy* proxy1); }; diff --git a/extern/bullet2/src/BulletCollision/BroadphaseCollision/btBroadphaseInterface.h b/extern/bullet2/src/BulletCollision/BroadphaseCollision/btBroadphaseInterface.h index 200ac365329..b6ace03c07a 100644 --- a/extern/bullet2/src/BulletCollision/BroadphaseCollision/btBroadphaseInterface.h +++ b/extern/bullet2/src/BulletCollision/BroadphaseCollision/btBroadphaseInterface.h @@ -20,34 +20,20 @@ subject to the following restrictions: struct btDispatcherInfo; class btDispatcher; -#include "btBroadphaseProxy.h" -class btOverlappingPairCache; +struct btBroadphaseProxy; +#include "../../LinearMath/btVector3.h" -#include "LinearMath/btVector3.h" - -///The btBroadphaseInterface class provides an interface to detect aabb-overlapping object pairs. -///Some implementations for this broadphase interface include btAxisSweep3, bt32BitAxisSweep3 and btDbvtBroadphase. -///The actual overlapping pair management, storage, adding and removing of pairs is dealt by the btOverlappingPairCache class. +///BroadphaseInterface for aabb-overlapping object pairs class btBroadphaseInterface { public: virtual ~btBroadphaseInterface() {} - virtual btBroadphaseProxy* createProxy( const btVector3& aabbMin, const btVector3& aabbMax,int shapeType,void* userPtr, short int collisionFilterGroup,short int collisionFilterMask, btDispatcher* dispatcher,void* multiSapProxy) =0; - virtual void destroyProxy(btBroadphaseProxy* proxy,btDispatcher* dispatcher)=0; - virtual void setAabb(btBroadphaseProxy* proxy,const btVector3& aabbMin,const btVector3& aabbMax, btDispatcher* dispatcher)=0; + virtual btBroadphaseProxy* createProxy( const btVector3& min, const btVector3& max,int shapeType,void* userPtr, short int collisionFilterGroup,short int collisionFilterMask) =0; + virtual void destroyProxy(btBroadphaseProxy* proxy)=0; + virtual void setAabb(btBroadphaseProxy* proxy,const btVector3& aabbMin,const btVector3& aabbMax)=0; + virtual void cleanProxyFromPairs(btBroadphaseProxy* proxy)=0; - ///calculateOverlappingPairs is optional: incremental algorithms (sweep and prune) might do it during the set aabb - virtual void calculateOverlappingPairs(btDispatcher* dispatcher)=0; - - virtual btOverlappingPairCache* getOverlappingPairCache()=0; - virtual const btOverlappingPairCache* getOverlappingPairCache() const =0; - - ///getAabb returns the axis aligned bounding box in the 'global' coordinate frame - ///will add some transform later - virtual void getBroadphaseAabb(btVector3& aabbMin,btVector3& aabbMax) const =0; - - virtual void printStats() = 0; }; diff --git a/extern/bullet2/src/BulletCollision/BroadphaseCollision/btBroadphaseProxy.h b/extern/bullet2/src/BulletCollision/BroadphaseCollision/btBroadphaseProxy.h index e0bb67f8521..40d9748ffa9 100644 --- a/extern/bullet2/src/BulletCollision/BroadphaseCollision/btBroadphaseProxy.h +++ b/extern/bullet2/src/BulletCollision/BroadphaseCollision/btBroadphaseProxy.h @@ -16,8 +16,7 @@ subject to the following restrictions: #ifndef BROADPHASE_PROXY_H #define BROADPHASE_PROXY_H -#include "LinearMath/btScalar.h" //for SIMD_FORCE_INLINE -#include "LinearMath/btAlignedAllocator.h" +#include "../../LinearMath/btScalar.h" //for SIMD_FORCE_INLINE /// btDispatcher uses these types @@ -39,7 +38,6 @@ IMPLICIT_CONVEX_SHAPES_START_HERE, CONE_SHAPE_PROXYTYPE, CONVEX_SHAPE_PROXYTYPE, CYLINDER_SHAPE_PROXYTYPE, - UNIFORM_SCALING_SHAPE_PROXYTYPE, MINKOWSKI_SUM_SHAPE_PROXYTYPE, MINKOWSKI_DIFFERENCE_SHAPE_PROXYTYPE, //concave shapes @@ -52,8 +50,6 @@ CONCAVE_SHAPES_START_HERE, TERRAIN_SHAPE_PROXYTYPE, ///Used for GIMPACT Trimesh integration GIMPACT_SHAPE_PROXYTYPE, -///Multimaterial mesh - MULTIMATERIAL_TRIANGLE_MESH_PROXYTYPE, EMPTY_SHAPE_PROXYTYPE, STATIC_PLANE_PROXYTYPE, @@ -61,18 +57,13 @@ CONCAVE_SHAPES_END_HERE, COMPOUND_SHAPE_PROXYTYPE, - SOFTBODY_SHAPE_PROXYTYPE, - MAX_BROADPHASE_COLLISION_TYPES }; -///The btBroadphaseProxy is the main class that can be used with the Bullet broadphases. -///It stores collision shape type information, collision filter information and a client object, typically a btCollisionObject or btRigidBody. -ATTRIBUTE_ALIGNED16(struct) btBroadphaseProxy +///btBroadphaseProxy +struct btBroadphaseProxy { - -BT_DECLARE_ALIGNED_ALLOCATOR(); ///optional filtering to cull potential collisions enum CollisionFilterGroups @@ -82,60 +73,44 @@ BT_DECLARE_ALIGNED_ALLOCATOR(); KinematicFilter = 4, DebrisFilter = 8, SensorTrigger = 16, - AllFilter = -1 //all bits sets: DefaultFilter | StaticFilter | KinematicFilter | DebrisFilter | SensorTrigger + AllFilter = DefaultFilter | StaticFilter | KinematicFilter | DebrisFilter | SensorTrigger }; //Usually the client btCollisionObject or Rigidbody class void* m_clientObject; - short int m_collisionFilterGroup; short int m_collisionFilterMask; - void* m_multiSapParentProxy; - - - int m_uniqueId;//m_uniqueId is introduced for paircache. could get rid of this, by calculating the address offset etc. - - SIMD_FORCE_INLINE int getUid() const - { - return m_uniqueId; - } - //used for memory pools - btBroadphaseProxy() :m_clientObject(0),m_multiSapParentProxy(0) - { - } + btBroadphaseProxy() :m_clientObject(0){} - btBroadphaseProxy(void* userPtr,short int collisionFilterGroup, short int collisionFilterMask,void* multiSapParentProxy=0) + btBroadphaseProxy(void* userPtr,short int collisionFilterGroup, short int collisionFilterMask) :m_clientObject(userPtr), m_collisionFilterGroup(collisionFilterGroup), m_collisionFilterMask(collisionFilterMask) { - m_multiSapParentProxy = multiSapParentProxy; } - - - static SIMD_FORCE_INLINE bool isPolyhedral(int proxyType) + static inline bool isPolyhedral(int proxyType) { return (proxyType < IMPLICIT_CONVEX_SHAPES_START_HERE); } - static SIMD_FORCE_INLINE bool isConvex(int proxyType) + static inline bool isConvex(int proxyType) { return (proxyType < CONCAVE_SHAPES_START_HERE); } - static SIMD_FORCE_INLINE bool isConcave(int proxyType) + static inline bool isConcave(int proxyType) { return ((proxyType > CONCAVE_SHAPES_START_HERE) && (proxyType < CONCAVE_SHAPES_END_HERE)); } - static SIMD_FORCE_INLINE bool isCompound(int proxyType) + static inline bool isCompound(int proxyType) { return (proxyType == COMPOUND_SHAPE_PROXYTYPE); } - static SIMD_FORCE_INLINE bool isInfinite(int proxyType) + static inline bool isInfinite(int proxyType) { return (proxyType == STATIC_PLANE_PROXYTYPE); } @@ -149,9 +124,8 @@ struct btBroadphaseProxy; -///The btBroadphasePair class contains a pair of aabb-overlapping objects. -///A btDispatcher can search a btCollisionAlgorithm that performs exact/narrowphase collision detection on the actual collision shapes. -ATTRIBUTE_ALIGNED16(struct) btBroadphasePair +/// contains a pair of aabb-overlapping objects +struct btBroadphasePair { btBroadphasePair () : @@ -162,8 +136,6 @@ ATTRIBUTE_ALIGNED16(struct) btBroadphasePair { } -BT_DECLARE_ALIGNED_ALLOCATOR(); - btBroadphasePair(const btBroadphasePair& other) : m_pProxy0(other.m_pProxy0), m_pProxy1(other.m_pProxy1), @@ -209,7 +181,6 @@ SIMD_FORCE_INLINE bool operator<(const btBroadphasePair& a, const btBroadphasePa */ - class btBroadphasePairSortPredicate { public: diff --git a/extern/bullet2/src/BulletCollision/BroadphaseCollision/btCollisionAlgorithm.cpp b/extern/bullet2/src/BulletCollision/BroadphaseCollision/btCollisionAlgorithm.cpp index c95d1be0f2c..2ad0c86d8a2 100644 --- a/extern/bullet2/src/BulletCollision/BroadphaseCollision/btCollisionAlgorithm.cpp +++ b/extern/bullet2/src/BulletCollision/BroadphaseCollision/btCollisionAlgorithm.cpp @@ -18,6 +18,6 @@ subject to the following restrictions: btCollisionAlgorithm::btCollisionAlgorithm(const btCollisionAlgorithmConstructionInfo& ci) { - m_dispatcher = ci.m_dispatcher1; + m_dispatcher = ci.m_dispatcher; } diff --git a/extern/bullet2/src/BulletCollision/BroadphaseCollision/btCollisionAlgorithm.h b/extern/bullet2/src/BulletCollision/BroadphaseCollision/btCollisionAlgorithm.h index 1618ad9fdd3..55cec386a7b 100644 --- a/extern/bullet2/src/BulletCollision/BroadphaseCollision/btCollisionAlgorithm.h +++ b/extern/bullet2/src/BulletCollision/BroadphaseCollision/btCollisionAlgorithm.h @@ -16,8 +16,7 @@ subject to the following restrictions: #ifndef COLLISION_ALGORITHM_H #define COLLISION_ALGORITHM_H -#include "LinearMath/btScalar.h" -#include "LinearMath/btAlignedObjectArray.h" +#include "../../LinearMath/btScalar.h" struct btBroadphaseProxy; class btDispatcher; @@ -26,22 +25,21 @@ class btCollisionObject; struct btDispatcherInfo; class btPersistentManifold; -typedef btAlignedObjectArray btManifoldArray; struct btCollisionAlgorithmConstructionInfo { btCollisionAlgorithmConstructionInfo() - :m_dispatcher1(0), + :m_dispatcher(0), m_manifold(0) { } btCollisionAlgorithmConstructionInfo(btDispatcher* dispatcher,int temp) - :m_dispatcher1(dispatcher) + :m_dispatcher(dispatcher) { (void)temp; } - btDispatcher* m_dispatcher1; + btDispatcher* m_dispatcher; btPersistentManifold* m_manifold; int getDispatcherId(); @@ -73,7 +71,6 @@ public: virtual btScalar calculateTimeOfImpact(btCollisionObject* body0,btCollisionObject* body1,const btDispatcherInfo& dispatchInfo,btManifoldResult* resultOut) = 0; - virtual void getAllContactManifolds(btManifoldArray& manifoldArray) = 0; }; diff --git a/extern/bullet2/src/BulletCollision/BroadphaseCollision/btDbvt.cpp b/extern/bullet2/src/BulletCollision/BroadphaseCollision/btDbvt.cpp deleted file mode 100644 index fade71179e6..00000000000 --- a/extern/bullet2/src/BulletCollision/BroadphaseCollision/btDbvt.cpp +++ /dev/null @@ -1,1320 +0,0 @@ -/* -Bullet Continuous Collision Detection and Physics Library -Copyright (c) 2003-2006 Erwin Coumans http://continuousphysics.com/Bullet/ - -This software is provided 'as-is', without any express or implied warranty. -In no event will the authors be held liable for any damages arising from the use of this software. -Permission is granted to anyone to use this software for any purpose, -including commercial applications, and to alter it and redistribute it freely, -subject to the following restrictions: - -1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. -2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. -3. This notice may not be removed or altered from any source distribution. -*/ -///btDbvt implementation by Nathanael Presson - -#include "btDbvt.h" - -// -typedef btAlignedObjectArray tNodeArray; -typedef btAlignedObjectArray tConstNodeArray; - -// -struct btDbvtNodeEnumerator : btDbvt::ICollide -{ -tConstNodeArray nodes; -void Process(const btDbvtNode* n) { nodes.push_back(n); } -}; - -// -static DBVT_INLINE int indexof(const btDbvtNode* node) -{ -return(node->parent->childs[1]==node); -} - -// -static DBVT_INLINE btDbvtVolume merge( const btDbvtVolume& a, - const btDbvtVolume& b) -{ -#if DBVT_MERGE_IMPL==DBVT_IMPL_SSE -DBVT_ALIGN char locals[sizeof(btDbvtAabbMm)]; -btDbvtVolume& res=*(btDbvtVolume*)locals; -#else -btDbvtVolume res; -#endif -Merge(a,b,res); -return(res); -} - -// volume+edge lengths -static DBVT_INLINE btScalar size(const btDbvtVolume& a) -{ -const btVector3 edges=a.Lengths(); -return( edges.x()*edges.y()*edges.z()+ - edges.x()+edges.y()+edges.z()); -} - -// -static void getmaxdepth(const btDbvtNode* node,int depth,int& maxdepth) -{ -if(node->isinternal()) - { - getmaxdepth(node->childs[0],depth+1,maxdepth); - getmaxdepth(node->childs[0],depth+1,maxdepth); - } else maxdepth=btMax(maxdepth,depth); -} - -// -static DBVT_INLINE void deletenode( btDbvt* pdbvt, - btDbvtNode* node) -{ -btAlignedFree(pdbvt->m_free); -pdbvt->m_free=node; -} - -// -static void recursedeletenode( btDbvt* pdbvt, - btDbvtNode* node) -{ -if(!node->isleaf()) - { - recursedeletenode(pdbvt,node->childs[0]); - recursedeletenode(pdbvt,node->childs[1]); - } -if(node==pdbvt->m_root) pdbvt->m_root=0; -deletenode(pdbvt,node); -} - -// -static DBVT_INLINE btDbvtNode* createnode( btDbvt* pdbvt, - btDbvtNode* parent, - void* data) -{ -btDbvtNode* node; -if(pdbvt->m_free) - { node=pdbvt->m_free;pdbvt->m_free=0; } - else - { node=new(btAlignedAlloc(sizeof(btDbvtNode),16)) btDbvtNode(); } -node->parent = parent; -node->data = data; -node->childs[1] = 0; -return(node); -} - -// -static DBVT_INLINE btDbvtNode* createnode( btDbvt* pdbvt, - btDbvtNode* parent, - const btDbvtVolume& volume, - void* data) -{ -btDbvtNode* node=createnode(pdbvt,parent,data); -node->volume=volume; -return(node); -} - -// -static DBVT_INLINE btDbvtNode* createnode( btDbvt* pdbvt, - btDbvtNode* parent, - const btDbvtVolume& volume0, - const btDbvtVolume& volume1, - void* data) -{ -btDbvtNode* node=createnode(pdbvt,parent,data); -Merge(volume0,volume1,node->volume); -return(node); -} - -// -static void insertleaf( btDbvt* pdbvt, - btDbvtNode* root, - btDbvtNode* leaf) -{ -if(!pdbvt->m_root) - { - pdbvt->m_root = leaf; - leaf->parent = 0; - } - else - { - if(!root->isleaf()) - { - do { - root=root->childs[Select( leaf->volume, - root->childs[0]->volume, - root->childs[1]->volume)]; - } while(!root->isleaf()); - } - btDbvtNode* prev=root->parent; - btDbvtNode* node=createnode(pdbvt,prev,leaf->volume,root->volume,0); - if(prev) - { - prev->childs[indexof(root)] = node; - node->childs[0] = root;root->parent=node; - node->childs[1] = leaf;leaf->parent=node; - do { - if(!prev->volume.Contain(node->volume)) - Merge(prev->childs[0]->volume,prev->childs[1]->volume,prev->volume); - else - break; - node=prev; - } while(0!=(prev=node->parent)); - } - else - { - node->childs[0] = root;root->parent=node; - node->childs[1] = leaf;leaf->parent=node; - pdbvt->m_root = node; - } - } -} - -// -static btDbvtNode* removeleaf( btDbvt* pdbvt, - btDbvtNode* leaf) -{ -if(leaf==pdbvt->m_root) - { - pdbvt->m_root=0; - return(0); - } - else - { - btDbvtNode* parent=leaf->parent; - btDbvtNode* prev=parent->parent; - btDbvtNode* sibling=parent->childs[1-indexof(leaf)]; - if(prev) - { - prev->childs[indexof(parent)]=sibling; - sibling->parent=prev; - deletenode(pdbvt,parent); - while(prev) - { - const btDbvtVolume pb=prev->volume; - Merge(prev->childs[0]->volume,prev->childs[1]->volume,prev->volume); - if(NotEqual(pb,prev->volume)) - { - prev=prev->parent; - } else break; - } - return(prev?prev:pdbvt->m_root); - } - else - { - pdbvt->m_root=sibling; - sibling->parent=0; - deletenode(pdbvt,parent); - return(pdbvt->m_root); - } - } -} - -// -static void fetchleaves(btDbvt* pdbvt, - btDbvtNode* root, - tNodeArray& leaves, - int depth=-1) -{ -if(root->isinternal()&&depth) - { - fetchleaves(pdbvt,root->childs[0],leaves,depth-1); - fetchleaves(pdbvt,root->childs[1],leaves,depth-1); - deletenode(pdbvt,root); - } - else - { - leaves.push_back(root); - } -} - -// -static void split( const tNodeArray& leaves, - tNodeArray& left, - tNodeArray& right, - const btVector3& org, - const btVector3& axis) -{ -left.resize(0); -right.resize(0); -for(int i=0,ni=leaves.size();ivolume.Center()-org)<0) - left.push_back(leaves[i]); - else - right.push_back(leaves[i]); - } -} - -// -static btDbvtVolume bounds( const tNodeArray& leaves) -{ -#if DBVT_MERGE_IMPL==DBVT_IMPL_SSE -DBVT_ALIGN char locals[sizeof(btDbvtVolume)]; -btDbvtVolume& volume=*(btDbvtVolume*)locals; -volume=leaves[0]->volume; -#else -btDbvtVolume volume=leaves[0]->volume; -#endif -for(int i=1,ni=leaves.size();ivolume,volume); - } -return(volume); -} - -// -static void bottomup( btDbvt* pdbvt, - tNodeArray& leaves) -{ -while(leaves.size()>1) - { - btScalar minsize=SIMD_INFINITY; - int minidx[2]={-1,-1}; - for(int i=0;ivolume,leaves[j]->volume)); - if(szvolume,n[1]->volume,0); - p->childs[0] = n[0]; - p->childs[1] = n[1]; - n[0]->parent = p; - n[1]->parent = p; - leaves[minidx[0]] = p; - leaves.swap(minidx[1],leaves.size()-1); - leaves.pop_back(); - } -} - -// -static btDbvtNode* topdown(btDbvt* pdbvt, - tNodeArray& leaves, - int bu_treshold) -{ -static const btVector3 axis[]={btVector3(1,0,0), - btVector3(0,1,0), - btVector3(0,0,1)}; -if(leaves.size()>1) - { - if(leaves.size()>bu_treshold) - { - const btDbvtVolume vol=bounds(leaves); - const btVector3 org=vol.Center(); - tNodeArray sets[2]; - int bestaxis=-1; - int bestmidp=leaves.size(); - int splitcount[3][2]={{0,0},{0,0},{0,0}}; - int i; - for( i=0;ivolume.Center()-org; - for(int j=0;j<3;++j) - { - ++splitcount[j][dot(x,axis[j])>0?1:0]; - } - } - for( i=0;i<3;++i) - { - if((splitcount[i][0]>0)&&(splitcount[i][1]>0)) - { - const int midp=(int)btFabs(btScalar(splitcount[i][0]-splitcount[i][1])); - if(midp=0) - { - sets[0].reserve(splitcount[bestaxis][0]); - sets[1].reserve(splitcount[bestaxis][1]); - split(leaves,sets[0],sets[1],org,axis[bestaxis]); - } - else - { - sets[0].reserve(leaves.size()/2+1); - sets[1].reserve(leaves.size()/2); - for(int i=0,ni=leaves.size();ichilds[0]=topdown(pdbvt,sets[0],bu_treshold); - node->childs[1]=topdown(pdbvt,sets[1],bu_treshold); - node->childs[0]->parent=node; - node->childs[1]->parent=node; - return(node); - } - else - { - bottomup(pdbvt,leaves); - return(leaves[0]); - } - } -return(leaves[0]); -} - -// -static DBVT_INLINE btDbvtNode* sort(btDbvtNode* n,btDbvtNode*& r) -{ -btDbvtNode* p=n->parent; -btAssert(n->isinternal()); -if(p>n) - { - const int i=indexof(n); - const int j=1-i; - btDbvtNode* s=p->childs[j]; - btDbvtNode* q=p->parent; - btAssert(n==p->childs[i]); - if(q) q->childs[indexof(p)]=n; else r=n; - s->parent=n; - p->parent=n; - n->parent=q; - p->childs[0]=n->childs[0]; - p->childs[1]=n->childs[1]; - n->childs[0]->parent=p; - n->childs[1]->parent=p; - n->childs[i]=p; - n->childs[j]=s; - btSwap(p->volume,n->volume); - return(p); - } -return(n); -} - -// -static DBVT_INLINE btDbvtNode* walkup(btDbvtNode* n,int count) -{ -while(n&&(count--)) n=n->parent; -return(n); -} - -// -// Api -// - -// - btDbvt::btDbvt() -{ -m_root = 0; -m_free = 0; -m_lkhd = -1; -m_leaves = 0; -m_opath = 0; -} - -// - btDbvt::~btDbvt() -{ -clear(); -} - -// -void btDbvt::clear() -{ -if(m_root) recursedeletenode(this,m_root); -btAlignedFree(m_free); -m_free=0; -} - -// -void btDbvt::optimizeBottomUp() -{ -if(m_root) - { - tNodeArray leaves; - leaves.reserve(m_leaves); - fetchleaves(this,m_root,leaves); - bottomup(this,leaves); - m_root=leaves[0]; - } -} - -// -void btDbvt::optimizeTopDown(int bu_treshold) -{ -if(m_root) - { - tNodeArray leaves; - leaves.reserve(m_leaves); - fetchleaves(this,m_root,leaves); - m_root=topdown(this,leaves,bu_treshold); - } -} - -// -void btDbvt::optimizeIncremental(int passes) -{ -if(passes<0) passes=m_leaves; -if(m_root&&(passes>0)) - { - do { - btDbvtNode* node=m_root; - unsigned bit=0; - while(node->isinternal()) - { - node=sort(node,m_root)->childs[(m_opath>>bit)&1]; - bit=(bit+1)&(sizeof(unsigned)*8-1); - } - update(node); - ++m_opath; - } while(--passes); - } -} - -// -btDbvtNode* btDbvt::insert(const btDbvtVolume& volume,void* data) -{ -btDbvtNode* leaf=createnode(this,0,volume,data); -insertleaf(this,m_root,leaf); -++m_leaves; -return(leaf); -} - -// -void btDbvt::update(btDbvtNode* leaf,int lookahead) -{ -btDbvtNode* root=removeleaf(this,leaf); -if(root) - { - if(lookahead>=0) - { - for(int i=0;(iparent;++i) - { - root=root->parent; - } - } else root=m_root; - } -insertleaf(this,root,leaf); -} - -// -void btDbvt::update(btDbvtNode* leaf,const btDbvtVolume& volume) -{ -btDbvtNode* root=removeleaf(this,leaf); -if(root) - { - if(m_lkhd>=0) - { - for(int i=0;(iparent;++i) - { - root=root->parent; - } - } else root=m_root; - } -leaf->volume=volume; -insertleaf(this,root,leaf); -} - -// -bool btDbvt::update(btDbvtNode* leaf,btDbvtVolume volume,const btVector3& velocity,btScalar margin) -{ -if(leaf->volume.Contain(volume)) return(false); -volume.Expand(btVector3(margin,margin,margin)); -volume.SignedExpand(velocity); -update(leaf,volume); -return(true); -} - -// -bool btDbvt::update(btDbvtNode* leaf,btDbvtVolume volume,const btVector3& velocity) -{ -if(leaf->volume.Contain(volume)) return(false); -volume.SignedExpand(velocity); -update(leaf,volume); -return(true); -} - -// -bool btDbvt::update(btDbvtNode* leaf,btDbvtVolume volume,btScalar margin) -{ -if(leaf->volume.Contain(volume)) return(false); -volume.Expand(btVector3(margin,margin,margin)); -update(leaf,volume); -return(true); -} - -// -void btDbvt::remove(btDbvtNode* leaf) -{ -removeleaf(this,leaf); -deletenode(this,leaf); ---m_leaves; -} - -// -void btDbvt::write(IWriter* iwriter) const -{ -btDbvtNodeEnumerator nodes; -nodes.nodes.reserve(m_leaves*2); -enumNodes(m_root,nodes); -iwriter->Prepare(m_root,nodes.nodes.size()); -for(int i=0;iparent) p=nodes.nodes.findLinearSearch(n->parent); - if(n->isinternal()) - { - const int c0=nodes.nodes.findLinearSearch(n->childs[0]); - const int c1=nodes.nodes.findLinearSearch(n->childs[1]); - iwriter->WriteNode(n,i,p,c0,c1); - } - else - { - iwriter->WriteLeaf(n,i,p); - } - } -} - -// -void btDbvt::clone(btDbvt& dest,IClone* iclone) const -{ -dest.clear(); -if(m_root!=0) - { - btAlignedObjectArray stack; - stack.reserve(m_leaves); - stack.push_back(sStkCLN(m_root,0)); - do { - const int i=stack.size()-1; - const sStkCLN e=stack[i]; - btDbvtNode* n=createnode(&dest,e.parent,e.node->volume,e.node->data); - stack.pop_back(); - if(e.parent!=0) - e.parent->childs[i&1]=n; - else - dest.m_root=n; - if(e.node->isinternal()) - { - stack.push_back(sStkCLN(e.node->childs[0],n)); - stack.push_back(sStkCLN(e.node->childs[1],n)); - } - else - { - iclone->CloneLeaf(n); - } - } while(stack.size()>0); - } -} - -// -int btDbvt::maxdepth(const btDbvtNode* node) -{ -int depth=0; -if(node) getmaxdepth(node,1,depth); -return(depth); -} - -// -int btDbvt::countLeaves(const btDbvtNode* node) -{ -if(node->isinternal()) - return(countLeaves(node->childs[0])+countLeaves(node->childs[1])); - else - return(1); -} - -// -void btDbvt::extractLeaves(const btDbvtNode* node,btAlignedObjectArray& leaves) -{ -if(node->isinternal()) - { - extractLeaves(node->childs[0],leaves); - extractLeaves(node->childs[1],leaves); - } - else - { - leaves.push_back(node); - } -} - -// -#if DBVT_ENABLE_BENCHMARK - -#include -#include -#include "LinearMath/btQuickProf.h" - -/* -q6600,2.4ghz - -/Ox /Ob2 /Oi /Ot /I "." /I "..\.." /I "..\..\src" /D "NDEBUG" /D "_LIB" /D "_WINDOWS" /D "_CRT_SECURE_NO_DEPRECATE" /D "_CRT_NONSTDC_NO_DEPRECATE" /D "WIN32" -/GF /FD /MT /GS- /Gy /arch:SSE2 /Zc:wchar_t- /Fp"..\..\out\release8\build\libbulletcollision\libbulletcollision.pch" -/Fo"..\..\out\release8\build\libbulletcollision\\" -/Fd"..\..\out\release8\build\libbulletcollision\bulletcollision.pdb" -/W3 /nologo /c /Wp64 /Zi /errorReport:prompt - -Benchmarking dbvt... - World scale: 100.000000 - Extents base: 1.000000 - Extents range: 4.000000 - Leaves: 8192 - sizeof(btDbvtVolume): 32 bytes - sizeof(btDbvtNode): 44 bytes -[1] btDbvtVolume intersections: 3537 ms (0%) -[2] btDbvtVolume merges: 1945 ms (0%) -[3] btDbvt::collideTT: 6646 ms (0%) -[4] btDbvt::collideTT self: 3389 ms (0%) -[5] btDbvt::collideTT xform: 7505 ms (0%) -[6] btDbvt::collideTT xform,self: 7480 ms (0%) -[7] btDbvt::collideRAY: 6307 ms (0%),(332511 r/s) -[8] insert/remove: 2105 ms (-3%),(996271 ir/s) -[9] updates (teleport): 1943 ms (0%),(1079337 u/s) -[10] updates (jitter): 1301 ms (0%),(1611953 u/s) -[11] optimize (incremental): 2510 ms (0%),(1671000 o/s) -[12] btDbvtVolume notequal: 3677 ms (0%) -[13] culling(OCL+fullsort): 2231 ms (0%),(458 t/s) -[14] culling(OCL+qsort): 3500 ms (0%),(2340 t/s) -[15] culling(KDOP+qsort): 1151 ms (0%),(7117 t/s) -[16] insert/remove batch(256): 5138 ms (0%),(816330 bir/s) -[17] btDbvtVolume proximity: 2842 ms (0%) -[18] btDbvtVolume select: 3390 ms (0%) -*/ - -struct btDbvtBenchmark -{ -struct NilPolicy : btDbvt::ICollide - { - NilPolicy() : m_pcount(0),m_depth(-SIMD_INFINITY),m_checksort(true) {} - void Process(const btDbvtNode*,const btDbvtNode*) { ++m_pcount; } - void Process(const btDbvtNode*) { ++m_pcount; } - void Process(const btDbvtNode*,btScalar depth) - { - ++m_pcount; - if(m_checksort) - { if(depth>=m_depth) m_depth=depth; else printf("wrong depth: %f (should be >= %f)\r\n",depth,m_depth); } - } - int m_pcount; - btScalar m_depth; - bool m_checksort; - }; -struct P14 : btDbvt::ICollide - { - struct Node - { - const btDbvtNode* leaf; - btScalar depth; - }; - void Process(const btDbvtNode* leaf,btScalar depth) - { - Node n; - n.leaf = leaf; - n.depth = depth; - } - static int sortfnc(const Node& a,const Node& b) - { - if(a.depthb.depth) return(-1); - return(0); - } - btAlignedObjectArray m_nodes; - }; -struct P15 : btDbvt::ICollide - { - struct Node - { - const btDbvtNode* leaf; - btScalar depth; - }; - void Process(const btDbvtNode* leaf) - { - Node n; - n.leaf = leaf; - n.depth = dot(leaf->volume.Center(),m_axis); - } - static int sortfnc(const Node& a,const Node& b) - { - if(a.depthb.depth) return(-1); - return(0); - } - btAlignedObjectArray m_nodes; - btVector3 m_axis; - }; -static btScalar RandUnit() - { - return(rand()/(btScalar)RAND_MAX); - } -static btVector3 RandVector3() - { - return(btVector3(RandUnit(),RandUnit(),RandUnit())); - } -static btVector3 RandVector3(btScalar cs) - { - return(RandVector3()*cs-btVector3(cs,cs,cs)/2); - } -static btDbvtVolume RandVolume(btScalar cs,btScalar eb,btScalar es) - { - return(btDbvtVolume::FromCE(RandVector3(cs),btVector3(eb,eb,eb)+RandVector3()*es)); - } -static btTransform RandTransform(btScalar cs) - { - btTransform t; - t.setOrigin(RandVector3(cs)); - t.setRotation(btQuaternion(RandUnit()*SIMD_PI*2,RandUnit()*SIMD_PI*2,RandUnit()*SIMD_PI*2).normalized()); - return(t); - } -static void RandTree(btScalar cs,btScalar eb,btScalar es,int leaves,btDbvt& dbvt) - { - dbvt.clear(); - for(int i=0;i volumes; - btAlignedObjectArray results; - volumes.resize(cfgLeaves); - results.resize(cfgLeaves); - for(int i=0;i volumes; - btAlignedObjectArray results; - volumes.resize(cfgLeaves); - results.resize(cfgLeaves); - for(int i=0;i transforms; - btDbvtBenchmark::NilPolicy policy; - transforms.resize(cfgBenchmark5_Iterations); - for(int i=0;i transforms; - btDbvtBenchmark::NilPolicy policy; - transforms.resize(cfgBenchmark6_Iterations); - for(int i=0;i rayorg; - btAlignedObjectArray raydir; - btDbvtBenchmark::NilPolicy policy; - rayorg.resize(cfgBenchmark7_Iterations); - raydir.resize(cfgBenchmark7_Iterations); - for(int i=0;i leaves; - btDbvtBenchmark::RandTree(cfgVolumeCenterScale,cfgVolumeExentsBase,cfgVolumeExentsScale,cfgLeaves,dbvt); - dbvt.optimizeTopDown(); - dbvt.extractLeaves(dbvt.m_root,leaves); - printf("[9] updates (teleport): "); - wallclock.reset(); - for(int i=0;i(leaves[rand()%cfgLeaves]), - btDbvtBenchmark::RandVolume(cfgVolumeCenterScale,cfgVolumeExentsBase,cfgVolumeExentsScale)); - } - } - const int time=(int)wallclock.getTimeMilliseconds(); - const int up=cfgBenchmark9_Passes*cfgBenchmark9_Iterations; - printf("%u ms (%i%%),(%u u/s)\r\n",time,(time-cfgBenchmark9_Reference)*100/time,up*1000/time); - } -if(cfgBenchmark10_Enable) - {// Benchmark 10 - srand(380843); - btDbvt dbvt; - btAlignedObjectArray leaves; - btAlignedObjectArray vectors; - vectors.resize(cfgBenchmark10_Iterations); - for(int i=0;i(leaves[rand()%cfgLeaves]); - btDbvtVolume v=btDbvtVolume::FromMM(l->volume.Mins()+d,l->volume.Maxs()+d); - dbvt.update(l,v); - } - } - const int time=(int)wallclock.getTimeMilliseconds(); - const int up=cfgBenchmark10_Passes*cfgBenchmark10_Iterations; - printf("%u ms (%i%%),(%u u/s)\r\n",time,(time-cfgBenchmark10_Reference)*100/time,up*1000/time); - } -if(cfgBenchmark11_Enable) - {// Benchmark 11 - srand(380843); - btDbvt dbvt; - btDbvtBenchmark::RandTree(cfgVolumeCenterScale,cfgVolumeExentsBase,cfgVolumeExentsScale,cfgLeaves,dbvt); - dbvt.optimizeTopDown(); - printf("[11] optimize (incremental): "); - wallclock.reset(); - for(int i=0;i volumes; - btAlignedObjectArray results; - volumes.resize(cfgLeaves); - results.resize(cfgLeaves); - for(int i=0;i vectors; - btDbvtBenchmark::NilPolicy policy; - vectors.resize(cfgBenchmark13_Iterations); - for(int i=0;i vectors; - btDbvtBenchmark::P14 policy; - vectors.resize(cfgBenchmark14_Iterations); - for(int i=0;i vectors; - btDbvtBenchmark::P15 policy; - vectors.resize(cfgBenchmark15_Iterations); - for(int i=0;i batch; - btDbvtBenchmark::RandTree(cfgVolumeCenterScale,cfgVolumeExentsBase,cfgVolumeExentsScale,cfgLeaves,dbvt); - dbvt.optimizeTopDown(); - batch.reserve(cfgBenchmark16_BatchCount); - printf("[16] insert/remove batch(%u): ",cfgBenchmark16_BatchCount); - wallclock.reset(); - for(int i=0;i volumes; - btAlignedObjectArray results; - volumes.resize(cfgLeaves); - results.resize(cfgLeaves); - for(int i=0;i volumes; - btAlignedObjectArray results; - btAlignedObjectArray indices; - volumes.resize(cfgLeaves); - results.resize(cfgLeaves); - indices.resize(cfgLeaves); - for(int i=0;i= 1400) - #define DBVT_USE_TEMPLATE 1 - #else - #define DBVT_USE_TEMPLATE 0 -#endif -#else -#define DBVT_USE_TEMPLATE 0 -#endif - -// Using memmov for collideOCL -#define DBVT_USE_MEMMOVE 1 - -// Enable benchmarking code -#define DBVT_ENABLE_BENCHMARK 0 - -// Inlining -#define DBVT_INLINE SIMD_FORCE_INLINE -// Align -#ifdef WIN32 -#define DBVT_ALIGN __declspec(align(16)) -#else -#define DBVT_ALIGN -#endif - -// Specific methods implementation -#ifdef WIN32_AVOID_WHEN_EMBEDDED_INSIDE_BLENDER -#define DBVT_PROXIMITY_IMPL DBVT_IMPL_SSE -#define DBVT_SELECT_IMPL DBVT_IMPL_SSE -#define DBVT_MERGE_IMPL DBVT_IMPL_SSE -#else -#define DBVT_PROXIMITY_IMPL DBVT_IMPL_GENERIC -#define DBVT_SELECT_IMPL DBVT_IMPL_GENERIC -#define DBVT_MERGE_IMPL DBVT_IMPL_GENERIC -#endif - -// -// Auto config and checks -// - -#if DBVT_USE_TEMPLATE -#define DBVT_VIRTUAL -#define DBVT_VIRTUAL_DTOR(a) -#define DBVT_PREFIX template -#define DBVT_IPOLICY T& policy -#define DBVT_CHECKTYPE static const ICollide& typechecker=*(T*)0; -#else -#define DBVT_VIRTUAL_DTOR(a) virtual ~a() {} -#define DBVT_VIRTUAL virtual -#define DBVT_PREFIX -#define DBVT_IPOLICY ICollide& policy -#define DBVT_CHECKTYPE -#endif - -#if DBVT_USE_MEMMOVE -#ifndef __CELLOS_LV2__ -#include -#endif -#include -#endif - -#ifndef DBVT_USE_TEMPLATE -#error "DBVT_USE_TEMPLATE undefined" -#endif - -#ifndef DBVT_USE_MEMMOVE -#error "DBVT_USE_MEMMOVE undefined" -#endif - -#ifndef DBVT_ENABLE_BENCHMARK -#error "DBVT_ENABLE_BENCHMARK undefined" -#endif - -#ifndef DBVT_PROXIMITY_IMPL -#error "DBVT_PROXIMITY_IMPL undefined" -#endif - -#ifndef DBVT_SELECT_IMPL -#error "DBVT_SELECT_IMPL undefined" -#endif - -#ifndef DBVT_MERGE_IMPL -#error "DBVT_MERGE_IMPL undefined" -#endif - -// -// Defaults volumes -// - -/* btDbvtAabbMm */ -struct btDbvtAabbMm -{ -DBVT_INLINE btVector3 Center() const { return((mi+mx)/2); } -DBVT_INLINE btVector3 Lengths() const { return(mx-mi); } -DBVT_INLINE btVector3 Extents() const { return((mx-mi)/2); } -DBVT_INLINE const btVector3& Mins() const { return(mi); } -DBVT_INLINE const btVector3& Maxs() const { return(mx); } -static inline btDbvtAabbMm FromCE(const btVector3& c,const btVector3& e); -static inline btDbvtAabbMm FromCR(const btVector3& c,btScalar r); -static inline btDbvtAabbMm FromMM(const btVector3& mi,const btVector3& mx); -static inline btDbvtAabbMm FromPoints(const btVector3* pts,int n); -static inline btDbvtAabbMm FromPoints(const btVector3** ppts,int n); -DBVT_INLINE void Expand(const btVector3 e); -DBVT_INLINE void SignedExpand(const btVector3 e); -DBVT_INLINE bool Contain(const btDbvtAabbMm& a) const; -DBVT_INLINE int Classify(const btVector3& n,btScalar o,int s) const; -DBVT_INLINE btScalar ProjectMinimum(const btVector3& v,unsigned signs) const; -DBVT_INLINE friend bool Intersect( const btDbvtAabbMm& a, - const btDbvtAabbMm& b); -DBVT_INLINE friend bool Intersect( const btDbvtAabbMm& a, - const btDbvtAabbMm& b, - const btTransform& xform); -DBVT_INLINE friend bool Intersect( const btDbvtAabbMm& a, - const btVector3& b); -DBVT_INLINE friend bool Intersect( const btDbvtAabbMm& a, - const btVector3& org, - const btVector3& invdir, - const unsigned* signs); -DBVT_INLINE friend btScalar Proximity( const btDbvtAabbMm& a, - const btDbvtAabbMm& b); -DBVT_INLINE friend int Select( const btDbvtAabbMm& o, - const btDbvtAabbMm& a, - const btDbvtAabbMm& b); -DBVT_INLINE friend void Merge( const btDbvtAabbMm& a, - const btDbvtAabbMm& b, - btDbvtAabbMm& r); -DBVT_INLINE friend bool NotEqual( const btDbvtAabbMm& a, - const btDbvtAabbMm& b); -private: -DBVT_INLINE void AddSpan(const btVector3& d,btScalar& smi,btScalar& smx) const; -private: -btVector3 mi,mx; -}; - -// Types -typedef btDbvtAabbMm btDbvtVolume; - -/* btDbvtNode */ -struct btDbvtNode -{ - btDbvtVolume volume; - btDbvtNode* parent; - bool isleaf() const { return(childs[1]==0); } - bool isinternal() const { return(!isleaf()); } - union { - btDbvtNode* childs[2]; - void* data; - }; -}; - -///The btDbvt class implements a fast dynamic bounding volume tree based on axis aligned bounding boxes (aabb tree). -///This btDbvt is used for soft body collision detection and for the btDbvtBroadphase. It has a fast insert, remove and update of nodes. -///Unlike the btQuantizedBvh, nodes can be dynamically moved around, which allows for change in topology of the underlying data structure. -struct btDbvt - { - - - /* Stack element */ - struct sStkNN - { - const btDbvtNode* a; - const btDbvtNode* b; - sStkNN() {} - sStkNN(const btDbvtNode* na,const btDbvtNode* nb) : a(na),b(nb) {} - }; - struct sStkNP - { - const btDbvtNode* node; - int mask; - sStkNP(const btDbvtNode* n,unsigned m) : node(n),mask(m) {} - }; - struct sStkNPS - { - const btDbvtNode* node; - int mask; - btScalar value; - sStkNPS() {} - sStkNPS(const btDbvtNode* n,unsigned m,btScalar v) : node(n),mask(m),value(v) {} - }; - struct sStkCLN - { - const btDbvtNode* node; - btDbvtNode* parent; - sStkCLN(const btDbvtNode* n,btDbvtNode* p) : node(n),parent(p) {} - }; - // Policies/Interfaces - - /* ICollide */ - struct ICollide - { - DBVT_VIRTUAL_DTOR(ICollide) - DBVT_VIRTUAL void Process(const btDbvtNode*,const btDbvtNode*) {} - DBVT_VIRTUAL void Process(const btDbvtNode*) {} - DBVT_VIRTUAL void Process(const btDbvtNode* n,btScalar) { Process(n); } - DBVT_VIRTUAL bool Descent(const btDbvtNode*) { return(true); } - DBVT_VIRTUAL bool AllLeaves(const btDbvtNode*) { return(true); } - }; - /* IWriter */ - struct IWriter - { - virtual ~IWriter() {} - virtual void Prepare(const btDbvtNode* root,int numnodes)=0; - virtual void WriteNode(const btDbvtNode*,int index,int parent,int child0,int child1)=0; - virtual void WriteLeaf(const btDbvtNode*,int index,int parent)=0; - }; - /* IClone */ - struct IClone - { - virtual ~IClone() {} - virtual void CloneLeaf(btDbvtNode*) {} - }; - - // Constants - enum { - SIMPLE_STACKSIZE = 64, - DOUBLE_STACKSIZE = SIMPLE_STACKSIZE*2 - }; - - // Fields - btDbvtNode* m_root; - btDbvtNode* m_free; - int m_lkhd; - int m_leaves; - unsigned m_opath; - // Methods - btDbvt(); - ~btDbvt(); - void clear(); - bool empty() const { return(0==m_root); } - void optimizeBottomUp(); - void optimizeTopDown(int bu_treshold=128); - void optimizeIncremental(int passes); - btDbvtNode* insert(const btDbvtVolume& box,void* data); - void update(btDbvtNode* leaf,int lookahead=-1); - void update(btDbvtNode* leaf,const btDbvtVolume& volume); - bool update(btDbvtNode* leaf,btDbvtVolume volume,const btVector3& velocity,btScalar margin); - bool update(btDbvtNode* leaf,btDbvtVolume volume,const btVector3& velocity); - bool update(btDbvtNode* leaf,btDbvtVolume volume,btScalar margin); - void remove(btDbvtNode* leaf); - void write(IWriter* iwriter) const; - void clone(btDbvt& dest,IClone* iclone=0) const; - static int maxdepth(const btDbvtNode* node); - static int countLeaves(const btDbvtNode* node); - static void extractLeaves(const btDbvtNode* node,btAlignedObjectArray& leaves); - #if DBVT_ENABLE_BENCHMARK - static void benchmark(); - #else - static void benchmark(){} - #endif - // DBVT_IPOLICY must support ICollide policy/interface - DBVT_PREFIX - static void enumNodes( const btDbvtNode* root, - DBVT_IPOLICY); - DBVT_PREFIX - static void enumLeaves( const btDbvtNode* root, - DBVT_IPOLICY); - DBVT_PREFIX - static void collideTT( const btDbvtNode* root0, - const btDbvtNode* root1, - DBVT_IPOLICY); - DBVT_PREFIX - static void collideTT( const btDbvtNode* root0, - const btDbvtNode* root1, - const btTransform& xform, - DBVT_IPOLICY); - DBVT_PREFIX - static void collideTT( const btDbvtNode* root0, - const btTransform& xform0, - const btDbvtNode* root1, - const btTransform& xform1, - DBVT_IPOLICY); - DBVT_PREFIX - static void collideTV( const btDbvtNode* root, - const btDbvtVolume& volume, - DBVT_IPOLICY); - DBVT_PREFIX - static void collideRAY( const btDbvtNode* root, - const btVector3& origin, - const btVector3& direction, - DBVT_IPOLICY); - DBVT_PREFIX - static void collideKDOP(const btDbvtNode* root, - const btVector3* normals, - const btScalar* offsets, - int count, - DBVT_IPOLICY); - DBVT_PREFIX - static void collideOCL( const btDbvtNode* root, - const btVector3* normals, - const btScalar* offsets, - const btVector3& sortaxis, - int count, - DBVT_IPOLICY, - bool fullsort=true); - DBVT_PREFIX - static void collideTU( const btDbvtNode* root, - DBVT_IPOLICY); - // Helpers - static DBVT_INLINE int nearest(const int* i,const btDbvt::sStkNPS* a,btScalar v,int l,int h) - { - int m=0; - while(l>1; - if(a[i[m]].value>=v) l=m+1; else h=m; - } - return(h); - } - static DBVT_INLINE int allocate( btAlignedObjectArray& ifree, - btAlignedObjectArray& stock, - const sStkNPS& value) - { - int i; - if(ifree.size()>0) - { i=ifree[ifree.size()-1];ifree.pop_back();stock[i]=value; } - else - { i=stock.size();stock.push_back(value); } - return(i); - } - // - private: - btDbvt(const btDbvt&) {} - }; - -// -// Inline's -// - -// -inline btDbvtAabbMm btDbvtAabbMm::FromCE(const btVector3& c,const btVector3& e) -{ -btDbvtAabbMm box; -box.mi=c-e;box.mx=c+e; -return(box); -} - -// -inline btDbvtAabbMm btDbvtAabbMm::FromCR(const btVector3& c,btScalar r) -{ -return(FromCE(c,btVector3(r,r,r))); -} - -// -inline btDbvtAabbMm btDbvtAabbMm::FromMM(const btVector3& mi,const btVector3& mx) -{ -btDbvtAabbMm box; -box.mi=mi;box.mx=mx; -return(box); -} - -// -inline btDbvtAabbMm btDbvtAabbMm::FromPoints(const btVector3* pts,int n) -{ -btDbvtAabbMm box; -box.mi=box.mx=pts[0]; -for(int i=1;i0) mx.setX(mx.x()+e.x()); else mi.setX(mi.x()+e.x()); -if(e.y()>0) mx.setY(mx.y()+e.y()); else mi.setY(mi.y()+e.y()); -if(e.z()>0) mx.setZ(mx.z()+e.z()); else mi.setZ(mi.z()+e.z()); -} - -// -DBVT_INLINE bool btDbvtAabbMm::Contain(const btDbvtAabbMm& a) const -{ -return( (mi.x()<=a.mi.x())&& - (mi.y()<=a.mi.y())&& - (mi.z()<=a.mi.z())&& - (mx.x()>=a.mx.x())&& - (mx.y()>=a.mx.y())&& - (mx.z()>=a.mx.z())); -} - -// -DBVT_INLINE int btDbvtAabbMm::Classify(const btVector3& n,btScalar o,int s) const -{ -btVector3 pi,px; -switch(s) - { - case (0+0+0): px=btVector3(mi.x(),mi.y(),mi.z()); - pi=btVector3(mx.x(),mx.y(),mx.z());break; - case (1+0+0): px=btVector3(mx.x(),mi.y(),mi.z()); - pi=btVector3(mi.x(),mx.y(),mx.z());break; - case (0+2+0): px=btVector3(mi.x(),mx.y(),mi.z()); - pi=btVector3(mx.x(),mi.y(),mx.z());break; - case (1+2+0): px=btVector3(mx.x(),mx.y(),mi.z()); - pi=btVector3(mi.x(),mi.y(),mx.z());break; - case (0+0+4): px=btVector3(mi.x(),mi.y(),mx.z()); - pi=btVector3(mx.x(),mx.y(),mi.z());break; - case (1+0+4): px=btVector3(mx.x(),mi.y(),mx.z()); - pi=btVector3(mi.x(),mx.y(),mi.z());break; - case (0+2+4): px=btVector3(mi.x(),mx.y(),mx.z()); - pi=btVector3(mx.x(),mi.y(),mi.z());break; - case (1+2+4): px=btVector3(mx.x(),mx.y(),mx.z()); - pi=btVector3(mi.x(),mi.y(),mi.z());break; - } -if((dot(n,px)+o)<0) return(-1); -if((dot(n,pi)+o)>=0) return(+1); -return(0); -} - -// -DBVT_INLINE btScalar btDbvtAabbMm::ProjectMinimum(const btVector3& v,unsigned signs) const -{ -const btVector3* b[]={&mx,&mi}; -const btVector3 p( b[(signs>>0)&1]->x(), - b[(signs>>1)&1]->y(), - b[(signs>>2)&1]->z()); -return(dot(p,v)); -} - -// -DBVT_INLINE void btDbvtAabbMm::AddSpan(const btVector3& d,btScalar& smi,btScalar& smx) const -{ -for(int i=0;i<3;++i) - { - if(d[i]<0) - { smi+=mx[i]*d[i];smx+=mi[i]*d[i]; } - else - { smi+=mi[i]*d[i];smx+=mx[i]*d[i]; } - } -} - -// -DBVT_INLINE bool Intersect( const btDbvtAabbMm& a, - const btDbvtAabbMm& b) -{ -return( (a.mi.x()<=b.mx.x())&& - (a.mx.x()>=b.mi.x())&& - (a.mi.y()<=b.mx.y())&& - (a.mx.y()>=b.mi.y())&& - (a.mi.z()<=b.mx.z())&& - (a.mx.z()>=b.mi.z())); -} - -// -DBVT_INLINE bool Intersect( const btDbvtAabbMm& a, - const btDbvtAabbMm& b, - const btTransform& xform) -{ -const btVector3 d0=xform*b.Center()-a.Center(); -const btVector3 d1=d0*xform.getBasis(); -btScalar s0[2]={0,0}; -btScalar s1[2]={dot(xform.getOrigin(),d0),s1[0]}; -a.AddSpan(d0,s0[0],s0[1]); -b.AddSpan(d1,s1[0],s1[1]); -if(s0[0]>(s1[1])) return(false); -if(s0[1]<(s1[0])) return(false); -return(true); -} - -// -DBVT_INLINE bool Intersect( const btDbvtAabbMm& a, - const btVector3& b) -{ -return( (b.x()>=a.mi.x())&& - (b.y()>=a.mi.y())&& - (b.z()>=a.mi.z())&& - (b.x()<=a.mx.x())&& - (b.y()<=a.mx.y())&& - (b.z()<=a.mx.z())); -} - -// -DBVT_INLINE bool Intersect( const btDbvtAabbMm& a, - const btVector3& org, - const btVector3& invdir, - const unsigned* signs) -{ -#if 0 -const btVector3 b0((a.mi-org)*invdir); -const btVector3 b1((a.mx-org)*invdir); -const btVector3 tmin(btMin(b0[0],b1[0]),btMin(b0[1],b1[1]),btMin(b0[2],b1[2])); -const btVector3 tmax(btMax(b0[0],b1[0]),btMax(b0[1],b1[1]),btMax(b0[2],b1[2])); -const btScalar tin=btMax(tmin[0],btMax(tmin[1],tmin[2])); -const btScalar tout=btMin(tmax[0],btMin(tmax[1],tmax[2])); -return(tinx()-org[0])*invdir[0]; -btScalar txmax=(bounds[1-signs[0]]->x()-org[0])*invdir[0]; -const btScalar tymin=(bounds[ signs[1]]->y()-org[1])*invdir[1]; -const btScalar tymax=(bounds[1-signs[1]]->y()-org[1])*invdir[1]; -if((txmin>tymax)||(tymin>txmax)) return(false); -if(tymin>txmin) txmin=tymin; -if(tymaxz()-org[2])*invdir[2]; -const btScalar tzmax=(bounds[1-signs[2]]->z()-org[2])*invdir[2]; -if((txmin>tzmax)||(tzmin>txmax)) return(false); -if(tzmin>txmin) txmin=tzmin; -if(tzmax0); -#endif -} - -// -DBVT_INLINE btScalar Proximity( const btDbvtAabbMm& a, - const btDbvtAabbMm& b) -{ -#if DBVT_PROXIMITY_IMPL == DBVT_IMPL_SSE -DBVT_ALIGN btScalar r[1]; -static DBVT_ALIGN const unsigned __int32 mask[]={0x7fffffff,0x7fffffff,0x7fffffff,0x7fffffff}; -__asm - { - mov eax,a - mov ecx,b - movaps xmm0,[eax] - movaps xmm2,[ecx] - movaps xmm1,[eax+16] - movaps xmm3,[ecx+16] - addps xmm0,xmm1 - addps xmm2,xmm3 - subps xmm0,xmm2 - andps xmm0,mask - movhlps xmm1,xmm0 - addps xmm0,xmm1 - pshufd xmm1,xmm0,1 - addss xmm0,xmm1 - movss r,xmm0 - } -return(r[0]); -#else -const btVector3 d=(a.mi+a.mx)-(b.mi+b.mx); -return(btFabs(d.x())+btFabs(d.y())+btFabs(d.z())); -#endif -} - -// -DBVT_INLINE int Select( const btDbvtAabbMm& o, - const btDbvtAabbMm& a, - const btDbvtAabbMm& b) -{ -#if DBVT_SELECT_IMPL == DBVT_IMPL_SSE -DBVT_ALIGN __int32 r[1]; -static DBVT_ALIGN const unsigned __int32 mask[]={0x7fffffff,0x7fffffff,0x7fffffff,0x7fffffff}; -__asm - { - mov eax,o - mov ecx,a - mov edx,b - movaps xmm0,[eax] - movaps xmm5,mask - addps xmm0,[eax+16] - movaps xmm1,[ecx] - movaps xmm2,[edx] - addps xmm1,[ecx+16] - addps xmm2,[edx+16] - subps xmm1,xmm0 - subps xmm2,xmm0 - andps xmm1,xmm5 - andps xmm2,xmm5 - movhlps xmm3,xmm1 - movhlps xmm4,xmm2 - addps xmm1,xmm3 - addps xmm2,xmm4 - pshufd xmm3,xmm1,1 - pshufd xmm4,xmm2,1 - addss xmm1,xmm3 - addss xmm2,xmm4 - cmpless xmm2,xmm1 - movss r,xmm2 - } -return(r[0]&1); -#else -return(Proximity(o,a)b.mx[i]) r.mx[i]=a.mx[i]; else r.mx[i]=b.mx[i]; - } -#endif -} - -// -DBVT_INLINE bool NotEqual( const btDbvtAabbMm& a, - const btDbvtAabbMm& b) -{ -return( (a.mi.x()!=b.mi.x())|| - (a.mi.y()!=b.mi.y())|| - (a.mi.z()!=b.mi.z())|| - (a.mx.x()!=b.mx.x())|| - (a.mx.y()!=b.mx.y())|| - (a.mx.z()!=b.mx.z())); -} - -// -// Inline's -// - -// -DBVT_PREFIX -inline void btDbvt::enumNodes( const btDbvtNode* root, - DBVT_IPOLICY) -{ -DBVT_CHECKTYPE -policy.Process(root); -if(root->isinternal()) - { - enumNodes(root->childs[0],policy); - enumNodes(root->childs[1],policy); - } -} - -// -DBVT_PREFIX -inline void btDbvt::enumLeaves( const btDbvtNode* root, - DBVT_IPOLICY) -{ -DBVT_CHECKTYPE -if(root->isinternal()) - { - enumLeaves(root->childs[0],policy); - enumLeaves(root->childs[1],policy); - } - else - { - policy.Process(root); - } -} - -// -DBVT_PREFIX -inline void btDbvt::collideTT( const btDbvtNode* root0, - const btDbvtNode* root1, - DBVT_IPOLICY) -{ -DBVT_CHECKTYPE -if(root0&&root1) - { - btAlignedObjectArray stack; - int depth=1; - int treshold=DOUBLE_STACKSIZE-4; - stack.resize(DOUBLE_STACKSIZE); - stack[0]=sStkNN(root0,root1); - do { - sStkNN p=stack[--depth]; - if(depth>treshold) - { - stack.resize(stack.size()*2); - treshold=stack.size()-4; - } - if(p.a==p.b) - { - if(p.a->isinternal()) - { - stack[depth++]=sStkNN(p.a->childs[0],p.a->childs[0]); - stack[depth++]=sStkNN(p.a->childs[1],p.a->childs[1]); - stack[depth++]=sStkNN(p.a->childs[0],p.a->childs[1]); - } - } - else if(Intersect(p.a->volume,p.b->volume)) - { - if(p.a->isinternal()) - { - if(p.b->isinternal()) - { - stack[depth++]=sStkNN(p.a->childs[0],p.b->childs[0]); - stack[depth++]=sStkNN(p.a->childs[1],p.b->childs[0]); - stack[depth++]=sStkNN(p.a->childs[0],p.b->childs[1]); - stack[depth++]=sStkNN(p.a->childs[1],p.b->childs[1]); - } - else - { - stack[depth++]=sStkNN(p.a->childs[0],p.b); - stack[depth++]=sStkNN(p.a->childs[1],p.b); - } - } - else - { - if(p.b->isinternal()) - { - stack[depth++]=sStkNN(p.a,p.b->childs[0]); - stack[depth++]=sStkNN(p.a,p.b->childs[1]); - } - else - { - policy.Process(p.a,p.b); - } - } - } - } while(depth); - } -} - -// -DBVT_PREFIX -inline void btDbvt::collideTT( const btDbvtNode* root0, - const btDbvtNode* root1, - const btTransform& xform, - DBVT_IPOLICY) -{ -DBVT_CHECKTYPE -if(root0&&root1) - { - btAlignedObjectArray stack; - int depth=1; - int treshold=DOUBLE_STACKSIZE-4; - stack.resize(DOUBLE_STACKSIZE); - stack[0]=sStkNN(root0,root1); - do { - sStkNN p=stack[--depth]; - if(Intersect(p.a->volume,p.b->volume,xform)) - { - if(depth>treshold) - { - stack.resize(stack.size()*2); - treshold=stack.size()-4; - } - if(p.a->isinternal()) - { - if(p.b->isinternal()) - { - stack[depth++]=sStkNN(p.a->childs[0],p.b->childs[0]); - stack[depth++]=sStkNN(p.a->childs[1],p.b->childs[0]); - stack[depth++]=sStkNN(p.a->childs[0],p.b->childs[1]); - stack[depth++]=sStkNN(p.a->childs[1],p.b->childs[1]); - } - else - { - stack[depth++]=sStkNN(p.a->childs[0],p.b); - stack[depth++]=sStkNN(p.a->childs[1],p.b); - } - } - else - { - if(p.b->isinternal()) - { - stack[depth++]=sStkNN(p.a,p.b->childs[0]); - stack[depth++]=sStkNN(p.a,p.b->childs[1]); - } - else - { - policy.Process(p.a,p.b); - } - } - } - } while(depth); - } -} - -// -DBVT_PREFIX -inline void btDbvt::collideTT( const btDbvtNode* root0, - const btTransform& xform0, - const btDbvtNode* root1, - const btTransform& xform1, - DBVT_IPOLICY) -{ -const btTransform xform=xform0.inverse()*xform1; -collideTT(root0,root1,xform,policy); -} - -// -DBVT_PREFIX -inline void btDbvt::collideTV( const btDbvtNode* root, - const btDbvtVolume& volume, - DBVT_IPOLICY) -{ -DBVT_CHECKTYPE -if(root) - { - btAlignedObjectArray stack; - stack.reserve(SIMPLE_STACKSIZE); - stack.push_back(root); - do { - const btDbvtNode* n=stack[stack.size()-1]; - stack.pop_back(); - if(Intersect(n->volume,volume)) - { - if(n->isinternal()) - { - stack.push_back(n->childs[0]); - stack.push_back(n->childs[1]); - } - else - { - policy.Process(n); - } - } - } while(stack.size()>0); - } -} - -// -DBVT_PREFIX -inline void btDbvt::collideRAY( const btDbvtNode* root, - const btVector3& origin, - const btVector3& direction, - DBVT_IPOLICY) -{ -DBVT_CHECKTYPE -if(root) - { - const btVector3 normal=direction.normalized(); - const btVector3 invdir( 1/normal.x(), - 1/normal.y(), - 1/normal.z()); - const unsigned signs[]={ direction.x()<0, - direction.y()<0, - direction.z()<0}; - btAlignedObjectArray stack; - stack.reserve(SIMPLE_STACKSIZE); - stack.push_back(root); - do { - const btDbvtNode* node=stack[stack.size()-1]; - stack.pop_back(); - if(Intersect(node->volume,origin,invdir,signs)) - { - if(node->isinternal()) - { - stack.push_back(node->childs[0]); - stack.push_back(node->childs[1]); - } - else - { - policy.Process(node); - } - } - } while(stack.size()); - } -} - -// -DBVT_PREFIX -inline void btDbvt::collideKDOP(const btDbvtNode* root, - const btVector3* normals, - const btScalar* offsets, - int count, - DBVT_IPOLICY) -{ -DBVT_CHECKTYPE -if(root) - { - const int inside=(1< stack; - int signs[sizeof(unsigned)*8]; - btAssert(count=0)?1:0)+ - ((normals[i].y()>=0)?2:0)+ - ((normals[i].z()>=0)?4:0); - } - stack.reserve(SIMPLE_STACKSIZE); - stack.push_back(sStkNP(root,0)); - do { - sStkNP se=stack[stack.size()-1]; - bool out=false; - stack.pop_back(); - for(int i=0,j=1;(!out)&&(ivolume.Classify(normals[i],offsets[i],signs[i]); - switch(side) - { - case -1: out=true;break; - case +1: se.mask|=j;break; - } - } - } - if(!out) - { - if((se.mask!=inside)&&(se.node->isinternal())) - { - stack.push_back(sStkNP(se.node->childs[0],se.mask)); - stack.push_back(sStkNP(se.node->childs[1],se.mask)); - } - else - { - if(policy.AllLeaves(se.node)) enumLeaves(se.node,policy); - } - } - } while(stack.size()); - } -} - -// -DBVT_PREFIX -inline void btDbvt::collideOCL( const btDbvtNode* root, - const btVector3* normals, - const btScalar* offsets, - const btVector3& sortaxis, - int count, - DBVT_IPOLICY, - bool fsort) -{ -DBVT_CHECKTYPE -if(root) - { - const unsigned srtsgns=(sortaxis[0]>=0?1:0)+ - (sortaxis[1]>=0?2:0)+ - (sortaxis[2]>=0?4:0); - const int inside=(1< stock; - btAlignedObjectArray ifree; - btAlignedObjectArray stack; - int signs[sizeof(unsigned)*8]; - btAssert(count=0)?1:0)+ - ((normals[i].y()>=0)?2:0)+ - ((normals[i].z()>=0)?4:0); - } - stock.reserve(SIMPLE_STACKSIZE); - stack.reserve(SIMPLE_STACKSIZE); - ifree.reserve(SIMPLE_STACKSIZE); - stack.push_back(allocate(ifree,stock,sStkNPS(root,0,root->volume.ProjectMinimum(sortaxis,srtsgns)))); - do { - const int id=stack[stack.size()-1]; - sStkNPS se=stock[id]; - stack.pop_back();ifree.push_back(id); - if(se.mask!=inside) - { - bool out=false; - for(int i=0,j=1;(!out)&&(ivolume.Classify(normals[i],offsets[i],signs[i]); - switch(side) - { - case -1: out=true;break; - case +1: se.mask|=j;break; - } - } - } - if(out) continue; - } - if(policy.Descent(se.node)) - { - if(se.node->isinternal()) - { - const btDbvtNode* pns[]={ se.node->childs[0],se.node->childs[1]}; - sStkNPS nes[]={ sStkNPS(pns[0],se.mask,pns[0]->volume.ProjectMinimum(sortaxis,srtsgns)), - sStkNPS(pns[1],se.mask,pns[1]->volume.ProjectMinimum(sortaxis,srtsgns))}; - const int q=nes[0].value0)) - { - /* Insert 0 */ - j=nearest(&stack[0],&stock[0],nes[q].value,0,stack.size()); - stack.push_back(0); - #if DBVT_USE_MEMMOVE - memmove(&stack[j+1],&stack[j],sizeof(int)*(stack.size()-j-1)); - #else - for(int k=stack.size()-1;k>j;--k) stack[k]=stack[k-1]; - #endif - stack[j]=allocate(ifree,stock,nes[q]); - /* Insert 1 */ - j=nearest(&stack[0],&stock[0],nes[1-q].value,j,stack.size()); - stack.push_back(0); - #if DBVT_USE_MEMMOVE - memmove(&stack[j+1],&stack[j],sizeof(int)*(stack.size()-j-1)); - #else - for(int k=stack.size()-1;k>j;--k) stack[k]=stack[k-1]; - #endif - stack[j]=allocate(ifree,stock,nes[1-q]); - } - else - { - stack.push_back(allocate(ifree,stock,nes[q])); - stack.push_back(allocate(ifree,stock,nes[1-q])); - } - } - else - { - policy.Process(se.node,se.value); - } - } - } while(stack.size()); - } -} - -// -DBVT_PREFIX -inline void btDbvt::collideTU( const btDbvtNode* root, - DBVT_IPOLICY) -{ -DBVT_CHECKTYPE -if(root) - { - btAlignedObjectArray stack; - stack.reserve(SIMPLE_STACKSIZE); - stack.push_back(root); - do { - const btDbvtNode* n=stack[stack.size()-1]; - stack.pop_back(); - if(policy.Descent(n)) - { - if(n->isinternal()) - { stack.push_back(n->childs[0]);stack.push_back(n->childs[1]); } - else - { policy.Process(n); } - } - } while(stack.size()>0); - } -} - -// -// PP Cleanup -// - -#undef DBVT_USE_MEMMOVE -#undef DBVT_USE_TEMPLATE -#undef DBVT_VIRTUAL_DTOR -#undef DBVT_VIRTUAL -#undef DBVT_PREFIX -#undef DBVT_IPOLICY -#undef DBVT_CHECKTYPE -#undef DBVT_IMPL_GENERIC -#undef DBVT_IMPL_FPU0x86 -#undef DBVT_IMPL_SSE - -#endif diff --git a/extern/bullet2/src/BulletCollision/BroadphaseCollision/btDbvtBroadphase.cpp b/extern/bullet2/src/BulletCollision/BroadphaseCollision/btDbvtBroadphase.cpp deleted file mode 100644 index c6086f28f19..00000000000 --- a/extern/bullet2/src/BulletCollision/BroadphaseCollision/btDbvtBroadphase.cpp +++ /dev/null @@ -1,344 +0,0 @@ -/* -Bullet Continuous Collision Detection and Physics Library -Copyright (c) 2003-2007 Erwin Coumans http://continuousphysics.com/Bullet/ - -This software is provided 'as-is', without any express or implied warranty. -In no event will the authors be held liable for any damages arising from the use of this software. -Permission is granted to anyone to use this software for any purpose, -including commercial applications, and to alter it and redistribute it freely, -subject to the following restrictions: - -1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. -2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. -3. This notice may not be removed or altered from any source distribution. -*/ -///btDbvtBroadphase implementation by Nathanael Presson - -#include "btDbvtBroadphase.h" - -// -// Profiling -// - -#if DBVT_BP_PROFILE -#include -struct ProfileScope - { - ProfileScope(btClock& clock,unsigned long& value) - { - m_clock=&clock; - m_value=&value; - m_base=clock.getTimeMicroseconds(); - } - ~ProfileScope() - { - (*m_value)+=m_clock->getTimeMicroseconds()-m_base; - } - btClock* m_clock; - unsigned long* m_value; - unsigned long m_base; - }; -#define SPC(_value_) ProfileScope spc_scope(m_clock,_value_) -#else -#define SPC(_value_) -#endif - -// -// Helpers -// - -// -template -static inline void listappend(T* item,T*& list) -{ -item->links[0]=0; -item->links[1]=list; -if(list) list->links[0]=item; -list=item; -} - -// -template -static inline void listremove(T* item,T*& list) -{ -if(item->links[0]) item->links[0]->links[1]=item->links[1]; else list=item->links[1]; -if(item->links[1]) item->links[1]->links[0]=item->links[0]; -} - -// -template -static inline int listcount(T* root) -{ -int n=0; -while(root) { ++n;root=root->links[1]; } -return(n); -} - -// -template -static inline void clear(T& value) -{ -static const struct ZeroDummy : T {} zerodummy; -value=zerodummy; -} - -// -// Colliders -// - -/* Tree collider */ -struct btDbvtTreeCollider : btDbvt::ICollide -{ -btDbvtBroadphase* pbp; - btDbvtTreeCollider(btDbvtBroadphase* p) : pbp(p) {} -void Process(const btDbvtNode* na,const btDbvtNode* nb) - { - btDbvtProxy* pa=(btDbvtProxy*)na->data; - btDbvtProxy* pb=(btDbvtProxy*)nb->data; - #if DBVT_BP_DISCRETPAIRS - if(Intersect(pa->aabb,pb->aabb)) - #endif - { - if(pa>pb) btSwap(pa,pb); - pbp->m_paircache->addOverlappingPair(pa,pb); - } - } -}; - -// -// btDbvtBroadphase -// - -// -btDbvtBroadphase::btDbvtBroadphase(btOverlappingPairCache* paircache) -{ -m_releasepaircache = (paircache!=0)?false:true; -m_predictedframes = 2; -m_stageCurrent = 0; -m_fupdates = 1; -m_dupdates = 1; -m_paircache = paircache? - paircache : - new(btAlignedAlloc(sizeof(btHashedOverlappingPairCache),16)) btHashedOverlappingPairCache(); -m_gid = 0; -m_pid = 0; -for(int i=0;i<=STAGECOUNT;++i) - { - m_stageRoots[i]=0; - } -#if DBVT_BP_PROFILE -clear(m_profiling); -#endif -} - -// -btDbvtBroadphase::~btDbvtBroadphase() -{ -if(m_releasepaircache) -{ - m_paircache->~btOverlappingPairCache(); - btAlignedFree(m_paircache); -} -} - -// -btBroadphaseProxy* btDbvtBroadphase::createProxy( const btVector3& aabbMin, - const btVector3& aabbMax, - int /*shapeType*/, - void* userPtr, - short int collisionFilterGroup, - short int collisionFilterMask, - btDispatcher* /*dispatcher*/, - void* /*multiSapProxy*/) -{ -btDbvtProxy* proxy=new(btAlignedAlloc(sizeof(btDbvtProxy),16)) btDbvtProxy( userPtr, - collisionFilterGroup, - collisionFilterMask); -proxy->aabb = btDbvtVolume::FromMM(aabbMin,aabbMax); -proxy->leaf = m_sets[0].insert(proxy->aabb,proxy); -proxy->stage = m_stageCurrent; -proxy->m_uniqueId = ++m_gid; -listappend(proxy,m_stageRoots[m_stageCurrent]); -return(proxy); -} - -// -void btDbvtBroadphase::destroyProxy( btBroadphaseProxy* absproxy, - btDispatcher* dispatcher) -{ -btDbvtProxy* proxy=(btDbvtProxy*)absproxy; -if(proxy->stage==STAGECOUNT) - m_sets[1].remove(proxy->leaf); - else - m_sets[0].remove(proxy->leaf); -listremove(proxy,m_stageRoots[proxy->stage]); -m_paircache->removeOverlappingPairsContainingProxy(proxy,dispatcher); -btAlignedFree(proxy); -} - -// -void btDbvtBroadphase::setAabb( btBroadphaseProxy* absproxy, - const btVector3& aabbMin, - const btVector3& aabbMax, - btDispatcher* /*dispatcher*/) -{ -btDbvtProxy* proxy=(btDbvtProxy*)absproxy; -btDbvtVolume aabb=btDbvtVolume::FromMM(aabbMin,aabbMax); -if(NotEqual(aabb,proxy->leaf->volume)) - { - if(proxy->stage==STAGECOUNT) - {/* fixed -> dynamic set */ - m_sets[1].remove(proxy->leaf); - proxy->leaf=m_sets[0].insert(aabb,proxy); - } - else - {/* dynamic set */ - if(Intersect(proxy->leaf->volume,aabb)) - {/* Moving */ - const btVector3 delta=(aabbMin+aabbMax)/2-proxy->aabb.Center(); - #ifdef DBVT_BP_MARGIN - m_sets[0].update(proxy->leaf,aabb,delta*m_predictedframes,DBVT_BP_MARGIN); - #else - m_sets[0].update(proxy->leaf,aabb,delta*m_predictedframes); - #endif - } - else - {/* Teleporting */ - m_sets[0].update(proxy->leaf,aabb); - } - } - listremove(proxy,m_stageRoots[proxy->stage]); - proxy->aabb = aabb; - proxy->stage = m_stageCurrent; - listappend(proxy,m_stageRoots[m_stageCurrent]); - } -} - -// -void btDbvtBroadphase::calculateOverlappingPairs(btDispatcher* dispatcher) -{ -collide(dispatcher); -#if DBVT_BP_PROFILE -if(0==(m_pid%DBVT_BP_PROFILING_RATE)) - { - printf("fixed(%u) dynamics(%u) pairs(%u)\r\n",m_sets[1].m_leaves,m_sets[0].m_leaves,m_paircache->getNumOverlappingPairs()); - unsigned int total=m_profiling.m_total; - if(total<=0) total=1; - printf("ddcollide: %u%% (%uus)\r\n",(50+m_profiling.m_ddcollide*100)/total,m_profiling.m_ddcollide/DBVT_BP_PROFILING_RATE); - printf("fdcollide: %u%% (%uus)\r\n",(50+m_profiling.m_fdcollide*100)/total,m_profiling.m_fdcollide/DBVT_BP_PROFILING_RATE); - printf("cleanup: %u%% (%uus)\r\n",(50+m_profiling.m_cleanup*100)/total,m_profiling.m_cleanup/DBVT_BP_PROFILING_RATE); - printf("total: %uus\r\n",total/DBVT_BP_PROFILING_RATE); - const unsigned long sum=m_profiling.m_ddcollide+ - m_profiling.m_fdcollide+ - m_profiling.m_cleanup; - printf("leaked: %u%% (%uus)\r\n",100-((50+sum*100)/total),(total-sum)/DBVT_BP_PROFILING_RATE); - printf("job counts: %u%%\r\n",(m_profiling.m_jobcount*100)/((m_sets[0].m_leaves+m_sets[1].m_leaves)*DBVT_BP_PROFILING_RATE)); - clear(m_profiling); - m_clock.reset(); - } -#endif -} - -// -void btDbvtBroadphase::collide(btDispatcher* dispatcher) -{ -SPC(m_profiling.m_total); -/* optimize */ -m_sets[0].optimizeIncremental(1+(m_sets[0].m_leaves*m_dupdates)/100); -m_sets[1].optimizeIncremental(1+(m_sets[1].m_leaves*m_fupdates)/100); -/* dynamic -> fixed set */ -m_stageCurrent=(m_stageCurrent+1)%STAGECOUNT; -btDbvtProxy* current=m_stageRoots[m_stageCurrent]; -if(current) - { - btDbvtTreeCollider collider(this); - do { - btDbvtProxy* next=current->links[1]; - listremove(current,m_stageRoots[current->stage]); - listappend(current,m_stageRoots[STAGECOUNT]); - btDbvt::collideTT(m_sets[1].m_root,current->leaf,collider); - m_sets[0].remove(current->leaf); - current->leaf = m_sets[1].insert(current->aabb,current); - current->stage = STAGECOUNT; - current = next; - } while(current); - } -/* collide dynamics */ - { - btDbvtTreeCollider collider(this); - { - SPC(m_profiling.m_fdcollide); - btDbvt::collideTT(m_sets[0].m_root,m_sets[1].m_root,collider); - } - { - SPC(m_profiling.m_ddcollide); - btDbvt::collideTT(m_sets[0].m_root,m_sets[0].m_root,collider); - } - } -/* clean up */ - { - SPC(m_profiling.m_cleanup); - btBroadphasePairArray& pairs=m_paircache->getOverlappingPairArray(); - if(pairs.size()>0) - { - for(int i=0,ni=pairs.size();iaabb,pb->aabb)) - { - if(pa>pb) btSwap(pa,pb); - m_paircache->removeOverlappingPair(pa,pb,dispatcher); - --ni;--i; - } - } - } - } -++m_pid; -} - -// -void btDbvtBroadphase::optimize() -{ -m_sets[0].optimizeTopDown(); -m_sets[1].optimizeTopDown(); -} - -// -btOverlappingPairCache* btDbvtBroadphase::getOverlappingPairCache() -{ -return(m_paircache); -} - -// -const btOverlappingPairCache* btDbvtBroadphase::getOverlappingPairCache() const -{ -return(m_paircache); -} - -// -void btDbvtBroadphase::getBroadphaseAabb(btVector3& aabbMin,btVector3& aabbMax) const -{ - - ATTRIBUTE_ALIGNED16(btDbvtVolume) bounds; - -if(!m_sets[0].empty()) - if(!m_sets[1].empty()) Merge( m_sets[0].m_root->volume, - m_sets[1].m_root->volume,bounds); - else - bounds=m_sets[0].m_root->volume; -else if(!m_sets[1].empty()) bounds=m_sets[1].m_root->volume; - else - bounds=btDbvtVolume::FromCR(btVector3(0,0,0),0); -aabbMin=bounds.Mins(); -aabbMax=bounds.Maxs(); -} - -// -void btDbvtBroadphase::printStats() -{} - -#if DBVT_BP_PROFILE -#undef SPC -#endif diff --git a/extern/bullet2/src/BulletCollision/BroadphaseCollision/btDbvtBroadphase.h b/extern/bullet2/src/BulletCollision/BroadphaseCollision/btDbvtBroadphase.h deleted file mode 100644 index 3f19075552b..00000000000 --- a/extern/bullet2/src/BulletCollision/BroadphaseCollision/btDbvtBroadphase.h +++ /dev/null @@ -1,103 +0,0 @@ -/* -Bullet Continuous Collision Detection and Physics Library -Copyright (c) 2003-2007 Erwin Coumans http://continuousphysics.com/Bullet/ - -This software is provided 'as-is', without any express or implied warranty. -In no event will the authors be held liable for any damages arising from the use of this software. -Permission is granted to anyone to use this software for any purpose, -including commercial applications, and to alter it and redistribute it freely, -subject to the following restrictions: - -1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. -2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. -3. This notice may not be removed or altered from any source distribution. -*/ -///btDbvtBroadphase implementation by Nathanael Presson -#ifndef BT_DBVT_BROADPHASE_H -#define BT_DBVT_BROADPHASE_H - -#include "BulletCollision/BroadphaseCollision/btDbvt.h" -#include "BulletCollision/BroadphaseCollision/btOverlappingPairCache.h" - -// -// Compile time config -// - -#define DBVT_BP_PROFILE 0 -#define DBVT_BP_DISCRETPAIRS 1 -#define DBVT_BP_MARGIN (btScalar)0.05 - -#if DBVT_BP_PROFILE - #define DBVT_BP_PROFILING_RATE 256 - #include "LinearMath/btQuickprof.h" -#endif - -// -// btDbvtProxy -// -struct btDbvtProxy : btBroadphaseProxy -{ -/* Fields */ -btDbvtAabbMm aabb; -btDbvtNode* leaf; -btDbvtProxy* links[2]; -int stage; -/* ctor */ -btDbvtProxy(void* userPtr,short int collisionFilterGroup, short int collisionFilterMask) : - btBroadphaseProxy(userPtr,collisionFilterGroup,collisionFilterMask) - { - links[0]=links[1]=0; - } -}; - -typedef btAlignedObjectArray btDbvtProxyArray; - -///The btDbvtBroadphase implements a broadphase using two dynamic AABB bounding volume hierarchies/trees (see btDbvt). -///One tree is used for static/non-moving objects, and another tree is used for dynamic objects. Objects can move from one tree to the other. -///This is a very fast broadphase, especially for very dynamic worlds where many objects are moving. Its insert/add and remove of objects is generally faster than the sweep and prune broadphases btAxisSweep3 and bt32BitAxisSweep3. -struct btDbvtBroadphase : btBroadphaseInterface -{ -/* Config */ -enum { - DYNAMIC_SET = 0, /* Dynamic set index */ - FIXED_SET = 1, /* Fixed set index */ - STAGECOUNT = 2 /* Number of stages */ - }; -/* Fields */ -btDbvt m_sets[2]; // Dbvt sets -btDbvtProxy* m_stageRoots[STAGECOUNT+1]; // Stages list -btOverlappingPairCache* m_paircache; // Pair cache -btScalar m_predictedframes; // Frames predicted -int m_stageCurrent; // Current stage -int m_fupdates; // % of fixed updates per frame -int m_dupdates; // % of dynamic updates per frame -int m_pid; // Parse id -int m_gid; // Gen id -bool m_releasepaircache; // Release pair cache on delete -#if DBVT_BP_PROFILE -btClock m_clock; -struct { - unsigned long m_total; - unsigned long m_ddcollide; - unsigned long m_fdcollide; - unsigned long m_cleanup; - unsigned long m_jobcount; - } m_profiling; -#endif -/* Methods */ -btDbvtBroadphase(btOverlappingPairCache* paircache=0); -~btDbvtBroadphase(); -void collide(btDispatcher* dispatcher); -void optimize(); -/* btBroadphaseInterface Implementation */ -btBroadphaseProxy* createProxy(const btVector3& aabbMin,const btVector3& aabbMax,int shapeType,void* userPtr,short int collisionFilterGroup,short int collisionFilterMask,btDispatcher* dispatcher,void* multiSapProxy); -void destroyProxy(btBroadphaseProxy* proxy,btDispatcher* dispatcher); -void setAabb(btBroadphaseProxy* proxy,const btVector3& aabbMin,const btVector3& aabbMax,btDispatcher* dispatcher); -void calculateOverlappingPairs(btDispatcher* dispatcher); -btOverlappingPairCache* getOverlappingPairCache(); -const btOverlappingPairCache* getOverlappingPairCache() const; -void getBroadphaseAabb(btVector3& aabbMin,btVector3& aabbMax) const; -void printStats(); -}; - -#endif diff --git a/extern/bullet2/src/BulletCollision/BroadphaseCollision/btDispatcher.h b/extern/bullet2/src/BulletCollision/BroadphaseCollision/btDispatcher.h index 6db71a0170e..3d958cc8fef 100644 --- a/extern/bullet2/src/BulletCollision/BroadphaseCollision/btDispatcher.h +++ b/extern/bullet2/src/BulletCollision/BroadphaseCollision/btDispatcher.h @@ -16,7 +16,7 @@ subject to the following restrictions: #ifndef _DISPATCHER_H #define _DISPATCHER_H -#include "LinearMath/btScalar.h" +#include "../../LinearMath/btScalar.h" class btCollisionAlgorithm; struct btBroadphaseProxy; @@ -43,9 +43,7 @@ struct btDispatcherInfo m_useContinuous(false), m_debugDraw(0), m_enableSatConvex(false), - m_enableSPU(true), - m_useEpa(true), - m_allowedCcdPenetration(btScalar(0.04)), + m_enableSPU(false), m_stackAllocator(0) { @@ -53,19 +51,17 @@ struct btDispatcherInfo btScalar m_timeStep; int m_stepCount; int m_dispatchFunc; - mutable btScalar m_timeOfImpact; + btScalar m_timeOfImpact; bool m_useContinuous; class btIDebugDraw* m_debugDraw; bool m_enableSatConvex; bool m_enableSPU; - bool m_useEpa; - btScalar m_allowedCcdPenetration; btStackAlloc* m_stackAllocator; }; -///The btDispatcher interface class can be used in combination with broadphase to dispatch calculations for overlapping pairs. -///For example for pairwise collision detection, calculating contact points stored in btPersistentManifold or user callbacks (game logic). +/// btDispatcher can be used in combination with broadphase to dispatch overlapping pairs. +/// For example for pairwise collision detection or user callbacks (game logic). class btDispatcher { @@ -85,18 +81,12 @@ public: virtual bool needsResponse(btCollisionObject* body0,btCollisionObject* body1)=0; - virtual void dispatchAllCollisionPairs(btOverlappingPairCache* pairCache,const btDispatcherInfo& dispatchInfo,btDispatcher* dispatcher) =0; + virtual void dispatchAllCollisionPairs(btOverlappingPairCache* pairCache,btDispatcherInfo& dispatchInfo)=0; virtual int getNumManifolds() const = 0; virtual btPersistentManifold* getManifoldByIndexInternal(int index) = 0; - virtual btPersistentManifold** getInternalManifoldPointer() = 0; - - virtual void* allocateCollisionAlgorithm(int size) = 0; - - virtual void freeCollisionAlgorithm(void* ptr) = 0; - }; diff --git a/extern/bullet2/src/BulletCollision/BroadphaseCollision/btMultiSapBroadphase.cpp b/extern/bullet2/src/BulletCollision/BroadphaseCollision/btMultiSapBroadphase.cpp deleted file mode 100644 index 3f866ab7c5f..00000000000 --- a/extern/bullet2/src/BulletCollision/BroadphaseCollision/btMultiSapBroadphase.cpp +++ /dev/null @@ -1,466 +0,0 @@ -/* -Bullet Continuous Collision Detection and Physics Library -Copyright (c) 2003-2006 Erwin Coumans http://continuousphysics.com/Bullet/ - -This software is provided 'as-is', without any express or implied warranty. -In no event will the authors be held liable for any damages arising from the use of this software. -Permission is granted to anyone to use this software for any purpose, -including commercial applications, and to alter it and redistribute it freely, -subject to the following restrictions: - -1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. -2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. -3. This notice may not be removed or altered from any source distribution. -*/ - -#include "btMultiSapBroadphase.h" - -#include "btSimpleBroadphase.h" -#include "LinearMath/btAabbUtil2.h" -#include "btQuantizedBvh.h" - -/// btSapBroadphaseArray m_sapBroadphases; - -/// btOverlappingPairCache* m_overlappingPairs; -extern int gOverlappingPairs; - -/* -class btMultiSapSortedOverlappingPairCache : public btSortedOverlappingPairCache -{ -public: - - virtual btBroadphasePair* addOverlappingPair(btBroadphaseProxy* proxy0,btBroadphaseProxy* proxy1) - { - return btSortedOverlappingPairCache::addOverlappingPair((btBroadphaseProxy*)proxy0->m_multiSapParentProxy,(btBroadphaseProxy*)proxy1->m_multiSapParentProxy); - } -}; - -*/ - -btMultiSapBroadphase::btMultiSapBroadphase(int /*maxProxies*/,btOverlappingPairCache* pairCache) -:m_overlappingPairs(pairCache), -m_optimizedAabbTree(0), -m_ownsPairCache(false), -m_invalidPair(0) -{ - if (!m_overlappingPairs) - { - m_ownsPairCache = true; - void* mem = btAlignedAlloc(sizeof(btSortedOverlappingPairCache),16); - m_overlappingPairs = new (mem)btSortedOverlappingPairCache(); - } - - struct btMultiSapOverlapFilterCallback : public btOverlapFilterCallback - { - virtual ~btMultiSapOverlapFilterCallback() - {} - // return true when pairs need collision - virtual bool needBroadphaseCollision(btBroadphaseProxy* childProxy0,btBroadphaseProxy* childProxy1) const - { - btBroadphaseProxy* multiProxy0 = (btBroadphaseProxy*)childProxy0->m_multiSapParentProxy; - btBroadphaseProxy* multiProxy1 = (btBroadphaseProxy*)childProxy1->m_multiSapParentProxy; - - bool collides = (multiProxy0->m_collisionFilterGroup & multiProxy1->m_collisionFilterMask) != 0; - collides = collides && (multiProxy1->m_collisionFilterGroup & multiProxy0->m_collisionFilterMask); - - return collides; - } - }; - - void* mem = btAlignedAlloc(sizeof(btMultiSapOverlapFilterCallback),16); - m_filterCallback = new (mem)btMultiSapOverlapFilterCallback(); - - m_overlappingPairs->setOverlapFilterCallback(m_filterCallback); -// mem = btAlignedAlloc(sizeof(btSimpleBroadphase),16); -// m_simpleBroadphase = new (mem) btSimpleBroadphase(maxProxies,m_overlappingPairs); -} - -btMultiSapBroadphase::~btMultiSapBroadphase() -{ - if (m_ownsPairCache) - { - m_overlappingPairs->~btOverlappingPairCache(); - btAlignedFree(m_overlappingPairs); - } -} - - -void btMultiSapBroadphase::buildTree(const btVector3& bvhAabbMin,const btVector3& bvhAabbMax) -{ - m_optimizedAabbTree = new btQuantizedBvh(); - m_optimizedAabbTree->setQuantizationValues(bvhAabbMin,bvhAabbMax); - QuantizedNodeArray& nodes = m_optimizedAabbTree->getLeafNodeArray(); - for (int i=0;igetBroadphaseAabb(aabbMin,aabbMax); - m_optimizedAabbTree->quantize(&node.m_quantizedAabbMin[0],aabbMin,0); - m_optimizedAabbTree->quantize(&node.m_quantizedAabbMax[0],aabbMax,1); - int partId = 0; - node.m_escapeIndexOrTriangleIndex = (partId<<(31-MAX_NUM_PARTS_IN_BITS)) | i; - nodes.push_back(node); - } - m_optimizedAabbTree->buildInternal(); -} - -btBroadphaseProxy* btMultiSapBroadphase::createProxy( const btVector3& aabbMin, const btVector3& aabbMax,int shapeType,void* userPtr, short int collisionFilterGroup,short int collisionFilterMask, btDispatcher* dispatcher,void* /*ignoreMe*/) -{ - //void* ignoreMe -> we could think of recursive multi-sap, if someone is interested - - void* mem = btAlignedAlloc(sizeof(btMultiSapProxy),16); - btMultiSapProxy* proxy = new (mem)btMultiSapProxy(aabbMin, aabbMax,shapeType,userPtr, collisionFilterGroup,collisionFilterMask); - m_multiSapProxies.push_back(proxy); - - ///this should deal with inserting/removal into child broadphases - setAabb(proxy,aabbMin,aabbMax,dispatcher); - return proxy; -} - -void btMultiSapBroadphase::destroyProxy(btBroadphaseProxy* /*proxy*/,btDispatcher* /*dispatcher*/) -{ - ///not yet - btAssert(0); - -} - - -void btMultiSapBroadphase::addToChildBroadphase(btMultiSapProxy* parentMultiSapProxy, btBroadphaseProxy* childProxy, btBroadphaseInterface* childBroadphase) -{ - void* mem = btAlignedAlloc(sizeof(btBridgeProxy),16); - btBridgeProxy* bridgeProxyRef = new(mem) btBridgeProxy; - bridgeProxyRef->m_childProxy = childProxy; - bridgeProxyRef->m_childBroadphase = childBroadphase; - parentMultiSapProxy->m_bridgeProxies.push_back(bridgeProxyRef); -} - - -bool boxIsContainedWithinBox(const btVector3& amin,const btVector3& amax,const btVector3& bmin,const btVector3& bmax); -bool boxIsContainedWithinBox(const btVector3& amin,const btVector3& amax,const btVector3& bmin,const btVector3& bmax) -{ -return -amin.getX() >= bmin.getX() && amax.getX() <= bmax.getX() && -amin.getY() >= bmin.getY() && amax.getY() <= bmax.getY() && -amin.getZ() >= bmin.getZ() && amax.getZ() <= bmax.getZ(); -} - - - - - - -//#include - -void btMultiSapBroadphase::setAabb(btBroadphaseProxy* proxy,const btVector3& aabbMin,const btVector3& aabbMax, btDispatcher* dispatcher) -{ - btMultiSapProxy* multiProxy = static_cast(proxy); - multiProxy->m_aabbMin = aabbMin; - multiProxy->m_aabbMax = aabbMax; - - -// bool fullyContained = false; -// bool alreadyInSimple = false; - - - - - struct MyNodeOverlapCallback : public btNodeOverlapCallback - { - btMultiSapBroadphase* m_multiSap; - btMultiSapProxy* m_multiProxy; - btDispatcher* m_dispatcher; - - MyNodeOverlapCallback(btMultiSapBroadphase* multiSap,btMultiSapProxy* multiProxy,btDispatcher* dispatcher) - :m_multiSap(multiSap), - m_multiProxy(multiProxy), - m_dispatcher(dispatcher) - { - - } - - virtual void processNode(int /*nodeSubPart*/, int broadphaseIndex) - { - btBroadphaseInterface* childBroadphase = m_multiSap->getBroadphaseArray()[broadphaseIndex]; - - int containingBroadphaseIndex = -1; - //already found? - for (int i=0;im_bridgeProxies.size();i++) - { - - if (m_multiProxy->m_bridgeProxies[i]->m_childBroadphase == childBroadphase) - { - containingBroadphaseIndex = i; - break; - } - } - if (containingBroadphaseIndex<0) - { - //add it - btBroadphaseProxy* childProxy = childBroadphase->createProxy(m_multiProxy->m_aabbMin,m_multiProxy->m_aabbMax,m_multiProxy->m_shapeType,m_multiProxy->m_clientObject,m_multiProxy->m_collisionFilterGroup,m_multiProxy->m_collisionFilterMask, m_dispatcher,m_multiProxy); - m_multiSap->addToChildBroadphase(m_multiProxy,childProxy,childBroadphase); - - } - } - }; - - MyNodeOverlapCallback myNodeCallback(this,multiProxy,dispatcher); - - - - - m_optimizedAabbTree->reportAabbOverlappingNodex(&myNodeCallback,aabbMin,aabbMax); - int i; - - for ( i=0;im_bridgeProxies.size();i++) - { - btVector3 worldAabbMin,worldAabbMax; - multiProxy->m_bridgeProxies[i]->m_childBroadphase->getBroadphaseAabb(worldAabbMin,worldAabbMax); - bool overlapsBroadphase = TestAabbAgainstAabb2(worldAabbMin,worldAabbMax,multiProxy->m_aabbMin,multiProxy->m_aabbMax); - if (!overlapsBroadphase) - { - //remove it now - btBridgeProxy* bridgeProxy = multiProxy->m_bridgeProxies[i]; - - btBroadphaseProxy* childProxy = bridgeProxy->m_childProxy; - bridgeProxy->m_childBroadphase->destroyProxy(childProxy,dispatcher); - - multiProxy->m_bridgeProxies.swap( i,multiProxy->m_bridgeProxies.size()-1); - multiProxy->m_bridgeProxies.pop_back(); - - } - } - - - /* - - if (1) - { - - //find broadphase that contain this multiProxy - int numChildBroadphases = getBroadphaseArray().size(); - for (int i=0;igetBroadphaseAabb(worldAabbMin,worldAabbMax); - bool overlapsBroadphase = TestAabbAgainstAabb2(worldAabbMin,worldAabbMax,multiProxy->m_aabbMin,multiProxy->m_aabbMax); - - // fullyContained = fullyContained || boxIsContainedWithinBox(worldAabbMin,worldAabbMax,multiProxy->m_aabbMin,multiProxy->m_aabbMax); - int containingBroadphaseIndex = -1; - - //if already contains this - - for (int i=0;im_bridgeProxies.size();i++) - { - if (multiProxy->m_bridgeProxies[i]->m_childBroadphase == childBroadphase) - { - containingBroadphaseIndex = i; - } - alreadyInSimple = alreadyInSimple || (multiProxy->m_bridgeProxies[i]->m_childBroadphase == m_simpleBroadphase); - } - - if (overlapsBroadphase) - { - if (containingBroadphaseIndex<0) - { - btBroadphaseProxy* childProxy = childBroadphase->createProxy(aabbMin,aabbMax,multiProxy->m_shapeType,multiProxy->m_clientObject,multiProxy->m_collisionFilterGroup,multiProxy->m_collisionFilterMask, dispatcher); - childProxy->m_multiSapParentProxy = multiProxy; - addToChildBroadphase(multiProxy,childProxy,childBroadphase); - } - } else - { - if (containingBroadphaseIndex>=0) - { - //remove - btBridgeProxy* bridgeProxy = multiProxy->m_bridgeProxies[containingBroadphaseIndex]; - - btBroadphaseProxy* childProxy = bridgeProxy->m_childProxy; - bridgeProxy->m_childBroadphase->destroyProxy(childProxy,dispatcher); - - multiProxy->m_bridgeProxies.swap( containingBroadphaseIndex,multiProxy->m_bridgeProxies.size()-1); - multiProxy->m_bridgeProxies.pop_back(); - } - } - } - - - ///If we are in no other child broadphase, stick the proxy in the global 'simple' broadphase (brute force) - ///hopefully we don't end up with many entries here (can assert/provide feedback on stats) - if (0)//!multiProxy->m_bridgeProxies.size()) - { - ///we don't pass the userPtr but our multisap proxy. We need to patch this, before processing an actual collision - ///this is needed to be able to calculate the aabb overlap - btBroadphaseProxy* childProxy = m_simpleBroadphase->createProxy(aabbMin,aabbMax,multiProxy->m_shapeType,multiProxy->m_clientObject,multiProxy->m_collisionFilterGroup,multiProxy->m_collisionFilterMask, dispatcher); - childProxy->m_multiSapParentProxy = multiProxy; - addToChildBroadphase(multiProxy,childProxy,m_simpleBroadphase); - } - } - - if (!multiProxy->m_bridgeProxies.size()) - { - ///we don't pass the userPtr but our multisap proxy. We need to patch this, before processing an actual collision - ///this is needed to be able to calculate the aabb overlap - btBroadphaseProxy* childProxy = m_simpleBroadphase->createProxy(aabbMin,aabbMax,multiProxy->m_shapeType,multiProxy->m_clientObject,multiProxy->m_collisionFilterGroup,multiProxy->m_collisionFilterMask, dispatcher); - childProxy->m_multiSapParentProxy = multiProxy; - addToChildBroadphase(multiProxy,childProxy,m_simpleBroadphase); - } -*/ - - - //update - for ( i=0;im_bridgeProxies.size();i++) - { - btBridgeProxy* bridgeProxyRef = multiProxy->m_bridgeProxies[i]; - bridgeProxyRef->m_childBroadphase->setAabb(bridgeProxyRef->m_childProxy,aabbMin,aabbMax,dispatcher); - } - -} -bool stopUpdating=false; - - - -class btMultiSapBroadphasePairSortPredicate -{ - public: - - bool operator() ( const btBroadphasePair& a1, const btBroadphasePair& b1 ) - { - btMultiSapBroadphase::btMultiSapProxy* aProxy0 = a1.m_pProxy0 ? (btMultiSapBroadphase::btMultiSapProxy*)a1.m_pProxy0->m_multiSapParentProxy : 0; - btMultiSapBroadphase::btMultiSapProxy* aProxy1 = a1.m_pProxy1 ? (btMultiSapBroadphase::btMultiSapProxy*)a1.m_pProxy1->m_multiSapParentProxy : 0; - btMultiSapBroadphase::btMultiSapProxy* bProxy0 = b1.m_pProxy0 ? (btMultiSapBroadphase::btMultiSapProxy*)b1.m_pProxy0->m_multiSapParentProxy : 0; - btMultiSapBroadphase::btMultiSapProxy* bProxy1 = b1.m_pProxy1 ? (btMultiSapBroadphase::btMultiSapProxy*)b1.m_pProxy1->m_multiSapParentProxy : 0; - - return aProxy0 > bProxy0 || - (aProxy0 == bProxy0 && aProxy1 > bProxy1) || - (aProxy0 == bProxy0 && aProxy1 == bProxy1 && a1.m_algorithm > b1.m_algorithm); - } -}; - - - ///calculateOverlappingPairs is optional: incremental algorithms (sweep and prune) might do it during the set aabb -void btMultiSapBroadphase::calculateOverlappingPairs(btDispatcher* dispatcher) -{ - -// m_simpleBroadphase->calculateOverlappingPairs(dispatcher); - - if (!stopUpdating && getOverlappingPairCache()->hasDeferredRemoval()) - { - - btBroadphasePairArray& overlappingPairArray = getOverlappingPairCache()->getOverlappingPairArray(); - - // quicksort(overlappingPairArray,0,overlappingPairArray.size()); - - overlappingPairArray.quickSort(btMultiSapBroadphasePairSortPredicate()); - - //perform a sort, to find duplicates and to sort 'invalid' pairs to the end - // overlappingPairArray.heapSort(btMultiSapBroadphasePairSortPredicate()); - - overlappingPairArray.resize(overlappingPairArray.size() - m_invalidPair); - m_invalidPair = 0; - - - int i; - - btBroadphasePair previousPair; - previousPair.m_pProxy0 = 0; - previousPair.m_pProxy1 = 0; - previousPair.m_algorithm = 0; - - - for (i=0;im_multiSapParentProxy : 0; - btMultiSapProxy* aProxy1 = pair.m_pProxy1 ? (btMultiSapProxy*)pair.m_pProxy1->m_multiSapParentProxy : 0; - btMultiSapProxy* bProxy0 = previousPair.m_pProxy0 ? (btMultiSapProxy*)previousPair.m_pProxy0->m_multiSapParentProxy : 0; - btMultiSapProxy* bProxy1 = previousPair.m_pProxy1 ? (btMultiSapProxy*)previousPair.m_pProxy1->m_multiSapParentProxy : 0; - - bool isDuplicate = (aProxy0 == bProxy0) && (aProxy1 == bProxy1); - - previousPair = pair; - - bool needsRemoval = false; - - if (!isDuplicate) - { - bool hasOverlap = testAabbOverlap(pair.m_pProxy0,pair.m_pProxy1); - - if (hasOverlap) - { - needsRemoval = false;//callback->processOverlap(pair); - } else - { - needsRemoval = true; - } - } else - { - //remove duplicate - needsRemoval = true; - //should have no algorithm - btAssert(!pair.m_algorithm); - } - - if (needsRemoval) - { - getOverlappingPairCache()->cleanOverlappingPair(pair,dispatcher); - - // m_overlappingPairArray.swap(i,m_overlappingPairArray.size()-1); - // m_overlappingPairArray.pop_back(); - pair.m_pProxy0 = 0; - pair.m_pProxy1 = 0; - m_invalidPair++; - gOverlappingPairs--; - } - - } - - ///if you don't like to skip the invalid pairs in the array, execute following code: - #define CLEAN_INVALID_PAIRS 1 - #ifdef CLEAN_INVALID_PAIRS - - //perform a sort, to sort 'invalid' pairs to the end - //overlappingPairArray.heapSort(btMultiSapBroadphasePairSortPredicate()); - overlappingPairArray.quickSort(btMultiSapBroadphasePairSortPredicate()); - - overlappingPairArray.resize(overlappingPairArray.size() - m_invalidPair); - m_invalidPair = 0; - #endif//CLEAN_INVALID_PAIRS - - //printf("overlappingPairArray.size()=%d\n",overlappingPairArray.size()); - } - - -} - - -bool btMultiSapBroadphase::testAabbOverlap(btBroadphaseProxy* childProxy0,btBroadphaseProxy* childProxy1) -{ - btMultiSapProxy* multiSapProxy0 = (btMultiSapProxy*)childProxy0->m_multiSapParentProxy; - btMultiSapProxy* multiSapProxy1 = (btMultiSapProxy*)childProxy1->m_multiSapParentProxy; - - return TestAabbAgainstAabb2(multiSapProxy0->m_aabbMin,multiSapProxy0->m_aabbMax, - multiSapProxy1->m_aabbMin,multiSapProxy1->m_aabbMax); - -} - - -void btMultiSapBroadphase::printStats() -{ -/* printf("---------------------------------\n"); - - printf("btMultiSapBroadphase.h\n"); - printf("numHandles = %d\n",m_multiSapProxies.size()); - //find broadphase that contain this multiProxy - int numChildBroadphases = getBroadphaseArray().size(); - for (int i=0;iprintStats(); - - } - */ - -} diff --git a/extern/bullet2/src/BulletCollision/BroadphaseCollision/btMultiSapBroadphase.h b/extern/bullet2/src/BulletCollision/BroadphaseCollision/btMultiSapBroadphase.h deleted file mode 100644 index a0c002de856..00000000000 --- a/extern/bullet2/src/BulletCollision/BroadphaseCollision/btMultiSapBroadphase.h +++ /dev/null @@ -1,144 +0,0 @@ -/* -Bullet Continuous Collision Detection and Physics Library -Copyright (c) 2003-2006 Erwin Coumans http://continuousphysics.com/Bullet/ - -This software is provided 'as-is', without any express or implied warranty. -In no event will the authors be held liable for any damages arising from the use of this software. -Permission is granted to anyone to use this software for any purpose, -including commercial applications, and to alter it and redistribute it freely, -subject to the following restrictions: - -1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. -2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. -3. This notice may not be removed or altered from any source distribution. -*/ -#ifndef BT_MULTI_SAP_BROADPHASE -#define BT_MULTI_SAP_BROADPHASE - -#include "btBroadphaseInterface.h" -#include "LinearMath/btAlignedObjectArray.h" -#include "btOverlappingPairCache.h" - - -class btBroadphaseInterface; -class btSimpleBroadphase; - - -typedef btAlignedObjectArray btSapBroadphaseArray; - -///The btMultiSapBroadphase is a broadphase that contains multiple SAP broadphases. -///The user can add SAP broadphases that cover the world. A btBroadphaseProxy can be in multiple child broadphases at the same time. -///A btQuantizedBvh acceleration structures finds overlapping SAPs for each btBroadphaseProxy. -///See http://www.continuousphysics.com/Bullet/phpBB2/viewtopic.php?t=328 -///and http://www.continuousphysics.com/Bullet/phpBB2/viewtopic.php?t=1329 -class btMultiSapBroadphase :public btBroadphaseInterface -{ - btSapBroadphaseArray m_sapBroadphases; - - btSimpleBroadphase* m_simpleBroadphase; - - btOverlappingPairCache* m_overlappingPairs; - - class btQuantizedBvh* m_optimizedAabbTree; - - - bool m_ownsPairCache; - - btOverlapFilterCallback* m_filterCallback; - - int m_invalidPair; - - struct btBridgeProxy - { - btBroadphaseProxy* m_childProxy; - btBroadphaseInterface* m_childBroadphase; - }; - - -public: - - struct btMultiSapProxy : public btBroadphaseProxy - { - - ///array with all the entries that this proxy belongs to - btAlignedObjectArray m_bridgeProxies; - btVector3 m_aabbMin; - btVector3 m_aabbMax; - - int m_shapeType; - -/* void* m_userPtr; - short int m_collisionFilterGroup; - short int m_collisionFilterMask; -*/ - btMultiSapProxy(const btVector3& aabbMin, const btVector3& aabbMax,int shapeType,void* userPtr, short int collisionFilterGroup,short int collisionFilterMask) - :btBroadphaseProxy(userPtr,collisionFilterGroup,collisionFilterMask), - m_aabbMin(aabbMin), - m_aabbMax(aabbMax), - m_shapeType(shapeType) - { - m_multiSapParentProxy =this; - } - - - }; - -protected: - - - btAlignedObjectArray m_multiSapProxies; - -public: - - btMultiSapBroadphase(int maxProxies = 16384,btOverlappingPairCache* pairCache=0); - - - btSapBroadphaseArray& getBroadphaseArray() - { - return m_sapBroadphases; - } - - const btSapBroadphaseArray& getBroadphaseArray() const - { - return m_sapBroadphases; - } - - virtual ~btMultiSapBroadphase(); - - virtual btBroadphaseProxy* createProxy( const btVector3& aabbMin, const btVector3& aabbMax,int shapeType,void* userPtr, short int collisionFilterGroup,short int collisionFilterMask, btDispatcher* dispatcher,void* multiSapProxy); - virtual void destroyProxy(btBroadphaseProxy* proxy,btDispatcher* dispatcher); - virtual void setAabb(btBroadphaseProxy* proxy,const btVector3& aabbMin,const btVector3& aabbMax, btDispatcher* dispatcher); - - void addToChildBroadphase(btMultiSapProxy* parentMultiSapProxy, btBroadphaseProxy* childProxy, btBroadphaseInterface* childBroadphase); - - ///calculateOverlappingPairs is optional: incremental algorithms (sweep and prune) might do it during the set aabb - virtual void calculateOverlappingPairs(btDispatcher* dispatcher); - - bool testAabbOverlap(btBroadphaseProxy* proxy0,btBroadphaseProxy* proxy1); - - virtual btOverlappingPairCache* getOverlappingPairCache() - { - return m_overlappingPairs; - } - virtual const btOverlappingPairCache* getOverlappingPairCache() const - { - return m_overlappingPairs; - } - - ///getAabb returns the axis aligned bounding box in the 'global' coordinate frame - ///will add some transform later - virtual void getBroadphaseAabb(btVector3& aabbMin,btVector3& aabbMax) const - { - aabbMin.setValue(-1e30f,-1e30f,-1e30f); - aabbMax.setValue(1e30f,1e30f,1e30f); - } - - void buildTree(const btVector3& bvhAabbMin,const btVector3& bvhAabbMax); - - virtual void printStats(); - - void quicksort (btBroadphasePairArray& a, int lo, int hi); - -}; - -#endif //BT_MULTI_SAP_BROADPHASE diff --git a/extern/bullet2/src/BulletCollision/BroadphaseCollision/btOverlappingPairCache.cpp b/extern/bullet2/src/BulletCollision/BroadphaseCollision/btOverlappingPairCache.cpp index ff65cdde79f..60f0a41a9d7 100644 --- a/extern/bullet2/src/BulletCollision/BroadphaseCollision/btOverlappingPairCache.cpp +++ b/extern/bullet2/src/BulletCollision/BroadphaseCollision/btOverlappingPairCache.cpp @@ -1,3 +1,4 @@ + /* Bullet Continuous Collision Detection and Physics Library Copyright (c) 2003-2006 Erwin Coumans http://continuousphysics.com/Bullet/ @@ -20,43 +21,44 @@ subject to the following restrictions: #include "btDispatcher.h" #include "btCollisionAlgorithm.h" -#include - int gOverlappingPairs = 0; -int gRemovePairs =0; -int gAddedPairs =0; -int gFindPairs =0; - - - - -btHashedOverlappingPairCache::btHashedOverlappingPairCache(): - m_overlapFilterCallback(0), - m_blockedForChanges(false) +btOverlappingPairCache::btOverlappingPairCache(): +m_blockedForChanges(false), +m_overlapFilterCallback(0) +//m_NumOverlapBroadphasePair(0) { - int initialAllocatedSize= 2; - m_overlappingPairArray.reserve(initialAllocatedSize); - growTables(); } - - -btHashedOverlappingPairCache::~btHashedOverlappingPairCache() +btOverlappingPairCache::~btOverlappingPairCache() { //todo/test: show we erase/delete data, or is it automatic } +void btOverlappingPairCache::removeOverlappingPair(btBroadphasePair& findPair) +{ + + int findIndex = m_overlappingPairArray.findLinearSearch(findPair); + if (findIndex < m_overlappingPairArray.size()) + { + gOverlappingPairs--; + btBroadphasePair& pair = m_overlappingPairArray[findIndex]; + cleanOverlappingPair(pair); + + m_overlappingPairArray.swap(findIndex,m_overlappingPairArray.size()-1); + m_overlappingPairArray.pop_back(); + } +} -void btHashedOverlappingPairCache::cleanOverlappingPair(btBroadphasePair& pair,btDispatcher* dispatcher) + +void btOverlappingPairCache::cleanOverlappingPair(btBroadphasePair& pair) { if (pair.m_algorithm) { { - pair.m_algorithm->~btCollisionAlgorithm(); - dispatcher->freeCollisionAlgorithm(pair.m_algorithm); + delete pair.m_algorithm;; pair.m_algorithm=0; } } @@ -65,370 +67,20 @@ void btHashedOverlappingPairCache::cleanOverlappingPair(btBroadphasePair& pair,b -void btHashedOverlappingPairCache::cleanProxyFromPairs(btBroadphaseProxy* proxy,btDispatcher* dispatcher) -{ - class CleanPairCallback : public btOverlapCallback - { - btBroadphaseProxy* m_cleanProxy; - btOverlappingPairCache* m_pairCache; - btDispatcher* m_dispatcher; - - public: - CleanPairCallback(btBroadphaseProxy* cleanProxy,btOverlappingPairCache* pairCache,btDispatcher* dispatcher) - :m_cleanProxy(cleanProxy), - m_pairCache(pairCache), - m_dispatcher(dispatcher) - { - } - virtual bool processOverlap(btBroadphasePair& pair) - { - if ((pair.m_pProxy0 == m_cleanProxy) || - (pair.m_pProxy1 == m_cleanProxy)) - { - m_pairCache->cleanOverlappingPair(pair,m_dispatcher); - } - return false; - } - - }; - - CleanPairCallback cleanPairs(proxy,this,dispatcher); - - processAllOverlappingPairs(&cleanPairs,dispatcher); - -} - - - - -void btHashedOverlappingPairCache::removeOverlappingPairsContainingProxy(btBroadphaseProxy* proxy,btDispatcher* dispatcher) -{ - - class RemovePairCallback : public btOverlapCallback - { - btBroadphaseProxy* m_obsoleteProxy; - - public: - RemovePairCallback(btBroadphaseProxy* obsoleteProxy) - :m_obsoleteProxy(obsoleteProxy) - { - } - virtual bool processOverlap(btBroadphasePair& pair) - { - return ((pair.m_pProxy0 == m_obsoleteProxy) || - (pair.m_pProxy1 == m_obsoleteProxy)); - } - - }; - - - RemovePairCallback removeCallback(proxy); - - processAllOverlappingPairs(&removeCallback,dispatcher); -} - - - - - -btBroadphasePair* btHashedOverlappingPairCache::findPair(btBroadphaseProxy* proxy0, btBroadphaseProxy* proxy1) -{ - gFindPairs++; - if(proxy0>proxy1) btSwap(proxy0,proxy1); - int proxyId1 = proxy0->getUid(); - int proxyId2 = proxy1->getUid(); - - /*if (proxyId1 > proxyId2) - btSwap(proxyId1, proxyId2);*/ - - int hash = static_cast(getHash(static_cast(proxyId1), static_cast(proxyId2)) & (m_overlappingPairArray.capacity()-1)); - - if (hash >= m_hashTable.size()) - { - return NULL; - } - - int index = m_hashTable[hash]; - while (index != BT_NULL_PAIR && equalsPair(m_overlappingPairArray[index], proxyId1, proxyId2) == false) - { - index = m_next[index]; - } - - if (index == BT_NULL_PAIR) - { - return NULL; - } - - btAssert(index < m_overlappingPairArray.size()); - - return &m_overlappingPairArray[index]; -} - -//#include - -void btHashedOverlappingPairCache::growTables() -{ - - int newCapacity = m_overlappingPairArray.capacity(); - - if (m_hashTable.size() < newCapacity) - { - //grow hashtable and next table - int curHashtableSize = m_hashTable.size(); - - m_hashTable.resize(newCapacity); - m_next.resize(newCapacity); - - - int i; - - for (i= 0; i < newCapacity; ++i) - { - m_hashTable[i] = BT_NULL_PAIR; - } - for (i = 0; i < newCapacity; ++i) - { - m_next[i] = BT_NULL_PAIR; - } - - for(i=0;igetUid(); - int proxyId2 = pair.m_pProxy1->getUid(); - /*if (proxyId1 > proxyId2) - btSwap(proxyId1, proxyId2);*/ - int hashValue = static_cast(getHash(static_cast(proxyId1),static_cast(proxyId2)) & (m_overlappingPairArray.capacity()-1)); // New hash value with new mask - m_next[i] = m_hashTable[hashValue]; - m_hashTable[hashValue] = i; - } - - - } -} - -btBroadphasePair* btHashedOverlappingPairCache::internalAddPair(btBroadphaseProxy* proxy0, btBroadphaseProxy* proxy1) -{ - if(proxy0>proxy1) btSwap(proxy0,proxy1); - int proxyId1 = proxy0->getUid(); - int proxyId2 = proxy1->getUid(); - - /*if (proxyId1 > proxyId2) - btSwap(proxyId1, proxyId2);*/ - - int hash = static_cast(getHash(static_cast(proxyId1),static_cast(proxyId2)) & (m_overlappingPairArray.capacity()-1)); // New hash value with new mask - - - btBroadphasePair* pair = internalFindPair(proxy0, proxy1, hash); - if (pair != NULL) - { - return pair; - } - /*for(int i=0;i%u\r\n",proxyId1,proxyId2); - internalFindPair(proxy0, proxy1, hash); - } - }*/ - int count = m_overlappingPairArray.size(); - int oldCapacity = m_overlappingPairArray.capacity(); - void* mem = &m_overlappingPairArray.expand(); - int newCapacity = m_overlappingPairArray.capacity(); - - if (oldCapacity < newCapacity) - { - growTables(); - //hash with new capacity - hash = static_cast(getHash(static_cast(proxyId1),static_cast(proxyId2)) & (m_overlappingPairArray.capacity()-1)); - } - - pair = new (mem) btBroadphasePair(*proxy0,*proxy1); -// pair->m_pProxy0 = proxy0; -// pair->m_pProxy1 = proxy1; - pair->m_algorithm = 0; - pair->m_userInfo = 0; - - - m_next[count] = m_hashTable[hash]; - m_hashTable[hash] = count; - - return pair; -} - - - -void* btHashedOverlappingPairCache::removeOverlappingPair(btBroadphaseProxy* proxy0, btBroadphaseProxy* proxy1,btDispatcher* dispatcher) -{ - gRemovePairs++; - if(proxy0>proxy1) btSwap(proxy0,proxy1); - int proxyId1 = proxy0->getUid(); - int proxyId2 = proxy1->getUid(); - - /*if (proxyId1 > proxyId2) - btSwap(proxyId1, proxyId2);*/ - - int hash = static_cast(getHash(static_cast(proxyId1),static_cast(proxyId2)) & (m_overlappingPairArray.capacity()-1)); - - btBroadphasePair* pair = internalFindPair(proxy0, proxy1, hash); - if (pair == NULL) - { - return 0; - } - - cleanOverlappingPair(*pair,dispatcher); - - void* userData = pair->m_userInfo; - - btAssert(pair->m_pProxy0->getUid() == proxyId1); - btAssert(pair->m_pProxy1->getUid() == proxyId2); - - int pairIndex = int(pair - &m_overlappingPairArray[0]); - btAssert(pairIndex < m_overlappingPairArray.size()); - - // Remove the pair from the hash table. - int index = m_hashTable[hash]; - btAssert(index != BT_NULL_PAIR); - - int previous = BT_NULL_PAIR; - while (index != pairIndex) - { - previous = index; - index = m_next[index]; - } - - if (previous != BT_NULL_PAIR) - { - btAssert(m_next[previous] == pairIndex); - m_next[previous] = m_next[pairIndex]; - } - else - { - m_hashTable[hash] = m_next[pairIndex]; - } - - // We now move the last pair into spot of the - // pair being removed. We need to fix the hash - // table indices to support the move. - - int lastPairIndex = m_overlappingPairArray.size() - 1; - - // If the removed pair is the last pair, we are done. - if (lastPairIndex == pairIndex) - { - m_overlappingPairArray.pop_back(); - return userData; - } - - // Remove the last pair from the hash table. - const btBroadphasePair* last = &m_overlappingPairArray[lastPairIndex]; - /* missing swap here too, Nat. */ - int lastHash = static_cast(getHash(static_cast(last->m_pProxy0->getUid()), static_cast(last->m_pProxy1->getUid())) & (m_overlappingPairArray.capacity()-1)); - - index = m_hashTable[lastHash]; - btAssert(index != BT_NULL_PAIR); - - previous = BT_NULL_PAIR; - while (index != lastPairIndex) - { - previous = index; - index = m_next[index]; - } - - if (previous != BT_NULL_PAIR) - { - btAssert(m_next[previous] == lastPairIndex); - m_next[previous] = m_next[lastPairIndex]; - } - else - { - m_hashTable[lastHash] = m_next[lastPairIndex]; - } - - // Copy the last pair into the remove pair's spot. - m_overlappingPairArray[pairIndex] = m_overlappingPairArray[lastPairIndex]; - - // Insert the last pair into the hash table - m_next[pairIndex] = m_hashTable[lastHash]; - m_hashTable[lastHash] = pairIndex; - - m_overlappingPairArray.pop_back(); - - return userData; -} -//#include - -void btHashedOverlappingPairCache::processAllOverlappingPairs(btOverlapCallback* callback,btDispatcher* dispatcher) -{ - - int i; - -// printf("m_overlappingPairArray.size()=%d\n",m_overlappingPairArray.size()); - for (i=0;iprocessOverlap(*pair)) - { - removeOverlappingPair(pair->m_pProxy0,pair->m_pProxy1,dispatcher); - - gOverlappingPairs--; - } else - { - i++; - } - } -} - - - -void* btSortedOverlappingPairCache::removeOverlappingPair(btBroadphaseProxy* proxy0,btBroadphaseProxy* proxy1, btDispatcher* dispatcher ) -{ - if (!hasDeferredRemoval()) - { - btBroadphasePair findPair(*proxy0,*proxy1); - - int findIndex = m_overlappingPairArray.findLinearSearch(findPair); - if (findIndex < m_overlappingPairArray.size()) - { - gOverlappingPairs--; - btBroadphasePair& pair = m_overlappingPairArray[findIndex]; - void* userData = pair.m_userInfo; - cleanOverlappingPair(pair,dispatcher); - - m_overlappingPairArray.swap(findIndex,m_overlappingPairArray.capacity()-1); - m_overlappingPairArray.pop_back(); - return userData; - } - } - - return 0; -} - - - - - - - - -btBroadphasePair* btSortedOverlappingPairCache::addOverlappingPair(btBroadphaseProxy* proxy0,btBroadphaseProxy* proxy1) +void btOverlappingPairCache::addOverlappingPair(btBroadphaseProxy* proxy0,btBroadphaseProxy* proxy1) { //don't add overlap with own assert(proxy0 != proxy1); if (!needsBroadphaseCollision(proxy0,proxy1)) - return 0; + return; + + + btBroadphasePair pair(*proxy0,*proxy1); - void* mem = &m_overlappingPairArray.expand(); - btBroadphasePair* pair = new (mem) btBroadphasePair(*proxy0,*proxy1); + m_overlappingPairArray.push_back(pair); gOverlappingPairs++; - gAddedPairs++; - return pair; } @@ -436,7 +88,7 @@ btBroadphasePair* btSortedOverlappingPairCache::addOverlappingPair(btBroadphaseP ///use a different solution. It is mainly used for Removing overlapping pairs. Removal could be delayed. ///we could keep a linked list in each proxy, and store pair in one of the proxies (with lowest memory address) ///Also we can use a 2D bitmap, which can be useful for a future GPU implementation - btBroadphasePair* btSortedOverlappingPairCache::findPair(btBroadphaseProxy* proxy0,btBroadphaseProxy* proxy1) + btBroadphasePair* btOverlappingPairCache::findPair(btBroadphaseProxy* proxy0,btBroadphaseProxy* proxy1) { if (!needsBroadphaseCollision(proxy0,proxy1)) return 0; @@ -457,81 +109,18 @@ btBroadphasePair* btSortedOverlappingPairCache::addOverlappingPair(btBroadphaseP - - - - - -//#include - -void btSortedOverlappingPairCache::processAllOverlappingPairs(btOverlapCallback* callback,btDispatcher* dispatcher) -{ - - int i; - - for (i=0;iprocessOverlap(*pair)) - { - cleanOverlappingPair(*pair,dispatcher); - - m_overlappingPairArray.swap(i,m_overlappingPairArray.capacity()-1); - m_overlappingPairArray.pop_back(); - gOverlappingPairs--; - } else - { - i++; - } - } -} - - - - -btSortedOverlappingPairCache::btSortedOverlappingPairCache(): - m_blockedForChanges(false), - m_hasDeferredRemoval(true), - m_overlapFilterCallback(0) -{ - int initialAllocatedSize= 2; - m_overlappingPairArray.reserve(initialAllocatedSize); -} - -btSortedOverlappingPairCache::~btSortedOverlappingPairCache() -{ - //todo/test: show we erase/delete data, or is it automatic -} - -void btSortedOverlappingPairCache::cleanOverlappingPair(btBroadphasePair& pair,btDispatcher* dispatcher) -{ - if (pair.m_algorithm) - { - { - pair.m_algorithm->~btCollisionAlgorithm(); - dispatcher->freeCollisionAlgorithm(pair.m_algorithm); - pair.m_algorithm=0; - gRemovePairs--; - } - } -} - - -void btSortedOverlappingPairCache::cleanProxyFromPairs(btBroadphaseProxy* proxy,btDispatcher* dispatcher) +void btOverlappingPairCache::cleanProxyFromPairs(btBroadphaseProxy* proxy) { class CleanPairCallback : public btOverlapCallback { btBroadphaseProxy* m_cleanProxy; btOverlappingPairCache* m_pairCache; - btDispatcher* m_dispatcher; public: - CleanPairCallback(btBroadphaseProxy* cleanProxy,btOverlappingPairCache* pairCache,btDispatcher* dispatcher) + CleanPairCallback(btBroadphaseProxy* cleanProxy,btOverlappingPairCache* pairCache) :m_cleanProxy(cleanProxy), - m_pairCache(pairCache), - m_dispatcher(dispatcher) + m_pairCache(pairCache) { } virtual bool processOverlap(btBroadphasePair& pair) @@ -539,21 +128,22 @@ void btSortedOverlappingPairCache::cleanProxyFromPairs(btBroadphaseProxy* proxy, if ((pair.m_pProxy0 == m_cleanProxy) || (pair.m_pProxy1 == m_cleanProxy)) { - m_pairCache->cleanOverlappingPair(pair,m_dispatcher); + m_pairCache->cleanOverlappingPair(pair); } return false; } }; - CleanPairCallback cleanPairs(proxy,this,dispatcher); + CleanPairCallback cleanPairs(proxy,this); - processAllOverlappingPairs(&cleanPairs,dispatcher); + processAllOverlappingPairs(&cleanPairs); } -void btSortedOverlappingPairCache::removeOverlappingPairsContainingProxy(btBroadphaseProxy* proxy,btDispatcher* dispatcher) + +void btOverlappingPairCache::removeOverlappingPairsContainingProxy(btBroadphaseProxy* proxy) { class RemovePairCallback : public btOverlapCallback @@ -573,7 +163,34 @@ void btSortedOverlappingPairCache::removeOverlappingPairsContainingProxy(btBroad }; + RemovePairCallback removeCallback(proxy); - processAllOverlappingPairs(&removeCallback,dispatcher); + processAllOverlappingPairs(&removeCallback); } + + + +void btOverlappingPairCache::processAllOverlappingPairs(btOverlapCallback* callback) +{ + + int i; + + for (i=0;iprocessOverlap(*pair)) + { + cleanOverlappingPair(*pair); + + m_overlappingPairArray.swap(i,m_overlappingPairArray.size()-1); + m_overlappingPairArray.pop_back(); + gOverlappingPairs--; + } else + { + i++; + } + } +} + diff --git a/extern/bullet2/src/BulletCollision/BroadphaseCollision/btOverlappingPairCache.h b/extern/bullet2/src/BulletCollision/BroadphaseCollision/btOverlappingPairCache.h index 66679bd218a..a81fe3264df 100644 --- a/extern/bullet2/src/BulletCollision/BroadphaseCollision/btOverlappingPairCache.h +++ b/extern/bullet2/src/BulletCollision/BroadphaseCollision/btOverlappingPairCache.h @@ -1,3 +1,4 @@ + /* Bullet Continuous Collision Detection and Physics Library Copyright (c) 2003-2006 Erwin Coumans http://continuousphysics.com/Bullet/ @@ -19,13 +20,9 @@ subject to the following restrictions: #include "btBroadphaseInterface.h" #include "btBroadphaseProxy.h" -#include "btOverlappingPairCallback.h" +#include "../../LinearMath/btPoint3.h" +#include "../../LinearMath/btAlignedObjectArray.h" -#include "LinearMath/btPoint3.h" -#include "LinearMath/btAlignedObjectArray.h" -class btDispatcher; - -typedef btAlignedObjectArray btBroadphasePairArray; struct btOverlapCallback { @@ -33,7 +30,6 @@ struct btOverlapCallback {} //return true for deletion of the pair virtual bool processOverlap(btBroadphasePair& pair) = 0; - }; struct btOverlapFilterCallback @@ -44,261 +40,38 @@ struct btOverlapFilterCallback virtual bool needBroadphaseCollision(btBroadphaseProxy* proxy0,btBroadphaseProxy* proxy1) const = 0; }; - - - - - - -extern int gRemovePairs; -extern int gAddedPairs; -extern int gFindPairs; - -const int BT_NULL_PAIR=0xffffffff; - -///The btOverlappingPairCache provides an interface for overlapping pair management (add, remove, storage), used by the btBroadphaseInterface broadphases. -///The btHashedOverlappingPairCache and btSortedOverlappingPairCache classes are two implementations. -class btOverlappingPairCache : public btOverlappingPairCallback -{ -public: - virtual ~btOverlappingPairCache() {} // this is needed so we can get to the derived class destructor - - virtual btBroadphasePair* getOverlappingPairArrayPtr() = 0; - - virtual const btBroadphasePair* getOverlappingPairArrayPtr() const = 0; - - virtual btBroadphasePairArray& getOverlappingPairArray() = 0; - - virtual void cleanOverlappingPair(btBroadphasePair& pair,btDispatcher* dispatcher) = 0; - - virtual int getNumOverlappingPairs() const = 0; - - virtual void cleanProxyFromPairs(btBroadphaseProxy* proxy,btDispatcher* dispatcher) = 0; - - virtual void setOverlapFilterCallback(btOverlapFilterCallback* callback) = 0; - - virtual void processAllOverlappingPairs(btOverlapCallback*,btDispatcher* dispatcher) = 0; - - virtual btBroadphasePair* findPair(btBroadphaseProxy* proxy0, btBroadphaseProxy* proxy1) = 0; - - virtual bool hasDeferredRemoval() = 0; - -}; - -/// Hash-space based Pair Cache, thanks to Erin Catto, Box2D, http://www.box2d.org, and Pierre Terdiman, Codercorner, http://codercorner.com -class btHashedOverlappingPairCache : public btOverlappingPairCache -{ - btBroadphasePairArray m_overlappingPairArray; - btOverlapFilterCallback* m_overlapFilterCallback; - bool m_blockedForChanges; - - -public: - btHashedOverlappingPairCache(); - virtual ~btHashedOverlappingPairCache(); - - - void removeOverlappingPairsContainingProxy(btBroadphaseProxy* proxy,btDispatcher* dispatcher); - - virtual void* removeOverlappingPair(btBroadphaseProxy* proxy0,btBroadphaseProxy* proxy1,btDispatcher* dispatcher); - - SIMD_FORCE_INLINE bool needsBroadphaseCollision(btBroadphaseProxy* proxy0,btBroadphaseProxy* proxy1) const - { - if (m_overlapFilterCallback) - return m_overlapFilterCallback->needBroadphaseCollision(proxy0,proxy1); - - bool collides = (proxy0->m_collisionFilterGroup & proxy1->m_collisionFilterMask) != 0; - collides = collides && (proxy1->m_collisionFilterGroup & proxy0->m_collisionFilterMask); - - return collides; - } - - // Add a pair and return the new pair. If the pair already exists, - // no new pair is created and the old one is returned. - virtual btBroadphasePair* addOverlappingPair(btBroadphaseProxy* proxy0,btBroadphaseProxy* proxy1) - { - gAddedPairs++; - - if (!needsBroadphaseCollision(proxy0,proxy1)) - return 0; - - return internalAddPair(proxy0,proxy1); - } - - - - void cleanProxyFromPairs(btBroadphaseProxy* proxy,btDispatcher* dispatcher); - - - virtual void processAllOverlappingPairs(btOverlapCallback*,btDispatcher* dispatcher); - - virtual btBroadphasePair* getOverlappingPairArrayPtr() - { - return &m_overlappingPairArray[0]; - } - - const btBroadphasePair* getOverlappingPairArrayPtr() const - { - return &m_overlappingPairArray[0]; - } - - btBroadphasePairArray& getOverlappingPairArray() - { - return m_overlappingPairArray; - } - - const btBroadphasePairArray& getOverlappingPairArray() const - { - return m_overlappingPairArray; - } - - void cleanOverlappingPair(btBroadphasePair& pair,btDispatcher* dispatcher); - - - - btBroadphasePair* findPair(btBroadphaseProxy* proxy0, btBroadphaseProxy* proxy1); - - int GetCount() const { return m_overlappingPairArray.size(); } -// btBroadphasePair* GetPairs() { return m_pairs; } - - btOverlapFilterCallback* getOverlapFilterCallback() - { - return m_overlapFilterCallback; - } - - void setOverlapFilterCallback(btOverlapFilterCallback* callback) - { - m_overlapFilterCallback = callback; - } - - int getNumOverlappingPairs() const - { - return m_overlappingPairArray.size(); - } -private: - - btBroadphasePair* internalAddPair(btBroadphaseProxy* proxy0,btBroadphaseProxy* proxy1); - - void growTables(); - - SIMD_FORCE_INLINE bool equalsPair(const btBroadphasePair& pair, int proxyId1, int proxyId2) - { - return pair.m_pProxy0->getUid() == proxyId1 && pair.m_pProxy1->getUid() == proxyId2; - } - - /* - // Thomas Wang's hash, see: http://www.concentric.net/~Ttwang/tech/inthash.htm - // This assumes proxyId1 and proxyId2 are 16-bit. - SIMD_FORCE_INLINE int getHash(int proxyId1, int proxyId2) - { - int key = (proxyId2 << 16) | proxyId1; - key = ~key + (key << 15); - key = key ^ (key >> 12); - key = key + (key << 2); - key = key ^ (key >> 4); - key = key * 2057; - key = key ^ (key >> 16); - return key; - } - */ - - - - SIMD_FORCE_INLINE unsigned int getHash(unsigned int proxyId1, unsigned int proxyId2) - { - int key = static_cast(((unsigned int)proxyId1) | (((unsigned int)proxyId2) <<16)); - // Thomas Wang's hash - - key += ~(key << 15); - key ^= (key >> 10); - key += (key << 3); - key ^= (key >> 6); - key += ~(key << 11); - key ^= (key >> 16); - return static_cast(key); - } - - - - - - SIMD_FORCE_INLINE btBroadphasePair* internalFindPair(btBroadphaseProxy* proxy0, btBroadphaseProxy* proxy1, int hash) - { - int proxyId1 = proxy0->getUid(); - int proxyId2 = proxy1->getUid(); - #if 0 // wrong, 'equalsPair' use unsorted uids, copy-past devil striked again. Nat. - if (proxyId1 > proxyId2) - btSwap(proxyId1, proxyId2); - #endif - - int index = m_hashTable[hash]; - - while( index != BT_NULL_PAIR && equalsPair(m_overlappingPairArray[index], proxyId1, proxyId2) == false) - { - index = m_next[index]; - } - - if ( index == BT_NULL_PAIR ) - { - return NULL; - } - - btAssert(index < m_overlappingPairArray.size()); - - return &m_overlappingPairArray[index]; - } - - virtual bool hasDeferredRemoval() - { - return false; - } - -public: - - btAlignedObjectArray m_hashTable; - btAlignedObjectArray m_next; - -}; - - - - -///btSortedOverlappingPairCache maintains the objects with overlapping AABB +///btOverlappingPairCache maintains the objects with overlapping AABB ///Typically managed by the Broadphase, Axis3Sweep or btSimpleBroadphase -class btSortedOverlappingPairCache : public btOverlappingPairCache +class btOverlappingPairCache : public btBroadphaseInterface { protected: //avoid brute-force finding all the time - btBroadphasePairArray m_overlappingPairArray; - + btAlignedObjectArray m_overlappingPairArray; + //during the dispatch, check that user doesn't destroy/create proxy bool m_blockedForChanges; - - ///by default, do the removal during the pair traversal - bool m_hasDeferredRemoval; //if set, use the callback instead of the built in filter in needBroadphaseCollision btOverlapFilterCallback* m_overlapFilterCallback; - public: - btSortedOverlappingPairCache(); - virtual ~btSortedOverlappingPairCache(); + btOverlappingPairCache(); + virtual ~btOverlappingPairCache(); - virtual void processAllOverlappingPairs(btOverlapCallback*,btDispatcher* dispatcher); + virtual void processAllOverlappingPairs(btOverlapCallback*); - void* removeOverlappingPair(btBroadphaseProxy* proxy0,btBroadphaseProxy* proxy1,btDispatcher* dispatcher); + void removeOverlappingPair(btBroadphasePair& pair); - void cleanOverlappingPair(btBroadphasePair& pair,btDispatcher* dispatcher); + void cleanOverlappingPair(btBroadphasePair& pair); - btBroadphasePair* addOverlappingPair(btBroadphaseProxy* proxy0,btBroadphaseProxy* proxy1); + void addOverlappingPair(btBroadphaseProxy* proxy0,btBroadphaseProxy* proxy1); btBroadphasePair* findPair(btBroadphaseProxy* proxy0,btBroadphaseProxy* proxy1); - void cleanProxyFromPairs(btBroadphaseProxy* proxy,btDispatcher* dispatcher); + void cleanProxyFromPairs(btBroadphaseProxy* proxy); - void removeOverlappingPairsContainingProxy(btBroadphaseProxy* proxy,btDispatcher* dispatcher); + void removeOverlappingPairsContainingProxy(btBroadphaseProxy* proxy); inline bool needsBroadphaseCollision(btBroadphaseProxy* proxy0,btBroadphaseProxy* proxy1) const @@ -311,19 +84,10 @@ class btSortedOverlappingPairCache : public btOverlappingPairCache return collides; } - - btBroadphasePairArray& getOverlappingPairArray() - { - return m_overlappingPairArray; - } - - const btBroadphasePairArray& getOverlappingPairArray() const - { - return m_overlappingPairArray; - } - + + virtual void refreshOverlappingPairs() =0; btBroadphasePair* getOverlappingPairArrayPtr() { @@ -350,88 +114,7 @@ class btSortedOverlappingPairCache : public btOverlappingPairCache m_overlapFilterCallback = callback; } - virtual bool hasDeferredRemoval() - { - return m_hasDeferredRemoval; - } - - }; - - - -///btNullPairCache skips add/removal of overlapping pairs. Userful for benchmarking and testing. -class btNullPairCache : public btOverlappingPairCache -{ - - btBroadphasePairArray m_overlappingPairArray; - -public: - - virtual btBroadphasePair* getOverlappingPairArrayPtr() - { - return &m_overlappingPairArray[0]; - } - const btBroadphasePair* getOverlappingPairArrayPtr() const - { - return &m_overlappingPairArray[0]; - } - btBroadphasePairArray& getOverlappingPairArray() - { - return m_overlappingPairArray; - } - - virtual void cleanOverlappingPair(btBroadphasePair& /*pair*/,btDispatcher* /*dispatcher*/) - { - - } - - virtual int getNumOverlappingPairs() const - { - return 0; - } - - virtual void cleanProxyFromPairs(btBroadphaseProxy* /*proxy*/,btDispatcher* /*dispatcher*/) - { - - } - - virtual void setOverlapFilterCallback(btOverlapFilterCallback* /*callback*/) - { - } - - virtual void processAllOverlappingPairs(btOverlapCallback*,btDispatcher* /*dispatcher*/) - { - } - - virtual btBroadphasePair* findPair(btBroadphaseProxy* /*proxy0*/, btBroadphaseProxy* /*proxy1*/) - { - return 0; - } - - virtual bool hasDeferredRemoval() - { - return true; - } - - virtual btBroadphasePair* addOverlappingPair(btBroadphaseProxy* /*proxy0*/,btBroadphaseProxy* /*proxy1*/) - { - return 0; - } - - virtual void* removeOverlappingPair(btBroadphaseProxy* /*proxy0*/,btBroadphaseProxy* /*proxy1*/,btDispatcher* /*dispatcher*/) - { - return 0; - } - - virtual void removeOverlappingPairsContainingProxy(btBroadphaseProxy* /*proxy0*/,btDispatcher* /*dispatcher*/) - { - } - - -}; - - #endif //OVERLAPPING_PAIR_CACHE_H diff --git a/extern/bullet2/src/BulletCollision/BroadphaseCollision/btOverlappingPairCallback.h b/extern/bullet2/src/BulletCollision/BroadphaseCollision/btOverlappingPairCallback.h deleted file mode 100644 index 9c7b6f81367..00000000000 --- a/extern/bullet2/src/BulletCollision/BroadphaseCollision/btOverlappingPairCallback.h +++ /dev/null @@ -1,40 +0,0 @@ - -/* -Bullet Continuous Collision Detection and Physics Library -Copyright (c) 2003-2006 Erwin Coumans http://continuousphysics.com/Bullet/ - -This software is provided 'as-is', without any express or implied warranty. -In no event will the authors be held liable for any damages arising from the use of this software. -Permission is granted to anyone to use this software for any purpose, -including commercial applications, and to alter it and redistribute it freely, -subject to the following restrictions: - -1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. -2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. -3. This notice may not be removed or altered from any source distribution. -*/ - -#ifndef OVERLAPPING_PAIR_CALLBACK_H -#define OVERLAPPING_PAIR_CALLBACK_H - -class btDispatcher; -struct btBroadphasePair; - -///The btOverlappingPairCallback class is an additional optional broadphase user callback for adding/removing overlapping pairs, similar interface to btOverlappingPairCache. -class btOverlappingPairCallback -{ -public: - virtual ~btOverlappingPairCallback() - { - - } - - virtual btBroadphasePair* addOverlappingPair(btBroadphaseProxy* proxy0,btBroadphaseProxy* proxy1) = 0; - - virtual void* removeOverlappingPair(btBroadphaseProxy* proxy0,btBroadphaseProxy* proxy1,btDispatcher* dispatcher) = 0; - - virtual void removeOverlappingPairsContainingProxy(btBroadphaseProxy* proxy0,btDispatcher* dispatcher) = 0; - -}; - -#endif //OVERLAPPING_PAIR_CALLBACK_H diff --git a/extern/bullet2/src/BulletCollision/BroadphaseCollision/btQuantizedBvh.cpp b/extern/bullet2/src/BulletCollision/BroadphaseCollision/btQuantizedBvh.cpp deleted file mode 100644 index a30bd1fd9e1..00000000000 --- a/extern/bullet2/src/BulletCollision/BroadphaseCollision/btQuantizedBvh.cpp +++ /dev/null @@ -1,1025 +0,0 @@ -/* -Bullet Continuous Collision Detection and Physics Library -Copyright (c) 2003-2006 Erwin Coumans http://continuousphysics.com/Bullet/ - -This software is provided 'as-is', without any express or implied warranty. -In no event will the authors be held liable for any damages arising from the use of this software. -Permission is granted to anyone to use this software for any purpose, -including commercial applications, and to alter it and redistribute it freely, -subject to the following restrictions: - -1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. -2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. -3. This notice may not be removed or altered from any source distribution. -*/ - -#include "btQuantizedBvh.h" - -#include "LinearMath/btAabbUtil2.h" -#include "LinearMath/btIDebugDraw.h" - - -btQuantizedBvh::btQuantizedBvh() : m_useQuantization(false), - //m_traversalMode(TRAVERSAL_STACKLESS_CACHE_FRIENDLY) - m_traversalMode(TRAVERSAL_STACKLESS) - //m_traversalMode(TRAVERSAL_RECURSIVE) - ,m_subtreeHeaderCount(0) //PCK: add this line -{ - -} - - - - - -void btQuantizedBvh::buildInternal() -{ - ///assumes that caller filled in the m_quantizedLeafNodes - m_useQuantization = true; - int numLeafNodes = 0; - - if (m_useQuantization) - { - //now we have an array of leafnodes in m_leafNodes - numLeafNodes = m_quantizedLeafNodes.size(); - - m_quantizedContiguousNodes.resize(2*numLeafNodes); - - } - - m_curNodeIndex = 0; - - buildTree(0,numLeafNodes); - - ///if the entire tree is small then subtree size, we need to create a header info for the tree - if(m_useQuantization && !m_SubtreeHeaders.size()) - { - btBvhSubtreeInfo& subtree = m_SubtreeHeaders.expand(); - subtree.setAabbFromQuantizeNode(m_quantizedContiguousNodes[0]); - subtree.m_rootNodeIndex = 0; - subtree.m_subtreeSize = m_quantizedContiguousNodes[0].isLeafNode() ? 1 : m_quantizedContiguousNodes[0].getEscapeIndex(); - } - - //PCK: update the copy of the size - m_subtreeHeaderCount = m_SubtreeHeaders.size(); - - //PCK: clear m_quantizedLeafNodes and m_leafNodes, they are temporary - m_quantizedLeafNodes.clear(); - m_leafNodes.clear(); -} - - - -///just for debugging, to visualize the individual patches/subtrees -#ifdef DEBUG_PATCH_COLORS -btVector3 color[4]= -{ - btVector3(255,0,0), - btVector3(0,255,0), - btVector3(0,0,255), - btVector3(0,255,255) -}; -#endif //DEBUG_PATCH_COLORS - - - -void btQuantizedBvh::setQuantizationValues(const btVector3& bvhAabbMin,const btVector3& bvhAabbMax,btScalar quantizationMargin) -{ - //enlarge the AABB to avoid division by zero when initializing the quantization values - btVector3 clampValue(quantizationMargin,quantizationMargin,quantizationMargin); - m_bvhAabbMin = bvhAabbMin - clampValue; - m_bvhAabbMax = bvhAabbMax + clampValue; - btVector3 aabbSize = m_bvhAabbMax - m_bvhAabbMin; - m_bvhQuantization = btVector3(btScalar(65533.0),btScalar(65533.0),btScalar(65533.0)) / aabbSize; - m_useQuantization = true; -} - - - - -btQuantizedBvh::~btQuantizedBvh() -{ -} - -#ifdef DEBUG_TREE_BUILDING -int gStackDepth = 0; -int gMaxStackDepth = 0; -#endif //DEBUG_TREE_BUILDING - -void btQuantizedBvh::buildTree (int startIndex,int endIndex) -{ -#ifdef DEBUG_TREE_BUILDING - gStackDepth++; - if (gStackDepth > gMaxStackDepth) - gMaxStackDepth = gStackDepth; -#endif //DEBUG_TREE_BUILDING - - - int splitAxis, splitIndex, i; - int numIndices =endIndex-startIndex; - int curIndex = m_curNodeIndex; - - assert(numIndices>0); - - if (numIndices==1) - { -#ifdef DEBUG_TREE_BUILDING - gStackDepth--; -#endif //DEBUG_TREE_BUILDING - - assignInternalNodeFromLeafNode(m_curNodeIndex,startIndex); - - m_curNodeIndex++; - return; - } - //calculate Best Splitting Axis and where to split it. Sort the incoming 'leafNodes' array within range 'startIndex/endIndex'. - - splitAxis = calcSplittingAxis(startIndex,endIndex); - - splitIndex = sortAndCalcSplittingIndex(startIndex,endIndex,splitAxis); - - int internalNodeIndex = m_curNodeIndex; - - setInternalNodeAabbMax(m_curNodeIndex,m_bvhAabbMin); - setInternalNodeAabbMin(m_curNodeIndex,m_bvhAabbMax); - - for (i=startIndex;im_escapeIndex; - - int leftChildNodexIndex = m_curNodeIndex; - - //build left child tree - buildTree(startIndex,splitIndex); - - int rightChildNodexIndex = m_curNodeIndex; - //build right child tree - buildTree(splitIndex,endIndex); - -#ifdef DEBUG_TREE_BUILDING - gStackDepth--; -#endif //DEBUG_TREE_BUILDING - - int escapeIndex = m_curNodeIndex - curIndex; - - if (m_useQuantization) - { - //escapeIndex is the number of nodes of this subtree - const int sizeQuantizedNode =sizeof(btQuantizedBvhNode); - const int treeSizeInBytes = escapeIndex * sizeQuantizedNode; - if (treeSizeInBytes > MAX_SUBTREE_SIZE_IN_BYTES) - { - updateSubtreeHeaders(leftChildNodexIndex,rightChildNodexIndex); - } - } - - setInternalNodeEscapeIndex(internalNodeIndex,escapeIndex); - -} - -void btQuantizedBvh::updateSubtreeHeaders(int leftChildNodexIndex,int rightChildNodexIndex) -{ - btAssert(m_useQuantization); - - btQuantizedBvhNode& leftChildNode = m_quantizedContiguousNodes[leftChildNodexIndex]; - int leftSubTreeSize = leftChildNode.isLeafNode() ? 1 : leftChildNode.getEscapeIndex(); - int leftSubTreeSizeInBytes = leftSubTreeSize * static_cast(sizeof(btQuantizedBvhNode)); - - btQuantizedBvhNode& rightChildNode = m_quantizedContiguousNodes[rightChildNodexIndex]; - int rightSubTreeSize = rightChildNode.isLeafNode() ? 1 : rightChildNode.getEscapeIndex(); - int rightSubTreeSizeInBytes = rightSubTreeSize * static_cast(sizeof(btQuantizedBvhNode)); - - if(leftSubTreeSizeInBytes <= MAX_SUBTREE_SIZE_IN_BYTES) - { - btBvhSubtreeInfo& subtree = m_SubtreeHeaders.expand(); - subtree.setAabbFromQuantizeNode(leftChildNode); - subtree.m_rootNodeIndex = leftChildNodexIndex; - subtree.m_subtreeSize = leftSubTreeSize; - } - - if(rightSubTreeSizeInBytes <= MAX_SUBTREE_SIZE_IN_BYTES) - { - btBvhSubtreeInfo& subtree = m_SubtreeHeaders.expand(); - subtree.setAabbFromQuantizeNode(rightChildNode); - subtree.m_rootNodeIndex = rightChildNodexIndex; - subtree.m_subtreeSize = rightSubTreeSize; - } - - //PCK: update the copy of the size - m_subtreeHeaderCount = m_SubtreeHeaders.size(); -} - - -int btQuantizedBvh::sortAndCalcSplittingIndex(int startIndex,int endIndex,int splitAxis) -{ - int i; - int splitIndex =startIndex; - int numIndices = endIndex - startIndex; - btScalar splitValue; - - btVector3 means(btScalar(0.),btScalar(0.),btScalar(0.)); - for (i=startIndex;i splitValue) - { - //swap - swapLeafNodes(i,splitIndex); - splitIndex++; - } - } - - //if the splitIndex causes unbalanced trees, fix this by using the center in between startIndex and endIndex - //otherwise the tree-building might fail due to stack-overflows in certain cases. - //unbalanced1 is unsafe: it can cause stack overflows - //bool unbalanced1 = ((splitIndex==startIndex) || (splitIndex == (endIndex-1))); - - //unbalanced2 should work too: always use center (perfect balanced trees) - //bool unbalanced2 = true; - - //this should be safe too: - int rangeBalancedIndices = numIndices/3; - bool unbalanced = ((splitIndex<=(startIndex+rangeBalancedIndices)) || (splitIndex >=(endIndex-1-rangeBalancedIndices))); - - if (unbalanced) - { - splitIndex = startIndex+ (numIndices>>1); - } - - bool unbal = (splitIndex==startIndex) || (splitIndex == (endIndex)); - (void)unbal; - btAssert(!unbal); - - return splitIndex; -} - - -int btQuantizedBvh::calcSplittingAxis(int startIndex,int endIndex) -{ - int i; - - btVector3 means(btScalar(0.),btScalar(0.),btScalar(0.)); - btVector3 variance(btScalar(0.),btScalar(0.),btScalar(0.)); - int numIndices = endIndex-startIndex; - - for (i=startIndex;im_aabbMinOrg,rootNode->m_aabbMaxOrg); - isLeafNode = rootNode->m_escapeIndex == -1; - - //PCK: unsigned instead of bool - if (isLeafNode && (aabbOverlap != 0)) - { - nodeCallback->processNode(rootNode->m_subPart,rootNode->m_triangleIndex); - } - - //PCK: unsigned instead of bool - if ((aabbOverlap != 0) || isLeafNode) - { - rootNode++; - curIndex++; - } else - { - escapeIndex = rootNode->m_escapeIndex; - rootNode += escapeIndex; - curIndex += escapeIndex; - } - } - if (maxIterations < walkIterations) - maxIterations = walkIterations; - -} - -/* -///this was the original recursive traversal, before we optimized towards stackless traversal -void btQuantizedBvh::walkTree(btOptimizedBvhNode* rootNode,btNodeOverlapCallback* nodeCallback,const btVector3& aabbMin,const btVector3& aabbMax) const -{ - bool isLeafNode, aabbOverlap = TestAabbAgainstAabb2(aabbMin,aabbMax,rootNode->m_aabbMin,rootNode->m_aabbMax); - if (aabbOverlap) - { - isLeafNode = (!rootNode->m_leftChild && !rootNode->m_rightChild); - if (isLeafNode) - { - nodeCallback->processNode(rootNode); - } else - { - walkTree(rootNode->m_leftChild,nodeCallback,aabbMin,aabbMax); - walkTree(rootNode->m_rightChild,nodeCallback,aabbMin,aabbMax); - } - } - -} -*/ - -void btQuantizedBvh::walkRecursiveQuantizedTreeAgainstQueryAabb(const btQuantizedBvhNode* currentNode,btNodeOverlapCallback* nodeCallback,unsigned short int* quantizedQueryAabbMin,unsigned short int* quantizedQueryAabbMax) const -{ - btAssert(m_useQuantization); - - bool isLeafNode; - //PCK: unsigned instead of bool - unsigned aabbOverlap; - - //PCK: unsigned instead of bool - aabbOverlap = testQuantizedAabbAgainstQuantizedAabb(quantizedQueryAabbMin,quantizedQueryAabbMax,currentNode->m_quantizedAabbMin,currentNode->m_quantizedAabbMax); - isLeafNode = currentNode->isLeafNode(); - - //PCK: unsigned instead of bool - if (aabbOverlap != 0) - { - if (isLeafNode) - { - nodeCallback->processNode(currentNode->getPartId(),currentNode->getTriangleIndex()); - } else - { - //process left and right children - const btQuantizedBvhNode* leftChildNode = currentNode+1; - walkRecursiveQuantizedTreeAgainstQueryAabb(leftChildNode,nodeCallback,quantizedQueryAabbMin,quantizedQueryAabbMax); - - const btQuantizedBvhNode* rightChildNode = leftChildNode->isLeafNode() ? leftChildNode+1:leftChildNode+leftChildNode->getEscapeIndex(); - walkRecursiveQuantizedTreeAgainstQueryAabb(rightChildNode,nodeCallback,quantizedQueryAabbMin,quantizedQueryAabbMax); - } - } -} - - - - - -void btQuantizedBvh::walkStacklessQuantizedTreeAgainstRay(btNodeOverlapCallback* nodeCallback, const btVector3& raySource, const btVector3& rayTarget, const btVector3& aabbMin, const btVector3& aabbMax, int startNodeIndex,int endNodeIndex) const -{ - btAssert(m_useQuantization); - - int curIndex = startNodeIndex; - int walkIterations = 0; - int subTreeSize = endNodeIndex - startNodeIndex; - (void)subTreeSize; - - const btQuantizedBvhNode* rootNode = &m_quantizedContiguousNodes[startNodeIndex]; - int escapeIndex; - - bool isLeafNode; - //PCK: unsigned instead of bool - unsigned boxBoxOverlap = 0; - unsigned rayBoxOverlap = 0; - - btScalar lambda_max = 1.0; -#define RAYAABB2 -#ifdef RAYAABB2 - btVector3 rayFrom = raySource; - btVector3 rayDirection = (rayTarget-raySource); - rayDirection.normalize (); - lambda_max = rayDirection.dot(rayTarget-raySource); - ///what about division by zero? --> just set rayDirection[i] to 1.0 - rayDirection[0] = rayDirection[0] == btScalar(0.0) ? btScalar(1e30) : btScalar(1.0) / rayDirection[0]; - rayDirection[1] = rayDirection[1] == btScalar(0.0) ? btScalar(1e30) : btScalar(1.0) / rayDirection[1]; - rayDirection[2] = rayDirection[2] == btScalar(0.0) ? btScalar(1e30) : btScalar(1.0) / rayDirection[2]; - unsigned int sign[3] = { rayDirection[0] < 0.0, rayDirection[1] < 0.0, rayDirection[2] < 0.0}; -#endif - - /* Quick pruning by quantized box */ - btVector3 rayAabbMin = raySource; - btVector3 rayAabbMax = raySource; - rayAabbMin.setMin(rayTarget); - rayAabbMax.setMax(rayTarget); - - /* Add box cast extents to bounding box */ - rayAabbMin += aabbMin; - rayAabbMax += aabbMax; - - unsigned short int quantizedQueryAabbMin[3]; - unsigned short int quantizedQueryAabbMax[3]; - quantizeWithClamp(quantizedQueryAabbMin,rayAabbMin,0); - quantizeWithClamp(quantizedQueryAabbMax,rayAabbMax,1); - - while (curIndex < endNodeIndex) - { - -//#define VISUALLY_ANALYZE_BVH 1 -#ifdef VISUALLY_ANALYZE_BVH - //some code snippet to debugDraw aabb, to visually analyze bvh structure - static int drawPatch = 0; - //need some global access to a debugDrawer - extern btIDebugDraw* debugDrawerPtr; - if (curIndex==drawPatch) - { - btVector3 aabbMin,aabbMax; - aabbMin = unQuantize(rootNode->m_quantizedAabbMin); - aabbMax = unQuantize(rootNode->m_quantizedAabbMax); - btVector3 color(1,0,0); - debugDrawerPtr->drawAabb(aabbMin,aabbMax,color); - } -#endif//VISUALLY_ANALYZE_BVH - - //catch bugs in tree data - assert (walkIterations < subTreeSize); - - walkIterations++; - //PCK: unsigned instead of bool - // only interested if this is closer than any previous hit - btScalar param = 1.0; - rayBoxOverlap = 0; - boxBoxOverlap = testQuantizedAabbAgainstQuantizedAabb(quantizedQueryAabbMin,quantizedQueryAabbMax,rootNode->m_quantizedAabbMin,rootNode->m_quantizedAabbMax); - isLeafNode = rootNode->isLeafNode(); - if (boxBoxOverlap) - { - btVector3 bounds[2]; - bounds[0] = unQuantize(rootNode->m_quantizedAabbMin); - bounds[1] = unQuantize(rootNode->m_quantizedAabbMax); - /* Add box cast extents */ - bounds[0] += aabbMin; - bounds[1] += aabbMax; - btVector3 normal; -#if 0 - bool ra2 = btRayAabb2 (raySource, rayDirection, sign, bounds, param, 0.0, lambda_max); - bool ra = btRayAabb (raySource, rayTarget, bounds[0], bounds[1], param, normal); - if (ra2 != ra) - { - printf("functions don't match\n"); - } -#endif -#ifdef RAYAABB2 - ///careful with this check: need to check division by zero (above) and fix the unQuantize method - ///thanks Joerg/hiker for the reproduction case! - ///http://www.bulletphysics.com/Bullet/phpBB3/viewtopic.php?f=9&t=1858 - - rayBoxOverlap = btRayAabb2 (raySource, rayDirection, sign, bounds, param, 0.0f, lambda_max); -#else - rayBoxOverlap = true;//btRayAabb(raySource, rayTarget, bounds[0], bounds[1], param, normal); -#endif - } - - if (isLeafNode && rayBoxOverlap) - { - nodeCallback->processNode(rootNode->getPartId(),rootNode->getTriangleIndex()); - } - - //PCK: unsigned instead of bool - if ((rayBoxOverlap != 0) || isLeafNode) - { - rootNode++; - curIndex++; - } else - { - escapeIndex = rootNode->getEscapeIndex(); - rootNode += escapeIndex; - curIndex += escapeIndex; - } - } - if (maxIterations < walkIterations) - maxIterations = walkIterations; - -} - -void btQuantizedBvh::walkStacklessQuantizedTree(btNodeOverlapCallback* nodeCallback,unsigned short int* quantizedQueryAabbMin,unsigned short int* quantizedQueryAabbMax,int startNodeIndex,int endNodeIndex) const -{ - btAssert(m_useQuantization); - - int curIndex = startNodeIndex; - int walkIterations = 0; - int subTreeSize = endNodeIndex - startNodeIndex; - (void)subTreeSize; - - const btQuantizedBvhNode* rootNode = &m_quantizedContiguousNodes[startNodeIndex]; - int escapeIndex; - - bool isLeafNode; - //PCK: unsigned instead of bool - unsigned aabbOverlap; - - while (curIndex < endNodeIndex) - { - -//#define VISUALLY_ANALYZE_BVH 1 -#ifdef VISUALLY_ANALYZE_BVH - //some code snippet to debugDraw aabb, to visually analyze bvh structure - static int drawPatch = 0; - //need some global access to a debugDrawer - extern btIDebugDraw* debugDrawerPtr; - if (curIndex==drawPatch) - { - btVector3 aabbMin,aabbMax; - aabbMin = unQuantize(rootNode->m_quantizedAabbMin); - aabbMax = unQuantize(rootNode->m_quantizedAabbMax); - btVector3 color(1,0,0); - debugDrawerPtr->drawAabb(aabbMin,aabbMax,color); - } -#endif//VISUALLY_ANALYZE_BVH - - //catch bugs in tree data - assert (walkIterations < subTreeSize); - - walkIterations++; - //PCK: unsigned instead of bool - aabbOverlap = testQuantizedAabbAgainstQuantizedAabb(quantizedQueryAabbMin,quantizedQueryAabbMax,rootNode->m_quantizedAabbMin,rootNode->m_quantizedAabbMax); - isLeafNode = rootNode->isLeafNode(); - - if (isLeafNode && aabbOverlap) - { - nodeCallback->processNode(rootNode->getPartId(),rootNode->getTriangleIndex()); - } - - //PCK: unsigned instead of bool - if ((aabbOverlap != 0) || isLeafNode) - { - rootNode++; - curIndex++; - } else - { - escapeIndex = rootNode->getEscapeIndex(); - rootNode += escapeIndex; - curIndex += escapeIndex; - } - } - if (maxIterations < walkIterations) - maxIterations = walkIterations; - -} - -//This traversal can be called from Playstation 3 SPU -void btQuantizedBvh::walkStacklessQuantizedTreeCacheFriendly(btNodeOverlapCallback* nodeCallback,unsigned short int* quantizedQueryAabbMin,unsigned short int* quantizedQueryAabbMax) const -{ - btAssert(m_useQuantization); - - int i; - - - for (i=0;im_SubtreeHeaders.size();i++) - { - const btBvhSubtreeInfo& subtree = m_SubtreeHeaders[i]; - - //PCK: unsigned instead of bool - unsigned overlap = testQuantizedAabbAgainstQuantizedAabb(quantizedQueryAabbMin,quantizedQueryAabbMax,subtree.m_quantizedAabbMin,subtree.m_quantizedAabbMax); - if (overlap != 0) - { - walkStacklessQuantizedTree(nodeCallback,quantizedQueryAabbMin,quantizedQueryAabbMax, - subtree.m_rootNodeIndex, - subtree.m_rootNodeIndex+subtree.m_subtreeSize); - } - } -} - - -void btQuantizedBvh::reportRayOverlappingNodex (btNodeOverlapCallback* nodeCallback, const btVector3& raySource, const btVector3& rayTarget) const -{ - bool fast_path = m_useQuantization && m_traversalMode == TRAVERSAL_STACKLESS; - if (fast_path) - { - walkStacklessQuantizedTreeAgainstRay(nodeCallback, raySource, rayTarget, btVector3(0, 0, 0), btVector3(0, 0, 0), 0, m_curNodeIndex); - } else { - /* Otherwise fallback to AABB overlap test */ - btVector3 aabbMin = raySource; - btVector3 aabbMax = raySource; - aabbMin.setMin(rayTarget); - aabbMax.setMax(rayTarget); - reportAabbOverlappingNodex(nodeCallback,aabbMin,aabbMax); - } -} - - -void btQuantizedBvh::reportBoxCastOverlappingNodex(btNodeOverlapCallback* nodeCallback, const btVector3& raySource, const btVector3& rayTarget, const btVector3& aabbMin,const btVector3& aabbMax) const -{ - bool fast_path = m_useQuantization && m_traversalMode == TRAVERSAL_STACKLESS; - if (fast_path) - { - walkStacklessQuantizedTreeAgainstRay(nodeCallback, raySource, rayTarget, aabbMin, aabbMax, 0, m_curNodeIndex); - } else { - /* Slow path: - Construct the bounding box for the entire box cast and send that down the tree */ - btVector3 qaabbMin = raySource; - btVector3 qaabbMax = raySource; - qaabbMin.setMin(rayTarget); - qaabbMax.setMax(rayTarget); - qaabbMin += aabbMin; - qaabbMax += aabbMax; - reportAabbOverlappingNodex(nodeCallback,qaabbMin,qaabbMax); - } -} - - -void btQuantizedBvh::swapLeafNodes(int i,int splitIndex) -{ - if (m_useQuantization) - { - btQuantizedBvhNode tmp = m_quantizedLeafNodes[i]; - m_quantizedLeafNodes[i] = m_quantizedLeafNodes[splitIndex]; - m_quantizedLeafNodes[splitIndex] = tmp; - } else - { - btOptimizedBvhNode tmp = m_leafNodes[i]; - m_leafNodes[i] = m_leafNodes[splitIndex]; - m_leafNodes[splitIndex] = tmp; - } -} - -void btQuantizedBvh::assignInternalNodeFromLeafNode(int internalNode,int leafNodeIndex) -{ - if (m_useQuantization) - { - m_quantizedContiguousNodes[internalNode] = m_quantizedLeafNodes[leafNodeIndex]; - } else - { - m_contiguousNodes[internalNode] = m_leafNodes[leafNodeIndex]; - } -} - -//PCK: include -#include - -//PCK: consts -static const unsigned BVH_ALIGNMENT = 16; -static const unsigned BVH_ALIGNMENT_MASK = BVH_ALIGNMENT-1; - -static const unsigned BVH_ALIGNMENT_BLOCKS = 2; - - - -unsigned int btQuantizedBvh::getAlignmentSerializationPadding() -{ - return BVH_ALIGNMENT_BLOCKS * BVH_ALIGNMENT; -} - -unsigned btQuantizedBvh::calculateSerializeBufferSize() -{ - unsigned baseSize = sizeof(btQuantizedBvh) + getAlignmentSerializationPadding(); - baseSize += sizeof(btBvhSubtreeInfo) * m_subtreeHeaderCount; - if (m_useQuantization) - { - return baseSize + m_curNodeIndex * sizeof(btQuantizedBvhNode); - } - return baseSize + m_curNodeIndex * sizeof(btOptimizedBvhNode); -} - -bool btQuantizedBvh::serialize(void *o_alignedDataBuffer, unsigned /*i_dataBufferSize */, bool i_swapEndian) -{ - assert(m_subtreeHeaderCount == m_SubtreeHeaders.size()); - m_subtreeHeaderCount = m_SubtreeHeaders.size(); - -/* if (i_dataBufferSize < calculateSerializeBufferSize() || o_alignedDataBuffer == NULL || (((unsigned)o_alignedDataBuffer & BVH_ALIGNMENT_MASK) != 0)) - { - ///check alignedment for buffer? - btAssert(0); - return false; - } -*/ - - btQuantizedBvh *targetBvh = (btQuantizedBvh *)o_alignedDataBuffer; - - // construct the class so the virtual function table, etc will be set up - // Also, m_leafNodes and m_quantizedLeafNodes will be initialized to default values by the constructor - new (targetBvh) btQuantizedBvh; - - if (i_swapEndian) - { - targetBvh->m_curNodeIndex = static_cast(btSwapEndian(m_curNodeIndex)); - - - btSwapVector3Endian(m_bvhAabbMin,targetBvh->m_bvhAabbMin); - btSwapVector3Endian(m_bvhAabbMax,targetBvh->m_bvhAabbMax); - btSwapVector3Endian(m_bvhQuantization,targetBvh->m_bvhQuantization); - - targetBvh->m_traversalMode = (btTraversalMode)btSwapEndian(m_traversalMode); - targetBvh->m_subtreeHeaderCount = static_cast(btSwapEndian(m_subtreeHeaderCount)); - } - else - { - targetBvh->m_curNodeIndex = m_curNodeIndex; - targetBvh->m_bvhAabbMin = m_bvhAabbMin; - targetBvh->m_bvhAabbMax = m_bvhAabbMax; - targetBvh->m_bvhQuantization = m_bvhQuantization; - targetBvh->m_traversalMode = m_traversalMode; - targetBvh->m_subtreeHeaderCount = m_subtreeHeaderCount; - } - - targetBvh->m_useQuantization = m_useQuantization; - - unsigned char *nodeData = (unsigned char *)targetBvh; - nodeData += sizeof(btQuantizedBvh); - - unsigned sizeToAdd = 0;//(BVH_ALIGNMENT-((unsigned)nodeData & BVH_ALIGNMENT_MASK))&BVH_ALIGNMENT_MASK; - nodeData += sizeToAdd; - - int nodeCount = m_curNodeIndex; - - if (m_useQuantization) - { - targetBvh->m_quantizedContiguousNodes.initializeFromBuffer(nodeData, nodeCount, nodeCount); - - if (i_swapEndian) - { - for (int nodeIndex = 0; nodeIndex < nodeCount; nodeIndex++) - { - targetBvh->m_quantizedContiguousNodes[nodeIndex].m_quantizedAabbMin[0] = btSwapEndian(m_quantizedContiguousNodes[nodeIndex].m_quantizedAabbMin[0]); - targetBvh->m_quantizedContiguousNodes[nodeIndex].m_quantizedAabbMin[1] = btSwapEndian(m_quantizedContiguousNodes[nodeIndex].m_quantizedAabbMin[1]); - targetBvh->m_quantizedContiguousNodes[nodeIndex].m_quantizedAabbMin[2] = btSwapEndian(m_quantizedContiguousNodes[nodeIndex].m_quantizedAabbMin[2]); - - targetBvh->m_quantizedContiguousNodes[nodeIndex].m_quantizedAabbMax[0] = btSwapEndian(m_quantizedContiguousNodes[nodeIndex].m_quantizedAabbMax[0]); - targetBvh->m_quantizedContiguousNodes[nodeIndex].m_quantizedAabbMax[1] = btSwapEndian(m_quantizedContiguousNodes[nodeIndex].m_quantizedAabbMax[1]); - targetBvh->m_quantizedContiguousNodes[nodeIndex].m_quantizedAabbMax[2] = btSwapEndian(m_quantizedContiguousNodes[nodeIndex].m_quantizedAabbMax[2]); - - targetBvh->m_quantizedContiguousNodes[nodeIndex].m_escapeIndexOrTriangleIndex = static_cast(btSwapEndian(m_quantizedContiguousNodes[nodeIndex].m_escapeIndexOrTriangleIndex)); - } - } - else - { - for (int nodeIndex = 0; nodeIndex < nodeCount; nodeIndex++) - { - - targetBvh->m_quantizedContiguousNodes[nodeIndex].m_quantizedAabbMin[0] = m_quantizedContiguousNodes[nodeIndex].m_quantizedAabbMin[0]; - targetBvh->m_quantizedContiguousNodes[nodeIndex].m_quantizedAabbMin[1] = m_quantizedContiguousNodes[nodeIndex].m_quantizedAabbMin[1]; - targetBvh->m_quantizedContiguousNodes[nodeIndex].m_quantizedAabbMin[2] = m_quantizedContiguousNodes[nodeIndex].m_quantizedAabbMin[2]; - - targetBvh->m_quantizedContiguousNodes[nodeIndex].m_quantizedAabbMax[0] = m_quantizedContiguousNodes[nodeIndex].m_quantizedAabbMax[0]; - targetBvh->m_quantizedContiguousNodes[nodeIndex].m_quantizedAabbMax[1] = m_quantizedContiguousNodes[nodeIndex].m_quantizedAabbMax[1]; - targetBvh->m_quantizedContiguousNodes[nodeIndex].m_quantizedAabbMax[2] = m_quantizedContiguousNodes[nodeIndex].m_quantizedAabbMax[2]; - - targetBvh->m_quantizedContiguousNodes[nodeIndex].m_escapeIndexOrTriangleIndex = m_quantizedContiguousNodes[nodeIndex].m_escapeIndexOrTriangleIndex; - - - } - } - nodeData += sizeof(btQuantizedBvhNode) * nodeCount; - } - else - { - targetBvh->m_contiguousNodes.initializeFromBuffer(nodeData, nodeCount, nodeCount); - - if (i_swapEndian) - { - for (int nodeIndex = 0; nodeIndex < nodeCount; nodeIndex++) - { - btSwapVector3Endian(m_contiguousNodes[nodeIndex].m_aabbMinOrg, targetBvh->m_contiguousNodes[nodeIndex].m_aabbMinOrg); - btSwapVector3Endian(m_contiguousNodes[nodeIndex].m_aabbMaxOrg, targetBvh->m_contiguousNodes[nodeIndex].m_aabbMaxOrg); - - targetBvh->m_contiguousNodes[nodeIndex].m_escapeIndex = static_cast(btSwapEndian(m_contiguousNodes[nodeIndex].m_escapeIndex)); - targetBvh->m_contiguousNodes[nodeIndex].m_subPart = static_cast(btSwapEndian(m_contiguousNodes[nodeIndex].m_subPart)); - targetBvh->m_contiguousNodes[nodeIndex].m_triangleIndex = static_cast(btSwapEndian(m_contiguousNodes[nodeIndex].m_triangleIndex)); - } - } - else - { - for (int nodeIndex = 0; nodeIndex < nodeCount; nodeIndex++) - { - targetBvh->m_contiguousNodes[nodeIndex].m_aabbMinOrg = m_contiguousNodes[nodeIndex].m_aabbMinOrg; - targetBvh->m_contiguousNodes[nodeIndex].m_aabbMaxOrg = m_contiguousNodes[nodeIndex].m_aabbMaxOrg; - - targetBvh->m_contiguousNodes[nodeIndex].m_escapeIndex = m_contiguousNodes[nodeIndex].m_escapeIndex; - targetBvh->m_contiguousNodes[nodeIndex].m_subPart = m_contiguousNodes[nodeIndex].m_subPart; - targetBvh->m_contiguousNodes[nodeIndex].m_triangleIndex = m_contiguousNodes[nodeIndex].m_triangleIndex; - } - } - nodeData += sizeof(btOptimizedBvhNode) * nodeCount; - } - - sizeToAdd = 0;//(BVH_ALIGNMENT-((unsigned)nodeData & BVH_ALIGNMENT_MASK))&BVH_ALIGNMENT_MASK; - nodeData += sizeToAdd; - - // Now serialize the subtree headers - targetBvh->m_SubtreeHeaders.initializeFromBuffer(nodeData, m_subtreeHeaderCount, m_subtreeHeaderCount); - if (i_swapEndian) - { - for (int i = 0; i < m_subtreeHeaderCount; i++) - { - targetBvh->m_SubtreeHeaders[i].m_quantizedAabbMin[0] = btSwapEndian(m_SubtreeHeaders[i].m_quantizedAabbMin[0]); - targetBvh->m_SubtreeHeaders[i].m_quantizedAabbMin[1] = btSwapEndian(m_SubtreeHeaders[i].m_quantizedAabbMin[1]); - targetBvh->m_SubtreeHeaders[i].m_quantizedAabbMin[2] = btSwapEndian(m_SubtreeHeaders[i].m_quantizedAabbMin[2]); - - targetBvh->m_SubtreeHeaders[i].m_quantizedAabbMax[0] = btSwapEndian(m_SubtreeHeaders[i].m_quantizedAabbMax[0]); - targetBvh->m_SubtreeHeaders[i].m_quantizedAabbMax[1] = btSwapEndian(m_SubtreeHeaders[i].m_quantizedAabbMax[1]); - targetBvh->m_SubtreeHeaders[i].m_quantizedAabbMax[2] = btSwapEndian(m_SubtreeHeaders[i].m_quantizedAabbMax[2]); - - targetBvh->m_SubtreeHeaders[i].m_rootNodeIndex = static_cast(btSwapEndian(m_SubtreeHeaders[i].m_rootNodeIndex)); - targetBvh->m_SubtreeHeaders[i].m_subtreeSize = static_cast(btSwapEndian(m_SubtreeHeaders[i].m_subtreeSize)); - } - } - else - { - for (int i = 0; i < m_subtreeHeaderCount; i++) - { - targetBvh->m_SubtreeHeaders[i].m_quantizedAabbMin[0] = (m_SubtreeHeaders[i].m_quantizedAabbMin[0]); - targetBvh->m_SubtreeHeaders[i].m_quantizedAabbMin[1] = (m_SubtreeHeaders[i].m_quantizedAabbMin[1]); - targetBvh->m_SubtreeHeaders[i].m_quantizedAabbMin[2] = (m_SubtreeHeaders[i].m_quantizedAabbMin[2]); - - targetBvh->m_SubtreeHeaders[i].m_quantizedAabbMax[0] = (m_SubtreeHeaders[i].m_quantizedAabbMax[0]); - targetBvh->m_SubtreeHeaders[i].m_quantizedAabbMax[1] = (m_SubtreeHeaders[i].m_quantizedAabbMax[1]); - targetBvh->m_SubtreeHeaders[i].m_quantizedAabbMax[2] = (m_SubtreeHeaders[i].m_quantizedAabbMax[2]); - - targetBvh->m_SubtreeHeaders[i].m_rootNodeIndex = (m_SubtreeHeaders[i].m_rootNodeIndex); - targetBvh->m_SubtreeHeaders[i].m_subtreeSize = (m_SubtreeHeaders[i].m_subtreeSize); - targetBvh->m_SubtreeHeaders[i] = m_SubtreeHeaders[i]; - } - } - - nodeData += sizeof(btBvhSubtreeInfo) * m_subtreeHeaderCount; - - return true; -} - -btQuantizedBvh *btQuantizedBvh::deSerializeInPlace(void *i_alignedDataBuffer, unsigned int i_dataBufferSize, bool i_swapEndian) -{ - - if (i_alignedDataBuffer == NULL)// || (((unsigned)i_alignedDataBuffer & BVH_ALIGNMENT_MASK) != 0)) - { - return NULL; - } - btQuantizedBvh *bvh = (btQuantizedBvh *)i_alignedDataBuffer; - - if (i_swapEndian) - { - bvh->m_curNodeIndex = static_cast(btSwapEndian(bvh->m_curNodeIndex)); - - btUnSwapVector3Endian(bvh->m_bvhAabbMin); - btUnSwapVector3Endian(bvh->m_bvhAabbMax); - btUnSwapVector3Endian(bvh->m_bvhQuantization); - - bvh->m_traversalMode = (btTraversalMode)btSwapEndian(bvh->m_traversalMode); - bvh->m_subtreeHeaderCount = static_cast(btSwapEndian(bvh->m_subtreeHeaderCount)); - } - - unsigned int calculatedBufSize = bvh->calculateSerializeBufferSize(); - btAssert(calculatedBufSize <= i_dataBufferSize); - - if (calculatedBufSize > i_dataBufferSize) - { - return NULL; - } - - unsigned char *nodeData = (unsigned char *)bvh; - nodeData += sizeof(btQuantizedBvh); - - unsigned sizeToAdd = 0;//(BVH_ALIGNMENT-((unsigned)nodeData & BVH_ALIGNMENT_MASK))&BVH_ALIGNMENT_MASK; - nodeData += sizeToAdd; - - int nodeCount = bvh->m_curNodeIndex; - - // Must call placement new to fill in virtual function table, etc, but we don't want to overwrite most data, so call a special version of the constructor - // Also, m_leafNodes and m_quantizedLeafNodes will be initialized to default values by the constructor - new (bvh) btQuantizedBvh(*bvh, false); - - if (bvh->m_useQuantization) - { - bvh->m_quantizedContiguousNodes.initializeFromBuffer(nodeData, nodeCount, nodeCount); - - if (i_swapEndian) - { - for (int nodeIndex = 0; nodeIndex < nodeCount; nodeIndex++) - { - bvh->m_quantizedContiguousNodes[nodeIndex].m_quantizedAabbMin[0] = btSwapEndian(bvh->m_quantizedContiguousNodes[nodeIndex].m_quantizedAabbMin[0]); - bvh->m_quantizedContiguousNodes[nodeIndex].m_quantizedAabbMin[1] = btSwapEndian(bvh->m_quantizedContiguousNodes[nodeIndex].m_quantizedAabbMin[1]); - bvh->m_quantizedContiguousNodes[nodeIndex].m_quantizedAabbMin[2] = btSwapEndian(bvh->m_quantizedContiguousNodes[nodeIndex].m_quantizedAabbMin[2]); - - bvh->m_quantizedContiguousNodes[nodeIndex].m_quantizedAabbMax[0] = btSwapEndian(bvh->m_quantizedContiguousNodes[nodeIndex].m_quantizedAabbMax[0]); - bvh->m_quantizedContiguousNodes[nodeIndex].m_quantizedAabbMax[1] = btSwapEndian(bvh->m_quantizedContiguousNodes[nodeIndex].m_quantizedAabbMax[1]); - bvh->m_quantizedContiguousNodes[nodeIndex].m_quantizedAabbMax[2] = btSwapEndian(bvh->m_quantizedContiguousNodes[nodeIndex].m_quantizedAabbMax[2]); - - bvh->m_quantizedContiguousNodes[nodeIndex].m_escapeIndexOrTriangleIndex = static_cast(btSwapEndian(bvh->m_quantizedContiguousNodes[nodeIndex].m_escapeIndexOrTriangleIndex)); - } - } - nodeData += sizeof(btQuantizedBvhNode) * nodeCount; - } - else - { - bvh->m_contiguousNodes.initializeFromBuffer(nodeData, nodeCount, nodeCount); - - if (i_swapEndian) - { - for (int nodeIndex = 0; nodeIndex < nodeCount; nodeIndex++) - { - btUnSwapVector3Endian(bvh->m_contiguousNodes[nodeIndex].m_aabbMinOrg); - btUnSwapVector3Endian(bvh->m_contiguousNodes[nodeIndex].m_aabbMaxOrg); - - bvh->m_contiguousNodes[nodeIndex].m_escapeIndex = static_cast(btSwapEndian(bvh->m_contiguousNodes[nodeIndex].m_escapeIndex)); - bvh->m_contiguousNodes[nodeIndex].m_subPart = static_cast(btSwapEndian(bvh->m_contiguousNodes[nodeIndex].m_subPart)); - bvh->m_contiguousNodes[nodeIndex].m_triangleIndex = static_cast(btSwapEndian(bvh->m_contiguousNodes[nodeIndex].m_triangleIndex)); - } - } - nodeData += sizeof(btOptimizedBvhNode) * nodeCount; - } - - sizeToAdd = 0;//(BVH_ALIGNMENT-((unsigned)nodeData & BVH_ALIGNMENT_MASK))&BVH_ALIGNMENT_MASK; - nodeData += sizeToAdd; - - // Now serialize the subtree headers - bvh->m_SubtreeHeaders.initializeFromBuffer(nodeData, bvh->m_subtreeHeaderCount, bvh->m_subtreeHeaderCount); - if (i_swapEndian) - { - for (int i = 0; i < bvh->m_subtreeHeaderCount; i++) - { - bvh->m_SubtreeHeaders[i].m_quantizedAabbMin[0] = btSwapEndian(bvh->m_SubtreeHeaders[i].m_quantizedAabbMin[0]); - bvh->m_SubtreeHeaders[i].m_quantizedAabbMin[1] = btSwapEndian(bvh->m_SubtreeHeaders[i].m_quantizedAabbMin[1]); - bvh->m_SubtreeHeaders[i].m_quantizedAabbMin[2] = btSwapEndian(bvh->m_SubtreeHeaders[i].m_quantizedAabbMin[2]); - - bvh->m_SubtreeHeaders[i].m_quantizedAabbMax[0] = btSwapEndian(bvh->m_SubtreeHeaders[i].m_quantizedAabbMax[0]); - bvh->m_SubtreeHeaders[i].m_quantizedAabbMax[1] = btSwapEndian(bvh->m_SubtreeHeaders[i].m_quantizedAabbMax[1]); - bvh->m_SubtreeHeaders[i].m_quantizedAabbMax[2] = btSwapEndian(bvh->m_SubtreeHeaders[i].m_quantizedAabbMax[2]); - - bvh->m_SubtreeHeaders[i].m_rootNodeIndex = static_cast(btSwapEndian(bvh->m_SubtreeHeaders[i].m_rootNodeIndex)); - bvh->m_SubtreeHeaders[i].m_subtreeSize = static_cast(btSwapEndian(bvh->m_SubtreeHeaders[i].m_subtreeSize)); - } - } - - return bvh; -} - -// Constructor that prevents btVector3's default constructor from being called -btQuantizedBvh::btQuantizedBvh(btQuantizedBvh &self, bool /* ownsMemory */) : -m_bvhAabbMin(self.m_bvhAabbMin), -m_bvhAabbMax(self.m_bvhAabbMax), -m_bvhQuantization(self.m_bvhQuantization) -{ - - -} - - - diff --git a/extern/bullet2/src/BulletCollision/BroadphaseCollision/btQuantizedBvh.h b/extern/bullet2/src/BulletCollision/BroadphaseCollision/btQuantizedBvh.h deleted file mode 100644 index 8a149b533fa..00000000000 --- a/extern/bullet2/src/BulletCollision/BroadphaseCollision/btQuantizedBvh.h +++ /dev/null @@ -1,486 +0,0 @@ -/* -Bullet Continuous Collision Detection and Physics Library -Copyright (c) 2003-2006 Erwin Coumans http://continuousphysics.com/Bullet/ - -This software is provided 'as-is', without any express or implied warranty. -In no event will the authors be held liable for any damages arising from the use of this software. -Permission is granted to anyone to use this software for any purpose, -including commercial applications, and to alter it and redistribute it freely, -subject to the following restrictions: - -1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. -2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. -3. This notice may not be removed or altered from any source distribution. -*/ - -#ifndef QUANTIZED_BVH_H -#define QUANTIZED_BVH_H - -//#define DEBUG_CHECK_DEQUANTIZATION 1 -#ifdef DEBUG_CHECK_DEQUANTIZATION -#ifdef __SPU__ -#define printf spu_printf -#endif //__SPU__ - -#include -#include -#endif //DEBUG_CHECK_DEQUANTIZATION - -#include "LinearMath/btVector3.h" -#include "LinearMath/btAlignedAllocator.h" - - -//http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vclang/html/vclrf__m128.asp - - -//Note: currently we have 16 bytes per quantized node -#define MAX_SUBTREE_SIZE_IN_BYTES 2048 - -// 10 gives the potential for 1024 parts, with at most 2^21 (2097152) (minus one -// actually) triangles each (since the sign bit is reserved -#define MAX_NUM_PARTS_IN_BITS 10 - -///btQuantizedBvhNode is a compressed aabb node, 16 bytes. -///Node can be used for leafnode or internal node. Leafnodes can point to 32-bit triangle index (non-negative range). -ATTRIBUTE_ALIGNED16 (struct) btQuantizedBvhNode -{ - BT_DECLARE_ALIGNED_ALLOCATOR(); - - //12 bytes - unsigned short int m_quantizedAabbMin[3]; - unsigned short int m_quantizedAabbMax[3]; - //4 bytes - int m_escapeIndexOrTriangleIndex; - - bool isLeafNode() const - { - //skipindex is negative (internal node), triangleindex >=0 (leafnode) - return (m_escapeIndexOrTriangleIndex >= 0); - } - int getEscapeIndex() const - { - btAssert(!isLeafNode()); - return -m_escapeIndexOrTriangleIndex; - } - int getTriangleIndex() const - { - btAssert(isLeafNode()); - // Get only the lower bits where the triangle index is stored - return (m_escapeIndexOrTriangleIndex&~((~0)<<(31-MAX_NUM_PARTS_IN_BITS))); - } - int getPartId() const - { - btAssert(isLeafNode()); - // Get only the highest bits where the part index is stored - return (m_escapeIndexOrTriangleIndex>>(31-MAX_NUM_PARTS_IN_BITS)); - } -} -; - -/// btOptimizedBvhNode contains both internal and leaf node information. -/// Total node size is 44 bytes / node. You can use the compressed version of 16 bytes. -ATTRIBUTE_ALIGNED16 (struct) btOptimizedBvhNode -{ - BT_DECLARE_ALIGNED_ALLOCATOR(); - - //32 bytes - btVector3 m_aabbMinOrg; - btVector3 m_aabbMaxOrg; - - //4 - int m_escapeIndex; - - //8 - //for child nodes - int m_subPart; - int m_triangleIndex; - int m_padding[5];//bad, due to alignment - - -}; - - -///btBvhSubtreeInfo provides info to gather a subtree of limited size -ATTRIBUTE_ALIGNED16(class) btBvhSubtreeInfo -{ -public: - BT_DECLARE_ALIGNED_ALLOCATOR(); - - //12 bytes - unsigned short int m_quantizedAabbMin[3]; - unsigned short int m_quantizedAabbMax[3]; - //4 bytes, points to the root of the subtree - int m_rootNodeIndex; - //4 bytes - int m_subtreeSize; - int m_padding[3]; - - btBvhSubtreeInfo() - { - //memset(&m_padding[0], 0, sizeof(m_padding)); - } - - - void setAabbFromQuantizeNode(const btQuantizedBvhNode& quantizedNode) - { - m_quantizedAabbMin[0] = quantizedNode.m_quantizedAabbMin[0]; - m_quantizedAabbMin[1] = quantizedNode.m_quantizedAabbMin[1]; - m_quantizedAabbMin[2] = quantizedNode.m_quantizedAabbMin[2]; - m_quantizedAabbMax[0] = quantizedNode.m_quantizedAabbMax[0]; - m_quantizedAabbMax[1] = quantizedNode.m_quantizedAabbMax[1]; - m_quantizedAabbMax[2] = quantizedNode.m_quantizedAabbMax[2]; - } -} -; - - -class btNodeOverlapCallback -{ -public: - virtual ~btNodeOverlapCallback() {}; - - virtual void processNode(int subPart, int triangleIndex) = 0; -}; - -#include "LinearMath/btAlignedAllocator.h" -#include "LinearMath/btAlignedObjectArray.h" - - - -///for code readability: -typedef btAlignedObjectArray NodeArray; -typedef btAlignedObjectArray QuantizedNodeArray; -typedef btAlignedObjectArray BvhSubtreeInfoArray; - - -///The btQuantizedBvh class stores an AABB tree that can be quickly traversed on CPU and Cell SPU. -///It is used by the btBvhTriangleMeshShape as midphase, and by the btMultiSapBroadphase. -///It is recommended to use quantization for better performance and lower memory requirements. -ATTRIBUTE_ALIGNED16(class) btQuantizedBvh -{ -protected: - - NodeArray m_leafNodes; - NodeArray m_contiguousNodes; - - QuantizedNodeArray m_quantizedLeafNodes; - - QuantizedNodeArray m_quantizedContiguousNodes; - - int m_curNodeIndex; - - - //quantization data - bool m_useQuantization; - btVector3 m_bvhAabbMin; - btVector3 m_bvhAabbMax; - btVector3 m_bvhQuantization; -public: - BT_DECLARE_ALIGNED_ALLOCATOR(); - - enum btTraversalMode - { - TRAVERSAL_STACKLESS = 0, - TRAVERSAL_STACKLESS_CACHE_FRIENDLY, - TRAVERSAL_RECURSIVE - }; -protected: - - btTraversalMode m_traversalMode; - - BvhSubtreeInfoArray m_SubtreeHeaders; - - //This is only used for serialization so we don't have to add serialization directly to btAlignedObjectArray - int m_subtreeHeaderCount; - - - ///two versions, one for quantized and normal nodes. This allows code-reuse while maintaining readability (no template/macro!) - ///this might be refactored into a virtual, it is usually not calculated at run-time - void setInternalNodeAabbMin(int nodeIndex, const btVector3& aabbMin) - { - if (m_useQuantization) - { - quantize(&m_quantizedContiguousNodes[nodeIndex].m_quantizedAabbMin[0] ,aabbMin,0); - } else - { - m_contiguousNodes[nodeIndex].m_aabbMinOrg = aabbMin; - - } - } - void setInternalNodeAabbMax(int nodeIndex,const btVector3& aabbMax) - { - if (m_useQuantization) - { - quantize(&m_quantizedContiguousNodes[nodeIndex].m_quantizedAabbMax[0],aabbMax,1); - } else - { - m_contiguousNodes[nodeIndex].m_aabbMaxOrg = aabbMax; - } - } - - btVector3 getAabbMin(int nodeIndex) const - { - if (m_useQuantization) - { - return unQuantize(&m_quantizedLeafNodes[nodeIndex].m_quantizedAabbMin[0]); - } - //non-quantized - return m_leafNodes[nodeIndex].m_aabbMinOrg; - - } - btVector3 getAabbMax(int nodeIndex) const - { - if (m_useQuantization) - { - return unQuantize(&m_quantizedLeafNodes[nodeIndex].m_quantizedAabbMax[0]); - } - //non-quantized - return m_leafNodes[nodeIndex].m_aabbMaxOrg; - - } - - - void setInternalNodeEscapeIndex(int nodeIndex, int escapeIndex) - { - if (m_useQuantization) - { - m_quantizedContiguousNodes[nodeIndex].m_escapeIndexOrTriangleIndex = -escapeIndex; - } - else - { - m_contiguousNodes[nodeIndex].m_escapeIndex = escapeIndex; - } - - } - - void mergeInternalNodeAabb(int nodeIndex,const btVector3& newAabbMin,const btVector3& newAabbMax) - { - if (m_useQuantization) - { - unsigned short int quantizedAabbMin[3]; - unsigned short int quantizedAabbMax[3]; - quantize(quantizedAabbMin,newAabbMin,0); - quantize(quantizedAabbMax,newAabbMax,1); - for (int i=0;i<3;i++) - { - if (m_quantizedContiguousNodes[nodeIndex].m_quantizedAabbMin[i] > quantizedAabbMin[i]) - m_quantizedContiguousNodes[nodeIndex].m_quantizedAabbMin[i] = quantizedAabbMin[i]; - - if (m_quantizedContiguousNodes[nodeIndex].m_quantizedAabbMax[i] < quantizedAabbMax[i]) - m_quantizedContiguousNodes[nodeIndex].m_quantizedAabbMax[i] = quantizedAabbMax[i]; - - } - } else - { - //non-quantized - m_contiguousNodes[nodeIndex].m_aabbMinOrg.setMin(newAabbMin); - m_contiguousNodes[nodeIndex].m_aabbMaxOrg.setMax(newAabbMax); - } - } - - void swapLeafNodes(int firstIndex,int secondIndex); - - void assignInternalNodeFromLeafNode(int internalNode,int leafNodeIndex); - -protected: - - - - void buildTree (int startIndex,int endIndex); - - int calcSplittingAxis(int startIndex,int endIndex); - - int sortAndCalcSplittingIndex(int startIndex,int endIndex,int splitAxis); - - void walkStacklessTree(btNodeOverlapCallback* nodeCallback,const btVector3& aabbMin,const btVector3& aabbMax) const; - - void walkStacklessQuantizedTreeAgainstRay(btNodeOverlapCallback* nodeCallback, const btVector3& raySource, const btVector3& rayTarget, const btVector3& aabbMin, const btVector3& aabbMax, int startNodeIndex,int endNodeIndex) const; - void walkStacklessQuantizedTree(btNodeOverlapCallback* nodeCallback,unsigned short int* quantizedQueryAabbMin,unsigned short int* quantizedQueryAabbMax,int startNodeIndex,int endNodeIndex) const; - - ///tree traversal designed for small-memory processors like PS3 SPU - void walkStacklessQuantizedTreeCacheFriendly(btNodeOverlapCallback* nodeCallback,unsigned short int* quantizedQueryAabbMin,unsigned short int* quantizedQueryAabbMax) const; - - ///use the 16-byte stackless 'skipindex' node tree to do a recursive traversal - void walkRecursiveQuantizedTreeAgainstQueryAabb(const btQuantizedBvhNode* currentNode,btNodeOverlapCallback* nodeCallback,unsigned short int* quantizedQueryAabbMin,unsigned short int* quantizedQueryAabbMax) const; - - ///use the 16-byte stackless 'skipindex' node tree to do a recursive traversal - void walkRecursiveQuantizedTreeAgainstQuantizedTree(const btQuantizedBvhNode* treeNodeA,const btQuantizedBvhNode* treeNodeB,btNodeOverlapCallback* nodeCallback) const; - - -#define USE_BANCHLESS 1 -#ifdef USE_BANCHLESS - //This block replaces the block below and uses no branches, and replaces the 8 bit return with a 32 bit return for improved performance (~3x on XBox 360) - SIMD_FORCE_INLINE unsigned testQuantizedAabbAgainstQuantizedAabb(unsigned short int* aabbMin1,unsigned short int* aabbMax1,const unsigned short int* aabbMin2,const unsigned short int* aabbMax2) const - { - return static_cast(btSelect((unsigned)((aabbMin1[0] <= aabbMax2[0]) & (aabbMax1[0] >= aabbMin2[0]) - & (aabbMin1[2] <= aabbMax2[2]) & (aabbMax1[2] >= aabbMin2[2]) - & (aabbMin1[1] <= aabbMax2[1]) & (aabbMax1[1] >= aabbMin2[1])), - 1, 0)); - } -#else - SIMD_FORCE_INLINE bool testQuantizedAabbAgainstQuantizedAabb(unsigned short int* aabbMin1,unsigned short int* aabbMax1,const unsigned short int* aabbMin2,const unsigned short int* aabbMax2) const - { - bool overlap = true; - overlap = (aabbMin1[0] > aabbMax2[0] || aabbMax1[0] < aabbMin2[0]) ? false : overlap; - overlap = (aabbMin1[2] > aabbMax2[2] || aabbMax1[2] < aabbMin2[2]) ? false : overlap; - overlap = (aabbMin1[1] > aabbMax2[1] || aabbMax1[1] < aabbMin2[1]) ? false : overlap; - return overlap; - } -#endif //USE_BANCHLESS - - void updateSubtreeHeaders(int leftChildNodexIndex,int rightChildNodexIndex); - -public: - btQuantizedBvh(); - - virtual ~btQuantizedBvh(); - - - ///***************************************** expert/internal use only ************************* - void setQuantizationValues(const btVector3& bvhAabbMin,const btVector3& bvhAabbMax,btScalar quantizationMargin=btScalar(1.0)); - QuantizedNodeArray& getLeafNodeArray() { return m_quantizedLeafNodes; } - ///buildInternal is expert use only: assumes that setQuantizationValues and LeafNodeArray are initialized - void buildInternal(); - ///***************************************** expert/internal use only ************************* - - void reportAabbOverlappingNodex(btNodeOverlapCallback* nodeCallback,const btVector3& aabbMin,const btVector3& aabbMax) const; - void reportRayOverlappingNodex (btNodeOverlapCallback* nodeCallback, const btVector3& raySource, const btVector3& rayTarget) const; - void reportBoxCastOverlappingNodex(btNodeOverlapCallback* nodeCallback, const btVector3& raySource, const btVector3& rayTarget, const btVector3& aabbMin,const btVector3& aabbMax) const; - - SIMD_FORCE_INLINE void quantize(unsigned short* out, const btVector3& point,int isMax) const - { - - btAssert(m_useQuantization); - - btAssert(point.getX() <= m_bvhAabbMax.getX()); - btAssert(point.getY() <= m_bvhAabbMax.getY()); - btAssert(point.getZ() <= m_bvhAabbMax.getZ()); - - btAssert(point.getX() >= m_bvhAabbMin.getX()); - btAssert(point.getY() >= m_bvhAabbMin.getY()); - btAssert(point.getZ() >= m_bvhAabbMin.getZ()); - - btVector3 v = (point - m_bvhAabbMin) * m_bvhQuantization; - ///Make sure rounding is done in a way that unQuantize(quantizeWithClamp(...)) is conservative - ///end-points always set the first bit, so that they are sorted properly (so that neighbouring AABBs overlap properly) - ///todo: double-check this - if (isMax) - { - out[0] = (unsigned short) (((unsigned short)(v.getX()+btScalar(1.)) | 1)); - out[1] = (unsigned short) (((unsigned short)(v.getY()+btScalar(1.)) | 1)); - out[2] = (unsigned short) (((unsigned short)(v.getZ()+btScalar(1.)) | 1)); - } else - { - out[0] = (unsigned short) (((unsigned short)(v.getX()) & 0xfffe)); - out[1] = (unsigned short) (((unsigned short)(v.getY()) & 0xfffe)); - out[2] = (unsigned short) (((unsigned short)(v.getZ()) & 0xfffe)); - } - - -#ifdef DEBUG_CHECK_DEQUANTIZATION - btVector3 newPoint = unQuantize(out); - if (isMax) - { - if (newPoint.getX() < point.getX()) - { - printf("unconservative X, diffX = %f, oldX=%f,newX=%f\n",newPoint.getX()-point.getX(), newPoint.getX(),point.getX()); - } - if (newPoint.getY() < point.getY()) - { - printf("unconservative Y, diffY = %f, oldY=%f,newY=%f\n",newPoint.getY()-point.getY(), newPoint.getY(),point.getY()); - } - if (newPoint.getZ() < point.getZ()) - { - - printf("unconservative Z, diffZ = %f, oldZ=%f,newZ=%f\n",newPoint.getZ()-point.getZ(), newPoint.getZ(),point.getZ()); - } - } else - { - if (newPoint.getX() > point.getX()) - { - printf("unconservative X, diffX = %f, oldX=%f,newX=%f\n",newPoint.getX()-point.getX(), newPoint.getX(),point.getX()); - } - if (newPoint.getY() > point.getY()) - { - printf("unconservative Y, diffY = %f, oldY=%f,newY=%f\n",newPoint.getY()-point.getY(), newPoint.getY(),point.getY()); - } - if (newPoint.getZ() > point.getZ()) - { - printf("unconservative Z, diffZ = %f, oldZ=%f,newZ=%f\n",newPoint.getZ()-point.getZ(), newPoint.getZ(),point.getZ()); - } - } -#endif //DEBUG_CHECK_DEQUANTIZATION - - } - - - SIMD_FORCE_INLINE void quantizeWithClamp(unsigned short* out, const btVector3& point2,int isMax) const - { - - btAssert(m_useQuantization); - - btVector3 clampedPoint(point2); - clampedPoint.setMax(m_bvhAabbMin); - clampedPoint.setMin(m_bvhAabbMax); - - quantize(out,clampedPoint,isMax); - - } - - SIMD_FORCE_INLINE btVector3 unQuantize(const unsigned short* vecIn) const - { - btVector3 vecOut; - vecOut.setValue( - (btScalar)(vecIn[0]) / (m_bvhQuantization.getX()), - (btScalar)(vecIn[1]) / (m_bvhQuantization.getY()), - (btScalar)(vecIn[2]) / (m_bvhQuantization.getZ())); - vecOut += m_bvhAabbMin; - return vecOut; - } - - ///setTraversalMode let's you choose between stackless, recursive or stackless cache friendly tree traversal. Note this is only implemented for quantized trees. - void setTraversalMode(btTraversalMode traversalMode) - { - m_traversalMode = traversalMode; - } - - - SIMD_FORCE_INLINE QuantizedNodeArray& getQuantizedNodeArray() - { - return m_quantizedContiguousNodes; - } - - - SIMD_FORCE_INLINE BvhSubtreeInfoArray& getSubtreeInfoArray() - { - return m_SubtreeHeaders; - } - - - /////Calculate space needed to store BVH for serialization - unsigned calculateSerializeBufferSize(); - - /// Data buffer MUST be 16 byte aligned - virtual bool serialize(void *o_alignedDataBuffer, unsigned i_dataBufferSize, bool i_swapEndian); - - ///deSerializeInPlace loads and initializes a BVH from a buffer in memory 'in place' - static btQuantizedBvh *deSerializeInPlace(void *i_alignedDataBuffer, unsigned int i_dataBufferSize, bool i_swapEndian); - - static unsigned int getAlignmentSerializationPadding(); - - SIMD_FORCE_INLINE bool isQuantized() - { - return m_useQuantization; - } - -private: - // Special "copy" constructor that allows for in-place deserialization - // Prevents btVector3's default constructor from being called, but doesn't inialize much else - // ownsMemory should most likely be false if deserializing, and if you are not, don't call this (it also changes the function signature, which we need) - btQuantizedBvh(btQuantizedBvh &other, bool ownsMemory); - -} -; - - -#endif //QUANTIZED_BVH_H diff --git a/extern/bullet2/src/BulletCollision/BroadphaseCollision/btSimpleBroadphase.cpp b/extern/bullet2/src/BulletCollision/BroadphaseCollision/btSimpleBroadphase.cpp index 2d27f22567f..30bcbe0c5f1 100644 --- a/extern/bullet2/src/BulletCollision/BroadphaseCollision/btSimpleBroadphase.cpp +++ b/extern/bullet2/src/BulletCollision/BroadphaseCollision/btSimpleBroadphase.cpp @@ -14,86 +14,83 @@ subject to the following restrictions: */ #include "btSimpleBroadphase.h" -#include "BulletCollision/BroadphaseCollision/btDispatcher.h" -#include "BulletCollision/BroadphaseCollision/btCollisionAlgorithm.h" +#include +#include #include "LinearMath/btVector3.h" #include "LinearMath/btTransform.h" #include "LinearMath/btMatrix3x3.h" #include -extern int gOverlappingPairs; void btSimpleBroadphase::validate() { - for (int i=0;i=0;i--) { - m_pairCache->~btOverlappingPairCache(); - btAlignedFree(m_pairCache); + BP_Proxy* proxy = m_pProxies[i]; + destroyProxy(proxy); } + */ } -btBroadphaseProxy* btSimpleBroadphase::createProxy( const btVector3& aabbMin, const btVector3& aabbMax,int shapeType,void* userPtr ,short int collisionFilterGroup,short int collisionFilterMask, btDispatcher* /*dispatcher*/,void* multiSapProxy) +btBroadphaseProxy* btSimpleBroadphase::createProxy( const btVector3& min, const btVector3& max,int shapeType,void* userPtr ,short int collisionFilterGroup,short int collisionFilterMask) { - if (m_numHandles >= m_maxHandles) + if (m_numProxies >= m_maxProxies) { - btAssert(0); + assert(0); return 0; //should never happen, but don't let the game crash ;-) } - assert(aabbMin[0]<= aabbMax[0] && aabbMin[1]<= aabbMax[1] && aabbMin[2]<= aabbMax[2]); + assert(min[0]<= max[0] && min[1]<= max[1] && min[2]<= max[2]); - int newHandleIndex = allocHandle(); - btSimpleBroadphaseProxy* proxy = new (&m_pHandles[newHandleIndex])btSimpleBroadphaseProxy(aabbMin,aabbMax,shapeType,userPtr,collisionFilterGroup,collisionFilterMask,multiSapProxy); + int freeIndex= m_freeProxies[m_firstFreeProxy]; + btSimpleBroadphaseProxy* proxy = new (&m_proxies[freeIndex])btSimpleBroadphaseProxy(min,max,shapeType,userPtr,collisionFilterGroup,collisionFilterMask); + m_firstFreeProxy++; + + btSimpleBroadphaseProxy* proxy1 = &m_proxies[0]; + + int index = int(proxy - proxy1); + btAssert(index == freeIndex); + + m_pProxies[m_numProxies] = proxy; + m_numProxies++; + //validate(); return proxy; } @@ -127,19 +124,34 @@ protected: }; }; -void btSimpleBroadphase::destroyProxy(btBroadphaseProxy* proxyOrg,btDispatcher* dispatcher) +void btSimpleBroadphase::destroyProxy(btBroadphaseProxy* proxyOrg) { + int i; + btSimpleBroadphaseProxy* proxy0 = static_cast(proxyOrg); - freeHandle(proxy0); - - m_pairCache->removeOverlappingPairsContainingProxy(proxyOrg,dispatcher); + btSimpleBroadphaseProxy* proxy1 = &m_proxies[0]; + + int index = int(proxy0 - proxy1); + btAssert (index < m_maxProxies); + m_freeProxies[--m_firstFreeProxy] = index; + removeOverlappingPairsContainingProxy(proxyOrg); + + for (i=0;im_min = aabbMin; @@ -174,137 +186,37 @@ public: } }; -void btSimpleBroadphase::calculateOverlappingPairs(btDispatcher* dispatcher) +void btSimpleBroadphase::refreshOverlappingPairs() { //first check for new overlapping pairs int i,j; - if (m_firstAllocatedHandle >= 0) + for (i=0;ifindPair(proxy0,proxy1)) - { - m_pairCache->addOverlappingPair(proxy0,proxy1); - } - } else - { - if (!m_pairCache->hasDeferredRemoval()) - { - if ( m_pairCache->findPair(proxy0,proxy1)) - { - m_pairCache->removeOverlappingPair(proxy0,proxy1,dispatcher); - } - } - - } + addOverlappingPair(proxy0,proxy1); } - proxy1 = &m_pHandles[proxy1->GetNextAllocated()]; - } - proxy0 = &m_pHandles[proxy0->GetNextAllocated()]; - - } - - if (m_ownsPairCache && m_pairCache->hasDeferredRemoval()) - { - - btBroadphasePairArray& overlappingPairArray = m_pairCache->getOverlappingPairArray(); - - //perform a sort, to find duplicates and to sort 'invalid' pairs to the end - overlappingPairArray.quickSort(btBroadphasePairSortPredicate()); - - overlappingPairArray.resize(overlappingPairArray.size() - m_invalidPair); - m_invalidPair = 0; - - - btBroadphasePair previousPair; - previousPair.m_pProxy0 = 0; - previousPair.m_pProxy1 = 0; - previousPair.m_algorithm = 0; - - - for (i=0;iprocessOverlap(pair); - } else - { - needsRemoval = true; - } - } else - { - //remove duplicate - needsRemoval = true; - //should have no algorithm - btAssert(!pair.m_algorithm); - } - - if (needsRemoval) - { - m_pairCache->cleanOverlappingPair(pair,dispatcher); - - // m_overlappingPairArray.swap(i,m_overlappingPairArray.size()-1); - // m_overlappingPairArray.pop_back(); - pair.m_pProxy0 = 0; - pair.m_pProxy1 = 0; - m_invalidPair++; - gOverlappingPairs--; - } - - } - - ///if you don't like to skip the invalid pairs in the array, execute following code: - #define CLEAN_INVALID_PAIRS 1 - #ifdef CLEAN_INVALID_PAIRS - - //perform a sort, to sort 'invalid' pairs to the end - overlappingPairArray.quickSort(btBroadphasePairSortPredicate()); - - overlappingPairArray.resize(overlappingPairArray.size() - m_invalidPair); - m_invalidPair = 0; - #endif//CLEAN_INVALID_PAIRS } } + + + CheckOverlapCallback checkOverlap; + + processAllOverlappingPairs(&checkOverlap); + + } -bool btSimpleBroadphase::testAabbOverlap(btBroadphaseProxy* proxy0,btBroadphaseProxy* proxy1) -{ - btSimpleBroadphaseProxy* p0 = getSimpleProxyFromProxy(proxy0); - btSimpleBroadphaseProxy* p1 = getSimpleProxyFromProxy(proxy1); - return aabbOverlap(p0,p1); -} - - - diff --git a/extern/bullet2/src/BulletCollision/BroadphaseCollision/btSimpleBroadphase.h b/extern/bullet2/src/BulletCollision/BroadphaseCollision/btSimpleBroadphase.h index 49dfeb84900..fb155e7047c 100644 --- a/extern/bullet2/src/BulletCollision/BroadphaseCollision/btSimpleBroadphase.h +++ b/extern/bullet2/src/BulletCollision/BroadphaseCollision/btSimpleBroadphase.h @@ -24,78 +24,35 @@ struct btSimpleBroadphaseProxy : public btBroadphaseProxy { btVector3 m_min; btVector3 m_max; - int m_nextFree; - int m_nextAllocated; -// int m_handleId; - btSimpleBroadphaseProxy() {}; - btSimpleBroadphaseProxy(const btPoint3& minpt,const btPoint3& maxpt,int shapeType,void* userPtr,short int collisionFilterGroup,short int collisionFilterMask,void* multiSapProxy) - :btBroadphaseProxy(userPtr,collisionFilterGroup,collisionFilterMask,multiSapProxy), + btSimpleBroadphaseProxy(const btPoint3& minpt,const btPoint3& maxpt,int shapeType,void* userPtr,short int collisionFilterGroup,short int collisionFilterMask) + :btBroadphaseProxy(userPtr,collisionFilterGroup,collisionFilterMask), m_min(minpt),m_max(maxpt) { (void)shapeType; } - - SIMD_FORCE_INLINE void SetNextFree(int next) {m_nextFree = next;} - SIMD_FORCE_INLINE int GetNextFree() const {return m_nextFree;} - - SIMD_FORCE_INLINE void SetNextAllocated(int next) {m_nextAllocated = next;} - SIMD_FORCE_INLINE int GetNextAllocated() const {return m_nextAllocated;} - }; -///The SimpleBroadphase is just a unit-test for btAxisSweep3, bt32BitAxisSweep3, or btDbvtBroadphase, so use those classes instead. -///It is a brute force aabb culling broadphase based on O(n^2) aabb checks -class btSimpleBroadphase : public btBroadphaseInterface +///SimpleBroadphase is a brute force aabb culling broadphase based on O(n^2) aabb checks +class btSimpleBroadphase : public btOverlappingPairCache { protected: - int m_numHandles; // number of active handles - int m_maxHandles; // max number of handles - btSimpleBroadphaseProxy* m_pHandles; // handles pool - void* m_pHandlesRawPtr; - int m_firstFreeHandle; // free handles list - int m_firstAllocatedHandle; + btSimpleBroadphaseProxy* m_proxies; + int* m_freeProxies; + int m_firstFreeProxy; - int allocHandle() - { + btSimpleBroadphaseProxy** m_pProxies; + int m_numProxies; - int freeHandle = m_firstFreeHandle; - m_firstFreeHandle = m_pHandles[freeHandle].GetNextFree(); - - m_pHandles[freeHandle].SetNextAllocated(m_firstAllocatedHandle); - m_firstAllocatedHandle = freeHandle; - - m_numHandles++; - - return freeHandle; - } - - void freeHandle(btSimpleBroadphaseProxy* proxy) - { - int handle = int(proxy-m_pHandles); - btAssert(handle >= 0 && handle < m_maxHandles); - - proxy->SetNextFree(m_firstFreeHandle); - m_firstFreeHandle = handle; - - m_firstAllocatedHandle = proxy->GetNextAllocated(); - proxy->SetNextAllocated(-1); - - m_numHandles--; - } - - - btOverlappingPairCache* m_pairCache; - bool m_ownsPairCache; - - int m_invalidPair; + + int m_maxProxies; inline btSimpleBroadphaseProxy* getSimpleProxyFromProxy(btBroadphaseProxy* proxy) @@ -110,48 +67,26 @@ protected: protected: - - + virtual void refreshOverlappingPairs(); public: - btSimpleBroadphase(int maxProxies=16384,btOverlappingPairCache* overlappingPairCache=0); + btSimpleBroadphase(int maxProxies=16384); virtual ~btSimpleBroadphase(); static bool aabbOverlap(btSimpleBroadphaseProxy* proxy0,btSimpleBroadphaseProxy* proxy1); - virtual btBroadphaseProxy* createProxy( const btVector3& aabbMin, const btVector3& aabbMax,int shapeType,void* userPtr ,short int collisionFilterGroup,short int collisionFilterMask, btDispatcher* dispatcher,void* multiSapProxy); + virtual btBroadphaseProxy* createProxy( const btVector3& min, const btVector3& max,int shapeType,void* userPtr ,short int collisionFilterGroup,short int collisionFilterMask); - virtual void calculateOverlappingPairs(btDispatcher* dispatcher); - virtual void destroyProxy(btBroadphaseProxy* proxy,btDispatcher* dispatcher); - virtual void setAabb(btBroadphaseProxy* proxy,const btVector3& aabbMin,const btVector3& aabbMax, btDispatcher* dispatcher); + virtual void destroyProxy(btBroadphaseProxy* proxy); + virtual void setAabb(btBroadphaseProxy* proxy,const btVector3& aabbMin,const btVector3& aabbMax); - btOverlappingPairCache* getOverlappingPairCache() - { - return m_pairCache; - } - const btOverlappingPairCache* getOverlappingPairCache() const - { - return m_pairCache; - } - - bool testAabbOverlap(btBroadphaseProxy* proxy0,btBroadphaseProxy* proxy1); + + - ///getAabb returns the axis aligned bounding box in the 'global' coordinate frame - ///will add some transform later - virtual void getBroadphaseAabb(btVector3& aabbMin,btVector3& aabbMax) const - { - aabbMin.setValue(-1e30f,-1e30f,-1e30f); - aabbMax.setValue(1e30f,1e30f,1e30f); - } - virtual void printStats() - { -// printf("btSimpleBroadphase.h\n"); -// printf("numHandles = %d, maxHandles = %d\n",m_numHandles,m_maxHandles); - } }; diff --git a/extern/bullet2/src/BulletCollision/CollisionDispatch/SphereTriangleDetector.cpp b/extern/bullet2/src/BulletCollision/CollisionDispatch/SphereTriangleDetector.cpp index f6c1e32ac7c..81133670f0c 100644 --- a/extern/bullet2/src/BulletCollision/CollisionDispatch/SphereTriangleDetector.cpp +++ b/extern/bullet2/src/BulletCollision/CollisionDispatch/SphereTriangleDetector.cpp @@ -26,7 +26,7 @@ m_triangle(triangle) } -void SphereTriangleDetector::getClosestPoints(const ClosestPointInput& input,Result& output,class btIDebugDraw* debugDraw,bool swapResults) +void SphereTriangleDetector::getClosestPoints(const ClosestPointInput& input,Result& output,class btIDebugDraw* debugDraw) { (void)debugDraw; @@ -42,16 +42,7 @@ void SphereTriangleDetector::getClosestPoints(const ClosestPointInput& input,Res if (collide(sphereInTr.getOrigin(),point,normal,depth,timeOfImpact)) { - if (swapResults) - { - btVector3 normalOnB = transformB.getBasis()*normal; - btVector3 normalOnA = -normalOnB; - btVector3 pointOnA = transformB*point+normalOnB*depth; - output.addContactPoint(normalOnA,pointOnA,depth); - } else - { - output.addContactPoint(transformB.getBasis()*normal,transformB*point,depth); - } + output.addContactPoint(transformB.getBasis()*normal,transformB*point,depth); } } @@ -62,8 +53,6 @@ void SphereTriangleDetector::getClosestPoints(const ClosestPointInput& input,Res // See also geometrictools.com // Basic idea: D = |p - (lo + t0*lv)| where t0 = lv . (p - lo) / lv . lv -btScalar SegmentSqrDistance(const btVector3& from, const btVector3& to,const btVector3 &p, btVector3 &nearest); - btScalar SegmentSqrDistance(const btVector3& from, const btVector3& to,const btVector3 &p, btVector3 &nearest) { btVector3 diff = p - from; btVector3 v = to - from; diff --git a/extern/bullet2/src/BulletCollision/CollisionDispatch/SphereTriangleDetector.h b/extern/bullet2/src/BulletCollision/CollisionDispatch/SphereTriangleDetector.h index 26dabaa480e..b32806a6846 100644 --- a/extern/bullet2/src/BulletCollision/CollisionDispatch/SphereTriangleDetector.h +++ b/extern/bullet2/src/BulletCollision/CollisionDispatch/SphereTriangleDetector.h @@ -16,8 +16,8 @@ subject to the following restrictions: #ifndef SPHERE_TRIANGLE_DETECTOR_H #define SPHERE_TRIANGLE_DETECTOR_H -#include "BulletCollision/NarrowPhaseCollision/btDiscreteCollisionDetectorInterface.h" -#include "LinearMath/btPoint3.h" +#include "../NarrowPhaseCollision/btDiscreteCollisionDetectorInterface.h" +#include "../../LinearMath/btPoint3.h" class btSphereShape; @@ -28,7 +28,7 @@ class btTriangleShape; /// sphere-triangle to match the btDiscreteCollisionDetectorInterface struct SphereTriangleDetector : public btDiscreteCollisionDetectorInterface { - virtual void getClosestPoints(const ClosestPointInput& input,Result& output,class btIDebugDraw* debugDraw,bool swapResults=false); + virtual void getClosestPoints(const ClosestPointInput& input,Result& output,class btIDebugDraw* debugDraw); SphereTriangleDetector(btSphereShape* sphere,btTriangleShape* triangle); diff --git a/extern/bullet2/src/BulletCollision/CollisionDispatch/btBoxBoxCollisionAlgorithm.cpp b/extern/bullet2/src/BulletCollision/CollisionDispatch/btBoxBoxCollisionAlgorithm.cpp deleted file mode 100644 index cd0c028012c..00000000000 --- a/extern/bullet2/src/BulletCollision/CollisionDispatch/btBoxBoxCollisionAlgorithm.cpp +++ /dev/null @@ -1,85 +0,0 @@ -/* -Bullet Continuous Collision Detection and Physics Library -Copyright (c) 2003-2006 Erwin Coumans http://continuousphysics.com/Bullet/ - -This software is provided 'as-is', without any express or implied warranty. -In no event will the authors be held liable for any damages arising from the use of this software. -Permission is granted to anyone to use this software for any purpose, -including commercial applications, and to alter it and redistribute it freely, -subject to the following restrictions: - -1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. -2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. -3. This notice may not be removed or altered from any source distribution. -*/ - -#include "btBoxBoxCollisionAlgorithm.h" -#include "BulletCollision/CollisionDispatch/btCollisionDispatcher.h" -#include "BulletCollision/CollisionShapes/btBoxShape.h" -#include "BulletCollision/CollisionDispatch/btCollisionObject.h" -#include "btBoxBoxDetector.h" - -#define USE_PERSISTENT_CONTACTS 1 - -btBoxBoxCollisionAlgorithm::btBoxBoxCollisionAlgorithm(btPersistentManifold* mf,const btCollisionAlgorithmConstructionInfo& ci,btCollisionObject* obj0,btCollisionObject* obj1) -: btCollisionAlgorithm(ci), -m_ownManifold(false), -m_manifoldPtr(mf) -{ - if (!m_manifoldPtr && m_dispatcher->needsCollision(obj0,obj1)) - { - m_manifoldPtr = m_dispatcher->getNewManifold(obj0,obj1); - m_ownManifold = true; - } -} - -btBoxBoxCollisionAlgorithm::~btBoxBoxCollisionAlgorithm() -{ - if (m_ownManifold) - { - if (m_manifoldPtr) - m_dispatcher->releaseManifold(m_manifoldPtr); - } -} - -void btBoxBoxCollisionAlgorithm::processCollision (btCollisionObject* body0,btCollisionObject* body1,const btDispatcherInfo& dispatchInfo,btManifoldResult* resultOut) -{ - if (!m_manifoldPtr) - return; - - btCollisionObject* col0 = body0; - btCollisionObject* col1 = body1; - btBoxShape* box0 = (btBoxShape*)col0->getCollisionShape(); - btBoxShape* box1 = (btBoxShape*)col1->getCollisionShape(); - - - - /// report a contact. internally this will be kept persistent, and contact reduction is done - resultOut->setPersistentManifold(m_manifoldPtr); -#ifndef USE_PERSISTENT_CONTACTS - m_manifoldPtr->clearManifold(); -#endif //USE_PERSISTENT_CONTACTS - - btDiscreteCollisionDetectorInterface::ClosestPointInput input; - input.m_maximumDistanceSquared = 1e30f; - input.m_transformA = body0->getWorldTransform(); - input.m_transformB = body1->getWorldTransform(); - - btBoxBoxDetector detector(box0,box1); - detector.getClosestPoints(input,*resultOut,dispatchInfo.m_debugDraw); - -#ifdef USE_PERSISTENT_CONTACTS - // refreshContactPoints is only necessary when using persistent contact points. otherwise all points are newly added - if (m_ownManifold) - { - resultOut->refreshContactPoints(); - } -#endif //USE_PERSISTENT_CONTACTS - -} - -btScalar btBoxBoxCollisionAlgorithm::calculateTimeOfImpact(btCollisionObject* /*body0*/,btCollisionObject* /*body1*/,const btDispatcherInfo& /*dispatchInfo*/,btManifoldResult* /*resultOut*/) -{ - //not yet - return 1.f; -} diff --git a/extern/bullet2/src/BulletCollision/CollisionDispatch/btBoxBoxCollisionAlgorithm.h b/extern/bullet2/src/BulletCollision/CollisionDispatch/btBoxBoxCollisionAlgorithm.h deleted file mode 100644 index 35afaf175a1..00000000000 --- a/extern/bullet2/src/BulletCollision/CollisionDispatch/btBoxBoxCollisionAlgorithm.h +++ /dev/null @@ -1,66 +0,0 @@ -/* -Bullet Continuous Collision Detection and Physics Library -Copyright (c) 2003-2006 Erwin Coumans http://continuousphysics.com/Bullet/ - -This software is provided 'as-is', without any express or implied warranty. -In no event will the authors be held liable for any damages arising from the use of this software. -Permission is granted to anyone to use this software for any purpose, -including commercial applications, and to alter it and redistribute it freely, -subject to the following restrictions: - -1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. -2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. -3. This notice may not be removed or altered from any source distribution. -*/ - -#ifndef BOX_BOX__COLLISION_ALGORITHM_H -#define BOX_BOX__COLLISION_ALGORITHM_H - -#include "BulletCollision/BroadphaseCollision/btCollisionAlgorithm.h" -#include "BulletCollision/BroadphaseCollision/btBroadphaseProxy.h" -#include "BulletCollision/BroadphaseCollision/btDispatcher.h" -#include "BulletCollision/CollisionDispatch/btCollisionCreateFunc.h" - -class btPersistentManifold; - -///box-box collision detection -class btBoxBoxCollisionAlgorithm : public btCollisionAlgorithm -{ - bool m_ownManifold; - btPersistentManifold* m_manifoldPtr; - -public: - btBoxBoxCollisionAlgorithm(const btCollisionAlgorithmConstructionInfo& ci) - : btCollisionAlgorithm(ci) {} - - virtual void processCollision (btCollisionObject* body0,btCollisionObject* body1,const btDispatcherInfo& dispatchInfo,btManifoldResult* resultOut); - - virtual btScalar calculateTimeOfImpact(btCollisionObject* body0,btCollisionObject* body1,const btDispatcherInfo& dispatchInfo,btManifoldResult* resultOut); - - btBoxBoxCollisionAlgorithm(btPersistentManifold* mf,const btCollisionAlgorithmConstructionInfo& ci,btCollisionObject* body0,btCollisionObject* body1); - - virtual ~btBoxBoxCollisionAlgorithm(); - - virtual void getAllContactManifolds(btManifoldArray& manifoldArray) - { - if (m_manifoldPtr && m_ownManifold) - { - manifoldArray.push_back(m_manifoldPtr); - } - } - - - struct CreateFunc :public btCollisionAlgorithmCreateFunc - { - virtual btCollisionAlgorithm* CreateCollisionAlgorithm(btCollisionAlgorithmConstructionInfo& ci, btCollisionObject* body0,btCollisionObject* body1) - { - int bbsize = sizeof(btBoxBoxCollisionAlgorithm); - void* ptr = ci.m_dispatcher1->allocateCollisionAlgorithm(bbsize); - return new(ptr) btBoxBoxCollisionAlgorithm(0,ci,body0,body1); - } - }; - -}; - -#endif //BOX_BOX__COLLISION_ALGORITHM_H - diff --git a/extern/bullet2/src/BulletCollision/CollisionDispatch/btBoxBoxDetector.cpp b/extern/bullet2/src/BulletCollision/CollisionDispatch/btBoxBoxDetector.cpp deleted file mode 100644 index e55604632c0..00000000000 --- a/extern/bullet2/src/BulletCollision/CollisionDispatch/btBoxBoxDetector.cpp +++ /dev/null @@ -1,683 +0,0 @@ - -/* - * Box-Box collision detection re-distributed under the ZLib license with permission from Russell L. Smith - * Original version is from Open Dynamics Engine, Copyright (C) 2001,2002 Russell L. Smith. - * All rights reserved. Email: russ@q12.org Web: www.q12.org - Bullet Continuous Collision Detection and Physics Library - Bullet is Copyright (c) 2003-2006 Erwin Coumans http://continuousphysics.com/Bullet/ - -This software is provided 'as-is', without any express or implied warranty. -In no event will the authors be held liable for any damages arising from the use of this software. -Permission is granted to anyone to use this software for any purpose, -including commercial applications, and to alter it and redistribute it freely, -subject to the following restrictions: - -1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. -2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. -3. This notice may not be removed or altered from any source distribution. -*/ - -///ODE box-box collision detection is adapted to work with Bullet - -#include "btBoxBoxDetector.h" -#include "BulletCollision/CollisionShapes/btBoxShape.h" - -#include -#include - -btBoxBoxDetector::btBoxBoxDetector(btBoxShape* box1,btBoxShape* box2) -: m_box1(box1), -m_box2(box2) -{ - -} - - -// given two boxes (p1,R1,side1) and (p2,R2,side2), collide them together and -// generate contact points. this returns 0 if there is no contact otherwise -// it returns the number of contacts generated. -// `normal' returns the contact normal. -// `depth' returns the maximum penetration depth along that normal. -// `return_code' returns a number indicating the type of contact that was -// detected: -// 1,2,3 = box 2 intersects with a face of box 1 -// 4,5,6 = box 1 intersects with a face of box 2 -// 7..15 = edge-edge contact -// `maxc' is the maximum number of contacts allowed to be generated, i.e. -// the size of the `contact' array. -// `contact' and `skip' are the contact array information provided to the -// collision functions. this function only fills in the position and depth -// fields. -struct dContactGeom; -#define dDOTpq(a,b,p,q) ((a)[0]*(b)[0] + (a)[p]*(b)[q] + (a)[2*(p)]*(b)[2*(q)]) -#define dInfinity FLT_MAX - - -/*PURE_INLINE btScalar dDOT (const btScalar *a, const btScalar *b) { return dDOTpq(a,b,1,1); } -PURE_INLINE btScalar dDOT13 (const btScalar *a, const btScalar *b) { return dDOTpq(a,b,1,3); } -PURE_INLINE btScalar dDOT31 (const btScalar *a, const btScalar *b) { return dDOTpq(a,b,3,1); } -PURE_INLINE btScalar dDOT33 (const btScalar *a, const btScalar *b) { return dDOTpq(a,b,3,3); } -*/ -static btScalar dDOT (const btScalar *a, const btScalar *b) { return dDOTpq(a,b,1,1); } -static btScalar dDOT44 (const btScalar *a, const btScalar *b) { return dDOTpq(a,b,4,4); } -static btScalar dDOT41 (const btScalar *a, const btScalar *b) { return dDOTpq(a,b,4,1); } -static btScalar dDOT14 (const btScalar *a, const btScalar *b) { return dDOTpq(a,b,1,4); } -#define dMULTIPLYOP1_331(A,op,B,C) \ -{\ - (A)[0] op dDOT41((B),(C)); \ - (A)[1] op dDOT41((B+1),(C)); \ - (A)[2] op dDOT41((B+2),(C)); \ -} - -#define dMULTIPLYOP0_331(A,op,B,C) \ -{ \ - (A)[0] op dDOT((B),(C)); \ - (A)[1] op dDOT((B+4),(C)); \ - (A)[2] op dDOT((B+8),(C)); \ -} - -#define dMULTIPLY1_331(A,B,C) dMULTIPLYOP1_331(A,=,B,C) -#define dMULTIPLY0_331(A,B,C) dMULTIPLYOP0_331(A,=,B,C) - -typedef btScalar dMatrix3[4*3]; - -void dLineClosestApproach (const btVector3& pa, const btVector3& ua, - const btVector3& pb, const btVector3& ub, - btScalar *alpha, btScalar *beta); -void dLineClosestApproach (const btVector3& pa, const btVector3& ua, - const btVector3& pb, const btVector3& ub, - btScalar *alpha, btScalar *beta) -{ - btVector3 p; - p[0] = pb[0] - pa[0]; - p[1] = pb[1] - pa[1]; - p[2] = pb[2] - pa[2]; - btScalar uaub = dDOT(ua,ub); - btScalar q1 = dDOT(ua,p); - btScalar q2 = -dDOT(ub,p); - btScalar d = 1-uaub*uaub; - if (d <= btScalar(0.0001f)) { - // @@@ this needs to be made more robust - *alpha = 0; - *beta = 0; - } - else { - d = 1.f/d; - *alpha = (q1 + uaub*q2)*d; - *beta = (uaub*q1 + q2)*d; - } -} - - - -// find all the intersection points between the 2D rectangle with vertices -// at (+/-h[0],+/-h[1]) and the 2D quadrilateral with vertices (p[0],p[1]), -// (p[2],p[3]),(p[4],p[5]),(p[6],p[7]). -// -// the intersection points are returned as x,y pairs in the 'ret' array. -// the number of intersection points is returned by the function (this will -// be in the range 0 to 8). - -static int intersectRectQuad2 (btScalar h[2], btScalar p[8], btScalar ret[16]) -{ - // q (and r) contain nq (and nr) coordinate points for the current (and - // chopped) polygons - int nq=4,nr=0; - btScalar buffer[16]; - btScalar *q = p; - btScalar *r = ret; - for (int dir=0; dir <= 1; dir++) { - // direction notation: xy[0] = x axis, xy[1] = y axis - for (int sign=-1; sign <= 1; sign += 2) { - // chop q along the line xy[dir] = sign*h[dir] - btScalar *pq = q; - btScalar *pr = r; - nr = 0; - for (int i=nq; i > 0; i--) { - // go through all points in q and all lines between adjacent points - if (sign*pq[dir] < h[dir]) { - // this point is inside the chopping line - pr[0] = pq[0]; - pr[1] = pq[1]; - pr += 2; - nr++; - if (nr & 8) { - q = r; - goto done; - } - } - btScalar *nextq = (i > 1) ? pq+2 : q; - if ((sign*pq[dir] < h[dir]) ^ (sign*nextq[dir] < h[dir])) { - // this line crosses the chopping line - pr[1-dir] = pq[1-dir] + (nextq[1-dir]-pq[1-dir]) / - (nextq[dir]-pq[dir]) * (sign*h[dir]-pq[dir]); - pr[dir] = sign*h[dir]; - pr += 2; - nr++; - if (nr & 8) { - q = r; - goto done; - } - } - pq += 2; - } - q = r; - r = (q==ret) ? buffer : ret; - nq = nr; - } - } - done: - if (q != ret) memcpy (ret,q,nr*2*sizeof(btScalar)); - return nr; -} - - -#define M__PI 3.14159265f - -// given n points in the plane (array p, of size 2*n), generate m points that -// best represent the whole set. the definition of 'best' here is not -// predetermined - the idea is to select points that give good box-box -// collision detection behavior. the chosen point indexes are returned in the -// array iret (of size m). 'i0' is always the first entry in the array. -// n must be in the range [1..8]. m must be in the range [1..n]. i0 must be -// in the range [0..n-1]. - -void cullPoints2 (int n, btScalar p[], int m, int i0, int iret[]); -void cullPoints2 (int n, btScalar p[], int m, int i0, int iret[]) -{ - // compute the centroid of the polygon in cx,cy - int i,j; - btScalar a,cx,cy,q; - if (n==1) { - cx = p[0]; - cy = p[1]; - } - else if (n==2) { - cx = btScalar(0.5)*(p[0] + p[2]); - cy = btScalar(0.5)*(p[1] + p[3]); - } - else { - a = 0; - cx = 0; - cy = 0; - for (i=0; i<(n-1); i++) { - q = p[i*2]*p[i*2+3] - p[i*2+2]*p[i*2+1]; - a += q; - cx += q*(p[i*2]+p[i*2+2]); - cy += q*(p[i*2+1]+p[i*2+3]); - } - q = p[n*2-2]*p[1] - p[0]*p[n*2-1]; - a = 1.f/(btScalar(3.0)*(a+q)); - cx = a*(cx + q*(p[n*2-2]+p[0])); - cy = a*(cy + q*(p[n*2-1]+p[1])); - } - - // compute the angle of each point w.r.t. the centroid - btScalar A[8]; - for (i=0; i M__PI) a -= 2*M__PI; - btScalar maxdiff=1e9,diff; -#ifndef dNODEBUG - *iret = i0; // iret is not allowed to keep this value -#endif - for (i=0; i M__PI) diff = 2*M__PI - diff; - if (diff < maxdiff) { - maxdiff = diff; - *iret = i; - } - } - } -#ifndef dNODEBUG - btAssert (*iret != i0); // ensure iret got set -#endif - avail[*iret] = 0; - iret++; - } -} - - - -int dBoxBox2 (const btVector3& p1, const dMatrix3 R1, - const btVector3& side1, const btVector3& p2, - const dMatrix3 R2, const btVector3& side2, - btVector3& normal, btScalar *depth, int *return_code, - int maxc, dContactGeom * /*contact*/, int /*skip*/,btDiscreteCollisionDetectorInterface::Result& output); -int dBoxBox2 (const btVector3& p1, const dMatrix3 R1, - const btVector3& side1, const btVector3& p2, - const dMatrix3 R2, const btVector3& side2, - btVector3& normal, btScalar *depth, int *return_code, - int maxc, dContactGeom * /*contact*/, int /*skip*/,btDiscreteCollisionDetectorInterface::Result& output) -{ - const btScalar fudge_factor = btScalar(1.05); - btVector3 p,pp,normalC; - const btScalar *normalR = 0; - btScalar A[3],B[3],R11,R12,R13,R21,R22,R23,R31,R32,R33, - Q11,Q12,Q13,Q21,Q22,Q23,Q31,Q32,Q33,s,s2,l; - int i,j,invert_normal,code; - - // get vector from centers of box 1 to box 2, relative to box 1 - p = p2 - p1; - dMULTIPLY1_331 (pp,R1,p); // get pp = p relative to body 1 - - // get side lengths / 2 - A[0] = side1[0]*btScalar(0.5); - A[1] = side1[1]*btScalar(0.5); - A[2] = side1[2]*btScalar(0.5); - B[0] = side2[0]*btScalar(0.5); - B[1] = side2[1]*btScalar(0.5); - B[2] = side2[2]*btScalar(0.5); - - // Rij is R1'*R2, i.e. the relative rotation between R1 and R2 - R11 = dDOT44(R1+0,R2+0); R12 = dDOT44(R1+0,R2+1); R13 = dDOT44(R1+0,R2+2); - R21 = dDOT44(R1+1,R2+0); R22 = dDOT44(R1+1,R2+1); R23 = dDOT44(R1+1,R2+2); - R31 = dDOT44(R1+2,R2+0); R32 = dDOT44(R1+2,R2+1); R33 = dDOT44(R1+2,R2+2); - - Q11 = btFabs(R11); Q12 = btFabs(R12); Q13 = btFabs(R13); - Q21 = btFabs(R21); Q22 = btFabs(R22); Q23 = btFabs(R23); - Q31 = btFabs(R31); Q32 = btFabs(R32); Q33 = btFabs(R33); - - // for all 15 possible separating axes: - // * see if the axis separates the boxes. if so, return 0. - // * find the depth of the penetration along the separating axis (s2) - // * if this is the largest depth so far, record it. - // the normal vector will be set to the separating axis with the smallest - // depth. note: normalR is set to point to a column of R1 or R2 if that is - // the smallest depth normal so far. otherwise normalR is 0 and normalC is - // set to a vector relative to body 1. invert_normal is 1 if the sign of - // the normal should be flipped. - -#define TST(expr1,expr2,norm,cc) \ - s2 = btFabs(expr1) - (expr2); \ - if (s2 > 0) return 0; \ - if (s2 > s) { \ - s = s2; \ - normalR = norm; \ - invert_normal = ((expr1) < 0); \ - code = (cc); \ - } - - s = -dInfinity; - invert_normal = 0; - code = 0; - - // separating axis = u1,u2,u3 - TST (pp[0],(A[0] + B[0]*Q11 + B[1]*Q12 + B[2]*Q13),R1+0,1); - TST (pp[1],(A[1] + B[0]*Q21 + B[1]*Q22 + B[2]*Q23),R1+1,2); - TST (pp[2],(A[2] + B[0]*Q31 + B[1]*Q32 + B[2]*Q33),R1+2,3); - - // separating axis = v1,v2,v3 - TST (dDOT41(R2+0,p),(A[0]*Q11 + A[1]*Q21 + A[2]*Q31 + B[0]),R2+0,4); - TST (dDOT41(R2+1,p),(A[0]*Q12 + A[1]*Q22 + A[2]*Q32 + B[1]),R2+1,5); - TST (dDOT41(R2+2,p),(A[0]*Q13 + A[1]*Q23 + A[2]*Q33 + B[2]),R2+2,6); - - // note: cross product axes need to be scaled when s is computed. - // normal (n1,n2,n3) is relative to box 1. -#undef TST -#define TST(expr1,expr2,n1,n2,n3,cc) \ - s2 = btFabs(expr1) - (expr2); \ - if (s2 > 0) return 0; \ - l = btSqrt((n1)*(n1) + (n2)*(n2) + (n3)*(n3)); \ - if (l > 0) { \ - s2 /= l; \ - if (s2*fudge_factor > s) { \ - s = s2; \ - normalR = 0; \ - normalC[0] = (n1)/l; normalC[1] = (n2)/l; normalC[2] = (n3)/l; \ - invert_normal = ((expr1) < 0); \ - code = (cc); \ - } \ - } - - // separating axis = u1 x (v1,v2,v3) - TST(pp[2]*R21-pp[1]*R31,(A[1]*Q31+A[2]*Q21+B[1]*Q13+B[2]*Q12),0,-R31,R21,7); - TST(pp[2]*R22-pp[1]*R32,(A[1]*Q32+A[2]*Q22+B[0]*Q13+B[2]*Q11),0,-R32,R22,8); - TST(pp[2]*R23-pp[1]*R33,(A[1]*Q33+A[2]*Q23+B[0]*Q12+B[1]*Q11),0,-R33,R23,9); - - // separating axis = u2 x (v1,v2,v3) - TST(pp[0]*R31-pp[2]*R11,(A[0]*Q31+A[2]*Q11+B[1]*Q23+B[2]*Q22),R31,0,-R11,10); - TST(pp[0]*R32-pp[2]*R12,(A[0]*Q32+A[2]*Q12+B[0]*Q23+B[2]*Q21),R32,0,-R12,11); - TST(pp[0]*R33-pp[2]*R13,(A[0]*Q33+A[2]*Q13+B[0]*Q22+B[1]*Q21),R33,0,-R13,12); - - // separating axis = u3 x (v1,v2,v3) - TST(pp[1]*R11-pp[0]*R21,(A[0]*Q21+A[1]*Q11+B[1]*Q33+B[2]*Q32),-R21,R11,0,13); - TST(pp[1]*R12-pp[0]*R22,(A[0]*Q22+A[1]*Q12+B[0]*Q33+B[2]*Q31),-R22,R12,0,14); - TST(pp[1]*R13-pp[0]*R23,(A[0]*Q23+A[1]*Q13+B[0]*Q32+B[1]*Q31),-R23,R13,0,15); - -#undef TST - - if (!code) return 0; - - // if we get to this point, the boxes interpenetrate. compute the normal - // in global coordinates. - if (normalR) { - normal[0] = normalR[0]; - normal[1] = normalR[4]; - normal[2] = normalR[8]; - } - else { - dMULTIPLY0_331 (normal,R1,normalC); - } - if (invert_normal) { - normal[0] = -normal[0]; - normal[1] = -normal[1]; - normal[2] = -normal[2]; - } - *depth = -s; - - // compute contact point(s) - - if (code > 6) { - // an edge from box 1 touches an edge from box 2. - // find a point pa on the intersecting edge of box 1 - btVector3 pa; - btScalar sign; - for (i=0; i<3; i++) pa[i] = p1[i]; - for (j=0; j<3; j++) { - sign = (dDOT14(normal,R1+j) > 0) ? btScalar(1.0) : btScalar(-1.0); - for (i=0; i<3; i++) pa[i] += sign * A[j] * R1[i*4+j]; - } - - // find a point pb on the intersecting edge of box 2 - btVector3 pb; - for (i=0; i<3; i++) pb[i] = p2[i]; - for (j=0; j<3; j++) { - sign = (dDOT14(normal,R2+j) > 0) ? btScalar(-1.0) : btScalar(1.0); - for (i=0; i<3; i++) pb[i] += sign * B[j] * R2[i*4+j]; - } - - btScalar alpha,beta; - btVector3 ua,ub; - for (i=0; i<3; i++) ua[i] = R1[((code)-7)/3 + i*4]; - for (i=0; i<3; i++) ub[i] = R2[((code)-7)%3 + i*4]; - - dLineClosestApproach (pa,ua,pb,ub,&alpha,&beta); - for (i=0; i<3; i++) pa[i] += ua[i]*alpha; - for (i=0; i<3; i++) pb[i] += ub[i]*beta; - - { - - //contact[0].pos[i] = btScalar(0.5)*(pa[i]+pb[i]); - //contact[0].depth = *depth; - btVector3 pointInWorld; - -#ifdef USE_CENTER_POINT - for (i=0; i<3; i++) - pointInWorld[i] = (pa[i]+pb[i])*btScalar(0.5); - output.addContactPoint(-normal,pointInWorld,-*depth); -#else - output.addContactPoint(-normal,pb,-*depth); -#endif // - *return_code = code; - } - return 1; - } - - // okay, we have a face-something intersection (because the separating - // axis is perpendicular to a face). define face 'a' to be the reference - // face (i.e. the normal vector is perpendicular to this) and face 'b' to be - // the incident face (the closest face of the other box). - - const btScalar *Ra,*Rb,*pa,*pb,*Sa,*Sb; - if (code <= 3) { - Ra = R1; - Rb = R2; - pa = p1; - pb = p2; - Sa = A; - Sb = B; - } - else { - Ra = R2; - Rb = R1; - pa = p2; - pb = p1; - Sa = B; - Sb = A; - } - - // nr = normal vector of reference face dotted with axes of incident box. - // anr = absolute values of nr. - btVector3 normal2,nr,anr; - if (code <= 3) { - normal2[0] = normal[0]; - normal2[1] = normal[1]; - normal2[2] = normal[2]; - } - else { - normal2[0] = -normal[0]; - normal2[1] = -normal[1]; - normal2[2] = -normal[2]; - } - dMULTIPLY1_331 (nr,Rb,normal2); - anr[0] = btFabs (nr[0]); - anr[1] = btFabs (nr[1]); - anr[2] = btFabs (nr[2]); - - // find the largest compontent of anr: this corresponds to the normal - // for the indident face. the other axis numbers of the indicent face - // are stored in a1,a2. - int lanr,a1,a2; - if (anr[1] > anr[0]) { - if (anr[1] > anr[2]) { - a1 = 0; - lanr = 1; - a2 = 2; - } - else { - a1 = 0; - a2 = 1; - lanr = 2; - } - } - else { - if (anr[0] > anr[2]) { - lanr = 0; - a1 = 1; - a2 = 2; - } - else { - a1 = 0; - a2 = 1; - lanr = 2; - } - } - - // compute center point of incident face, in reference-face coordinates - btVector3 center; - if (nr[lanr] < 0) { - for (i=0; i<3; i++) center[i] = pb[i] - pa[i] + Sb[lanr] * Rb[i*4+lanr]; - } - else { - for (i=0; i<3; i++) center[i] = pb[i] - pa[i] - Sb[lanr] * Rb[i*4+lanr]; - } - - // find the normal and non-normal axis numbers of the reference box - int codeN,code1,code2; - if (code <= 3) codeN = code-1; else codeN = code-4; - if (codeN==0) { - code1 = 1; - code2 = 2; - } - else if (codeN==1) { - code1 = 0; - code2 = 2; - } - else { - code1 = 0; - code2 = 1; - } - - // find the four corners of the incident face, in reference-face coordinates - btScalar quad[8]; // 2D coordinate of incident face (x,y pairs) - btScalar c1,c2,m11,m12,m21,m22; - c1 = dDOT14 (center,Ra+code1); - c2 = dDOT14 (center,Ra+code2); - // optimize this? - we have already computed this data above, but it is not - // stored in an easy-to-index format. for now it's quicker just to recompute - // the four dot products. - m11 = dDOT44 (Ra+code1,Rb+a1); - m12 = dDOT44 (Ra+code1,Rb+a2); - m21 = dDOT44 (Ra+code2,Rb+a1); - m22 = dDOT44 (Ra+code2,Rb+a2); - { - btScalar k1 = m11*Sb[a1]; - btScalar k2 = m21*Sb[a1]; - btScalar k3 = m12*Sb[a2]; - btScalar k4 = m22*Sb[a2]; - quad[0] = c1 - k1 - k3; - quad[1] = c2 - k2 - k4; - quad[2] = c1 - k1 + k3; - quad[3] = c2 - k2 + k4; - quad[4] = c1 + k1 + k3; - quad[5] = c2 + k2 + k4; - quad[6] = c1 + k1 - k3; - quad[7] = c2 + k2 - k4; - } - - // find the size of the reference face - btScalar rect[2]; - rect[0] = Sa[code1]; - rect[1] = Sa[code2]; - - // intersect the incident and reference faces - btScalar ret[16]; - int n = intersectRectQuad2 (rect,quad,ret); - if (n < 1) return 0; // this should never happen - - // convert the intersection points into reference-face coordinates, - // and compute the contact position and depth for each point. only keep - // those points that have a positive (penetrating) depth. delete points in - // the 'ret' array as necessary so that 'point' and 'ret' correspond. - btScalar point[3*8]; // penetrating contact points - btScalar dep[8]; // depths for those points - btScalar det1 = 1.f/(m11*m22 - m12*m21); - m11 *= det1; - m12 *= det1; - m21 *= det1; - m22 *= det1; - int cnum = 0; // number of penetrating contact points found - for (j=0; j < n; j++) { - btScalar k1 = m22*(ret[j*2]-c1) - m12*(ret[j*2+1]-c2); - btScalar k2 = -m21*(ret[j*2]-c1) + m11*(ret[j*2+1]-c2); - for (i=0; i<3; i++) point[cnum*3+i] = - center[i] + k1*Rb[i*4+a1] + k2*Rb[i*4+a2]; - dep[cnum] = Sa[codeN] - dDOT(normal2,point+cnum*3); - if (dep[cnum] >= 0) { - ret[cnum*2] = ret[j*2]; - ret[cnum*2+1] = ret[j*2+1]; - cnum++; - } - } - if (cnum < 1) return 0; // this should never happen - - // we can't generate more contacts than we actually have - if (maxc > cnum) maxc = cnum; - if (maxc < 1) maxc = 1; - - if (cnum <= maxc) { - // we have less contacts than we need, so we use them all - for (j=0; j < cnum; j++) { - - //AddContactPoint... - - //dContactGeom *con = CONTACT(contact,skip*j); - //for (i=0; i<3; i++) con->pos[i] = point[j*3+i] + pa[i]; - //con->depth = dep[j]; - - btVector3 pointInWorld; - for (i=0; i<3; i++) - pointInWorld[i] = point[j*3+i] + pa[i]; - output.addContactPoint(-normal,pointInWorld,-dep[j]); - - } - } - else { - // we have more contacts than are wanted, some of them must be culled. - // find the deepest point, it is always the first contact. - int i1 = 0; - btScalar maxdepth = dep[0]; - for (i=1; i maxdepth) { - maxdepth = dep[i]; - i1 = i; - } - } - - int iret[8]; - cullPoints2 (cnum,ret,maxc,i1,iret); - - for (j=0; j < maxc; j++) { -// dContactGeom *con = CONTACT(contact,skip*j); - // for (i=0; i<3; i++) con->pos[i] = point[iret[j]*3+i] + pa[i]; - // con->depth = dep[iret[j]]; - - btVector3 posInWorld; - for (i=0; i<3; i++) - posInWorld[i] = point[iret[j]*3+i] + pa[i]; - output.addContactPoint(-normal,posInWorld,-dep[iret[j]]); - } - cnum = maxc; - } - - *return_code = code; - return cnum; -} - -void btBoxBoxDetector::getClosestPoints(const ClosestPointInput& input,Result& output,class btIDebugDraw* /*debugDraw*/,bool /*swapResults*/) -{ - - const btTransform& transformA = input.m_transformA; - const btTransform& transformB = input.m_transformB; - - int skip = 0; - dContactGeom *contact = 0; - - dMatrix3 R1; - dMatrix3 R2; - - for (int j=0;j<3;j++) - { - R1[0+4*j] = transformA.getBasis()[j].x(); - R2[0+4*j] = transformB.getBasis()[j].x(); - - R1[1+4*j] = transformA.getBasis()[j].y(); - R2[1+4*j] = transformB.getBasis()[j].y(); - - - R1[2+4*j] = transformA.getBasis()[j].z(); - R2[2+4*j] = transformB.getBasis()[j].z(); - - } - - - - btVector3 normal; - btScalar depth; - int return_code; - int maxc = 4; - - - dBoxBox2 (transformA.getOrigin(), - R1, - 2.f*m_box1->getHalfExtentsWithMargin(), - transformB.getOrigin(), - R2, - 2.f*m_box2->getHalfExtentsWithMargin(), - normal, &depth, &return_code, - maxc, contact, skip, - output - ); - -} diff --git a/extern/bullet2/src/BulletCollision/CollisionDispatch/btBoxBoxDetector.h b/extern/bullet2/src/BulletCollision/CollisionDispatch/btBoxBoxDetector.h deleted file mode 100644 index 605294d47bd..00000000000 --- a/extern/bullet2/src/BulletCollision/CollisionDispatch/btBoxBoxDetector.h +++ /dev/null @@ -1,44 +0,0 @@ -/* - * Box-Box collision detection re-distributed under the ZLib license with permission from Russell L. Smith - * Original version is from Open Dynamics Engine, Copyright (C) 2001,2002 Russell L. Smith. - * All rights reserved. Email: russ@q12.org Web: www.q12.org - -Bullet Continuous Collision Detection and Physics Library -Copyright (c) 2003-2006 Erwin Coumans http://continuousphysics.com/Bullet/ - -This software is provided 'as-is', without any express or implied warranty. -In no event will the authors be held liable for any damages arising from the use of this software. -Permission is granted to anyone to use this software for any purpose, -including commercial applications, and to alter it and redistribute it freely, -subject to the following restrictions: - -1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. -2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. -3. This notice may not be removed or altered from any source distribution. -*/ -#ifndef BOX_BOX_DETECTOR_H -#define BOX_BOX_DETECTOR_H - - -class btBoxShape; -#include "BulletCollision/NarrowPhaseCollision/btDiscreteCollisionDetectorInterface.h" - - -/// btBoxBoxDetector wraps the ODE box-box collision detector -/// re-distributed under the Zlib license with permission from Russell L. Smith -struct btBoxBoxDetector : public btDiscreteCollisionDetectorInterface -{ - btBoxShape* m_box1; - btBoxShape* m_box2; - -public: - - btBoxBoxDetector(btBoxShape* box1,btBoxShape* box2); - - virtual ~btBoxBoxDetector() {}; - - virtual void getClosestPoints(const ClosestPointInput& input,Result& output,class btIDebugDraw* debugDraw,bool swapResults=false); - -}; - -#endif //BT_BOX_BOX_DETECTOR_H diff --git a/extern/bullet2/src/BulletCollision/CollisionDispatch/btCollisionConfiguration.h b/extern/bullet2/src/BulletCollision/CollisionDispatch/btCollisionConfiguration.h deleted file mode 100644 index fad770ac26d..00000000000 --- a/extern/bullet2/src/BulletCollision/CollisionDispatch/btCollisionConfiguration.h +++ /dev/null @@ -1,47 +0,0 @@ -/* -Bullet Continuous Collision Detection and Physics Library -Copyright (c) 2003-2006 Erwin Coumans http://continuousphysics.com/Bullet/ - -This software is provided 'as-is', without any express or implied warranty. -In no event will the authors be held liable for any damages arising from the use of this software. -Permission is granted to anyone to use this software for any purpose, -including commercial applications, and to alter it and redistribute it freely, -subject to the following restrictions: - -1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. -2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. -3. This notice may not be removed or altered from any source distribution. -*/ - -#ifndef BT_COLLISION_CONFIGURATION -#define BT_COLLISION_CONFIGURATION -struct btCollisionAlgorithmCreateFunc; - -class btStackAlloc; -class btPoolAllocator; - -///btCollisionConfiguration allows to configure Bullet collision detection -///stack allocator size, default collision algorithms and persistent manifold pool size -///todo: describe the meaning -class btCollisionConfiguration -{ - -public: - - virtual ~btCollisionConfiguration() - { - } - - ///memory pools - virtual btPoolAllocator* getPersistentManifoldPool() = 0; - - virtual btPoolAllocator* getCollisionAlgorithmPool() = 0; - - virtual btStackAlloc* getStackAllocator() = 0; - - virtual btCollisionAlgorithmCreateFunc* getCollisionAlgorithmCreateFunc(int proxyType0,int proxyType1) =0; - -}; - -#endif //BT_COLLISION_CONFIGURATION - diff --git a/extern/bullet2/src/BulletCollision/CollisionDispatch/btCollisionCreateFunc.h b/extern/bullet2/src/BulletCollision/CollisionDispatch/btCollisionCreateFunc.h index c6728918d16..d51a59af7f0 100644 --- a/extern/bullet2/src/BulletCollision/CollisionDispatch/btCollisionCreateFunc.h +++ b/extern/bullet2/src/BulletCollision/CollisionDispatch/btCollisionCreateFunc.h @@ -16,7 +16,7 @@ subject to the following restrictions: #ifndef COLLISION_CREATE_FUNC #define COLLISION_CREATE_FUNC -#include "LinearMath/btAlignedObjectArray.h" +#include "../../LinearMath/btAlignedObjectArray.h" typedef btAlignedObjectArray btCollisionObjectArray; class btCollisionAlgorithm; class btCollisionObject; diff --git a/extern/bullet2/src/BulletCollision/CollisionDispatch/btCollisionDispatcher.cpp b/extern/bullet2/src/BulletCollision/CollisionDispatch/btCollisionDispatcher.cpp index a031a9f9784..b535fac6563 100644 --- a/extern/bullet2/src/BulletCollision/CollisionDispatch/btCollisionDispatcher.cpp +++ b/extern/bullet2/src/BulletCollision/CollisionDispatch/btCollisionDispatcher.cpp @@ -19,39 +19,69 @@ subject to the following restrictions: #include "BulletCollision/BroadphaseCollision/btCollisionAlgorithm.h" - +#include "BulletCollision/CollisionDispatch/btConvexConvexAlgorithm.h" +#include "BulletCollision/CollisionDispatch/btEmptyCollisionAlgorithm.h" +#include "BulletCollision/CollisionDispatch/btConvexConcaveCollisionAlgorithm.h" +#include "BulletCollision/CollisionDispatch/btCompoundCollisionAlgorithm.h" #include "BulletCollision/CollisionShapes/btCollisionShape.h" #include "BulletCollision/CollisionDispatch/btCollisionObject.h" #include "BulletCollision/BroadphaseCollision/btOverlappingPairCache.h" -#include "LinearMath/btPoolAllocator.h" -#include "BulletCollision/CollisionDispatch/btCollisionConfiguration.h" int gNumManifold = 0; -#ifdef BT_DEBUG #include -#endif + +btCollisionDispatcher::btCollisionDispatcher(bool noDefaultAlgorithms): +m_count(0), +m_useIslands(true), +m_convexConvexCreateFunc(0), +m_convexConcaveCreateFunc(0), +m_swappedConvexConcaveCreateFunc(0), +m_compoundCreateFunc(0), +m_swappedCompoundCreateFunc(0), +m_emptyCreateFunc(0) +{ + (void)noDefaultAlgorithms; + int i; -btCollisionDispatcher::btCollisionDispatcher (btCollisionConfiguration* collisionConfiguration): + setNearCallback(defaultNearCallback); + + m_emptyCreateFunc = new btEmptyAlgorithm::CreateFunc; + for (i=0;igetCollisionAlgorithmPool(); - - m_persistentManifoldPoolAllocator = collisionConfiguration->getPersistentManifoldPool(); + //default CreationFunctions, filling the m_doubleDispatch table + m_convexConvexCreateFunc = new btConvexConvexAlgorithm::CreateFunc; + m_convexConcaveCreateFunc = new btConvexConcaveCollisionAlgorithm::CreateFunc; + m_swappedConvexConcaveCreateFunc = new btConvexConcaveCollisionAlgorithm::SwappedCreateFunc; + m_compoundCreateFunc = new btCompoundCollisionAlgorithm::CreateFunc; + m_swappedCompoundCreateFunc = new btCompoundCollisionAlgorithm::SwappedCreateFunc; + m_emptyCreateFunc = new btEmptyAlgorithm::CreateFunc; for (i=0;igetCollisionAlgorithmCreateFunc(i,j); + m_doubleDispatch[i][j] = internalFindCreateFunc(i,j); assert(m_doubleDispatch[i][j]); } } @@ -59,6 +89,8 @@ btCollisionDispatcher::btCollisionDispatcher (btCollisionConfiguration* collisio }; +#endif //BT_EXCLUDE_DEFAULT_COLLISIONALGORITHM_REGISTRATION + void btCollisionDispatcher::registerCollisionCreateFunc(int proxyType0, int proxyType1, btCollisionAlgorithmCreateFunc *createFunc) { @@ -67,6 +99,12 @@ void btCollisionDispatcher::registerCollisionCreateFunc(int proxyType0, int prox btCollisionDispatcher::~btCollisionDispatcher() { + delete m_convexConvexCreateFunc; + delete m_convexConcaveCreateFunc; + delete m_swappedConvexConcaveCreateFunc; + delete m_compoundCreateFunc; + delete m_swappedCompoundCreateFunc; + delete m_emptyCreateFunc; } btPersistentManifold* btCollisionDispatcher::getNewManifold(void* b0,void* b1) @@ -79,18 +117,7 @@ btPersistentManifold* btCollisionDispatcher::getNewManifold(void* b0,void* b1) btCollisionObject* body0 = (btCollisionObject*)b0; btCollisionObject* body1 = (btCollisionObject*)b1; - void* mem = 0; - - if (m_persistentManifoldPoolAllocator->getFreeCount()) - { - mem = m_persistentManifoldPoolAllocator->allocate(sizeof(btPersistentManifold)); - } else - { - mem = btAlignedAlloc(sizeof(btPersistentManifold),16); - - } - btPersistentManifold* manifold = new(mem) btPersistentManifold (body0,body1,0); - manifold->m_index1a = m_manifoldsPtr.size(); + btPersistentManifold* manifold = new btPersistentManifold (body0,body1); m_manifoldsPtr.push_back(manifold); return manifold; @@ -110,19 +137,13 @@ void btCollisionDispatcher::releaseManifold(btPersistentManifold* manifold) //printf("releaseManifold: gNumManifold %d\n",gNumManifold); clearManifold(manifold); - int findIndex = manifold->m_index1a; - btAssert(findIndex < m_manifoldsPtr.size()); - m_manifoldsPtr.swap(findIndex,m_manifoldsPtr.size()-1); - m_manifoldsPtr[findIndex]->m_index1a = findIndex; - m_manifoldsPtr.pop_back(); - - manifold->~btPersistentManifold(); - if (m_persistentManifoldPoolAllocator->validPtr(manifold)) + ///todo: this can be improved a lot, linear search might be slow part! + int findIndex = m_manifoldsPtr.findLinearSearch(manifold); + if (findIndex < m_manifoldsPtr.size()) { - m_persistentManifoldPoolAllocator->freeMemory(manifold); - } else - { - btAlignedFree(manifold); + m_manifoldsPtr.swap(findIndex,m_manifoldsPtr.size()-1); + m_manifoldsPtr.pop_back(); + delete manifold; } } @@ -131,19 +152,99 @@ void btCollisionDispatcher::releaseManifold(btPersistentManifold* manifold) btCollisionAlgorithm* btCollisionDispatcher::findAlgorithm(btCollisionObject* body0,btCollisionObject* body1,btPersistentManifold* sharedManifold) { + +#ifdef USE_DISPATCH_REGISTRY_ARRAY btCollisionAlgorithmConstructionInfo ci; - - ci.m_dispatcher1 = this; + ci.m_dispatcher = this; ci.m_manifold = sharedManifold; - btCollisionAlgorithm* algo = m_doubleDispatch[body0->getCollisionShape()->getShapeType()][body1->getCollisionShape()->getShapeType()]->CreateCollisionAlgorithm(ci,body0,body1); - + btCollisionAlgorithm* algo = m_doubleDispatch[body0->getCollisionShape()->getShapeType()][body1->getCollisionShape()->getShapeType()] + ->CreateCollisionAlgorithm(ci,body0,body1); +#else + btCollisionAlgorithm* algo = internalFindAlgorithm(body0,body1); +#endif //USE_DISPATCH_REGISTRY_ARRAY return algo; } +#ifndef BT_EXCLUDE_DEFAULT_COLLISIONALGORITHM_REGISTRATION + +btCollisionAlgorithmCreateFunc* btCollisionDispatcher::internalFindCreateFunc(int proxyType0,int proxyType1) +{ + + if (btBroadphaseProxy::isConvex(proxyType0) && btBroadphaseProxy::isConvex(proxyType1)) + { + return m_convexConvexCreateFunc; + } + + if (btBroadphaseProxy::isConvex(proxyType0) && btBroadphaseProxy::isConcave(proxyType1)) + { + return m_convexConcaveCreateFunc; + } + + if (btBroadphaseProxy::isConvex(proxyType1) && btBroadphaseProxy::isConcave(proxyType0)) + { + return m_swappedConvexConcaveCreateFunc; + } + + if (btBroadphaseProxy::isCompound(proxyType0)) + { + return m_compoundCreateFunc; + } else + { + if (btBroadphaseProxy::isCompound(proxyType1)) + { + return m_swappedCompoundCreateFunc; + } + } + + //failed to find an algorithm + return m_emptyCreateFunc; +} + +#endif //BT_EXCLUDE_DEFAULT_COLLISIONALGORITHM_REGISTRATION +#ifndef USE_DISPATCH_REGISTRY_ARRAY + +btCollisionAlgorithm* btCollisionDispatcher::internalFindAlgorithm(btCollisionObject* body0,btCollisionObject* body1,btPersistentManifold* sharedManifold) +{ + m_count++; + + btCollisionAlgorithmConstructionInfo ci; + ci.m_dispatcher = this; + + if (body0->getCollisionShape()->isConvex() && body1->getCollisionShape()->isConvex() ) + { + return new btConvexConvexAlgorithm(sharedManifold,ci,body0,body1); + } + + if (body0->getCollisionShape()->isConvex() && body1->getCollisionShape()->isConcave()) + { + return new btConvexConcaveCollisionAlgorithm(ci,body0,body1,false); + } + + if (body1->getCollisionShape()->isConvex() && body0->getCollisionShape()->isConcave()) + { + return new btConvexConcaveCollisionAlgorithm(ci,body0,body1,true); + } + + if (body0->getCollisionShape()->isCompound()) + { + return new btCompoundCollisionAlgorithm(ci,body0,body1,false); + } else + { + if (body1->getCollisionShape()->isCompound()) + { + return new btCompoundCollisionAlgorithm(ci,body0,body1,true); + } + } + + //failed to find an algorithm + return new btEmptyAlgorithm(ci); + +} +#endif //USE_DISPATCH_REGISTRY_ARRAY bool btCollisionDispatcher::needsResponse(btCollisionObject* body0,btCollisionObject* body1) { @@ -163,19 +264,13 @@ bool btCollisionDispatcher::needsCollision(btCollisionObject* body0,btCollisionO bool needsCollision = true; -#ifdef BT_DEBUG - if (!m_staticWarningReported) + //broadphase filtering already deals with this + if ((body0->isStaticObject() || body0->isKinematicObject()) && + (body1->isStaticObject() || body1->isKinematicObject())) { - //broadphase filtering already deals with this - if ((body0->isStaticObject() || body0->isKinematicObject()) && - (body1->isStaticObject() || body1->isKinematicObject())) - { - m_staticWarningReported = true; - printf("warning btCollisionDispatcher::needsCollision: static-static collision!\n"); - } + printf("warning btCollisionDispatcher::needsCollision: static-static collision!\n"); } -#endif //BT_DEBUG - + if ((!body0->isActive()) && (!body1->isActive())) needsCollision = false; else if (!body0->checkCollideWith(body1)) @@ -191,25 +286,23 @@ bool btCollisionDispatcher::needsCollision(btCollisionObject* body0,btCollisionO ///this is useful for the collision dispatcher. class btCollisionPairCallback : public btOverlapCallback { - const btDispatcherInfo& m_dispatchInfo; + btDispatcherInfo& m_dispatchInfo; btCollisionDispatcher* m_dispatcher; public: - btCollisionPairCallback(const btDispatcherInfo& dispatchInfo,btCollisionDispatcher* dispatcher) + btCollisionPairCallback(btDispatcherInfo& dispatchInfo,btCollisionDispatcher* dispatcher) :m_dispatchInfo(dispatchInfo), m_dispatcher(dispatcher) { } - /*btCollisionPairCallback& operator=(btCollisionPairCallback& other) + btCollisionPairCallback& operator=(btCollisionPairCallback& other) { m_dispatchInfo = other.m_dispatchInfo; m_dispatcher = other.m_dispatcher; return *this; } - */ - virtual ~btCollisionPairCallback() {} @@ -223,14 +316,13 @@ public: }; - -void btCollisionDispatcher::dispatchAllCollisionPairs(btOverlappingPairCache* pairCache,const btDispatcherInfo& dispatchInfo,btDispatcher* dispatcher) +void btCollisionDispatcher::dispatchAllCollisionPairs(btOverlappingPairCache* pairCache,btDispatcherInfo& dispatchInfo) { //m_blockedForChanges = true; btCollisionPairCallback collisionCallback(dispatchInfo,this); - pairCache->processAllOverlappingPairs(&collisionCallback,dispatcher); + pairCache->processAllOverlappingPairs(&collisionCallback); //m_blockedForChanges = false; @@ -240,7 +332,7 @@ void btCollisionDispatcher::dispatchAllCollisionPairs(btOverlappingPairCache* pa //by default, Bullet will use this near callback -void btCollisionDispatcher::defaultNearCallback(btBroadphasePair& collisionPair, btCollisionDispatcher& dispatcher, const btDispatcherInfo& dispatchInfo) +void btCollisionDispatcher::defaultNearCallback(btBroadphasePair& collisionPair, btCollisionDispatcher& dispatcher, btDispatcherInfo& dispatchInfo) { btCollisionObject* colObj0 = (btCollisionObject*)collisionPair.m_pProxy0->m_clientObject; btCollisionObject* colObj1 = (btCollisionObject*)collisionPair.m_pProxy1->m_clientObject; @@ -273,26 +365,3 @@ void btCollisionDispatcher::defaultNearCallback(btBroadphasePair& collisionPair, } } - - -void* btCollisionDispatcher::allocateCollisionAlgorithm(int size) -{ - if (m_collisionAlgorithmPoolAllocator->getFreeCount()) - { - return m_collisionAlgorithmPoolAllocator->allocate(size); - } - - //warn user for overflow? - return btAlignedAlloc(static_cast(size), 16); -} - -void btCollisionDispatcher::freeCollisionAlgorithm(void* ptr) -{ - if (m_collisionAlgorithmPoolAllocator->validPtr(ptr)) - { - m_collisionAlgorithmPoolAllocator->freeMemory(ptr); - } else - { - btAlignedFree(ptr); - } -} diff --git a/extern/bullet2/src/BulletCollision/CollisionDispatch/btCollisionDispatcher.h b/extern/bullet2/src/BulletCollision/CollisionDispatch/btCollisionDispatcher.h index a9c9cd414c1..ca5aba8f01c 100644 --- a/extern/bullet2/src/BulletCollision/CollisionDispatch/btCollisionDispatcher.h +++ b/extern/bullet2/src/BulletCollision/CollisionDispatch/btCollisionDispatcher.h @@ -16,18 +16,17 @@ subject to the following restrictions: #ifndef COLLISION__DISPATCHER_H #define COLLISION__DISPATCHER_H -#include "BulletCollision/BroadphaseCollision/btDispatcher.h" -#include "BulletCollision/NarrowPhaseCollision/btPersistentManifold.h" +#include "../BroadphaseCollision/btDispatcher.h" +#include "../NarrowPhaseCollision/btPersistentManifold.h" -#include "BulletCollision/CollisionDispatch/btManifoldResult.h" +#include "../CollisionDispatch/btManifoldResult.h" -#include "BulletCollision/BroadphaseCollision/btBroadphaseProxy.h" -#include "LinearMath/btAlignedObjectArray.h" +#include "../BroadphaseCollision/btBroadphaseProxy.h" +#include "../../LinearMath/btAlignedObjectArray.h" class btIDebugDraw; class btOverlappingPairCache; -class btPoolAllocator; -class btCollisionConfiguration; + #include "btCollisionCreateFunc.h" @@ -35,7 +34,7 @@ class btCollisionConfiguration; class btCollisionDispatcher; ///user can override this nearcallback for collision filtering and more finegrained control over collision detection -typedef void (*btNearCallback)(btBroadphasePair& collisionPair, btCollisionDispatcher& dispatcher, const btDispatcherInfo& dispatchInfo); +typedef void (*btNearCallback)(btBroadphasePair& collisionPair, btCollisionDispatcher& dispatcher, btDispatcherInfo& dispatchInfo); ///btCollisionDispatcher supports algorithms that handle ConvexConvex and ConvexConcave collision pairs. @@ -47,22 +46,26 @@ class btCollisionDispatcher : public btDispatcher btAlignedObjectArray m_manifoldsPtr; bool m_useIslands; - - bool m_staticWarningReported; btManifoldResult m_defaultManifoldResult; btNearCallback m_nearCallback; - btPoolAllocator* m_collisionAlgorithmPoolAllocator; - - btPoolAllocator* m_persistentManifoldPoolAllocator; - btCollisionAlgorithmCreateFunc* m_doubleDispatch[MAX_BROADPHASE_COLLISION_TYPES][MAX_BROADPHASE_COLLISION_TYPES]; + btCollisionAlgorithmCreateFunc* internalFindCreateFunc(int proxyType0,int proxyType1); - btCollisionConfiguration* m_collisionConfiguration; + //default CreationFunctions, filling the m_doubleDispatch table + btCollisionAlgorithmCreateFunc* m_convexConvexCreateFunc; + btCollisionAlgorithmCreateFunc* m_convexConcaveCreateFunc; + btCollisionAlgorithmCreateFunc* m_swappedConvexConcaveCreateFunc; + btCollisionAlgorithmCreateFunc* m_compoundCreateFunc; + btCollisionAlgorithmCreateFunc* m_swappedCompoundCreateFunc; + btCollisionAlgorithmCreateFunc* m_emptyCreateFunc; +#ifndef USE_DISPATCH_REGISTRY_ARRAY + btCollisionAlgorithm* internalFindAlgorithm(btCollisionObject* body0,btCollisionObject* body1,btPersistentManifold* sharedManifold = 0); +#endif //USE_DISPATCH_REGISTRY_ARRAY public: @@ -89,7 +92,11 @@ public: return m_manifoldsPtr[index]; } - btCollisionDispatcher (btCollisionConfiguration* collisionConfiguration); + ///the default constructor creates/register default collision algorithms, for convex, compound and concave shape support + btCollisionDispatcher (); + + ///a special constructor that doesn't create/register the default collision algorithms + btCollisionDispatcher(bool noDefaultAlgorithms); virtual ~btCollisionDispatcher(); @@ -107,7 +114,7 @@ public: virtual bool needsResponse(btCollisionObject* body0,btCollisionObject* body1); - virtual void dispatchAllCollisionPairs(btOverlappingPairCache* pairCache,const btDispatcherInfo& dispatchInfo,btDispatcher* dispatcher) ; + virtual void dispatchAllCollisionPairs(btOverlappingPairCache* pairCache,btDispatcherInfo& dispatchInfo); void setNearCallback(btNearCallback nearCallback) { @@ -120,26 +127,7 @@ public: } //by default, Bullet will use this near callback - static void defaultNearCallback(btBroadphasePair& collisionPair, btCollisionDispatcher& dispatcher, const btDispatcherInfo& dispatchInfo); - - virtual void* allocateCollisionAlgorithm(int size); - - virtual void freeCollisionAlgorithm(void* ptr); - - btCollisionConfiguration* getCollisionConfiguration() - { - return m_collisionConfiguration; - } - - const btCollisionConfiguration* getCollisionConfiguration() const - { - return m_collisionConfiguration; - } - - void setCollisionConfiguration(btCollisionConfiguration* config) - { - m_collisionConfiguration = config; - } + static void defaultNearCallback(btBroadphasePair& collisionPair, btCollisionDispatcher& dispatcher, btDispatcherInfo& dispatchInfo); }; diff --git a/extern/bullet2/src/BulletCollision/CollisionDispatch/btCollisionObject.cpp b/extern/bullet2/src/BulletCollision/CollisionDispatch/btCollisionObject.cpp index d1641249568..d4c0a4e8cb3 100644 --- a/extern/bullet2/src/BulletCollision/CollisionDispatch/btCollisionObject.cpp +++ b/extern/bullet2/src/BulletCollision/CollisionDispatch/btCollisionObject.cpp @@ -13,22 +13,15 @@ subject to the following restrictions: 3. This notice may not be removed or altered from any source distribution. */ - #include "btCollisionObject.h" btCollisionObject::btCollisionObject() : m_broadphaseHandle(0), m_collisionShape(0), - m_rootCollisionShape(0), - m_collisionFlags(btCollisionObject::CF_STATIC_OBJECT), - m_islandTag1(-1), - m_companionId(-1), + m_collisionFlags(0), m_activationState1(1), m_deactivationTime(btScalar(0.)), - m_friction(btScalar(0.5)), - m_restitution(btScalar(0.)), m_userObjectPointer(0), - m_internalType(CO_COLLISION_OBJECT), m_hitFraction(btScalar(1.)), m_ccdSweptSphereRadius(btScalar(0.)), m_ccdSquareMotionThreshold(btScalar(0.)), @@ -62,4 +55,3 @@ void btCollisionObject::activate(bool forceActivation) } - diff --git a/extern/bullet2/src/BulletCollision/CollisionDispatch/btCollisionObject.h b/extern/bullet2/src/BulletCollision/CollisionDispatch/btCollisionObject.h index 96cbd1c3eb8..9fb6a67c4a3 100644 --- a/extern/bullet2/src/BulletCollision/CollisionDispatch/btCollisionObject.h +++ b/extern/bullet2/src/BulletCollision/CollisionDispatch/btCollisionObject.h @@ -16,7 +16,7 @@ subject to the following restrictions: #ifndef COLLISION_OBJECT_H #define COLLISION_OBJECT_H -#include "LinearMath/btTransform.h" +#include "../../LinearMath/btTransform.h" //island management, m_activationState1 #define ACTIVE_TAG 1 @@ -27,8 +27,7 @@ subject to the following restrictions: struct btBroadphaseProxy; class btCollisionShape; -#include "LinearMath/btMotionState.h" -#include "LinearMath/btAlignedAllocator.h" +#include "../../LinearMath/btMotionState.h" @@ -51,11 +50,6 @@ protected: btVector3 m_interpolationAngularVelocity; btBroadphaseProxy* m_broadphaseHandle; btCollisionShape* m_collisionShape; - - ///m_rootCollisionShape is temporarily used to store the original collision shape - ///The m_collisionShape might be temporarily replaced by a child collision shape during collision detection purposes - ///If it is NULL, the m_collisionShape is not temporarily replaced. - btCollisionShape* m_rootCollisionShape; int m_collisionFlags; @@ -71,9 +65,8 @@ protected: ///users can point to their objects, m_userPointer is not used by Bullet, see setUserPointer/getUserPointer void* m_userObjectPointer; - ///m_internalType is reserved to distinguish Bullet's btCollisionObject, btRigidBody, btSoftBody etc. - ///do not assign your own m_internalType unless you write a new dynamics object class. - int m_internalType; + ///m_internalOwner is reserved to point to Bullet's btRigidBody. Don't use this, use m_userObjectPointer instead. + void* m_internalOwner; ///time of impact calculation btScalar m_hitFraction; @@ -89,15 +82,13 @@ protected: char m_pad[7]; - virtual bool checkCollideWithOverride(btCollisionObject* /* co */) + virtual bool checkCollideWithOverride(btCollisionObject* co) { return true; } public: - BT_DECLARE_ALIGNED_ALLOCATOR(); - enum CollisionFlags { CF_STATIC_OBJECT= 1, @@ -106,35 +97,29 @@ public: CF_CUSTOM_MATERIAL_CALLBACK = 8//this allows per-triangle material (friction/restitution) }; - enum CollisionObjectTypes - { - CO_COLLISION_OBJECT =1, - CO_RIGID_BODY, - CO_SOFT_BODY - }; - SIMD_FORCE_INLINE bool mergesSimulationIslands() const + inline bool mergesSimulationIslands() const { ///static objects, kinematic and object without contact response don't merge islands return ((m_collisionFlags & (CF_STATIC_OBJECT | CF_KINEMATIC_OBJECT | CF_NO_CONTACT_RESPONSE) )==0); } - SIMD_FORCE_INLINE bool isStaticObject() const { + inline bool isStaticObject() const { return (m_collisionFlags & CF_STATIC_OBJECT) != 0; } - SIMD_FORCE_INLINE bool isKinematicObject() const + inline bool isKinematicObject() const { return (m_collisionFlags & CF_KINEMATIC_OBJECT) != 0; } - SIMD_FORCE_INLINE bool isStaticOrKinematicObject() const + inline bool isStaticOrKinematicObject() const { return (m_collisionFlags & (CF_KINEMATIC_OBJECT | CF_STATIC_OBJECT)) != 0 ; } - SIMD_FORCE_INLINE bool hasContactResponse() const { + inline bool hasContactResponse() const { return (m_collisionFlags & CF_NO_CONTACT_RESPONSE)==0; } @@ -146,35 +131,20 @@ public: void setCollisionShape(btCollisionShape* collisionShape) { m_collisionShape = collisionShape; - m_rootCollisionShape = collisionShape; } - SIMD_FORCE_INLINE const btCollisionShape* getCollisionShape() const + const btCollisionShape* getCollisionShape() const { return m_collisionShape; } - SIMD_FORCE_INLINE btCollisionShape* getCollisionShape() + btCollisionShape* getCollisionShape() { return m_collisionShape; } - SIMD_FORCE_INLINE const btCollisionShape* getRootCollisionShape() const - { - return m_rootCollisionShape; - } + - SIMD_FORCE_INLINE btCollisionShape* getRootCollisionShape() - { - return m_rootCollisionShape; - } - - ///Avoid using this internal API call - ///internalSetTemporaryCollisionShape is used to temporary replace the actual collision shape by a child collision shape. - void internalSetTemporaryCollisionShape(btCollisionShape* collisionShape) - { - m_collisionShape = collisionShape; - } int getActivationState() const { return m_activationState1;} @@ -216,9 +186,14 @@ public: } ///reserved for Bullet internal usage - int getInternalType() const + void* getInternalOwner() { - return m_internalType; + return m_internalOwner; + } + + const void* getInternalOwner() const + { + return m_internalOwner; } btTransform& getWorldTransform() @@ -356,7 +331,6 @@ public: m_userObjectPointer = userPointer; } - inline bool checkCollideWith(btCollisionObject* co) { if (m_checkCollideWith) @@ -364,6 +338,9 @@ public: return true; } -}; + + +} +; #endif //COLLISION_OBJECT_H diff --git a/extern/bullet2/src/BulletCollision/CollisionDispatch/btCollisionWorld.cpp b/extern/bullet2/src/BulletCollision/CollisionDispatch/btCollisionWorld.cpp index 7c2ecd6098a..7dc7d8d2f68 100644 --- a/extern/bullet2/src/BulletCollision/CollisionDispatch/btCollisionWorld.cpp +++ b/extern/bullet2/src/BulletCollision/CollisionDispatch/btCollisionWorld.cpp @@ -4,8 +4,8 @@ Copyright (c) 2003-2006 Erwin Coumans http://continuousphysics.com/Bullet/ This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. -Permission is granted to anyone to use this software for any purpose, -including commercial applications, and to alter it and redistribute it freely, +Permission is granted to anyone to use this software for any purpose, +including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. @@ -18,57 +18,59 @@ subject to the following restrictions: #include "BulletCollision/CollisionDispatch/btCollisionObject.h" #include "BulletCollision/CollisionShapes/btCollisionShape.h" #include "BulletCollision/CollisionShapes/btConvexShape.h" -#include "BulletCollision/NarrowPhaseCollision/btGjkEpaPenetrationDepthSolver.h" + #include "BulletCollision/CollisionShapes/btSphereShape.h" //for raycasting -#include "BulletCollision/CollisionShapes/btBvhTriangleMeshShape.h" //for raycasting +#include "BulletCollision/CollisionShapes/btTriangleMeshShape.h" //for raycasting #include "BulletCollision/NarrowPhaseCollision/btRaycastCallback.h" #include "BulletCollision/CollisionShapes/btCompoundShape.h" #include "BulletCollision/NarrowPhaseCollision/btSubSimplexConvexCast.h" -#include "BulletCollision/NarrowPhaseCollision/btGjkConvexCast.h" -#include "BulletCollision/NarrowPhaseCollision/btContinuousConvexCollision.h" - #include "BulletCollision/BroadphaseCollision/btBroadphaseInterface.h" #include "LinearMath/btAabbUtil2.h" #include "LinearMath/btQuickprof.h" #include "LinearMath/btStackAlloc.h" - //When the user doesn't provide dispatcher or broadphase, create basic versions (and delete them in destructor) #include "BulletCollision/CollisionDispatch/btCollisionDispatcher.h" #include "BulletCollision/BroadphaseCollision/btSimpleBroadphase.h" -#include "BulletCollision/CollisionDispatch/btCollisionConfiguration.h" -btCollisionWorld::btCollisionWorld(btDispatcher* dispatcher,btBroadphaseInterface* pairCache, btCollisionConfiguration* collisionConfiguration) +btCollisionWorld::btCollisionWorld(btDispatcher* dispatcher,btOverlappingPairCache* pairCache, int stackSize) :m_dispatcher1(dispatcher), m_broadphasePairCache(pairCache), -m_debugDrawer(0) +m_ownsDispatcher(false), +m_ownsBroadphasePairCache(false) { - m_stackAlloc = collisionConfiguration->getStackAllocator(); + m_stackAlloc = new btStackAlloc(stackSize); m_dispatchInfo.m_stackAllocator = m_stackAlloc; } btCollisionWorld::~btCollisionWorld() { + m_stackAlloc->destroy(); + delete m_stackAlloc; //clean up remaining objects int i; for (i=0;igetBroadphaseHandle(); if (bp) { // // only clear the cached algorithms // - getBroadphase()->getOverlappingPairCache()->cleanProxyFromPairs(bp,m_dispatcher1); - getBroadphase()->destroyProxy(bp,m_dispatcher1); + getBroadphase()->cleanProxyFromPairs(bp); + getBroadphase()->destroyProxy(bp); } } + if (m_ownsDispatcher) + delete m_dispatcher1; + if (m_ownsBroadphasePairCache) + delete m_broadphasePairCache; } @@ -103,100 +105,66 @@ void btCollisionWorld::addCollisionObject(btCollisionObject* collisionObject,sho type, collisionObject, collisionFilterGroup, - collisionFilterMask, - m_dispatcher1,0 + collisionFilterMask )) ; - + } -void btCollisionWorld::updateAabbs() -{ - BT_PROFILE("updateAabbs"); - - btTransform predictedTrans; - for ( int i=0;iisActive()) - { - btPoint3 minAabb,maxAabb; - colObj->getCollisionShape()->getAabb(colObj->getWorldTransform(), minAabb,maxAabb); - btBroadphaseInterface* bp = (btBroadphaseInterface*)m_broadphasePairCache; - - //moving objects should be moderately sized, probably something wrong if not - if ( colObj->isStaticObject() || ((maxAabb-minAabb).length2() < btScalar(1e12))) - { - bp->setAabb(colObj->getBroadphaseHandle(),minAabb,maxAabb, m_dispatcher1); - } else - { - //something went wrong, investigate - //this assert is unwanted in 3D modelers (danger of loosing work) - colObj->setActivationState(DISABLE_SIMULATION); - - static bool reportMe = true; - if (reportMe && m_debugDrawer) - { - reportMe = false; - m_debugDrawer->reportErrorWarning("Overflow in AABB, object removed from simulation"); - m_debugDrawer->reportErrorWarning("If you can reproduce this, please email bugs@continuousphysics.com\n"); - m_debugDrawer->reportErrorWarning("Please include above information, your Platform, version of OS.\n"); - m_debugDrawer->reportErrorWarning("Thanks.\n"); - } - } - } - } - -} void btCollisionWorld::performDiscreteCollisionDetection() { - BT_PROFILE("performDiscreteCollisionDetection"); - btDispatcherInfo& dispatchInfo = getDispatchInfo(); - updateAabbs(); + BEGIN_PROFILE("perform Broadphase Collision Detection"); + + //update aabb (of all moved objects) + + btVector3 aabbMin,aabbMax; + for (int i=0;icalculateOverlappingPairs(m_dispatcher1); + m_collisionObjects[i]->getCollisionShape()->getAabb(m_collisionObjects[i]->getWorldTransform(),aabbMin,aabbMax); + m_broadphasePairCache->setAabb(m_collisionObjects[i]->getBroadphaseHandle(),aabbMin,aabbMax); } + m_broadphasePairCache->refreshOverlappingPairs(); + + + END_PROFILE("perform Broadphase Collision Detection"); + + BEGIN_PROFILE("performDiscreteCollisionDetection"); btDispatcher* dispatcher = getDispatcher(); - { - BT_PROFILE("dispatchAllCollisionPairs"); - if (dispatcher) - dispatcher->dispatchAllCollisionPairs(m_broadphasePairCache->getOverlappingPairCache(),dispatchInfo,m_dispatcher1); - } + if (dispatcher) + dispatcher->dispatchAllCollisionPairs(m_broadphasePairCache,dispatchInfo); + + END_PROFILE("performDiscreteCollisionDetection"); } - void btCollisionWorld::removeCollisionObject(btCollisionObject* collisionObject) { - - + + //bool removeFromBroadphase = false; - + { - + btBroadphaseProxy* bp = collisionObject->getBroadphaseHandle(); if (bp) { // // only clear the cached algorithms // - getBroadphase()->getOverlappingPairCache()->cleanProxyFromPairs(bp,m_dispatcher1); - getBroadphase()->destroyProxy(bp,m_dispatcher1); + getBroadphase()->cleanProxyFromPairs(bp); + getBroadphase()->destroyProxy(bp); collisionObject->setBroadphaseHandle(0); } } @@ -213,457 +181,192 @@ void btCollisionWorld::rayTestSingle(const btTransform& rayFromTrans,const btTra btCollisionObject* collisionObject, const btCollisionShape* collisionShape, const btTransform& colObjWorldTransform, - RayResultCallback& resultCallback) + RayResultCallback& resultCallback, + short int collisionFilterMask, + bool faceNormal) { + btSphereShape pointShape(btScalar(0.0)); pointShape.setMargin(0.f); - const btConvexShape* castShape = &pointShape; - if (collisionShape->isConvex()) - { - btConvexCast::CastResult castResult; - castResult.m_fraction = resultCallback.m_closestHitFraction; - - btConvexShape* convexShape = (btConvexShape*) collisionShape; - btVoronoiSimplexSolver simplexSolver; -#define USE_SUBSIMPLEX_CONVEX_CAST 1 -#ifdef USE_SUBSIMPLEX_CONVEX_CAST - btSubsimplexConvexCast convexCaster(castShape,convexShape,&simplexSolver); -#else - //btGjkConvexCast convexCaster(castShape,convexShape,&simplexSolver); - //btContinuousConvexCollision convexCaster(castShape,convexShape,&simplexSolver,0); -#endif //#USE_SUBSIMPLEX_CONVEX_CAST - - if (convexCaster.calcTimeOfImpact(rayFromTrans,rayToTrans,colObjWorldTransform,colObjWorldTransform,castResult)) - { - //add hit - if (castResult.m_normal.length2() > btScalar(0.0001)) - { - if (castResult.m_fraction < resultCallback.m_closestHitFraction) - { -#ifdef USE_SUBSIMPLEX_CONVEX_CAST - //rotate normal into worldspace - castResult.m_normal = rayFromTrans.getBasis() * castResult.m_normal; -#endif //USE_SUBSIMPLEX_CONVEX_CAST - - castResult.m_normal.normalize(); - btCollisionWorld::LocalRayResult localRayResult - ( - collisionObject, - 0, - castResult.m_normal, - castResult.m_fraction - ); - - bool normalInWorldSpace = true; - resultCallback.addSingleResult(localRayResult, normalInWorldSpace); - - } - } - } - } else { - if (collisionShape->isConcave()) - { - if (collisionShape->getShapeType()==TRIANGLE_MESH_SHAPE_PROXYTYPE) - { - ///optimized version for btBvhTriangleMeshShape - btBvhTriangleMeshShape* triangleMesh = (btBvhTriangleMeshShape*)collisionShape; - btTransform worldTocollisionObject = colObjWorldTransform.inverse(); - btVector3 rayFromLocal = worldTocollisionObject * rayFromTrans.getOrigin(); - btVector3 rayToLocal = worldTocollisionObject * rayToTrans.getOrigin(); - - //ConvexCast::CastResult - struct BridgeTriangleRaycastCallback : public btTriangleRaycastCallback - { - btCollisionWorld::RayResultCallback* m_resultCallback; - btCollisionObject* m_collisionObject; - btTriangleMeshShape* m_triangleMesh; - - BridgeTriangleRaycastCallback( const btVector3& from,const btVector3& to, - btCollisionWorld::RayResultCallback* resultCallback, btCollisionObject* collisionObject,btTriangleMeshShape* triangleMesh): - btTriangleRaycastCallback(from,to), - m_resultCallback(resultCallback), - m_collisionObject(collisionObject), - m_triangleMesh(triangleMesh) - { - } - - - virtual btScalar reportHit(const btVector3& hitNormalLocal, btScalar hitFraction, int partId, int triangleIndex ) - { - btCollisionWorld::LocalShapeInfo shapeInfo; - shapeInfo.m_shapePart = partId; - shapeInfo.m_triangleIndex = triangleIndex; - - btCollisionWorld::LocalRayResult rayResult - (m_collisionObject, - &shapeInfo, - hitNormalLocal, - hitFraction); - - bool normalInWorldSpace = false; - return m_resultCallback->addSingleResult(rayResult,normalInWorldSpace); - } - - }; - - BridgeTriangleRaycastCallback rcb(rayFromLocal,rayToLocal,&resultCallback,collisionObject,triangleMesh); - rcb.m_hitFraction = resultCallback.m_closestHitFraction; - triangleMesh->performRaycast(&rcb,rayFromLocal,rayToLocal); - } else - { - btTriangleMeshShape* triangleMesh = (btTriangleMeshShape*)collisionShape; - - btTransform worldTocollisionObject = colObjWorldTransform.inverse(); - - btVector3 rayFromLocal = worldTocollisionObject * rayFromTrans.getOrigin(); - btVector3 rayToLocal = worldTocollisionObject * rayToTrans.getOrigin(); - - //ConvexCast::CastResult - - struct BridgeTriangleRaycastCallback : public btTriangleRaycastCallback - { - btCollisionWorld::RayResultCallback* m_resultCallback; - btCollisionObject* m_collisionObject; - btTriangleMeshShape* m_triangleMesh; - - BridgeTriangleRaycastCallback( const btVector3& from,const btVector3& to, - btCollisionWorld::RayResultCallback* resultCallback, btCollisionObject* collisionObject,btTriangleMeshShape* triangleMesh): - btTriangleRaycastCallback(from,to), - m_resultCallback(resultCallback), - m_collisionObject(collisionObject), - m_triangleMesh(triangleMesh) - { - } - - - virtual btScalar reportHit(const btVector3& hitNormalLocal, btScalar hitFraction, int partId, int triangleIndex ) - { - btCollisionWorld::LocalShapeInfo shapeInfo; - shapeInfo.m_shapePart = partId; - shapeInfo.m_triangleIndex = triangleIndex; - - btCollisionWorld::LocalRayResult rayResult - (m_collisionObject, - &shapeInfo, - hitNormalLocal, - hitFraction); - - bool normalInWorldSpace = false; - return m_resultCallback->addSingleResult(rayResult,normalInWorldSpace); - - - } - - }; - - - BridgeTriangleRaycastCallback rcb(rayFromLocal,rayToLocal,&resultCallback,collisionObject,triangleMesh); - rcb.m_hitFraction = resultCallback.m_closestHitFraction; - - btVector3 rayAabbMinLocal = rayFromLocal; - rayAabbMinLocal.setMin(rayToLocal); - btVector3 rayAabbMaxLocal = rayFromLocal; - rayAabbMaxLocal.setMax(rayToLocal); - - triangleMesh->processAllTriangles(&rcb,rayAabbMinLocal,rayAabbMaxLocal); - } - } else { - //todo: use AABB tree or other BVH acceleration structure! - if (collisionShape->isCompound()) - { - const btCompoundShape* compoundShape = static_cast(collisionShape); - int i=0; - for (i=0;igetNumChildShapes();i++) - { - btTransform childTrans = compoundShape->getChildTransform(i); - const btCollisionShape* childCollisionShape = compoundShape->getChildShape(i); - btTransform childWorldTrans = colObjWorldTransform * childTrans; - rayTestSingle(rayFromTrans,rayToTrans, - collisionObject, - childCollisionShape, - childWorldTrans, - resultCallback); - - } - } - } - } + objectQuerySingle(&pointShape,rayFromTrans,rayToTrans, + collisionObject, + collisionShape, + colObjWorldTransform, + resultCallback,collisionFilterMask,faceNormal); } -void btCollisionWorld::objectQuerySingle(const btConvexShape* castShape,const btTransform& convexFromTrans,const btTransform& convexToTrans, +void btCollisionWorld::objectQuerySingle(const btConvexShape* castShape,const btTransform& rayFromTrans,const btTransform& rayToTrans, btCollisionObject* collisionObject, const btCollisionShape* collisionShape, const btTransform& colObjWorldTransform, - ConvexResultCallback& resultCallback, btScalar allowedPenetration) + RayResultCallback& resultCallback, + short int collisionFilterMask, + bool faceNormal) { + + if (collisionShape->isConvex()) - { - btConvexCast::CastResult castResult; - castResult.m_allowedPenetration = allowedPenetration; - castResult.m_fraction = btScalar(1.);//?? - - btConvexShape* convexShape = (btConvexShape*) collisionShape; - btVoronoiSimplexSolver simplexSolver; - btGjkEpaPenetrationDepthSolver gjkEpaPenetrationSolver; - - btContinuousConvexCollision convexCaster1(castShape,convexShape,&simplexSolver,&gjkEpaPenetrationSolver); - //btGjkConvexCast convexCaster2(castShape,convexShape,&simplexSolver); - //btSubsimplexConvexCast convexCaster3(castShape,convexShape,&simplexSolver); - - btConvexCast* castPtr = &convexCaster1; - - - - if (castPtr->calcTimeOfImpact(convexFromTrans,convexToTrans,colObjWorldTransform,colObjWorldTransform,castResult)) - { - //add hit - if (castResult.m_normal.length2() > btScalar(0.0001)) { - if (castResult.m_fraction < resultCallback.m_closestHitFraction) + btConvexCast::CastResult castResult; + castResult.m_fraction = btScalar(1.);//?? + + btConvexShape* convexShape = (btConvexShape*) collisionShape; + btVoronoiSimplexSolver simplexSolver; + btSubsimplexConvexCast convexCaster(castShape,convexShape,&simplexSolver); + //GjkConvexCast convexCaster(castShape,convexShape,&simplexSolver); + //ContinuousConvexCollision convexCaster(castShape,convexShape,&simplexSolver,0); + + if (convexCaster.calcTimeOfImpact(rayFromTrans,rayToTrans,colObjWorldTransform,colObjWorldTransform,castResult)) { - castResult.m_normal.normalize(); - btCollisionWorld::LocalConvexResult localConvexResult + //add hit + if (castResult.m_normal.length2() > btScalar(0.0001)) + { + castResult.m_normal.normalize(); + if (castResult.m_fraction < resultCallback.m_closestHitFraction) + { + + btCollisionWorld::LocalRayResult localRayResult ( - collisionObject, + collisionObject, 0, castResult.m_normal, - castResult.m_hitPoint, castResult.m_fraction ); - bool normalInWorldSpace = true; - resultCallback.addSingleResult(localConvexResult, normalInWorldSpace); + resultCallback.AddSingleResult(localRayResult); + } + } } } - } - } else { - if (collisionShape->isConcave()) - { - if (collisionShape->getShapeType()==TRIANGLE_MESH_SHAPE_PROXYTYPE) + else { - btBvhTriangleMeshShape* triangleMesh = (btBvhTriangleMeshShape*)collisionShape; - btTransform worldTocollisionObject = colObjWorldTransform.inverse(); - btVector3 convexFromLocal = worldTocollisionObject * convexFromTrans.getOrigin(); - btVector3 convexToLocal = worldTocollisionObject * convexToTrans.getOrigin(); - // rotation of box in local mesh space = MeshRotation^-1 * ConvexToRotation - btTransform rotationXform = btTransform(worldTocollisionObject.getBasis() * convexToTrans.getBasis()); - - //ConvexCast::CastResult - struct BridgeTriangleConvexcastCallback : public btTriangleConvexcastCallback - { - btCollisionWorld::ConvexResultCallback* m_resultCallback; - btCollisionObject* m_collisionObject; - btTriangleMeshShape* m_triangleMesh; - - BridgeTriangleConvexcastCallback(const btConvexShape* castShape, const btTransform& from,const btTransform& to, - btCollisionWorld::ConvexResultCallback* resultCallback, btCollisionObject* collisionObject,btTriangleMeshShape* triangleMesh, const btTransform& triangleToWorld): - btTriangleConvexcastCallback(castShape, from,to, triangleToWorld, triangleMesh->getMargin()), - m_resultCallback(resultCallback), - m_collisionObject(collisionObject), - m_triangleMesh(triangleMesh) - { - } - - - virtual btScalar reportHit(const btVector3& hitNormalLocal, const btVector3& hitPointLocal, btScalar hitFraction, int partId, int triangleIndex ) + + if (collisionShape->isConcave()) { - btCollisionWorld::LocalShapeInfo shapeInfo; - shapeInfo.m_shapePart = partId; - shapeInfo.m_triangleIndex = triangleIndex; - if (hitFraction <= m_resultCallback->m_closestHitFraction) + + btTriangleMeshShape* triangleMesh = (btTriangleMeshShape*)collisionShape; + + btTransform worldTocollisionObject = colObjWorldTransform.inverse(); + + btVector3 rayFromLocal = worldTocollisionObject * rayFromTrans.getOrigin(); + btVector3 rayToLocal = worldTocollisionObject * rayToTrans.getOrigin(); + + //ConvexCast::CastResult + + struct BridgeTriangleRaycastCallback : public btTriangleRaycastCallback { + btCollisionWorld::RayResultCallback* m_resultCallback; + btCollisionObject* m_collisionObject; + btTriangleMeshShape* m_triangleMesh; - btCollisionWorld::LocalConvexResult convexResult - (m_collisionObject, - &shapeInfo, - hitNormalLocal, - hitPointLocal, - hitFraction); - - bool normalInWorldSpace = true; + BridgeTriangleRaycastCallback( const btVector3& from,const btVector3& to,bool faceNormal, + btCollisionWorld::RayResultCallback* resultCallback, btCollisionObject* collisionObject,btTriangleMeshShape* triangleMesh): + btTriangleRaycastCallback(from,to,faceNormal), + m_resultCallback(resultCallback), + m_collisionObject(collisionObject), + m_triangleMesh(triangleMesh) + { + } - return m_resultCallback->addSingleResult(convexResult,normalInWorldSpace); - } - return hitFraction; - } - - }; - - BridgeTriangleConvexcastCallback tccb(castShape, convexFromTrans,convexToTrans,&resultCallback,collisionObject,triangleMesh, colObjWorldTransform); - tccb.m_hitFraction = resultCallback.m_closestHitFraction; - btVector3 boxMinLocal, boxMaxLocal; - castShape->getAabb(rotationXform, boxMinLocal, boxMaxLocal); - triangleMesh->performConvexcast(&tccb,convexFromLocal,convexToLocal,boxMinLocal, boxMaxLocal); - } else - { - btBvhTriangleMeshShape* triangleMesh = (btBvhTriangleMeshShape*)collisionShape; - btTransform worldTocollisionObject = colObjWorldTransform.inverse(); - btVector3 convexFromLocal = worldTocollisionObject * convexFromTrans.getOrigin(); - btVector3 convexToLocal = worldTocollisionObject * convexToTrans.getOrigin(); - // rotation of box in local mesh space = MeshRotation^-1 * ConvexToRotation - btTransform rotationXform = btTransform(worldTocollisionObject.getBasis() * convexToTrans.getBasis()); - - //ConvexCast::CastResult - struct BridgeTriangleConvexcastCallback : public btTriangleConvexcastCallback - { - btCollisionWorld::ConvexResultCallback* m_resultCallback; - btCollisionObject* m_collisionObject; - btTriangleMeshShape* m_triangleMesh; - - BridgeTriangleConvexcastCallback(const btConvexShape* castShape, const btTransform& from,const btTransform& to, - btCollisionWorld::ConvexResultCallback* resultCallback, btCollisionObject* collisionObject,btTriangleMeshShape* triangleMesh, const btTransform& triangleToWorld): - btTriangleConvexcastCallback(castShape, from,to, triangleToWorld, triangleMesh->getMargin()), - m_resultCallback(resultCallback), - m_collisionObject(collisionObject), - m_triangleMesh(triangleMesh) - { - } + virtual btScalar reportHit(const btVector3& hitNormalLocal, btScalar hitFraction, int partId, int triangleIndex ) + { + btCollisionWorld::LocalShapeInfo shapeInfo; + shapeInfo.m_shapePart = partId; + shapeInfo.m_triangleIndex = triangleIndex; + shapeInfo.m_triangleShape = m_triangleMesh; + + btCollisionWorld::LocalRayResult rayResult + (m_collisionObject, + &shapeInfo, + hitNormalLocal, + hitFraction); + + return m_resultCallback->AddSingleResult(rayResult); + + + } + + }; - virtual btScalar reportHit(const btVector3& hitNormalLocal, const btVector3& hitPointLocal, btScalar hitFraction, int partId, int triangleIndex ) + BridgeTriangleRaycastCallback rcb(rayFromLocal,rayToLocal,faceNormal,&resultCallback,collisionObject,triangleMesh); + rcb.m_hitFraction = resultCallback.m_closestHitFraction; + + btVector3 rayAabbMinLocal = rayFromLocal; + rayAabbMinLocal.setMin(rayToLocal); + btVector3 rayAabbMaxLocal = rayFromLocal; + rayAabbMaxLocal.setMax(rayToLocal); + + triangleMesh->processAllTriangles(&rcb,rayAabbMinLocal,rayAabbMaxLocal); + + } else { - btCollisionWorld::LocalShapeInfo shapeInfo; - shapeInfo.m_shapePart = partId; - shapeInfo.m_triangleIndex = triangleIndex; - if (hitFraction <= m_resultCallback->m_closestHitFraction) + //todo: use AABB tree or other BVH acceleration structure! + if (collisionShape->isCompound()) { + const btCompoundShape* compoundShape = static_cast(collisionShape); + int i=0; + for (i=0;igetNumChildShapes();i++) + { + btTransform childTrans = compoundShape->getChildTransform(i); + const btCollisionShape* childCollisionShape = compoundShape->getChildShape(i); + btTransform childWorldTrans = colObjWorldTransform * childTrans; + objectQuerySingle(castShape, rayFromTrans,rayToTrans, + collisionObject, + childCollisionShape, + childWorldTrans, + resultCallback, collisionFilterMask, faceNormal); - btCollisionWorld::LocalConvexResult convexResult - (m_collisionObject, - &shapeInfo, - hitNormalLocal, - hitPointLocal, - hitFraction); + } - bool normalInWorldSpace = false; - return m_resultCallback->addSingleResult(convexResult,normalInWorldSpace); } - return hitFraction; } - - }; - - BridgeTriangleConvexcastCallback tccb(castShape, convexFromTrans,convexToTrans,&resultCallback,collisionObject,triangleMesh, colObjWorldTransform); - tccb.m_hitFraction = resultCallback.m_closestHitFraction; - btVector3 boxMinLocal, boxMaxLocal; - castShape->getAabb(rotationXform, boxMinLocal, boxMaxLocal); - - btVector3 rayAabbMinLocal = convexFromLocal; - rayAabbMinLocal.setMin(convexToLocal); - btVector3 rayAabbMaxLocal = convexFromLocal; - rayAabbMaxLocal.setMax(convexToLocal); - rayAabbMinLocal += boxMinLocal; - rayAabbMaxLocal += boxMaxLocal; - triangleMesh->processAllTriangles(&tccb,rayAabbMinLocal,rayAabbMaxLocal); } - } else { - //todo: use AABB tree or other BVH acceleration structure! - if (collisionShape->isCompound()) - { - const btCompoundShape* compoundShape = static_cast(collisionShape); - int i=0; - for (i=0;igetNumChildShapes();i++) - { - btTransform childTrans = compoundShape->getChildTransform(i); - const btCollisionShape* childCollisionShape = compoundShape->getChildShape(i); - btTransform childWorldTrans = colObjWorldTransform * childTrans; - objectQuerySingle(castShape, convexFromTrans,convexToTrans, - collisionObject, - childCollisionShape, - childWorldTrans, - resultCallback, allowedPenetration); - } - } - } - } } -void btCollisionWorld::rayTest(const btVector3& rayFromWorld, const btVector3& rayToWorld, RayResultCallback& resultCallback) const +void btCollisionWorld::rayTest(const btVector3& rayFromWorld, const btVector3& rayToWorld, RayResultCallback& resultCallback,short int collisionFilterMask, bool faceNormal) { - + btTransform rayFromTrans,rayToTrans; rayFromTrans.setIdentity(); rayFromTrans.setOrigin(rayFromWorld); rayToTrans.setIdentity(); - + rayToTrans.setOrigin(rayToWorld); /// go over all objects, and if the ray intersects their aabb, do a ray-shape query using convexCaster (CCD) - + int i; for (i=0;igetBroadphaseHandle())) { + if(collisionObject->getBroadphaseHandle()->m_collisionFilterGroup & collisionFilterMask) { //RigidcollisionObject* collisionObject = ctrl->GetRigidcollisionObject(); btVector3 collisionObjectAabbMin,collisionObjectAabbMax; collisionObject->getCollisionShape()->getAabb(collisionObject->getWorldTransform(),collisionObjectAabbMin,collisionObjectAabbMax); - btScalar hitLambda = resultCallback.m_closestHitFraction; + btScalar hitLambda = btScalar(1.); //could use resultCallback.m_closestHitFraction, but needs testing btVector3 hitNormal; if (btRayAabb(rayFromWorld,rayToWorld,collisionObjectAabbMin,collisionObjectAabbMax,hitLambda,hitNormal)) { - rayTestSingle(rayFromTrans,rayToTrans, - collisionObject, - collisionObject->getCollisionShape(), - collisionObject->getWorldTransform(), - resultCallback); - } - } - - } - -} - -void btCollisionWorld::convexSweepTest(const btConvexShape* castShape, const btTransform& convexFromWorld, const btTransform& convexToWorld, ConvexResultCallback& resultCallback) const -{ - btTransform convexFromTrans,convexToTrans; - convexFromTrans = convexFromWorld; - convexToTrans = convexToWorld; - btVector3 castShapeAabbMin, castShapeAabbMax; - /* Compute AABB that encompasses angular movement */ - { - btVector3 linVel, angVel; - btTransformUtil::calculateVelocity (convexFromTrans, convexToTrans, 1.0, linVel, angVel); - btTransform R; - R.setIdentity (); - R.setRotation (convexFromTrans.getRotation()); - castShape->calculateTemporalAabb (R, linVel, angVel, 1.0, castShapeAabbMin, castShapeAabbMax); - } - - /// go over all objects, and if the ray intersects their aabb + cast shape aabb, - // do a ray-shape query using convexCaster (CCD) - int i; - for (i=0;igetBroadphaseHandle())) { - //RigidcollisionObject* collisionObject = ctrl->GetRigidcollisionObject(); - btVector3 collisionObjectAabbMin,collisionObjectAabbMax; - collisionObject->getCollisionShape()->getAabb(collisionObject->getWorldTransform(),collisionObjectAabbMin,collisionObjectAabbMax); - AabbExpand (collisionObjectAabbMin, collisionObjectAabbMax, castShapeAabbMin, castShapeAabbMax); - btScalar hitLambda = btScalar(1.); //could use resultCallback.m_closestHitFraction, but needs testing - btVector3 hitNormal; - if (btRayAabb(convexFromWorld.getOrigin(),convexToWorld.getOrigin(),collisionObjectAabbMin,collisionObjectAabbMax,hitLambda,hitNormal)) - { - objectQuerySingle(castShape, convexFromTrans,convexToTrans, - collisionObject, - collisionObject->getCollisionShape(), - collisionObject->getWorldTransform(), - resultCallback, - getDispatchInfo().m_allowedCcdPenetration); - } + // before testing this object, verify that it is not filtered out + if (resultCallback.NeedRayCast(collisionObject)) + { + rayTestSingle(rayFromTrans,rayToTrans, + collisionObject, + collisionObject->getCollisionShape(), + collisionObject->getWorldTransform(), + resultCallback, + collisionFilterMask, + faceNormal); + } + } } } diff --git a/extern/bullet2/src/BulletCollision/CollisionDispatch/btCollisionWorld.h b/extern/bullet2/src/BulletCollision/CollisionDispatch/btCollisionWorld.h index 7557691a9a9..ed41232ece3 100644 --- a/extern/bullet2/src/BulletCollision/CollisionDispatch/btCollisionWorld.h +++ b/extern/bullet2/src/BulletCollision/CollisionDispatch/btCollisionWorld.h @@ -68,12 +68,12 @@ class btStackAlloc; class btCollisionShape; class btConvexShape; class btBroadphaseInterface; -#include "LinearMath/btVector3.h" -#include "LinearMath/btTransform.h" +#include "../../LinearMath/btVector3.h" +#include "../../LinearMath/btTransform.h" #include "btCollisionObject.h" #include "btCollisionDispatcher.h" //for definition of btCollisionObjectArray -#include "BulletCollision/BroadphaseCollision/btOverlappingPairCache.h" -#include "LinearMath/btAlignedObjectArray.h" +#include "../BroadphaseCollision/btOverlappingPairCache.h" +#include "../../LinearMath/btAlignedObjectArray.h" ///CollisionWorld is interface and container for the collision detection class btCollisionWorld @@ -90,22 +90,18 @@ protected: btStackAlloc* m_stackAlloc; - btBroadphaseInterface* m_broadphasePairCache; - - btIDebugDraw* m_debugDrawer; - + btOverlappingPairCache* m_broadphasePairCache; + bool m_ownsDispatcher; + bool m_ownsBroadphasePairCache; + public: //this constructor doesn't own the dispatcher and paircache/broadphase - btCollisionWorld(btDispatcher* dispatcher,btBroadphaseInterface* broadphasePairCache, btCollisionConfiguration* collisionConfiguration); + btCollisionWorld(btDispatcher* dispatcher,btOverlappingPairCache* pairCache, int stackSize = 2*1024*1024); virtual ~btCollisionWorld(); - void setBroadphase(btBroadphaseInterface* pairCache) - { - m_broadphasePairCache = pairCache; - } btBroadphaseInterface* getBroadphase() { @@ -114,7 +110,7 @@ public: btOverlappingPairCache* getPairCache() { - return m_broadphasePairCache->getOverlappingPairCache(); + return m_broadphasePairCache; } @@ -123,32 +119,14 @@ public: return m_dispatcher1; } - const btDispatcher* getDispatcher() const - { - return m_dispatcher1; - } - - virtual void updateAabbs(); - - virtual void setDebugDrawer(btIDebugDraw* debugDrawer) - { - m_debugDrawer = debugDrawer; - } - - virtual btIDebugDraw* getDebugDrawer() - { - return m_debugDrawer; - } - - ///LocalShapeInfo gives extra information for complex shapes ///Currently, only btTriangleMeshShape is available, so it just contains triangleIndex and subpart struct LocalShapeInfo { int m_shapePart; int m_triangleIndex; - - //const btCollisionShape* m_shapeTemp; + // needed in case of compound shape + const btCollisionShape* m_triangleShape; //const btTransform* m_shapeLocalTransform; }; @@ -175,43 +153,32 @@ public: ///RayResultCallback is used to report new raycast results struct RayResultCallback { - btScalar m_closestHitFraction; - btCollisionObject* m_collisionObject; - short int m_collisionFilterGroup; - short int m_collisionFilterMask; - virtual ~RayResultCallback() { } - bool hasHit() const + btScalar m_closestHitFraction; + bool HasHit() { - return (m_collisionObject != 0); + return (m_closestHitFraction < btScalar(1.)); } RayResultCallback() - :m_closestHitFraction(btScalar(1.)), - m_collisionObject(0), - m_collisionFilterGroup(btBroadphaseProxy::DefaultFilter), - m_collisionFilterMask(btBroadphaseProxy::AllFilter) + :m_closestHitFraction(btScalar(1.)) { } - - virtual bool needsCollision(btBroadphaseProxy* proxy0) const + virtual bool NeedRayCast(btCollisionObject* object) { - bool collides = (proxy0->m_collisionFilterGroup & m_collisionFilterMask) != 0; - collides = collides && (m_collisionFilterGroup & proxy0->m_collisionFilterMask); - return collides; + return true; } - - - virtual btScalar addSingleResult(LocalRayResult& rayResult,bool normalInWorldSpace) = 0; + virtual btScalar AddSingleResult(LocalRayResult& rayResult) = 0; }; struct ClosestRayResultCallback : public RayResultCallback { ClosestRayResultCallback(const btVector3& rayFromWorld,const btVector3& rayToWorld) :m_rayFromWorld(rayFromWorld), - m_rayToWorld(rayToWorld) + m_rayToWorld(rayToWorld), + m_collisionObject(0) { } @@ -220,121 +187,24 @@ public: btVector3 m_hitNormalWorld; btVector3 m_hitPointWorld; - - virtual btScalar addSingleResult(LocalRayResult& rayResult,bool normalInWorldSpace) + btCollisionObject* m_collisionObject; + + virtual btScalar AddSingleResult(LocalRayResult& rayResult) { - //caller already does the filter on the m_closestHitFraction - btAssert(rayResult.m_hitFraction <= m_closestHitFraction); + +//caller already does the filter on the m_closestHitFraction + assert(rayResult.m_hitFraction <= m_closestHitFraction); m_closestHitFraction = rayResult.m_hitFraction; m_collisionObject = rayResult.m_collisionObject; - if (normalInWorldSpace) - { - m_hitNormalWorld = rayResult.m_hitNormalLocal; - } else - { - ///need to transform normal into worldspace - m_hitNormalWorld = m_collisionObject->getWorldTransform().getBasis()*rayResult.m_hitNormalLocal; - } + m_hitNormalWorld = m_collisionObject->getWorldTransform().getBasis()*rayResult.m_hitNormalLocal; m_hitPointWorld.setInterpolate3(m_rayFromWorld,m_rayToWorld,rayResult.m_hitFraction); return rayResult.m_hitFraction; } }; - struct LocalConvexResult - { - LocalConvexResult(btCollisionObject* hitCollisionObject, - LocalShapeInfo* localShapeInfo, - const btVector3& hitNormalLocal, - const btVector3& hitPointLocal, - btScalar hitFraction - ) - :m_hitCollisionObject(hitCollisionObject), - m_localShapeInfo(localShapeInfo), - m_hitNormalLocal(hitNormalLocal), - m_hitPointLocal(hitPointLocal), - m_hitFraction(hitFraction) - { - } - - btCollisionObject* m_hitCollisionObject; - LocalShapeInfo* m_localShapeInfo; - btVector3 m_hitNormalLocal; - btVector3 m_hitPointLocal; - btScalar m_hitFraction; - }; - - ///RayResultCallback is used to report new raycast results - struct ConvexResultCallback - { - btScalar m_closestHitFraction; - short int m_collisionFilterGroup; - short int m_collisionFilterMask; - - ConvexResultCallback() - :m_closestHitFraction(btScalar(1.)), - m_collisionFilterGroup(btBroadphaseProxy::DefaultFilter), - m_collisionFilterMask(btBroadphaseProxy::AllFilter) - { - } - - virtual ~ConvexResultCallback() - { - } - - bool hasHit() const - { - return (m_closestHitFraction < btScalar(1.)); - } - - - - virtual bool needsCollision(btBroadphaseProxy* proxy0) const - { - bool collides = (proxy0->m_collisionFilterGroup & m_collisionFilterMask) != 0; - collides = collides && (m_collisionFilterGroup & proxy0->m_collisionFilterMask); - return collides; - } - - virtual btScalar addSingleResult(LocalConvexResult& convexResult,bool normalInWorldSpace) = 0; - }; - - struct ClosestConvexResultCallback : public ConvexResultCallback - { - ClosestConvexResultCallback(const btVector3& convexFromWorld,const btVector3& convexToWorld) - :m_convexFromWorld(convexFromWorld), - m_convexToWorld(convexToWorld), - m_hitCollisionObject(0) - { - } - - btVector3 m_convexFromWorld;//used to calculate hitPointWorld from hitFraction - btVector3 m_convexToWorld; - - btVector3 m_hitNormalWorld; - btVector3 m_hitPointWorld; - btCollisionObject* m_hitCollisionObject; - - virtual btScalar addSingleResult(LocalConvexResult& convexResult,bool normalInWorldSpace) - { -//caller already does the filter on the m_closestHitFraction - btAssert(convexResult.m_hitFraction <= m_closestHitFraction); - - m_closestHitFraction = convexResult.m_hitFraction; - m_hitCollisionObject = convexResult.m_hitCollisionObject; - if (normalInWorldSpace) - { - m_hitNormalWorld = convexResult.m_hitNormalLocal; - } else - { - ///need to transform normal into worldspace - m_hitNormalWorld = m_hitCollisionObject->getWorldTransform().getBasis()*convexResult.m_hitNormalLocal; - } - m_hitPointWorld = convexResult.m_hitPointLocal; - return convexResult.m_hitFraction; - } - }; + int getNumCollisionObjects() const { @@ -343,12 +213,7 @@ public: /// rayTest performs a raycast on all objects in the btCollisionWorld, and calls the resultCallback /// This allows for several queries: first hit, all hits, any hit, dependent on the value returned by the callback. - void rayTest(const btVector3& rayFromWorld, const btVector3& rayToWorld, RayResultCallback& resultCallback) const; - - // convexTest performs a swept convex cast on all objects in the btCollisionWorld, and calls the resultCallback - // This allows for several queries: first hit, all hits, any hit, dependent on the value return by the callback. - void convexSweepTest (const btConvexShape* castShape, const btTransform& from, const btTransform& to, ConvexResultCallback& resultCallback) const; - + void rayTest(const btVector3& rayFromWorld, const btVector3& rayToWorld, RayResultCallback& resultCallback, short int collisionFilterMask=-1, bool faceNormal=false); /// rayTestSingle performs a raycast call and calls the resultCallback. It is used internally by rayTest. /// In a future implementation, we consider moving the ray test as a virtual method in btCollisionShape. @@ -357,16 +222,20 @@ public: btCollisionObject* collisionObject, const btCollisionShape* collisionShape, const btTransform& colObjWorldTransform, - RayResultCallback& resultCallback); + RayResultCallback& resultCallback, + short int collisionFilterMask=-1, + bool faceNormal=false); /// objectQuerySingle performs a collision detection query and calls the resultCallback. It is used internally by rayTest. static void objectQuerySingle(const btConvexShape* castShape, const btTransform& rayFromTrans,const btTransform& rayToTrans, btCollisionObject* collisionObject, const btCollisionShape* collisionShape, const btTransform& colObjWorldTransform, - ConvexResultCallback& resultCallback, btScalar allowedPenetration); + RayResultCallback& resultCallback, + short int collisionFilterMask=-1, + bool faceNormal=false); - void addCollisionObject(btCollisionObject* collisionObject,short int collisionFilterGroup=btBroadphaseProxy::DefaultFilter,short int collisionFilterMask=btBroadphaseProxy::AllFilter); + void addCollisionObject(btCollisionObject* collisionObject,short int collisionFilterGroup=1,short int collisionFilterMask=1); btCollisionObjectArray& getCollisionObjectArray() { @@ -388,11 +257,6 @@ public: return m_dispatchInfo; } - const btDispatcherInfo& getDispatchInfo() const - { - return m_dispatchInfo; - } - }; diff --git a/extern/bullet2/src/BulletCollision/CollisionDispatch/btCompoundCollisionAlgorithm.cpp b/extern/bullet2/src/BulletCollision/CollisionDispatch/btCompoundCollisionAlgorithm.cpp index a29a6d624e5..92f4c8b28a6 100644 --- a/extern/bullet2/src/BulletCollision/CollisionDispatch/btCompoundCollisionAlgorithm.cpp +++ b/extern/bullet2/src/BulletCollision/CollisionDispatch/btCompoundCollisionAlgorithm.cpp @@ -19,8 +19,7 @@ subject to the following restrictions: btCompoundCollisionAlgorithm::btCompoundCollisionAlgorithm( const btCollisionAlgorithmConstructionInfo& ci,btCollisionObject* body0,btCollisionObject* body1,bool isSwapped) -:btCollisionAlgorithm(ci), -m_isSwapped(isSwapped) +:m_isSwapped(isSwapped) { btCollisionObject* colObj = m_isSwapped? body1 : body0; btCollisionObject* otherObj = m_isSwapped? body0 : body1; @@ -33,11 +32,11 @@ m_isSwapped(isSwapped) m_childCollisionAlgorithms.resize(numChildren); for (i=0;igetCollisionShape(); btCollisionShape* childShape = compoundShape->getChildShape(i); - colObj->internalSetTemporaryCollisionShape( childShape ); - m_childCollisionAlgorithms[i] = ci.m_dispatcher1->findAlgorithm(colObj,otherObj); - colObj->internalSetTemporaryCollisionShape( tmpShape ); + btCollisionShape* orgShape = colObj->getCollisionShape(); + colObj->setCollisionShape( childShape ); + m_childCollisionAlgorithms[i] = ci.m_dispatcher->findAlgorithm(colObj,otherObj); + colObj->setCollisionShape( orgShape ); } } @@ -48,8 +47,7 @@ btCompoundCollisionAlgorithm::~btCompoundCollisionAlgorithm() int i; for (i=0;i~btCollisionAlgorithm(); - m_dispatcher->freeCollisionAlgorithm(m_childCollisionAlgorithms[i]); + delete m_childCollisionAlgorithms[i]; } } @@ -77,21 +75,17 @@ void btCompoundCollisionAlgorithm::processCollision (btCollisionObject* body0,bt //backup btTransform orgTrans = colObj->getWorldTransform(); - btTransform orgInterpolationTrans = colObj->getInterpolationWorldTransform(); + btCollisionShape* orgShape = colObj->getCollisionShape(); const btTransform& childTrans = compoundShape->getChildTransform(i); - btTransform newChildWorldTrans = orgTrans*childTrans ; - colObj->setWorldTransform( newChildWorldTrans); - colObj->setInterpolationWorldTransform(newChildWorldTrans); - + //btTransform newChildWorldTrans = orgTrans*childTrans ; + colObj->setWorldTransform( orgTrans*childTrans ); //the contactpoint is still projected back using the original inverted worldtrans - btCollisionShape* tmpShape = colObj->getCollisionShape(); - colObj->internalSetTemporaryCollisionShape( childShape ); + colObj->setCollisionShape( childShape ); m_childCollisionAlgorithms[i]->processCollision(colObj,otherObj,dispatchInfo,resultOut); //revert back - colObj->internalSetTemporaryCollisionShape( tmpShape); + colObj->setCollisionShape( orgShape); colObj->setWorldTransform( orgTrans ); - colObj->setInterpolationWorldTransform(orgInterpolationTrans); } } @@ -123,20 +117,20 @@ btScalar btCompoundCollisionAlgorithm::calculateTimeOfImpact(btCollisionObject* //backup btTransform orgTrans = colObj->getWorldTransform(); - + btCollisionShape* orgShape = colObj->getCollisionShape(); + const btTransform& childTrans = compoundShape->getChildTransform(i); //btTransform newChildWorldTrans = orgTrans*childTrans ; colObj->setWorldTransform( orgTrans*childTrans ); - btCollisionShape* tmpShape = colObj->getCollisionShape(); - colObj->internalSetTemporaryCollisionShape( childShape ); + colObj->setCollisionShape( childShape ); btScalar frac = m_childCollisionAlgorithms[i]->calculateTimeOfImpact(colObj,otherObj,dispatchInfo,resultOut); if (fracinternalSetTemporaryCollisionShape( tmpShape); + colObj->setCollisionShape( orgShape); colObj->setWorldTransform( orgTrans); } return hitFraction; diff --git a/extern/bullet2/src/BulletCollision/CollisionDispatch/btCompoundCollisionAlgorithm.h b/extern/bullet2/src/BulletCollision/CollisionDispatch/btCompoundCollisionAlgorithm.h index 1682c6761cd..7091b233b46 100644 --- a/extern/bullet2/src/BulletCollision/CollisionDispatch/btCompoundCollisionAlgorithm.h +++ b/extern/bullet2/src/BulletCollision/CollisionDispatch/btCompoundCollisionAlgorithm.h @@ -16,16 +16,15 @@ subject to the following restrictions: #ifndef COMPOUND_COLLISION_ALGORITHM_H #define COMPOUND_COLLISION_ALGORITHM_H -#include "BulletCollision/BroadphaseCollision/btCollisionAlgorithm.h" -#include "BulletCollision/BroadphaseCollision/btDispatcher.h" -#include "BulletCollision/BroadphaseCollision/btBroadphaseInterface.h" +#include "../BroadphaseCollision/btCollisionAlgorithm.h" +#include "../BroadphaseCollision/btDispatcher.h" +#include "../BroadphaseCollision/btBroadphaseInterface.h" -#include "BulletCollision/NarrowPhaseCollision/btPersistentManifold.h" +#include "../NarrowPhaseCollision/btPersistentManifold.h" class btDispatcher; -#include "BulletCollision/BroadphaseCollision/btBroadphaseProxy.h" +#include "../BroadphaseCollision/btBroadphaseProxy.h" #include "btCollisionCreateFunc.h" -#include "LinearMath/btAlignedObjectArray.h" -class btDispatcher; +#include "../../LinearMath/btAlignedObjectArray.h" /// btCompoundCollisionAlgorithm supports collision between CompoundCollisionShapes and other collision shapes /// Place holder, not fully implemented yet @@ -44,21 +43,11 @@ public: btScalar calculateTimeOfImpact(btCollisionObject* body0,btCollisionObject* body1,const btDispatcherInfo& dispatchInfo,btManifoldResult* resultOut); - virtual void getAllContactManifolds(btManifoldArray& manifoldArray) - { - int i; - for (i=0;igetAllContactManifolds(manifoldArray); - } - } - struct CreateFunc :public btCollisionAlgorithmCreateFunc { virtual btCollisionAlgorithm* CreateCollisionAlgorithm(btCollisionAlgorithmConstructionInfo& ci, btCollisionObject* body0,btCollisionObject* body1) { - void* mem = ci.m_dispatcher1->allocateCollisionAlgorithm(sizeof(btCompoundCollisionAlgorithm)); - return new(mem) btCompoundCollisionAlgorithm(ci,body0,body1,false); + return new btCompoundCollisionAlgorithm(ci,body0,body1,false); } }; @@ -66,8 +55,7 @@ public: { virtual btCollisionAlgorithm* CreateCollisionAlgorithm(btCollisionAlgorithmConstructionInfo& ci, btCollisionObject* body0,btCollisionObject* body1) { - void* mem = ci.m_dispatcher1->allocateCollisionAlgorithm(sizeof(btCompoundCollisionAlgorithm)); - return new(mem) btCompoundCollisionAlgorithm(ci,body0,body1,true); + return new btCompoundCollisionAlgorithm(ci,body0,body1,true); } }; diff --git a/extern/bullet2/src/BulletCollision/CollisionDispatch/btConvexConcaveCollisionAlgorithm.cpp b/extern/bullet2/src/BulletCollision/CollisionDispatch/btConvexConcaveCollisionAlgorithm.cpp index 6d28904cb03..24ceacfd40d 100644 --- a/extern/bullet2/src/BulletCollision/CollisionDispatch/btConvexConcaveCollisionAlgorithm.cpp +++ b/extern/bullet2/src/BulletCollision/CollisionDispatch/btConvexConcaveCollisionAlgorithm.cpp @@ -29,7 +29,7 @@ subject to the following restrictions: btConvexConcaveCollisionAlgorithm::btConvexConcaveCollisionAlgorithm( const btCollisionAlgorithmConstructionInfo& ci, btCollisionObject* body0,btCollisionObject* body1,bool isSwapped) : btCollisionAlgorithm(ci), m_isSwapped(isSwapped), -m_btConvexTriangleCallback(ci.m_dispatcher1,body0,body1,isSwapped) +m_btConvexTriangleCallback(ci.m_dispatcher,body0,body1,isSwapped) { } @@ -37,13 +37,6 @@ btConvexConcaveCollisionAlgorithm::~btConvexConcaveCollisionAlgorithm() { } -void btConvexConcaveCollisionAlgorithm::getAllContactManifolds(btManifoldArray& manifoldArray) -{ - if (m_btConvexTriangleCallback.m_manifoldPtr) - { - manifoldArray.push_back(m_btConvexTriangleCallback.m_manifoldPtr); - } -} btConvexTriangleCallback::btConvexTriangleCallback(btDispatcher* dispatcher,btCollisionObject* body0,btCollisionObject* body1,bool isSwapped): @@ -86,7 +79,7 @@ void btConvexTriangleCallback::processTriangle(btVector3* triangle,int partId, i //aabb filter is already applied! btCollisionAlgorithmConstructionInfo ci; - ci.m_dispatcher1 = m_dispatcher; + ci.m_dispatcher = m_dispatcher; btCollisionObject* ob = static_cast(m_triBody); @@ -116,11 +109,13 @@ void btConvexTriangleCallback::processTriangle(btVector3* triangle,int partId, i { btTriangleShape tm(triangle[0],triangle[1],triangle[2]); tm.setMargin(m_collisionMarginTriangle); + btCollisionShape* tmpShape = ob->getCollisionShape(); - ob->internalSetTemporaryCollisionShape( &tm ); + ob->setCollisionShape( &tm ); - btCollisionAlgorithm* colAlgo = ci.m_dispatcher1->findAlgorithm(m_convexBody,m_triBody,m_manifoldPtr); + + btCollisionAlgorithm* colAlgo = ci.m_dispatcher->findAlgorithm(m_convexBody,m_triBody,m_manifoldPtr); ///this should use the btDispatcher, so the actual registered algorithm is used // btConvexConvexAlgorithm cvxcvxalgo(m_manifoldPtr,ci,m_convexBody,m_triBody); @@ -128,11 +123,12 @@ void btConvexTriangleCallback::processTriangle(btVector3* triangle,int partId, i // cvxcvxalgo.setShapeIdentifiers(-1,-1,partId,triangleIndex); // cvxcvxalgo.processCollision(m_convexBody,m_triBody,*m_dispatchInfoPtr,m_resultOut); colAlgo->processCollision(m_convexBody,m_triBody,*m_dispatchInfoPtr,m_resultOut); - colAlgo->~btCollisionAlgorithm(); - ci.m_dispatcher1->freeCollisionAlgorithm(colAlgo); - ob->internalSetTemporaryCollisionShape( tmpShape); + delete colAlgo; + ob->setCollisionShape( tmpShape ); + } + } @@ -192,10 +188,9 @@ void btConvexConcaveCollisionAlgorithm::processCollision (btCollisionObject* bod concaveShape->processAllTriangles( &m_btConvexTriangleCallback,m_btConvexTriangleCallback.getAabbMin(),m_btConvexTriangleCallback.getAabbMax()); - resultOut->refreshContactPoints(); } - + } } diff --git a/extern/bullet2/src/BulletCollision/CollisionDispatch/btConvexConcaveCollisionAlgorithm.h b/extern/bullet2/src/BulletCollision/CollisionDispatch/btConvexConcaveCollisionAlgorithm.h index 34b9a107be9..4915b6c20c8 100644 --- a/extern/bullet2/src/BulletCollision/CollisionDispatch/btConvexConcaveCollisionAlgorithm.h +++ b/extern/bullet2/src/BulletCollision/CollisionDispatch/btConvexConcaveCollisionAlgorithm.h @@ -16,13 +16,13 @@ subject to the following restrictions: #ifndef CONVEX_CONCAVE_COLLISION_ALGORITHM_H #define CONVEX_CONCAVE_COLLISION_ALGORITHM_H -#include "BulletCollision/BroadphaseCollision/btCollisionAlgorithm.h" -#include "BulletCollision/BroadphaseCollision/btDispatcher.h" -#include "BulletCollision/BroadphaseCollision/btBroadphaseInterface.h" -#include "BulletCollision/CollisionShapes/btTriangleCallback.h" -#include "BulletCollision/NarrowPhaseCollision/btPersistentManifold.h" +#include "../BroadphaseCollision/btCollisionAlgorithm.h" +#include "../BroadphaseCollision/btDispatcher.h" +#include "../BroadphaseCollision/btBroadphaseInterface.h" +#include "../CollisionShapes/btTriangleCallback.h" +#include "../NarrowPhaseCollision/btPersistentManifold.h" class btDispatcher; -#include "BulletCollision/BroadphaseCollision/btBroadphaseProxy.h" +#include "../BroadphaseCollision/btBroadphaseProxy.h" #include "btCollisionCreateFunc.h" ///For each triangle in the concave mesh that overlaps with the AABB of a convex (m_convexProxy), processTriangle is called. @@ -55,11 +55,11 @@ int m_triangleCount; void clearCache(); - SIMD_FORCE_INLINE const btVector3& getAabbMin() const + inline const btVector3& getAabbMin() const { return m_aabbMin; } - SIMD_FORCE_INLINE const btVector3& getAabbMax() const + inline const btVector3& getAabbMax() const { return m_aabbMax; } @@ -88,16 +88,13 @@ public: btScalar calculateTimeOfImpact(btCollisionObject* body0,btCollisionObject* body1,const btDispatcherInfo& dispatchInfo,btManifoldResult* resultOut); - virtual void getAllContactManifolds(btManifoldArray& manifoldArray); - void clearCache(); struct CreateFunc :public btCollisionAlgorithmCreateFunc { virtual btCollisionAlgorithm* CreateCollisionAlgorithm(btCollisionAlgorithmConstructionInfo& ci, btCollisionObject* body0,btCollisionObject* body1) { - void* mem = ci.m_dispatcher1->allocateCollisionAlgorithm(sizeof(btConvexConcaveCollisionAlgorithm)); - return new(mem) btConvexConcaveCollisionAlgorithm(ci,body0,body1,false); + return new btConvexConcaveCollisionAlgorithm(ci,body0,body1,false); } }; @@ -105,8 +102,7 @@ public: { virtual btCollisionAlgorithm* CreateCollisionAlgorithm(btCollisionAlgorithmConstructionInfo& ci, btCollisionObject* body0,btCollisionObject* body1) { - void* mem = ci.m_dispatcher1->allocateCollisionAlgorithm(sizeof(btConvexConcaveCollisionAlgorithm)); - return new(mem) btConvexConcaveCollisionAlgorithm(ci,body0,body1,true); + return new btConvexConcaveCollisionAlgorithm(ci,body0,body1,true); } }; diff --git a/extern/bullet2/src/BulletCollision/CollisionDispatch/btConvexConvexAlgorithm.cpp b/extern/bullet2/src/BulletCollision/CollisionDispatch/btConvexConvexAlgorithm.cpp index cb830f889be..9105fe20b49 100644 --- a/extern/bullet2/src/BulletCollision/CollisionDispatch/btConvexConvexAlgorithm.cpp +++ b/extern/bullet2/src/BulletCollision/CollisionDispatch/btConvexConvexAlgorithm.cpp @@ -15,7 +15,7 @@ subject to the following restrictions: #include "btConvexConvexAlgorithm.h" -//#include +#include #include "BulletCollision/NarrowPhaseCollision/btDiscreteCollisionDetectorInterface.h" #include "BulletCollision/BroadphaseCollision/btBroadphaseInterface.h" #include "BulletCollision/CollisionDispatch/btCollisionObject.h" @@ -33,6 +33,7 @@ subject to the following restrictions: +#include "BulletCollision/CollisionShapes/btMinkowskiSumShape.h" #include "BulletCollision/NarrowPhaseCollision/btVoronoiSimplexSolver.h" #include "BulletCollision/CollisionShapes/btSphereShape.h" @@ -47,16 +48,26 @@ subject to the following restrictions: - +btConvexConvexAlgorithm::CreateFunc::CreateFunc() +{ + m_ownsSolvers = true; + m_simplexSolver = new btVoronoiSimplexSolver(); + m_pdSolver = new btGjkEpaPenetrationDepthSolver; +} btConvexConvexAlgorithm::CreateFunc::CreateFunc(btSimplexSolverInterface* simplexSolver, btConvexPenetrationDepthSolver* pdSolver) { + m_ownsSolvers = false; m_simplexSolver = simplexSolver; m_pdSolver = pdSolver; } btConvexConvexAlgorithm::CreateFunc::~CreateFunc() { + if (m_ownsSolvers){ + delete m_simplexSolver; + delete m_pdSolver; + } } btConvexConvexAlgorithm::btConvexConvexAlgorithm(btPersistentManifold* mf,const btCollisionAlgorithmConstructionInfo& ci,btCollisionObject* body0,btCollisionObject* body1,btSimplexSolverInterface* simplexSolver, btConvexPenetrationDepthSolver* pdSolver) @@ -141,11 +152,6 @@ void btConvexConvexAlgorithm ::processCollision (btCollisionObject* body0,btColl m_gjkPairDetector.getClosestPoints(input,*resultOut,dispatchInfo.m_debugDraw); #endif - if (m_ownManifold) - { - resultOut->refreshContactPoints(); - } - } diff --git a/extern/bullet2/src/BulletCollision/CollisionDispatch/btConvexConvexAlgorithm.h b/extern/bullet2/src/BulletCollision/CollisionDispatch/btConvexConvexAlgorithm.h index a0030e6793d..cbea9a92b75 100644 --- a/extern/bullet2/src/BulletCollision/CollisionDispatch/btConvexConvexAlgorithm.h +++ b/extern/bullet2/src/BulletCollision/CollisionDispatch/btConvexConvexAlgorithm.h @@ -16,13 +16,12 @@ subject to the following restrictions: #ifndef CONVEX_CONVEX_ALGORITHM_H #define CONVEX_CONVEX_ALGORITHM_H -#include "BulletCollision/BroadphaseCollision/btCollisionAlgorithm.h" -#include "BulletCollision/NarrowPhaseCollision/btGjkPairDetector.h" -#include "BulletCollision/NarrowPhaseCollision/btPersistentManifold.h" -#include "BulletCollision/BroadphaseCollision/btBroadphaseProxy.h" -#include "BulletCollision/NarrowPhaseCollision/btVoronoiSimplexSolver.h" +#include "../BroadphaseCollision/btCollisionAlgorithm.h" +#include "../NarrowPhaseCollision/btGjkPairDetector.h" +#include "../NarrowPhaseCollision/btPersistentManifold.h" +#include "../BroadphaseCollision/btBroadphaseProxy.h" +#include "../NarrowPhaseCollision/btVoronoiSimplexSolver.h" #include "btCollisionCreateFunc.h" -#include "btCollisionDispatcher.h" class btConvexPenetrationDepthSolver; @@ -47,14 +46,6 @@ public: virtual btScalar calculateTimeOfImpact(btCollisionObject* body0,btCollisionObject* body1,const btDispatcherInfo& dispatchInfo,btManifoldResult* resultOut); - virtual void getAllContactManifolds(btManifoldArray& manifoldArray) - { - ///should we use m_ownManifold to avoid adding duplicates? - if (m_manifoldPtr && m_ownManifold) - manifoldArray.push_back(m_manifoldPtr); - } - - void setLowLevelOfDetail(bool useLowLevel); @@ -67,15 +58,15 @@ public: { btConvexPenetrationDepthSolver* m_pdSolver; btSimplexSolverInterface* m_simplexSolver; + bool m_ownsSolvers; CreateFunc(btSimplexSolverInterface* simplexSolver, btConvexPenetrationDepthSolver* pdSolver); - + CreateFunc(); virtual ~CreateFunc(); virtual btCollisionAlgorithm* CreateCollisionAlgorithm(btCollisionAlgorithmConstructionInfo& ci, btCollisionObject* body0,btCollisionObject* body1) { - void* mem = ci.m_dispatcher1->allocateCollisionAlgorithm(sizeof(btConvexConvexAlgorithm)); - return new(mem) btConvexConvexAlgorithm(ci.m_manifold,ci,body0,body1,m_simplexSolver,m_pdSolver); + return new btConvexConvexAlgorithm(ci.m_manifold,ci,body0,body1,m_simplexSolver,m_pdSolver); } }; diff --git a/extern/bullet2/src/BulletCollision/CollisionDispatch/btConvexPlaneCollisionAlgorithm.cpp b/extern/bullet2/src/BulletCollision/CollisionDispatch/btConvexPlaneCollisionAlgorithm.cpp deleted file mode 100644 index 391cf6c7bc4..00000000000 --- a/extern/bullet2/src/BulletCollision/CollisionDispatch/btConvexPlaneCollisionAlgorithm.cpp +++ /dev/null @@ -1,108 +0,0 @@ -/* -Bullet Continuous Collision Detection and Physics Library -Copyright (c) 2003-2006 Erwin Coumans http://continuousphysics.com/Bullet/ - -This software is provided 'as-is', without any express or implied warranty. -In no event will the authors be held liable for any damages arising from the use of this software. -Permission is granted to anyone to use this software for any purpose, -including commercial applications, and to alter it and redistribute it freely, -subject to the following restrictions: - -1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. -2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. -3. This notice may not be removed or altered from any source distribution. -*/ - -#include "btConvexPlaneCollisionAlgorithm.h" - -#include "BulletCollision/CollisionDispatch/btCollisionDispatcher.h" -#include "BulletCollision/CollisionDispatch/btCollisionObject.h" -#include "BulletCollision/CollisionShapes/btConvexShape.h" -#include "BulletCollision/CollisionShapes/btStaticPlaneShape.h" - -//#include - -btConvexPlaneCollisionAlgorithm::btConvexPlaneCollisionAlgorithm(btPersistentManifold* mf,const btCollisionAlgorithmConstructionInfo& ci,btCollisionObject* col0,btCollisionObject* col1, bool isSwapped) -: btCollisionAlgorithm(ci), -m_ownManifold(false), -m_manifoldPtr(mf), -m_isSwapped(isSwapped) -{ - btCollisionObject* convexObj = m_isSwapped? col1 : col0; - btCollisionObject* planeObj = m_isSwapped? col0 : col1; - - if (!m_manifoldPtr && m_dispatcher->needsCollision(convexObj,planeObj)) - { - m_manifoldPtr = m_dispatcher->getNewManifold(convexObj,planeObj); - m_ownManifold = true; - } -} - - -btConvexPlaneCollisionAlgorithm::~btConvexPlaneCollisionAlgorithm() -{ - if (m_ownManifold) - { - if (m_manifoldPtr) - m_dispatcher->releaseManifold(m_manifoldPtr); - } -} - - - -void btConvexPlaneCollisionAlgorithm::processCollision (btCollisionObject* body0,btCollisionObject* body1,const btDispatcherInfo& dispatchInfo,btManifoldResult* resultOut) -{ - (void)dispatchInfo; - (void)resultOut; - if (!m_manifoldPtr) - return; - - btCollisionObject* convexObj = m_isSwapped? body1 : body0; - btCollisionObject* planeObj = m_isSwapped? body0: body1; - - btConvexShape* convexShape = (btConvexShape*) convexObj->getCollisionShape(); - btStaticPlaneShape* planeShape = (btStaticPlaneShape*) planeObj->getCollisionShape(); - - bool hasCollision = false; - const btVector3& planeNormal = planeShape->getPlaneNormal(); - const btScalar& planeConstant = planeShape->getPlaneConstant(); - btTransform planeInConvex; - planeInConvex= convexObj->getWorldTransform().inverse() * planeObj->getWorldTransform(); - btTransform convexInPlaneTrans; - convexInPlaneTrans= planeObj->getWorldTransform().inverse() * convexObj->getWorldTransform(); - - btVector3 vtx = convexShape->localGetSupportingVertex(planeInConvex.getBasis()*-planeNormal); - btVector3 vtxInPlane = convexInPlaneTrans(vtx); - btScalar distance = (planeNormal.dot(vtxInPlane) - planeConstant); - - btVector3 vtxInPlaneProjected = vtxInPlane - distance*planeNormal; - btVector3 vtxInPlaneWorld = planeObj->getWorldTransform() * vtxInPlaneProjected; - - hasCollision = distance < m_manifoldPtr->getContactBreakingThreshold(); - resultOut->setPersistentManifold(m_manifoldPtr); - if (hasCollision) - { - /// report a contact. internally this will be kept persistent, and contact reduction is done - btVector3 normalOnSurfaceB = planeObj->getWorldTransform().getBasis() * planeNormal; - btVector3 pOnB = vtxInPlaneWorld; - resultOut->addContactPoint(normalOnSurfaceB,pOnB,distance); - } - if (m_ownManifold) - { - if (m_manifoldPtr->getNumContacts()) - { - resultOut->refreshContactPoints(); - } - } -} - -btScalar btConvexPlaneCollisionAlgorithm::calculateTimeOfImpact(btCollisionObject* col0,btCollisionObject* col1,const btDispatcherInfo& dispatchInfo,btManifoldResult* resultOut) -{ - (void)resultOut; - (void)dispatchInfo; - (void)col0; - (void)col1; - - //not yet - return btScalar(1.); -} diff --git a/extern/bullet2/src/BulletCollision/CollisionDispatch/btConvexPlaneCollisionAlgorithm.h b/extern/bullet2/src/BulletCollision/CollisionDispatch/btConvexPlaneCollisionAlgorithm.h deleted file mode 100644 index 7b258554171..00000000000 --- a/extern/bullet2/src/BulletCollision/CollisionDispatch/btConvexPlaneCollisionAlgorithm.h +++ /dev/null @@ -1,71 +0,0 @@ -/* -Bullet Continuous Collision Detection and Physics Library -Copyright (c) 2003-2006 Erwin Coumans http://continuousphysics.com/Bullet/ - -This software is provided 'as-is', without any express or implied warranty. -In no event will the authors be held liable for any damages arising from the use of this software. -Permission is granted to anyone to use this software for any purpose, -including commercial applications, and to alter it and redistribute it freely, -subject to the following restrictions: - -1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. -2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. -3. This notice may not be removed or altered from any source distribution. -*/ - -#ifndef CONVEX_PLANE_COLLISION_ALGORITHM_H -#define CONVEX_PLANE_COLLISION_ALGORITHM_H - -#include "BulletCollision/BroadphaseCollision/btCollisionAlgorithm.h" -#include "BulletCollision/BroadphaseCollision/btBroadphaseProxy.h" -#include "BulletCollision/CollisionDispatch/btCollisionCreateFunc.h" -class btPersistentManifold; -#include "btCollisionDispatcher.h" - -#include "LinearMath/btVector3.h" - -/// btSphereBoxCollisionAlgorithm provides sphere-box collision detection. -/// Other features are frame-coherency (persistent data) and collision response. -class btConvexPlaneCollisionAlgorithm : public btCollisionAlgorithm -{ - bool m_ownManifold; - btPersistentManifold* m_manifoldPtr; - bool m_isSwapped; - -public: - - btConvexPlaneCollisionAlgorithm(btPersistentManifold* mf,const btCollisionAlgorithmConstructionInfo& ci,btCollisionObject* col0,btCollisionObject* col1, bool isSwapped); - - virtual ~btConvexPlaneCollisionAlgorithm(); - - virtual void processCollision (btCollisionObject* body0,btCollisionObject* body1,const btDispatcherInfo& dispatchInfo,btManifoldResult* resultOut); - - virtual btScalar calculateTimeOfImpact(btCollisionObject* body0,btCollisionObject* body1,const btDispatcherInfo& dispatchInfo,btManifoldResult* resultOut); - - virtual void getAllContactManifolds(btManifoldArray& manifoldArray) - { - if (m_manifoldPtr && m_ownManifold) - { - manifoldArray.push_back(m_manifoldPtr); - } - } - - struct CreateFunc :public btCollisionAlgorithmCreateFunc - { - virtual btCollisionAlgorithm* CreateCollisionAlgorithm(btCollisionAlgorithmConstructionInfo& ci, btCollisionObject* body0,btCollisionObject* body1) - { - void* mem = ci.m_dispatcher1->allocateCollisionAlgorithm(sizeof(btConvexPlaneCollisionAlgorithm)); - if (!m_swapped) - { - return new(mem) btConvexPlaneCollisionAlgorithm(0,ci,body0,body1,false); - } else - { - return new(mem) btConvexPlaneCollisionAlgorithm(0,ci,body0,body1,true); - } - } - }; - -}; - -#endif //CONVEX_PLANE_COLLISION_ALGORITHM_H - diff --git a/extern/bullet2/src/BulletCollision/CollisionDispatch/btDefaultCollisionConfiguration.cpp b/extern/bullet2/src/BulletCollision/CollisionDispatch/btDefaultCollisionConfiguration.cpp deleted file mode 100644 index 3f94f4d4eac..00000000000 --- a/extern/bullet2/src/BulletCollision/CollisionDispatch/btDefaultCollisionConfiguration.cpp +++ /dev/null @@ -1,281 +0,0 @@ -/* -Bullet Continuous Collision Detection and Physics Library -Copyright (c) 2003-2006 Erwin Coumans http://continuousphysics.com/Bullet/ - -This software is provided 'as-is', without any express or implied warranty. -In no event will the authors be held liable for any damages arising from the use of this software. -Permission is granted to anyone to use this software for any purpose, -including commercial applications, and to alter it and redistribute it freely, -subject to the following restrictions: - -1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. -2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. -3. This notice may not be removed or altered from any source distribution. -*/ - -#include "btDefaultCollisionConfiguration.h" - -#include "BulletCollision/CollisionDispatch/btConvexConvexAlgorithm.h" -#include "BulletCollision/CollisionDispatch/btEmptyCollisionAlgorithm.h" -#include "BulletCollision/CollisionDispatch/btConvexConcaveCollisionAlgorithm.h" -#include "BulletCollision/CollisionDispatch/btCompoundCollisionAlgorithm.h" -#include "BulletCollision/CollisionDispatch/btConvexPlaneCollisionAlgorithm.h" -#include "BulletCollision/CollisionDispatch/btBoxBoxCollisionAlgorithm.h" -#include "BulletCollision/CollisionDispatch/btSphereSphereCollisionAlgorithm.h" -#include "BulletCollision/CollisionDispatch/btSphereBoxCollisionAlgorithm.h" -#include "BulletCollision/CollisionDispatch/btSphereTriangleCollisionAlgorithm.h" -#include "BulletCollision/NarrowPhaseCollision/btGjkEpaPenetrationDepthSolver.h" -#include "BulletCollision/NarrowPhaseCollision/btMinkowskiPenetrationDepthSolver.h" -#include "BulletCollision/NarrowPhaseCollision/btVoronoiSimplexSolver.h" - - - -#include "LinearMath/btStackAlloc.h" -#include "LinearMath/btPoolAllocator.h" - - - - - -btDefaultCollisionConfiguration::btDefaultCollisionConfiguration(const btDefaultCollisionConstructionInfo& constructionInfo) -//btDefaultCollisionConfiguration::btDefaultCollisionConfiguration(btStackAlloc* stackAlloc,btPoolAllocator* persistentManifoldPool,btPoolAllocator* collisionAlgorithmPool) -{ - - void* mem = btAlignedAlloc(sizeof(btVoronoiSimplexSolver),16); - m_simplexSolver = new (mem)btVoronoiSimplexSolver(); - -#define USE_EPA 1 -#ifdef USE_EPA - mem = btAlignedAlloc(sizeof(btGjkEpaPenetrationDepthSolver),16); - m_pdSolver = new (mem)btGjkEpaPenetrationDepthSolver; -#else - mem = btAlignedAlloc(sizeof(btMinkowskiPenetrationDepthSolver),16); - m_pdSolver = new (mem)btMinkowskiPenetrationDepthSolver; -#endif//USE_EPA - - - //default CreationFunctions, filling the m_doubleDispatch table - mem = btAlignedAlloc(sizeof(btConvexConvexAlgorithm::CreateFunc),16); - m_convexConvexCreateFunc = new(mem) btConvexConvexAlgorithm::CreateFunc(m_simplexSolver,m_pdSolver); - mem = btAlignedAlloc(sizeof(btConvexConcaveCollisionAlgorithm::CreateFunc),16); - m_convexConcaveCreateFunc = new (mem)btConvexConcaveCollisionAlgorithm::CreateFunc; - mem = btAlignedAlloc(sizeof(btConvexConcaveCollisionAlgorithm::CreateFunc),16); - m_swappedConvexConcaveCreateFunc = new (mem)btConvexConcaveCollisionAlgorithm::SwappedCreateFunc; - mem = btAlignedAlloc(sizeof(btCompoundCollisionAlgorithm::CreateFunc),16); - m_compoundCreateFunc = new (mem)btCompoundCollisionAlgorithm::CreateFunc; - mem = btAlignedAlloc(sizeof(btCompoundCollisionAlgorithm::SwappedCreateFunc),16); - m_swappedCompoundCreateFunc = new (mem)btCompoundCollisionAlgorithm::SwappedCreateFunc; - mem = btAlignedAlloc(sizeof(btEmptyAlgorithm::CreateFunc),16); - m_emptyCreateFunc = new(mem) btEmptyAlgorithm::CreateFunc; - - mem = btAlignedAlloc(sizeof(btSphereSphereCollisionAlgorithm::CreateFunc),16); - m_sphereSphereCF = new(mem) btSphereSphereCollisionAlgorithm::CreateFunc; - mem = btAlignedAlloc(sizeof(btSphereBoxCollisionAlgorithm::CreateFunc),16); - m_sphereBoxCF = new(mem) btSphereBoxCollisionAlgorithm::CreateFunc; - mem = btAlignedAlloc(sizeof(btSphereBoxCollisionAlgorithm::CreateFunc),16); - m_boxSphereCF = new (mem)btSphereBoxCollisionAlgorithm::CreateFunc; - m_boxSphereCF->m_swapped = true; - mem = btAlignedAlloc(sizeof(btSphereTriangleCollisionAlgorithm::CreateFunc),16); - m_sphereTriangleCF = new (mem)btSphereTriangleCollisionAlgorithm::CreateFunc; - mem = btAlignedAlloc(sizeof(btSphereTriangleCollisionAlgorithm::CreateFunc),16); - m_triangleSphereCF = new (mem)btSphereTriangleCollisionAlgorithm::CreateFunc; - m_triangleSphereCF->m_swapped = true; - - mem = btAlignedAlloc(sizeof(btBoxBoxCollisionAlgorithm::CreateFunc),16); - m_boxBoxCF = new(mem)btBoxBoxCollisionAlgorithm::CreateFunc; - - //convex versus plane - mem = btAlignedAlloc (sizeof(btConvexPlaneCollisionAlgorithm::CreateFunc),16); - m_convexPlaneCF = new (mem) btConvexPlaneCollisionAlgorithm::CreateFunc; - mem = btAlignedAlloc (sizeof(btConvexPlaneCollisionAlgorithm::CreateFunc),16); - m_planeConvexCF = new (mem) btConvexPlaneCollisionAlgorithm::CreateFunc; - m_planeConvexCF->m_swapped = true; - - ///calculate maximum element size, big enough to fit any collision algorithm in the memory pool - int maxSize = sizeof(btConvexConvexAlgorithm); - int maxSize2 = sizeof(btConvexConcaveCollisionAlgorithm); - int maxSize3 = sizeof(btCompoundCollisionAlgorithm); - int maxSize4 = sizeof(btEmptyAlgorithm); - - int collisionAlgorithmMaxElementSize = btMax(maxSize,maxSize2); - collisionAlgorithmMaxElementSize = btMax(collisionAlgorithmMaxElementSize,maxSize3); - collisionAlgorithmMaxElementSize = btMax(collisionAlgorithmMaxElementSize,maxSize4); - - if (constructionInfo.m_stackAlloc) - { - m_ownsStackAllocator = false; - this->m_stackAlloc = constructionInfo.m_stackAlloc; - } else - { - m_ownsStackAllocator = true; - void* mem = btAlignedAlloc(sizeof(btStackAlloc),16); - m_stackAlloc = new(mem)btStackAlloc(constructionInfo.m_defaultStackAllocatorSize); - } - - if (constructionInfo.m_persistentManifoldPool) - { - m_ownsPersistentManifoldPool = false; - m_persistentManifoldPool = constructionInfo.m_persistentManifoldPool; - } else - { - m_ownsPersistentManifoldPool = true; - void* mem = btAlignedAlloc(sizeof(btPoolAllocator),16); - m_persistentManifoldPool = new (mem) btPoolAllocator(sizeof(btPersistentManifold),constructionInfo.m_defaultMaxPersistentManifoldPoolSize); - } - - if (constructionInfo.m_collisionAlgorithmPool) - { - m_ownsCollisionAlgorithmPool = false; - m_collisionAlgorithmPool = constructionInfo.m_collisionAlgorithmPool; - } else - { - m_ownsCollisionAlgorithmPool = true; - void* mem = btAlignedAlloc(sizeof(btPoolAllocator),16); - m_collisionAlgorithmPool = new(mem) btPoolAllocator(collisionAlgorithmMaxElementSize,constructionInfo.m_defaultMaxCollisionAlgorithmPoolSize); - } - - -} - -btDefaultCollisionConfiguration::~btDefaultCollisionConfiguration() -{ - if (m_ownsStackAllocator) - { - m_stackAlloc->destroy(); - m_stackAlloc->~btStackAlloc(); - btAlignedFree(m_stackAlloc); - } - if (m_ownsCollisionAlgorithmPool) - { - m_collisionAlgorithmPool->~btPoolAllocator(); - btAlignedFree(m_collisionAlgorithmPool); - } - if (m_ownsPersistentManifoldPool) - { - m_persistentManifoldPool->~btPoolAllocator(); - btAlignedFree(m_persistentManifoldPool); - } - - m_convexConvexCreateFunc->~btCollisionAlgorithmCreateFunc(); - btAlignedFree( m_convexConvexCreateFunc); - - m_convexConcaveCreateFunc->~btCollisionAlgorithmCreateFunc(); - btAlignedFree( m_convexConcaveCreateFunc); - m_swappedConvexConcaveCreateFunc->~btCollisionAlgorithmCreateFunc(); - btAlignedFree( m_swappedConvexConcaveCreateFunc); - - m_compoundCreateFunc->~btCollisionAlgorithmCreateFunc(); - btAlignedFree( m_compoundCreateFunc); - - m_swappedCompoundCreateFunc->~btCollisionAlgorithmCreateFunc(); - btAlignedFree( m_swappedCompoundCreateFunc); - - m_emptyCreateFunc->~btCollisionAlgorithmCreateFunc(); - btAlignedFree( m_emptyCreateFunc); - - m_sphereSphereCF->~btCollisionAlgorithmCreateFunc(); - btAlignedFree( m_sphereSphereCF); - - m_sphereBoxCF->~btCollisionAlgorithmCreateFunc(); - btAlignedFree( m_sphereBoxCF); - m_boxSphereCF->~btCollisionAlgorithmCreateFunc(); - btAlignedFree( m_boxSphereCF); - m_sphereTriangleCF->~btCollisionAlgorithmCreateFunc(); - btAlignedFree( m_sphereTriangleCF); - m_triangleSphereCF->~btCollisionAlgorithmCreateFunc(); - btAlignedFree( m_triangleSphereCF); - m_boxBoxCF->~btCollisionAlgorithmCreateFunc(); - btAlignedFree( m_boxBoxCF); - - m_convexPlaneCF->~btCollisionAlgorithmCreateFunc(); - btAlignedFree( m_convexPlaneCF); - m_planeConvexCF->~btCollisionAlgorithmCreateFunc(); - btAlignedFree( m_planeConvexCF); - - m_simplexSolver->~btVoronoiSimplexSolver(); - btAlignedFree(m_simplexSolver); - - m_pdSolver->~btConvexPenetrationDepthSolver(); - - btAlignedFree(m_pdSolver); - - -} - - -btCollisionAlgorithmCreateFunc* btDefaultCollisionConfiguration::getCollisionAlgorithmCreateFunc(int proxyType0,int proxyType1) -{ - - - - if ((proxyType0 == SPHERE_SHAPE_PROXYTYPE) && (proxyType1==SPHERE_SHAPE_PROXYTYPE)) - { - return m_sphereSphereCF; - } - - if ((proxyType0 == SPHERE_SHAPE_PROXYTYPE) && (proxyType1==BOX_SHAPE_PROXYTYPE)) - { - return m_sphereBoxCF; - } - - if ((proxyType0 == BOX_SHAPE_PROXYTYPE ) && (proxyType1==SPHERE_SHAPE_PROXYTYPE)) - { - return m_boxSphereCF; - } - - if ((proxyType0 == SPHERE_SHAPE_PROXYTYPE ) && (proxyType1==TRIANGLE_SHAPE_PROXYTYPE)) - { - return m_sphereTriangleCF; - } - - if ((proxyType0 == TRIANGLE_SHAPE_PROXYTYPE ) && (proxyType1==SPHERE_SHAPE_PROXYTYPE)) - { - return m_triangleSphereCF; - } - - if ((proxyType0 == BOX_SHAPE_PROXYTYPE) && (proxyType1 == BOX_SHAPE_PROXYTYPE)) - { - return m_boxBoxCF; - } - - if (btBroadphaseProxy::isConvex(proxyType0) && (proxyType1 == STATIC_PLANE_PROXYTYPE)) - { - return m_convexPlaneCF; - } - - if (btBroadphaseProxy::isConvex(proxyType1) && (proxyType0 == STATIC_PLANE_PROXYTYPE)) - { - return m_planeConvexCF; - } - - - - if (btBroadphaseProxy::isConvex(proxyType0) && btBroadphaseProxy::isConvex(proxyType1)) - { - return m_convexConvexCreateFunc; - } - - if (btBroadphaseProxy::isConvex(proxyType0) && btBroadphaseProxy::isConcave(proxyType1)) - { - return m_convexConcaveCreateFunc; - } - - if (btBroadphaseProxy::isConvex(proxyType1) && btBroadphaseProxy::isConcave(proxyType0)) - { - return m_swappedConvexConcaveCreateFunc; - } - - if (btBroadphaseProxy::isCompound(proxyType0)) - { - return m_compoundCreateFunc; - } else - { - if (btBroadphaseProxy::isCompound(proxyType1)) - { - return m_swappedCompoundCreateFunc; - } - } - - //failed to find an algorithm - return m_emptyCreateFunc; -} diff --git a/extern/bullet2/src/BulletCollision/CollisionDispatch/btDefaultCollisionConfiguration.h b/extern/bullet2/src/BulletCollision/CollisionDispatch/btDefaultCollisionConfiguration.h deleted file mode 100644 index 0b274d394af..00000000000 --- a/extern/bullet2/src/BulletCollision/CollisionDispatch/btDefaultCollisionConfiguration.h +++ /dev/null @@ -1,112 +0,0 @@ -/* -Bullet Continuous Collision Detection and Physics Library -Copyright (c) 2003-2006 Erwin Coumans http://continuousphysics.com/Bullet/ - -This software is provided 'as-is', without any express or implied warranty. -In no event will the authors be held liable for any damages arising from the use of this software. -Permission is granted to anyone to use this software for any purpose, -including commercial applications, and to alter it and redistribute it freely, -subject to the following restrictions: - -1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. -2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. -3. This notice may not be removed or altered from any source distribution. -*/ - -#ifndef BT_DEFAULT_COLLISION_CONFIGURATION -#define BT_DEFAULT_COLLISION_CONFIGURATION - -#include "btCollisionConfiguration.h" -class btVoronoiSimplexSolver; -class btConvexPenetrationDepthSolver; - -struct btDefaultCollisionConstructionInfo -{ - btStackAlloc* m_stackAlloc; - btPoolAllocator* m_persistentManifoldPool; - btPoolAllocator* m_collisionAlgorithmPool; - int m_defaultMaxPersistentManifoldPoolSize; - int m_defaultMaxCollisionAlgorithmPoolSize; - int m_defaultStackAllocatorSize; - - btDefaultCollisionConstructionInfo() - :m_stackAlloc(0), - m_persistentManifoldPool(0), - m_collisionAlgorithmPool(0), - m_defaultMaxPersistentManifoldPoolSize(65535), - m_defaultMaxCollisionAlgorithmPoolSize(65535), - m_defaultStackAllocatorSize(5*1024*1024) - { - } -}; - - - -///btCollisionConfiguration allows to configure Bullet collision detection -///stack allocator, pool memory allocators -///todo: describe the meaning -class btDefaultCollisionConfiguration : public btCollisionConfiguration -{ - - int m_persistentManifoldPoolSize; - - btStackAlloc* m_stackAlloc; - bool m_ownsStackAllocator; - - btPoolAllocator* m_persistentManifoldPool; - bool m_ownsPersistentManifoldPool; - - btPoolAllocator* m_collisionAlgorithmPool; - bool m_ownsCollisionAlgorithmPool; - - //default simplex/penetration depth solvers - btVoronoiSimplexSolver* m_simplexSolver; - btConvexPenetrationDepthSolver* m_pdSolver; - - //default CreationFunctions, filling the m_doubleDispatch table - btCollisionAlgorithmCreateFunc* m_convexConvexCreateFunc; - btCollisionAlgorithmCreateFunc* m_convexConcaveCreateFunc; - btCollisionAlgorithmCreateFunc* m_swappedConvexConcaveCreateFunc; - btCollisionAlgorithmCreateFunc* m_compoundCreateFunc; - btCollisionAlgorithmCreateFunc* m_swappedCompoundCreateFunc; - btCollisionAlgorithmCreateFunc* m_emptyCreateFunc; - btCollisionAlgorithmCreateFunc* m_sphereSphereCF; - btCollisionAlgorithmCreateFunc* m_sphereBoxCF; - btCollisionAlgorithmCreateFunc* m_boxSphereCF; - btCollisionAlgorithmCreateFunc* m_boxBoxCF; - btCollisionAlgorithmCreateFunc* m_sphereTriangleCF; - btCollisionAlgorithmCreateFunc* m_triangleSphereCF; - btCollisionAlgorithmCreateFunc* m_planeConvexCF; - btCollisionAlgorithmCreateFunc* m_convexPlaneCF; - -public: - - - btDefaultCollisionConfiguration(const btDefaultCollisionConstructionInfo& constructionInfo = btDefaultCollisionConstructionInfo()); - - virtual ~btDefaultCollisionConfiguration(); - - ///memory pools - virtual btPoolAllocator* getPersistentManifoldPool() - { - return m_persistentManifoldPool; - } - - virtual btPoolAllocator* getCollisionAlgorithmPool() - { - return m_collisionAlgorithmPool; - } - - virtual btStackAlloc* getStackAllocator() - { - return m_stackAlloc; - } - - - virtual btCollisionAlgorithmCreateFunc* getCollisionAlgorithmCreateFunc(int proxyType0,int proxyType1); - - -}; - -#endif //BT_DEFAULT_COLLISION_CONFIGURATION - diff --git a/extern/bullet2/src/BulletCollision/CollisionDispatch/btEmptyCollisionAlgorithm.h b/extern/bullet2/src/BulletCollision/CollisionDispatch/btEmptyCollisionAlgorithm.h index e54721dec21..b1a193d2cfd 100644 --- a/extern/bullet2/src/BulletCollision/CollisionDispatch/btEmptyCollisionAlgorithm.h +++ b/extern/bullet2/src/BulletCollision/CollisionDispatch/btEmptyCollisionAlgorithm.h @@ -15,9 +15,8 @@ subject to the following restrictions: #ifndef EMPTY_ALGORITH #define EMPTY_ALGORITH -#include "BulletCollision/BroadphaseCollision/btCollisionAlgorithm.h" +#include "../BroadphaseCollision/btCollisionAlgorithm.h" #include "btCollisionCreateFunc.h" -#include "btCollisionDispatcher.h" #define ATTRIBUTE_ALIGNED(a) @@ -34,18 +33,13 @@ public: virtual btScalar calculateTimeOfImpact(btCollisionObject* body0,btCollisionObject* body1,const btDispatcherInfo& dispatchInfo,btManifoldResult* resultOut); - virtual void getAllContactManifolds(btManifoldArray& manifoldArray) - { - } - struct CreateFunc :public btCollisionAlgorithmCreateFunc { virtual btCollisionAlgorithm* CreateCollisionAlgorithm(btCollisionAlgorithmConstructionInfo& ci, btCollisionObject* body0,btCollisionObject* body1) { (void)body0; (void)body1; - void* mem = ci.m_dispatcher1->allocateCollisionAlgorithm(sizeof(btEmptyAlgorithm)); - return new(mem) btEmptyAlgorithm(ci); + return new btEmptyAlgorithm(ci); } }; diff --git a/extern/bullet2/src/BulletCollision/CollisionDispatch/btManifoldResult.cpp b/extern/bullet2/src/BulletCollision/CollisionDispatch/btManifoldResult.cpp index d5b12598be2..490acc0b611 100644 --- a/extern/bullet2/src/BulletCollision/CollisionDispatch/btManifoldResult.cpp +++ b/extern/bullet2/src/BulletCollision/CollisionDispatch/btManifoldResult.cpp @@ -79,30 +79,12 @@ void btManifoldResult::addContactPoint(const btVector3& normalOnBInWorld,const b } btManifoldPoint newPt(localA,localB,normalOnBInWorld,depth); - newPt.m_positionWorldOnA = pointA; - newPt.m_positionWorldOnB = pointInWorld; - + int insertIndex = m_manifoldPtr->getCacheEntry(newPt); newPt.m_combinedFriction = calculateCombinedFriction(m_body0,m_body1); newPt.m_combinedRestitution = calculateCombinedRestitution(m_body0,m_body1); - //BP mod, store contact triangles. - newPt.m_partId0 = m_partId0; - newPt.m_partId1 = m_partId1; - newPt.m_index0 = m_index0; - newPt.m_index1 = m_index1; - - ///todo, check this for any side effects - if (insertIndex >= 0) - { - //const btManifoldPoint& oldPoint = m_manifoldPtr->getContactPoint(insertIndex); - m_manifoldPtr->replaceContactPoint(newPt,insertIndex); - } else - { - insertIndex = m_manifoldPtr->addManifoldPoint(newPt); - } - //User can override friction and/or restitution if (gContactAddedCallback && //and if either of the two bodies requires custom material @@ -112,8 +94,16 @@ void btManifoldResult::addContactPoint(const btVector3& normalOnBInWorld,const b //experimental feature info, for per-triangle material etc. btCollisionObject* obj0 = isSwapped? m_body1 : m_body0; btCollisionObject* obj1 = isSwapped? m_body0 : m_body1; - (*gContactAddedCallback)(m_manifoldPtr->getContactPoint(insertIndex),obj0,m_partId0,m_index0,obj1,m_partId1,m_index1); + (*gContactAddedCallback)(newPt,obj0,m_partId0,m_index0,obj1,m_partId1,m_index1); } + if (insertIndex >= 0) + { + //const btManifoldPoint& oldPoint = m_manifoldPtr->getContactPoint(insertIndex); + m_manifoldPtr->replaceContactPoint(newPt,insertIndex); + } else + { + m_manifoldPtr->AddManifoldPoint(newPt); + } } diff --git a/extern/bullet2/src/BulletCollision/CollisionDispatch/btManifoldResult.h b/extern/bullet2/src/BulletCollision/CollisionDispatch/btManifoldResult.h index 5aac9a46f6a..77192625513 100644 --- a/extern/bullet2/src/BulletCollision/CollisionDispatch/btManifoldResult.h +++ b/extern/bullet2/src/BulletCollision/CollisionDispatch/btManifoldResult.h @@ -18,12 +18,12 @@ subject to the following restrictions: #define MANIFOLD_RESULT_H class btCollisionObject; -#include "BulletCollision/NarrowPhaseCollision/btPersistentManifold.h" +class btPersistentManifold; class btManifoldPoint; #include "BulletCollision/NarrowPhaseCollision/btDiscreteCollisionDetectorInterface.h" -#include "LinearMath/btTransform.h" +#include "../../LinearMath/btTransform.h" typedef bool (*ContactAddedCallback)(btManifoldPoint& cp, const btCollisionObject* colObj0,int partId0,int index0,const btCollisionObject* colObj1,int partId1,int index1); extern ContactAddedCallback gContactAddedCallback; @@ -60,15 +60,6 @@ public: m_manifoldPtr = manifoldPtr; } - const btPersistentManifold* getPersistentManifold() const - { - return m_manifoldPtr; - } - btPersistentManifold* getPersistentManifold() - { - return m_manifoldPtr; - } - virtual void setShapeIdentifiers(int partId0,int index0, int partId1,int index1) { m_partId0=partId0; @@ -79,22 +70,6 @@ public: virtual void addContactPoint(const btVector3& normalOnBInWorld,const btVector3& pointInWorld,btScalar depth); - SIMD_FORCE_INLINE void refreshContactPoints() - { - btAssert(m_manifoldPtr); - if (!m_manifoldPtr->getNumContacts()) - return; - - bool isSwapped = m_manifoldPtr->getBody0() != m_body0; - - if (isSwapped) - { - m_manifoldPtr->refreshContactPoints(m_rootTransB,m_rootTransA); - } else - { - m_manifoldPtr->refreshContactPoints(m_rootTransA,m_rootTransB); - } - } }; diff --git a/extern/bullet2/src/BulletCollision/CollisionDispatch/btSimulationIslandManager.cpp b/extern/bullet2/src/BulletCollision/CollisionDispatch/btSimulationIslandManager.cpp index 1cc78f76acd..ac2e8554c3a 100644 --- a/extern/bullet2/src/BulletCollision/CollisionDispatch/btSimulationIslandManager.cpp +++ b/extern/bullet2/src/BulletCollision/CollisionDispatch/btSimulationIslandManager.cpp @@ -1,17 +1,3 @@ -/* -Bullet Continuous Collision Detection and Physics Library -Copyright (c) 2003-2006 Erwin Coumans http://continuousphysics.com/Bullet/ - -This software is provided 'as-is', without any express or implied warranty. -In no event will the authors be held liable for any damages arising from the use of this software. -Permission is granted to anyone to use this software for any purpose, -including commercial applications, and to alter it and redistribute it freely, -subject to the following restrictions: - -1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. -2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. -3. This notice may not be removed or altered from any source distribution. -*/ #include "LinearMath/btScalar.h" @@ -21,7 +7,7 @@ subject to the following restrictions: #include "BulletCollision/CollisionDispatch/btCollisionObject.h" #include "BulletCollision/CollisionDispatch/btCollisionWorld.h" -//#include +#include #include "LinearMath/btQuickprof.h" btSimulationIslandManager::btSimulationIslandManager() @@ -39,17 +25,17 @@ void btSimulationIslandManager::initUnionFind(int n) } -void btSimulationIslandManager::findUnions(btDispatcher* /* dispatcher */,btCollisionWorld* colWorld) +void btSimulationIslandManager::findUnions(btDispatcher* dispatcher) { { - btBroadphasePair* pairPtr = colWorld->getPairCache()->getOverlappingPairArrayPtr(); - - for (int i=0;igetPairCache()->getNumOverlappingPairs();i++) + for (int i=0;igetNumManifolds();i++) { - const btBroadphasePair& collisionPair = pairPtr[i]; - btCollisionObject* colObj0 = (btCollisionObject*)collisionPair.m_pProxy0->m_clientObject; - btCollisionObject* colObj1 = (btCollisionObject*)collisionPair.m_pProxy1->m_clientObject; + const btPersistentManifold* manifold = dispatcher->getManifoldByIndexInternal(i); + //static objects (invmass btScalar(0.)) don't merge ! + + const btCollisionObject* colObj0 = static_cast(manifold->getBody0()); + const btCollisionObject* colObj1 = static_cast(manifold->getBody1()); if (((colObj0) && ((colObj0)->mergesSimulationIslands())) && ((colObj1) && ((colObj1)->mergesSimulationIslands()))) @@ -85,7 +71,7 @@ void btSimulationIslandManager::updateActivationState(btCollisionWorld* colWorld } // do the union find - findUnions(dispatcher,colWorld); + findUnions(dispatcher); @@ -143,13 +129,30 @@ class btPersistentManifoldSortPredicate }; -void btSimulationIslandManager::buildIslands(btDispatcher* dispatcher,btCollisionObjectArray& collisionObjects) + + + +// +// todo: this is random access, it can be walked 'cache friendly'! +// +void btSimulationIslandManager::buildAndProcessIslands(btDispatcher* dispatcher,btCollisionObjectArray& collisionObjects, IslandCallback* callback) { - BT_PROFILE("islandUnionFindAndQuickSort"); - m_islandmanifold.resize(0); + + /*if (0) + { + int maxNumManifolds = dispatcher->getNumManifolds(); + btCollisionDispatcher* colDis = (btCollisionDispatcher*)dispatcher; + btPersistentManifold** manifold = colDis->getInternalManifoldPointer(); + callback->ProcessIsland(&collisionObjects[0],collisionObjects.size(),manifold,maxNumManifolds, 0); + return; + } + */ + + BEGIN_PROFILE("islandUnionFindAndHeapSort"); + //we are going to sort the unionfind array, and store the element id in the size //afterwards, we clean unionfind, to make sure no-one uses it anymore @@ -180,7 +183,7 @@ void btSimulationIslandManager::buildIslands(btDispatcher* dispatcher,btCollisio btCollisionObject* colObj0 = collisionObjects[i]; if ((colObj0->getIslandTag() != islandId) && (colObj0->getIslandTag() != -1)) { -// printf("error in island management\n"); + printf("error in island management\n"); } assert((colObj0->getIslandTag() == islandId) || (colObj0->getIslandTag() == -1)); @@ -207,7 +210,7 @@ void btSimulationIslandManager::buildIslands(btDispatcher* dispatcher,btCollisio btCollisionObject* colObj0 = collisionObjects[i]; if ((colObj0->getIslandTag() != islandId) && (colObj0->getIslandTag() != -1)) { -// printf("error in island management\n"); + printf("error in island management\n"); } assert((colObj0->getIslandTag() == islandId) || (colObj0->getIslandTag() == -1)); @@ -228,7 +231,7 @@ void btSimulationIslandManager::buildIslands(btDispatcher* dispatcher,btCollisio btCollisionObject* colObj0 = collisionObjects[i]; if ((colObj0->getIslandTag() != islandId) && (colObj0->getIslandTag() != -1)) { -// printf("error in island management\n"); + printf("error in island management\n"); } assert((colObj0->getIslandTag() == islandId) || (colObj0->getIslandTag() == -1)); @@ -244,17 +247,11 @@ void btSimulationIslandManager::buildIslands(btDispatcher* dispatcher,btCollisio } } - + btAlignedObjectArray islandmanifold; int i; int maxNumManifolds = dispatcher->getNumManifolds(); + islandmanifold.reserve(maxNumManifolds); -#define SPLIT_ISLANDS 1 -#ifdef SPLIT_ISLANDS - - -#endif //SPLIT_ISLANDS - - for (i=0;igetManifoldByIndexInternal(i); @@ -268,52 +265,29 @@ void btSimulationIslandManager::buildIslands(btDispatcher* dispatcher,btCollisio { //kinematic objects don't merge islands, but wake up all connected objects - if (colObj0->isKinematicObject() && colObj0->getActivationState() != ISLAND_SLEEPING) + if (colObj0->isStaticOrKinematicObject() && colObj0->getActivationState() != ISLAND_SLEEPING) { colObj1->activate(); } - if (colObj1->isKinematicObject() && colObj1->getActivationState() != ISLAND_SLEEPING) + if (colObj1->isStaticOrKinematicObject() && colObj1->getActivationState() != ISLAND_SLEEPING) { colObj0->activate(); } -#ifdef SPLIT_ISLANDS - // //filtering for response + + //filtering for response if (dispatcher->needsResponse(colObj0,colObj1)) - m_islandmanifold.push_back(manifold); -#endif //SPLIT_ISLANDS + islandmanifold.push_back(manifold); } } -} + int numManifolds = int (islandmanifold.size()); - -// -// todo: this is random access, it can be walked 'cache friendly'! -// -void btSimulationIslandManager::buildAndProcessIslands(btDispatcher* dispatcher,btCollisionObjectArray& collisionObjects, IslandCallback* callback) -{ - - buildIslands(dispatcher,collisionObjects); - - int endIslandIndex=1; - int startIslandIndex; - int numElem = getUnionFind().getNumElements(); - - BT_PROFILE("processIslands"); - -#ifndef SPLIT_ISLANDS - btPersistentManifold** manifold = dispatcher->getInternalManifoldPointer(); - - callback->ProcessIsland(&collisionObjects[0],collisionObjects.size(),manifold,maxNumManifolds, -1); -#else // Sort manifolds, based on islands // Sort the vector using predicate and std::sort //std::sort(islandmanifold.begin(), islandmanifold.end(), btPersistentManifoldSortPredicate); - int numManifolds = int (m_islandmanifold.size()); - //we should do radix sort, it it much faster (O(n) instead of O (n log2(n)) - m_islandmanifold.quickSort(btPersistentManifoldSortPredicate()); + islandmanifold.heapSort(btPersistentManifoldSortPredicate()); //now process all active islands (sets of manifolds for now) @@ -322,9 +296,10 @@ void btSimulationIslandManager::buildAndProcessIslands(btDispatcher* dispatcher, //int islandId; - + END_PROFILE("islandUnionFindAndHeapSort"); + + btAlignedObjectArray islandBodies; -// printf("Start Islands\n"); //traverse the simulation islands, and call the solver, unless all objects are sleeping/deactivated for ( startIslandIndex=0;startIslandIndexisActive()) islandSleeping = true; } @@ -350,12 +325,12 @@ void btSimulationIslandManager::buildAndProcessIslands(btDispatcher* dispatcher, if (startManifoldIndexProcessIsland(&m_islandBodies[0],m_islandBodies.size(),startManifold,numIslandManifolds, islandId); -// printf("Island callback of size:%d bodies, %d manifolds\n",islandBodies.size(),numIslandManifolds); + callback->ProcessIsland(&islandBodies[0],islandBodies.size(),startManifold,numIslandManifolds, islandId); } if (numIslandManifolds) @@ -376,9 +350,8 @@ void btSimulationIslandManager::buildAndProcessIslands(btDispatcher* dispatcher, startManifoldIndex = endManifoldIndex; } - m_islandBodies.resize(0); + islandBodies.resize(0); } -#endif //SPLIT_ISLANDS - + } diff --git a/extern/bullet2/src/BulletCollision/CollisionDispatch/btSimulationIslandManager.h b/extern/bullet2/src/BulletCollision/CollisionDispatch/btSimulationIslandManager.h index 5f4d54cd803..d91ed1c20eb 100644 --- a/extern/bullet2/src/BulletCollision/CollisionDispatch/btSimulationIslandManager.h +++ b/extern/bullet2/src/BulletCollision/CollisionDispatch/btSimulationIslandManager.h @@ -16,26 +16,18 @@ subject to the following restrictions: #ifndef SIMULATION_ISLAND_MANAGER_H #define SIMULATION_ISLAND_MANAGER_H -#include "BulletCollision/CollisionDispatch/btUnionFind.h" +#include "../CollisionDispatch/btUnionFind.h" #include "btCollisionCreateFunc.h" -#include "LinearMath/btAlignedObjectArray.h" - class btCollisionObject; class btCollisionWorld; class btDispatcher; -class btPersistentManifold; - ///SimulationIslandManager creates and handles simulation islands, using btUnionFind class btSimulationIslandManager { btUnionFind m_unionFind; - btAlignedObjectArray m_islandmanifold; - btAlignedObjectArray m_islandBodies; - - public: btSimulationIslandManager(); virtual ~btSimulationIslandManager(); @@ -50,7 +42,7 @@ public: virtual void storeIslandActivationState(btCollisionWorld* world); - void findUnions(btDispatcher* dispatcher,btCollisionWorld* colWorld); + void findUnions(btDispatcher* dispatcher); @@ -63,8 +55,6 @@ public: void buildAndProcessIslands(btDispatcher* dispatcher,btCollisionObjectArray& collisionObjects, IslandCallback* callback); - void buildIslands(btDispatcher* dispatcher,btCollisionObjectArray& collisionObjects); - }; #endif //SIMULATION_ISLAND_MANAGER_H diff --git a/extern/bullet2/src/BulletCollision/CollisionDispatch/btSphereBoxCollisionAlgorithm.cpp b/extern/bullet2/src/BulletCollision/CollisionDispatch/btSphereBoxCollisionAlgorithm.cpp index 1e4bbce451d..05556bd34e2 100644 --- a/extern/bullet2/src/BulletCollision/CollisionDispatch/btSphereBoxCollisionAlgorithm.cpp +++ b/extern/bullet2/src/BulletCollision/CollisionDispatch/btSphereBoxCollisionAlgorithm.cpp @@ -68,25 +68,18 @@ void btSphereBoxCollisionAlgorithm::processCollision (btCollisionObject* body0,b btScalar dist = getSphereDistance(boxObj,pOnBox,pOnSphere,sphereCenter,radius); - resultOut->setPersistentManifold(m_manifoldPtr); - if (dist < SIMD_EPSILON) { btVector3 normalOnSurfaceB = (pOnBox- pOnSphere).normalize(); /// report a contact. internally this will be kept persistent, and contact reduction is done + resultOut->setPersistentManifold(m_manifoldPtr); resultOut->addContactPoint(normalOnSurfaceB,pOnBox,dist); } - if (m_ownManifold) - { - if (m_manifoldPtr->getNumContacts()) - { - resultOut->refreshContactPoints(); - } - } + } @@ -109,8 +102,8 @@ btScalar btSphereBoxCollisionAlgorithm::getSphereDistance(btCollisionObject* box btVector3 bounds[2]; btBoxShape* boxShape= (btBoxShape*)boxObj->getCollisionShape(); - bounds[0] = -boxShape->getHalfExtentsWithoutMargin(); - bounds[1] = boxShape->getHalfExtentsWithoutMargin(); + bounds[0] = -boxShape->getHalfExtents(); + bounds[1] = boxShape->getHalfExtents(); margins = boxShape->getMargin();//also add sphereShape margin? @@ -216,10 +209,6 @@ btScalar btSphereBoxCollisionAlgorithm::getSpherePenetration( btCollisionObject* btVector3 p0, tmp, prel, n[6], normal; btScalar fSep = btScalar(-10000000.0), fSepThis; - // set p0 and normal to a default value to shup up GCC - p0.setValue(btScalar(0.), btScalar(0.), btScalar(0.)); - normal.setValue(btScalar(0.), btScalar(0.), btScalar(0.)); - n[0].setValue( btScalar(-1.0), btScalar(0.0), btScalar(0.0) ); n[1].setValue( btScalar(0.0), btScalar(-1.0), btScalar(0.0) ); n[2].setValue( btScalar(0.0), btScalar(0.0), btScalar(-1.0) ); diff --git a/extern/bullet2/src/BulletCollision/CollisionDispatch/btSphereBoxCollisionAlgorithm.h b/extern/bullet2/src/BulletCollision/CollisionDispatch/btSphereBoxCollisionAlgorithm.h index 158f0ffcc74..07592909200 100644 --- a/extern/bullet2/src/BulletCollision/CollisionDispatch/btSphereBoxCollisionAlgorithm.h +++ b/extern/bullet2/src/BulletCollision/CollisionDispatch/btSphereBoxCollisionAlgorithm.h @@ -16,13 +16,11 @@ subject to the following restrictions: #ifndef SPHERE_BOX_COLLISION_ALGORITHM_H #define SPHERE_BOX_COLLISION_ALGORITHM_H -#include "BulletCollision/BroadphaseCollision/btCollisionAlgorithm.h" -#include "BulletCollision/BroadphaseCollision/btBroadphaseProxy.h" -#include "BulletCollision/CollisionDispatch/btCollisionCreateFunc.h" +#include "../BroadphaseCollision/btCollisionAlgorithm.h" +#include "../BroadphaseCollision/btBroadphaseProxy.h" +#include "../CollisionDispatch/btCollisionCreateFunc.h" class btPersistentManifold; -#include "btCollisionDispatcher.h" - -#include "LinearMath/btVector3.h" +#include "../../LinearMath/btVector3.h" /// btSphereBoxCollisionAlgorithm provides sphere-box collision detection. /// Other features are frame-coherency (persistent data) and collision response. @@ -42,14 +40,6 @@ public: virtual btScalar calculateTimeOfImpact(btCollisionObject* body0,btCollisionObject* body1,const btDispatcherInfo& dispatchInfo,btManifoldResult* resultOut); - virtual void getAllContactManifolds(btManifoldArray& manifoldArray) - { - if (m_manifoldPtr && m_ownManifold) - { - manifoldArray.push_back(m_manifoldPtr); - } - } - btScalar getSphereDistance( btCollisionObject* boxObj,btVector3& v3PointOnBox, btVector3& v3PointOnSphere, const btVector3& v3SphereCenter, btScalar fRadius ); btScalar getSpherePenetration( btCollisionObject* boxObj, btVector3& v3PointOnBox, btVector3& v3PointOnSphere, const btVector3& v3SphereCenter, btScalar fRadius, const btVector3& aabbMin, const btVector3& aabbMax); @@ -58,13 +48,12 @@ public: { virtual btCollisionAlgorithm* CreateCollisionAlgorithm(btCollisionAlgorithmConstructionInfo& ci, btCollisionObject* body0,btCollisionObject* body1) { - void* mem = ci.m_dispatcher1->allocateCollisionAlgorithm(sizeof(btSphereBoxCollisionAlgorithm)); if (!m_swapped) { - return new(mem) btSphereBoxCollisionAlgorithm(0,ci,body0,body1,false); + return new btSphereBoxCollisionAlgorithm(0,ci,body0,body1,false); } else { - return new(mem) btSphereBoxCollisionAlgorithm(0,ci,body0,body1,true); + return new btSphereBoxCollisionAlgorithm(0,ci,body0,body1,true); } } }; diff --git a/extern/bullet2/src/BulletCollision/CollisionDispatch/btSphereSphereCollisionAlgorithm.cpp b/extern/bullet2/src/BulletCollision/CollisionDispatch/btSphereSphereCollisionAlgorithm.cpp index c9256473c00..424ff432f84 100644 --- a/extern/bullet2/src/BulletCollision/CollisionDispatch/btSphereSphereCollisionAlgorithm.cpp +++ b/extern/bullet2/src/BulletCollision/CollisionDispatch/btSphereSphereCollisionAlgorithm.cpp @@ -46,8 +46,6 @@ void btSphereSphereCollisionAlgorithm::processCollision (btCollisionObject* col0 if (!m_manifoldPtr) return; - resultOut->setPersistentManifold(m_manifoldPtr); - btSphereShape* sphere0 = (btSphereShape*)col0->getCollisionShape(); btSphereShape* sphere1 = (btSphereShape*)col1->getCollisionShape(); @@ -56,34 +54,23 @@ void btSphereSphereCollisionAlgorithm::processCollision (btCollisionObject* col0 btScalar radius0 = sphere0->getRadius(); btScalar radius1 = sphere1->getRadius(); - //m_manifoldPtr->clearManifold(); //don't do this, it disables warmstarting - ///iff distance positive, don't generate a new contact if ( len > (radius0+radius1)) - { return; - } + ///distance (negative means penetration) btScalar dist = len - (radius0+radius1); - btVector3 normalOnSurfaceB(1,0,0); - if (len > SIMD_EPSILON) - { - normalOnSurfaceB = diff / len; - } - + btVector3 normalOnSurfaceB = diff / len; ///point on A (worldspace) btVector3 pos0 = col0->getWorldTransform().getOrigin() - radius0 * normalOnSurfaceB; ///point on B (worldspace) btVector3 pos1 = col1->getWorldTransform().getOrigin() + radius1* normalOnSurfaceB; /// report a contact. internally this will be kept persistent, and contact reduction is done - - + resultOut->setPersistentManifold(m_manifoldPtr); resultOut->addContactPoint(normalOnSurfaceB,pos1,dist); - //no resultOut->refreshContactPoints(); needed, because of clearManifold (all points are new) - } btScalar btSphereSphereCollisionAlgorithm::calculateTimeOfImpact(btCollisionObject* col0,btCollisionObject* col1,const btDispatcherInfo& dispatchInfo,btManifoldResult* resultOut) diff --git a/extern/bullet2/src/BulletCollision/CollisionDispatch/btSphereSphereCollisionAlgorithm.h b/extern/bullet2/src/BulletCollision/CollisionDispatch/btSphereSphereCollisionAlgorithm.h index afdc2ee7fa0..7a19ff31edf 100644 --- a/extern/bullet2/src/BulletCollision/CollisionDispatch/btSphereSphereCollisionAlgorithm.h +++ b/extern/bullet2/src/BulletCollision/CollisionDispatch/btSphereSphereCollisionAlgorithm.h @@ -16,11 +16,9 @@ subject to the following restrictions: #ifndef SPHERE_SPHERE_COLLISION_ALGORITHM_H #define SPHERE_SPHERE_COLLISION_ALGORITHM_H -#include "BulletCollision/BroadphaseCollision/btCollisionAlgorithm.h" -#include "BulletCollision/BroadphaseCollision/btBroadphaseProxy.h" -#include "BulletCollision/CollisionDispatch/btCollisionCreateFunc.h" -#include "btCollisionDispatcher.h" - +#include "../BroadphaseCollision/btCollisionAlgorithm.h" +#include "../BroadphaseCollision/btBroadphaseProxy.h" +#include "../CollisionDispatch/btCollisionCreateFunc.h" class btPersistentManifold; /// btSphereSphereCollisionAlgorithm provides sphere-sphere collision detection. @@ -41,13 +39,6 @@ public: virtual btScalar calculateTimeOfImpact(btCollisionObject* body0,btCollisionObject* body1,const btDispatcherInfo& dispatchInfo,btManifoldResult* resultOut); - virtual void getAllContactManifolds(btManifoldArray& manifoldArray) - { - if (m_manifoldPtr && m_ownManifold) - { - manifoldArray.push_back(m_manifoldPtr); - } - } virtual ~btSphereSphereCollisionAlgorithm(); @@ -55,8 +46,7 @@ public: { virtual btCollisionAlgorithm* CreateCollisionAlgorithm(btCollisionAlgorithmConstructionInfo& ci, btCollisionObject* body0,btCollisionObject* body1) { - void* mem = ci.m_dispatcher1->allocateCollisionAlgorithm(sizeof(btSphereSphereCollisionAlgorithm)); - return new(mem) btSphereSphereCollisionAlgorithm(0,ci,body0,body1); + return new btSphereSphereCollisionAlgorithm(0,ci,body0,body1); } }; diff --git a/extern/bullet2/src/BulletCollision/CollisionDispatch/btSphereTriangleCollisionAlgorithm.cpp b/extern/bullet2/src/BulletCollision/CollisionDispatch/btSphereTriangleCollisionAlgorithm.cpp index 46961f5d61b..b011b707e3f 100644 --- a/extern/bullet2/src/BulletCollision/CollisionDispatch/btSphereTriangleCollisionAlgorithm.cpp +++ b/extern/bullet2/src/BulletCollision/CollisionDispatch/btSphereTriangleCollisionAlgorithm.cpp @@ -48,11 +48,8 @@ void btSphereTriangleCollisionAlgorithm::processCollision (btCollisionObject* co if (!m_manifoldPtr) return; - btCollisionObject* sphereObj = m_swapped? col1 : col0; - btCollisionObject* triObj = m_swapped? col0 : col1; - - btSphereShape* sphere = (btSphereShape*)sphereObj->getCollisionShape(); - btTriangleShape* triangle = (btTriangleShape*)triObj->getCollisionShape(); + btSphereShape* sphere = (btSphereShape*)col0->getCollisionShape(); + btTriangleShape* triangle = (btTriangleShape*)col1->getCollisionShape(); /// report a contact. internally this will be kept persistent, and contact reduction is done resultOut->setPersistentManifold(m_manifoldPtr); @@ -60,16 +57,11 @@ void btSphereTriangleCollisionAlgorithm::processCollision (btCollisionObject* co btDiscreteCollisionDetectorInterface::ClosestPointInput input; input.m_maximumDistanceSquared = btScalar(1e30);//todo: tighter bounds - input.m_transformA = sphereObj->getWorldTransform(); - input.m_transformB = triObj->getWorldTransform(); + input.m_transformA = col0->getWorldTransform(); + input.m_transformB = col1->getWorldTransform(); - bool swapResults = m_swapped && !m_ownManifold; + detector.getClosestPoints(input,*resultOut,dispatchInfo.m_debugDraw); - detector.getClosestPoints(input,*resultOut,dispatchInfo.m_debugDraw,swapResults); - - if (m_ownManifold) - resultOut->refreshContactPoints(); - } btScalar btSphereTriangleCollisionAlgorithm::calculateTimeOfImpact(btCollisionObject* col0,btCollisionObject* col1,const btDispatcherInfo& dispatchInfo,btManifoldResult* resultOut) diff --git a/extern/bullet2/src/BulletCollision/CollisionDispatch/btSphereTriangleCollisionAlgorithm.h b/extern/bullet2/src/BulletCollision/CollisionDispatch/btSphereTriangleCollisionAlgorithm.h index bbaf228c44c..57c6e6af619 100644 --- a/extern/bullet2/src/BulletCollision/CollisionDispatch/btSphereTriangleCollisionAlgorithm.h +++ b/extern/bullet2/src/BulletCollision/CollisionDispatch/btSphereTriangleCollisionAlgorithm.h @@ -16,11 +16,10 @@ subject to the following restrictions: #ifndef SPHERE_TRIANGLE_COLLISION_ALGORITHM_H #define SPHERE_TRIANGLE_COLLISION_ALGORITHM_H -#include "BulletCollision/BroadphaseCollision/btCollisionAlgorithm.h" -#include "BulletCollision/BroadphaseCollision/btBroadphaseProxy.h" -#include "BulletCollision/CollisionDispatch/btCollisionCreateFunc.h" +#include "../BroadphaseCollision/btCollisionAlgorithm.h" +#include "../BroadphaseCollision/btBroadphaseProxy.h" +#include "../CollisionDispatch/btCollisionCreateFunc.h" class btPersistentManifold; -#include "btCollisionDispatcher.h" /// btSphereSphereCollisionAlgorithm provides sphere-sphere collision detection. /// Other features are frame-coherency (persistent data) and collision response. @@ -41,13 +40,6 @@ public: virtual btScalar calculateTimeOfImpact(btCollisionObject* body0,btCollisionObject* body1,const btDispatcherInfo& dispatchInfo,btManifoldResult* resultOut); - virtual void getAllContactManifolds(btManifoldArray& manifoldArray) - { - if (m_manifoldPtr && m_ownManifold) - { - manifoldArray.push_back(m_manifoldPtr); - } - } virtual ~btSphereTriangleCollisionAlgorithm(); @@ -57,9 +49,7 @@ public: virtual btCollisionAlgorithm* CreateCollisionAlgorithm(btCollisionAlgorithmConstructionInfo& ci, btCollisionObject* body0,btCollisionObject* body1) { - void* mem = ci.m_dispatcher1->allocateCollisionAlgorithm(sizeof(btSphereTriangleCollisionAlgorithm)); - - return new(mem) btSphereTriangleCollisionAlgorithm(ci.m_manifold,ci,body0,body1,m_swapped); + return new btSphereTriangleCollisionAlgorithm(ci.m_manifold,ci,body0,body1,m_swapped); } }; diff --git a/extern/bullet2/src/BulletCollision/CollisionDispatch/btUnionFind.cpp b/extern/bullet2/src/BulletCollision/CollisionDispatch/btUnionFind.cpp index bb01b60fa85..62254335796 100644 --- a/extern/bullet2/src/BulletCollision/CollisionDispatch/btUnionFind.cpp +++ b/extern/bullet2/src/BulletCollision/CollisionDispatch/btUnionFind.cpp @@ -18,7 +18,6 @@ subject to the following restrictions: - btUnionFind::~btUnionFind() { Free(); @@ -77,7 +76,8 @@ void btUnionFind::sortIslands() // Sort the vector using predicate and std::sort //std::sort(m_elements.begin(), m_elements.end(), btUnionFindElementSortPredicate); - m_elements.quickSort(btUnionFindElementSortPredicate()); + //perhaps use radix sort? + m_elements.heapSort(btUnionFindElementSortPredicate()); } diff --git a/extern/bullet2/src/BulletCollision/CollisionDispatch/btUnionFind.h b/extern/bullet2/src/BulletCollision/CollisionDispatch/btUnionFind.h index 820c8bc858e..236cc33b94f 100644 --- a/extern/bullet2/src/BulletCollision/CollisionDispatch/btUnionFind.h +++ b/extern/bullet2/src/BulletCollision/CollisionDispatch/btUnionFind.h @@ -16,7 +16,7 @@ subject to the following restrictions: #ifndef UNION_FIND_H #define UNION_FIND_H -#include "LinearMath/btAlignedObjectArray.h" +#include "../../LinearMath/btAlignedObjectArray.h" #define USE_PATH_COMPRESSION 1 @@ -46,11 +46,11 @@ class btUnionFind void reset(int N); - SIMD_FORCE_INLINE int getNumElements() const + inline int getNumElements() const { return int(m_elements.size()); } - SIMD_FORCE_INLINE bool isRoot(int x) const + inline bool isRoot(int x) const { return (x == m_elements[x].m_id); } diff --git a/extern/bullet2/src/BulletCollision/CollisionShapes/btBoxShape.cpp b/extern/bullet2/src/BulletCollision/CollisionShapes/btBoxShape.cpp index adac455bbcb..636b0046c13 100644 --- a/extern/bullet2/src/BulletCollision/CollisionShapes/btBoxShape.cpp +++ b/extern/bullet2/src/BulletCollision/CollisionShapes/btBoxShape.cpp @@ -15,13 +15,16 @@ subject to the following restrictions: #include "btBoxShape.h" - +btVector3 btBoxShape::getHalfExtents() const +{ + return m_implicitShapeDimensions * m_localScaling; +} //{ void btBoxShape::getAabb(const btTransform& t,btVector3& aabbMin,btVector3& aabbMax) const { - const btVector3& halfExtents = getHalfExtentsWithoutMargin(); + btVector3 halfExtents = getHalfExtents(); btMatrix3x3 abs_b = t.getBasis().absolute(); btPoint3 center = t.getOrigin(); @@ -37,10 +40,10 @@ void btBoxShape::getAabb(const btTransform& t,btVector3& aabbMin,btVector3& aabb } -void btBoxShape::calculateLocalInertia(btScalar mass,btVector3& inertia) const +void btBoxShape::calculateLocalInertia(btScalar mass,btVector3& inertia) { //btScalar margin = btScalar(0.); - btVector3 halfExtents = getHalfExtentsWithMargin(); + btVector3 halfExtents = getHalfExtents(); btScalar lx=btScalar(2.)*(halfExtents.x()); btScalar ly=btScalar(2.)*(halfExtents.y()); diff --git a/extern/bullet2/src/BulletCollision/CollisionShapes/btBoxShape.h b/extern/bullet2/src/BulletCollision/CollisionShapes/btBoxShape.h index 4d4fbefea37..bc42f146c7c 100644 --- a/extern/bullet2/src/BulletCollision/CollisionShapes/btBoxShape.h +++ b/extern/bullet2/src/BulletCollision/CollisionShapes/btBoxShape.h @@ -18,11 +18,11 @@ subject to the following restrictions: #include "btPolyhedralConvexShape.h" #include "btCollisionMargin.h" -#include "BulletCollision/BroadphaseCollision/btBroadphaseProxy.h" -#include "LinearMath/btPoint3.h" -#include "LinearMath/btMinMax.h" +#include "../BroadphaseCollision/btBroadphaseProxy.h" +#include "../../LinearMath/btPoint3.h" +#include "../../LinearMath/btSimdMinMax.h" -///The btBoxShape is a box primitive around the origin, its sides axis aligned with length specified by half extents, in local shape coordinates. When used as part of a btCollisionObject or btRigidBody it will be an oriented box in world space. +///btBoxShape implements both a feature based (vertex/edge/plane) and implicit (getSupportingVertex) Box class btBoxShape: public btPolyhedralConvexShape { @@ -31,52 +31,47 @@ class btBoxShape: public btPolyhedralConvexShape public: - btVector3 getHalfExtentsWithMargin() const - { - btVector3 halfExtents = getHalfExtentsWithoutMargin(); - btVector3 margin(getMargin(),getMargin(),getMargin()); - halfExtents += margin; - return halfExtents; - } - - const btVector3& getHalfExtentsWithoutMargin() const - { - return m_implicitShapeDimensions;//changed in Bullet 2.63: assume the scaling and margin are included - } - - + btVector3 getHalfExtents() const; + virtual int getShapeType() const { return BOX_SHAPE_PROXYTYPE;} virtual btVector3 localGetSupportingVertex(const btVector3& vec) const { - btVector3 halfExtents = getHalfExtentsWithoutMargin(); - btVector3 margin(getMargin(),getMargin(),getMargin()); - halfExtents += margin; - return btVector3(btFsels(vec.x(), halfExtents.x(), -halfExtents.x()), - btFsels(vec.y(), halfExtents.y(), -halfExtents.y()), - btFsels(vec.z(), halfExtents.z(), -halfExtents.z())); + btVector3 halfExtents = getHalfExtents(); + + btVector3 supVertex; + supVertex = btPoint3(vec.x() < btScalar(0.0) ? -halfExtents.x() : halfExtents.x(), + vec.y() < btScalar(0.0) ? -halfExtents.y() : halfExtents.y(), + vec.z() < btScalar(0.0) ? -halfExtents.z() : halfExtents.z()); + + return supVertex; } - SIMD_FORCE_INLINE btVector3 localGetSupportingVertexWithoutMargin(const btVector3& vec)const + virtual inline btVector3 localGetSupportingVertexWithoutMargin(const btVector3& vec)const { - const btVector3& halfExtents = getHalfExtentsWithoutMargin(); - - return btVector3(btFsels(vec.x(), halfExtents.x(), -halfExtents.x()), - btFsels(vec.y(), halfExtents.y(), -halfExtents.y()), - btFsels(vec.z(), halfExtents.z(), -halfExtents.z())); + btVector3 halfExtents = getHalfExtents(); + btVector3 margin(getMargin(),getMargin(),getMargin()); + halfExtents -= margin; + + return btVector3(vec.x() < btScalar(0.0) ? -halfExtents.x() : halfExtents.x(), + vec.y() < btScalar(0.0) ? -halfExtents.y() : halfExtents.y(), + vec.z() < btScalar(0.0) ? -halfExtents.z() : halfExtents.z()); } virtual void batchedUnitVectorGetSupportingVertexWithoutMargin(const btVector3* vectors,btVector3* supportVerticesOut,int numVectors) const { - const btVector3& halfExtents = getHalfExtentsWithoutMargin(); - + btVector3 halfExtents = getHalfExtents(); + btVector3 margin(getMargin(),getMargin(),getMargin()); + halfExtents -= margin; + + for (int i=0;ihasPremadeAabb()) - { - meshInterface->getPremadeAabb(&bvhAabbMin, &bvhAabbMax); - } - else - { - meshInterface->calculateAabbBruteForce(bvhAabbMin,bvhAabbMax); - } - - if (buildBvh) - { - void* mem = btAlignedAlloc(sizeof(btOptimizedBvh),16); - m_bvh = new (mem) btOptimizedBvh(); - m_bvh->build(meshInterface,m_useQuantizedAabbCompression,bvhAabbMin,bvhAabbMax); - m_ownsBvh = true; - } + meshInterface->calculateAabbBruteForce(bvhAabbMin,bvhAabbMax); + m_bvh->build(meshInterface,m_useQuantizedAabbCompression,bvhAabbMin,bvhAabbMax); #endif //DISABLE_BVH } -btBvhTriangleMeshShape::btBvhTriangleMeshShape(btStridingMeshInterface* meshInterface, bool useQuantizedAabbCompression,const btVector3& bvhAabbMin,const btVector3& bvhAabbMax,bool buildBvh) -:btTriangleMeshShape(meshInterface), -m_bvh(0), -m_useQuantizedAabbCompression(useQuantizedAabbCompression), -m_ownsBvh(false) +btBvhTriangleMeshShape::btBvhTriangleMeshShape(btStridingMeshInterface* meshInterface, bool useQuantizedAabbCompression,const btVector3& bvhAabbMin,const btVector3& bvhAabbMax) +:btTriangleMeshShape(meshInterface),m_useQuantizedAabbCompression(useQuantizedAabbCompression) { //construct bvh from meshInterface #ifndef DISABLE_BVH - if (buildBvh) - { - void* mem = btAlignedAlloc(sizeof(btOptimizedBvh),16); - m_bvh = new (mem) btOptimizedBvh(); - - m_bvh->build(meshInterface,m_useQuantizedAabbCompression,bvhAabbMin,bvhAabbMax); - m_ownsBvh = true; - } + m_bvh = new btOptimizedBvh(); + m_bvh->build(meshInterface,m_useQuantizedAabbCompression,bvhAabbMin,bvhAabbMax); #endif //DISABLE_BVH @@ -82,140 +58,16 @@ void btBvhTriangleMeshShape::partialRefitTree(const btVector3& aabbMin,const btV } -void btBvhTriangleMeshShape::refitTree(const btVector3& aabbMin,const btVector3& aabbMax) +void btBvhTriangleMeshShape::refitTree() { - m_bvh->refit( m_meshInterface, aabbMin,aabbMax ); + m_bvh->refit( m_meshInterface ); recalcLocalAabb(); } btBvhTriangleMeshShape::~btBvhTriangleMeshShape() { - if (m_ownsBvh) - { - m_bvh->~btOptimizedBvh(); - btAlignedFree(m_bvh); - } -} - -void btBvhTriangleMeshShape::performRaycast (btTriangleCallback* callback, const btVector3& raySource, const btVector3& rayTarget) -{ - struct MyNodeOverlapCallback : public btNodeOverlapCallback - { - btStridingMeshInterface* m_meshInterface; - btTriangleCallback* m_callback; - - MyNodeOverlapCallback(btTriangleCallback* callback,btStridingMeshInterface* meshInterface) - :m_meshInterface(meshInterface), - m_callback(callback) - { - } - - virtual void processNode(int nodeSubPart, int nodeTriangleIndex) - { - btVector3 m_triangle[3]; - const unsigned char *vertexbase; - int numverts; - PHY_ScalarType type; - int stride; - const unsigned char *indexbase; - int indexstride; - int numfaces; - PHY_ScalarType indicestype; - - m_meshInterface->getLockedReadOnlyVertexIndexBase( - &vertexbase, - numverts, - type, - stride, - &indexbase, - indexstride, - numfaces, - indicestype, - nodeSubPart); - - unsigned int* gfxbase = (unsigned int*)(indexbase+nodeTriangleIndex*indexstride); - btAssert(indicestype==PHY_INTEGER||indicestype==PHY_SHORT); - - const btVector3& meshScaling = m_meshInterface->getScaling(); - for (int j=2;j>=0;j--) - { - int graphicsindex = indicestype==PHY_SHORT?((unsigned short*)gfxbase)[j]:gfxbase[j]; - - btScalar* graphicsbase = (btScalar*)(vertexbase+graphicsindex*stride); - - m_triangle[j] = btVector3(graphicsbase[0]*meshScaling.getX(),graphicsbase[1]*meshScaling.getY(),graphicsbase[2]*meshScaling.getZ()); - } - - /* Perform ray vs. triangle collision here */ - m_callback->processTriangle(m_triangle,nodeSubPart,nodeTriangleIndex); - m_meshInterface->unLockReadOnlyVertexBase(nodeSubPart); - } - }; - - MyNodeOverlapCallback myNodeCallback(callback,m_meshInterface); - - m_bvh->reportRayOverlappingNodex(&myNodeCallback,raySource,rayTarget); -} - -void btBvhTriangleMeshShape::performConvexcast (btTriangleCallback* callback, const btVector3& raySource, const btVector3& rayTarget, const btVector3& aabbMin, const btVector3& aabbMax) -{ - struct MyNodeOverlapCallback : public btNodeOverlapCallback - { - btStridingMeshInterface* m_meshInterface; - btTriangleCallback* m_callback; - - MyNodeOverlapCallback(btTriangleCallback* callback,btStridingMeshInterface* meshInterface) - :m_meshInterface(meshInterface), - m_callback(callback) - { - } - - virtual void processNode(int nodeSubPart, int nodeTriangleIndex) - { - btVector3 m_triangle[3]; - const unsigned char *vertexbase; - int numverts; - PHY_ScalarType type; - int stride; - const unsigned char *indexbase; - int indexstride; - int numfaces; - PHY_ScalarType indicestype; - - m_meshInterface->getLockedReadOnlyVertexIndexBase( - &vertexbase, - numverts, - type, - stride, - &indexbase, - indexstride, - numfaces, - indicestype, - nodeSubPart); - - unsigned int* gfxbase = (unsigned int*)(indexbase+nodeTriangleIndex*indexstride); - btAssert(indicestype==PHY_INTEGER||indicestype==PHY_SHORT); - - const btVector3& meshScaling = m_meshInterface->getScaling(); - for (int j=2;j>=0;j--) - { - int graphicsindex = indicestype==PHY_SHORT?((unsigned short*)gfxbase)[j]:gfxbase[j]; - - btScalar* graphicsbase = (btScalar*)(vertexbase+graphicsindex*stride); - - m_triangle[j] = btVector3(graphicsbase[0]*meshScaling.getX(),graphicsbase[1]*meshScaling.getY(),graphicsbase[2]*meshScaling.getZ()); - } - - /* Perform ray vs. triangle collision here */ - m_callback->processTriangle(m_triangle,nodeSubPart,nodeTriangleIndex); - m_meshInterface->unLockReadOnlyVertexBase(nodeSubPart); - } - }; - - MyNodeOverlapCallback myNodeCallback(callback,m_meshInterface); - - m_bvh->reportBoxCastOverlappingNodex (&myNodeCallback, raySource, rayTarget, aabbMin, aabbMax); + delete m_bvh; } //perform bvh tree traversal and report overlapping triangles to 'callback' @@ -266,14 +118,13 @@ void btBvhTriangleMeshShape::processAllTriangles(btTriangleCallback* callback,co indicestype, nodeSubPart); - unsigned int* gfxbase = (unsigned int*)(indexbase+nodeTriangleIndex*indexstride); - btAssert(indicestype==PHY_INTEGER||indicestype==PHY_SHORT); + int* gfxbase = (int*)(indexbase+nodeTriangleIndex*indexstride); const btVector3& meshScaling = m_meshInterface->getScaling(); for (int j=2;j>=0;j--) { - int graphicsindex = indicestype==PHY_SHORT?((unsigned short*)gfxbase)[j]:gfxbase[j]; + int graphicsindex = gfxbase[j]; #ifdef DEBUG_TRIANGLE_MESH @@ -306,37 +157,17 @@ void btBvhTriangleMeshShape::processAllTriangles(btTriangleCallback* callback,co } -void btBvhTriangleMeshShape::setLocalScaling(const btVector3& scaling) + +void btBvhTriangleMeshShape::setLocalScaling(const btVector3& scaling) { - if ((getLocalScaling() -scaling).length2() > SIMD_EPSILON) - { - btTriangleMeshShape::setLocalScaling(scaling); - if (m_ownsBvh) - { - m_bvh->~btOptimizedBvh(); - btAlignedFree(m_bvh); - } - ///m_localAabbMin/m_localAabbMax is already re-calculated in btTriangleMeshShape. We could just scale aabb, but this needs some more work - void* mem = btAlignedAlloc(sizeof(btOptimizedBvh),16); - m_bvh = new(mem) btOptimizedBvh(); - //rebuild the bvh... - m_bvh->build(m_meshInterface,m_useQuantizedAabbCompression,m_localAabbMin,m_localAabbMax); - m_ownsBvh = true; - } + if ((getLocalScaling() -scaling).length2() > SIMD_EPSILON) + { + btTriangleMeshShape::setLocalScaling(scaling); + delete m_bvh; + ///m_localAabbMin/m_localAabbMax is already re-calculated in btTriangleMeshShape. We could just scale aabb, but this needs some more work + m_bvh = new btOptimizedBvh(); + //rebuild the bvh... + m_bvh->build(m_meshInterface,m_useQuantizedAabbCompression,m_localAabbMin,m_localAabbMax); + + } } - -void btBvhTriangleMeshShape::setOptimizedBvh(btOptimizedBvh* bvh, const btVector3& scaling) -{ - btAssert(!m_bvh); - btAssert(!m_ownsBvh); - - m_bvh = bvh; - m_ownsBvh = false; - // update the scaling without rebuilding the bvh - if ((getLocalScaling() -scaling).length2() > SIMD_EPSILON) - { - btTriangleMeshShape::setLocalScaling(scaling); - } -} - - diff --git a/extern/bullet2/src/BulletCollision/CollisionShapes/btBvhTriangleMeshShape.h b/extern/bullet2/src/BulletCollision/CollisionShapes/btBvhTriangleMeshShape.h index 6e587340dc1..4914d9f959c 100644 --- a/extern/bullet2/src/BulletCollision/CollisionShapes/btBvhTriangleMeshShape.h +++ b/extern/bullet2/src/BulletCollision/CollisionShapes/btBvhTriangleMeshShape.h @@ -18,55 +18,45 @@ subject to the following restrictions: #include "btTriangleMeshShape.h" #include "btOptimizedBvh.h" -#include "LinearMath/btAlignedAllocator.h" - -///The btBvhTriangleMeshShape is a static-triangle mesh shape with several optimizations, such as bounding volume hierarchy and cache friendly traversal for PlayStation 3 Cell SPU. It is recommended to enable useQuantizedAabbCompression for better memory usage. -///It takes a triangle mesh as input, for example a btTriangleMesh or btTriangleIndexVertexArray. The btBvhTriangleMeshShape class allows for triangle mesh deformations by a refit or partialRefit method. -///Instead of building the bounding volume hierarchy acceleration structure, it is also possible to serialize (save) and deserialize (load) the structure from disk. -///See Demos\ConcaveDemo\ConcavePhysicsDemo.cpp for an example. +///Bvh Concave triangle mesh is a static-triangle mesh shape with Bounding Volume Hierarchy optimization. +///Uses an interface to access the triangles to allow for sharing graphics/physics triangles. ATTRIBUTE_ALIGNED16(class) btBvhTriangleMeshShape : public btTriangleMeshShape { btOptimizedBvh* m_bvh; bool m_useQuantizedAabbCompression; - bool m_ownsBvh; - bool m_pad[11];////need padding due to alignment + bool m_pad[12];////need padding due to alignment public: - BT_DECLARE_ALIGNED_ALLOCATOR(); - - btBvhTriangleMeshShape() :btTriangleMeshShape(0),m_bvh(0),m_ownsBvh(false) {}; - btBvhTriangleMeshShape(btStridingMeshInterface* meshInterface, bool useQuantizedAabbCompression, bool buildBvh = true); + btBvhTriangleMeshShape() :btTriangleMeshShape(0) {}; + btBvhTriangleMeshShape(btStridingMeshInterface* meshInterface, bool useQuantizedAabbCompression); ///optionally pass in a larger bvh aabb, used for quantization. This allows for deformations within this aabb - btBvhTriangleMeshShape(btStridingMeshInterface* meshInterface, bool useQuantizedAabbCompression,const btVector3& bvhAabbMin,const btVector3& bvhAabbMax, bool buildBvh = true); + btBvhTriangleMeshShape(btStridingMeshInterface* meshInterface, bool useQuantizedAabbCompression,const btVector3& bvhAabbMin,const btVector3& bvhAabbMax); virtual ~btBvhTriangleMeshShape(); - bool getOwnsBvh () const - { - return m_ownsBvh; - } - + + /* virtual int getShapeType() const { return TRIANGLE_MESH_SHAPE_PROXYTYPE; } - - void performRaycast (btTriangleCallback* callback, const btVector3& raySource, const btVector3& rayTarget); - void performConvexcast (btTriangleCallback* callback, const btVector3& boxSource, const btVector3& boxTarget, const btVector3& boxMin, const btVector3& boxMax); + */ + + virtual void processAllTriangles(btTriangleCallback* callback,const btVector3& aabbMin,const btVector3& aabbMax) const; - void refitTree(const btVector3& aabbMin,const btVector3& aabbMax); + void refitTree(); ///for a fast incremental refit of parts of the tree. Note: the entire AABB of the tree will become more conservative, it never shrinks void partialRefitTree(const btVector3& aabbMin,const btVector3& aabbMax); //debugging - virtual const char* getName()const {return "BVHTRIANGLEMESH";} + virtual char* getName()const {return "BVHTRIANGLEMESH";} virtual void setLocalScaling(const btVector3& scaling); @@ -75,10 +65,6 @@ public: { return m_bvh; } - - - void setOptimizedBvh(btOptimizedBvh* bvh, const btVector3& localScaling=btVector3(1,1,1)); - bool usesQuantizedAabbCompression() const { return m_useQuantizedAabbCompression; diff --git a/extern/bullet2/src/BulletCollision/CollisionShapes/btCapsuleShape.cpp b/extern/bullet2/src/BulletCollision/CollisionShapes/btCapsuleShape.cpp index 26ba276b900..b7e15172da2 100644 --- a/extern/bullet2/src/BulletCollision/CollisionShapes/btCapsuleShape.cpp +++ b/extern/bullet2/src/BulletCollision/CollisionShapes/btCapsuleShape.cpp @@ -21,7 +21,6 @@ subject to the following restrictions: btCapsuleShape::btCapsuleShape(btScalar radius, btScalar height) { - m_upAxis = 1; m_implicitShapeDimensions.setValue(radius,0.5f*height,radius); } @@ -51,9 +50,7 @@ btCapsuleShape::btCapsuleShape(btScalar radius, btScalar height) { - btVector3 pos(0,0,0); - pos[getUpAxis()] = getHalfHeight(); - + btVector3 pos(0,getHalfHeight(),0); vtx = pos +vec*m_localScaling*(radius) - vec * getMargin(); newDot = vec.dot(vtx); if (newDot > maxDot) @@ -63,9 +60,7 @@ btCapsuleShape::btCapsuleShape(btScalar radius, btScalar height) } } { - btVector3 pos(0,0,0); - pos[getUpAxis()] = -getHalfHeight(); - + btVector3 pos(0,-getHalfHeight(),0); vtx = pos +vec*m_localScaling*(radius) - vec * getMargin(); newDot = vec.dot(vtx); if (newDot > maxDot) @@ -93,8 +88,7 @@ btCapsuleShape::btCapsuleShape(btScalar radius, btScalar height) btVector3 vtx; btScalar newDot; { - btVector3 pos(0,0,0); - pos[getUpAxis()] = getHalfHeight(); + btVector3 pos(0,getHalfHeight(),0); vtx = pos +vec*m_localScaling*(radius) - vec * getMargin(); newDot = vec.dot(vtx); if (newDot > maxDot) @@ -104,8 +98,7 @@ btCapsuleShape::btCapsuleShape(btScalar radius, btScalar height) } } { - btVector3 pos(0,0,0); - pos[getUpAxis()] = -getHalfHeight(); + btVector3 pos(0,-getHalfHeight(),0); vtx = pos +vec*m_localScaling*(radius) - vec * getMargin(); newDot = vec.dot(vtx); if (newDot > maxDot) @@ -119,7 +112,7 @@ btCapsuleShape::btCapsuleShape(btScalar radius, btScalar height) } -void btCapsuleShape::calculateLocalInertia(btScalar mass,btVector3& inertia) const +void btCapsuleShape::calculateLocalInertia(btScalar mass,btVector3& inertia) { //as an approximation, take the inertia of the box that bounds the spheres @@ -129,8 +122,7 @@ void btCapsuleShape::calculateLocalInertia(btScalar mass,btVector3& inertia) con btScalar radius = getRadius(); - btVector3 halfExtents(radius,radius,radius); - halfExtents[getUpAxis()]+=getHalfHeight(); + btVector3 halfExtents(radius,radius+getHalfHeight(),radius); btScalar margin = CONVEX_DISTANCE_MARGIN; @@ -148,22 +140,6 @@ void btCapsuleShape::calculateLocalInertia(btScalar mass,btVector3& inertia) con } -btCapsuleShapeX::btCapsuleShapeX(btScalar radius,btScalar height) -{ - m_upAxis = 0; - m_implicitShapeDimensions.setValue(0.5f*height, radius,radius); -} - - - - - - -btCapsuleShapeZ::btCapsuleShapeZ(btScalar radius,btScalar height) -{ - m_upAxis = 2; - m_implicitShapeDimensions.setValue(radius,radius,0.5f*height); -} diff --git a/extern/bullet2/src/BulletCollision/CollisionShapes/btCapsuleShape.h b/extern/bullet2/src/BulletCollision/CollisionShapes/btCapsuleShape.h index 92bcce55119..27da8adefa5 100644 --- a/extern/bullet2/src/BulletCollision/CollisionShapes/btCapsuleShape.h +++ b/extern/bullet2/src/BulletCollision/CollisionShapes/btCapsuleShape.h @@ -16,27 +16,20 @@ subject to the following restrictions: #ifndef BT_CAPSULE_SHAPE_H #define BT_CAPSULE_SHAPE_H -#include "btConvexInternalShape.h" -#include "BulletCollision/BroadphaseCollision/btBroadphaseProxy.h" // for the types +#include "btConvexShape.h" +#include "../BroadphaseCollision/btBroadphaseProxy.h" // for the types -///The btCapsuleShape represents a capsule around the Y axis, there is also the btCapsuleShapeX aligned around the X axis and btCapsuleShapeZ around the Z axis. -///The total height is height+2*radius, so the height is just the height between the center of each 'sphere' of the capsule caps. -///The btCapsuleShape is a convex hull of two spheres. The btMultiSphereShape is a more general collision shape that takes the convex hull of multiple sphere, so it can also represent a capsule when just using two spheres. -class btCapsuleShape : public btConvexInternalShape +///btCapsuleShape represents a capsule around the Y axis +///A more general solution that can represent capsules is the btMultiSphereShape +class btCapsuleShape : public btConvexShape { -protected: - int m_upAxis; - -protected: - ///only used for btCapsuleShapeZ and btCapsuleShapeX subclasses. - btCapsuleShape() {}; public: btCapsuleShape(btScalar radius,btScalar height); ///CollisionShape Interface - virtual void calculateLocalInertia(btScalar mass,btVector3& inertia) const; + virtual void calculateLocalInertia(btScalar mass,btVector3& inertia); /// btConvexShape Interface virtual btVector3 localGetSupportingVertexWithoutMargin(const btVector3& vec)const; @@ -45,75 +38,23 @@ public: virtual int getShapeType() const { return CAPSULE_SHAPE_PROXYTYPE; } - virtual void getAabb (const btTransform& t, btVector3& aabbMin, btVector3& aabbMax) const - { - btVector3 halfExtents(getRadius(),getRadius(),getRadius()); - halfExtents[m_upAxis] = getRadius() + getHalfHeight(); - btMatrix3x3 abs_b = t.getBasis().absolute(); - btPoint3 center = t.getOrigin(); - btVector3 extent = btVector3(abs_b[0].dot(halfExtents),abs_b[1].dot(halfExtents),abs_b[2].dot(halfExtents)); - extent += btVector3(getMargin(),getMargin(),getMargin()); - aabbMin = center - extent; - aabbMax = center + extent; - } - - virtual const char* getName()const + virtual char* getName()const { return "CapsuleShape"; } - int getUpAxis() const - { - return m_upAxis; - } - btScalar getRadius() const { - int radiusAxis = (m_upAxis+2)%3; - return m_implicitShapeDimensions[radiusAxis]; + return m_implicitShapeDimensions.getX(); } btScalar getHalfHeight() const { - return m_implicitShapeDimensions[m_upAxis]; + return m_implicitShapeDimensions.getY(); } }; -///btCapsuleShapeX represents a capsule around the Z axis -///the total height is height+2*radius, so the height is just the height between the center of each 'sphere' of the capsule caps. -class btCapsuleShapeX : public btCapsuleShape -{ -public: - - btCapsuleShapeX(btScalar radius,btScalar height); - - //debugging - virtual const char* getName()const - { - return "CapsuleX"; - } - - - -}; - -///btCapsuleShapeZ represents a capsule around the Z axis -///the total height is height+2*radius, so the height is just the height between the center of each 'sphere' of the capsule caps. -class btCapsuleShapeZ : public btCapsuleShape -{ -public: - btCapsuleShapeZ(btScalar radius,btScalar height); - - //debugging - virtual const char* getName()const - { - return "CapsuleZ"; - } - - -}; - #endif //BT_CAPSULE_SHAPE_H diff --git a/extern/bullet2/src/BulletCollision/CollisionShapes/btCollisionShape.cpp b/extern/bullet2/src/BulletCollision/CollisionShapes/btCollisionShape.cpp index 39e621aa946..81d82428f4c 100644 --- a/extern/bullet2/src/BulletCollision/CollisionShapes/btCollisionShape.cpp +++ b/extern/bullet2/src/BulletCollision/CollisionShapes/btCollisionShape.cpp @@ -21,12 +21,7 @@ subject to the following restrictions: can be used by probes that are checking whether the library is actually installed. */ -extern "C" -{ -void btBulletCollisionProbe (); - -void btBulletCollisionProbe () {} -} +extern "C" void btBulletCollisionProbe () {} @@ -51,7 +46,7 @@ btScalar btCollisionShape::getAngularMotionDisc() const return disc; } -void btCollisionShape::calculateTemporalAabb(const btTransform& curTrans,const btVector3& linvel,const btVector3& angvel,btScalar timeStep, btVector3& temporalAabbMin,btVector3& temporalAabbMax) const +void btCollisionShape::calculateTemporalAabb(const btTransform& curTrans,const btVector3& linvel,const btVector3& angvel,btScalar timeStep, btVector3& temporalAabbMin,btVector3& temporalAabbMax) { //start with static aabb getAabb(curTrans,temporalAabbMin,temporalAabbMax); diff --git a/extern/bullet2/src/BulletCollision/CollisionShapes/btCollisionShape.h b/extern/bullet2/src/BulletCollision/CollisionShapes/btCollisionShape.h index 3a352b90777..96268734a83 100644 --- a/extern/bullet2/src/BulletCollision/CollisionShapes/btCollisionShape.h +++ b/extern/bullet2/src/BulletCollision/CollisionShapes/btCollisionShape.h @@ -16,21 +16,18 @@ subject to the following restrictions: #ifndef COLLISION_SHAPE_H #define COLLISION_SHAPE_H -#include "LinearMath/btTransform.h" -#include "LinearMath/btVector3.h" -#include "LinearMath/btMatrix3x3.h" -#include "LinearMath/btPoint3.h" -#include "BulletCollision/BroadphaseCollision/btBroadphaseProxy.h" //for the shape types +#include "../../LinearMath/btTransform.h" +#include "../../LinearMath/btVector3.h" +#include "../../LinearMath/btMatrix3x3.h" +#include "../../LinearMath/btPoint3.h" +#include "../BroadphaseCollision/btBroadphaseProxy.h" //for the shape types -///The btCollisionShape class provides an interface for collision shapes that can be shared among btCollisionObjects. +///btCollisionShape provides interface for collision shapes that can be shared among btCollisionObjects. class btCollisionShape { - - void* m_userPointer; - public: - btCollisionShape() : m_userPointer(0) + btCollisionShape() { } virtual ~btCollisionShape() @@ -48,30 +45,30 @@ public: ///calculateTemporalAabb calculates the enclosing aabb for the moving object over interval [0..timeStep) ///result is conservative - void calculateTemporalAabb(const btTransform& curTrans,const btVector3& linvel,const btVector3& angvel,btScalar timeStep, btVector3& temporalAabbMin,btVector3& temporalAabbMax) const; + void calculateTemporalAabb(const btTransform& curTrans,const btVector3& linvel,const btVector3& angvel,btScalar timeStep, btVector3& temporalAabbMin,btVector3& temporalAabbMax); #ifndef __SPU__ - SIMD_FORCE_INLINE bool isPolyhedral() const + inline bool isPolyhedral() const { return btBroadphaseProxy::isPolyhedral(getShapeType()); } - SIMD_FORCE_INLINE bool isConvex() const + inline bool isConvex() const { return btBroadphaseProxy::isConvex(getShapeType()); } - SIMD_FORCE_INLINE bool isConcave() const + inline bool isConcave() const { return btBroadphaseProxy::isConcave(getShapeType()); } - SIMD_FORCE_INLINE bool isCompound() const + inline bool isCompound() const { return btBroadphaseProxy::isCompound(getShapeType()); } ///isInfinite is used to catch simulation error (aabb check) - SIMD_FORCE_INLINE bool isInfinite() const + inline bool isInfinite() const { return btBroadphaseProxy::isInfinite(getShapeType()); } @@ -79,11 +76,11 @@ public: virtual int getShapeType() const=0; virtual void setLocalScaling(const btVector3& scaling) =0; virtual const btVector3& getLocalScaling() const =0; - virtual void calculateLocalInertia(btScalar mass,btVector3& inertia) const = 0; + virtual void calculateLocalInertia(btScalar mass,btVector3& inertia) = 0; //debugging support - virtual const char* getName()const =0 ; + virtual char* getName()const =0 ; #endif //__SPU__ @@ -91,18 +88,6 @@ public: virtual void setMargin(btScalar margin) = 0; virtual btScalar getMargin() const = 0; - - ///optional user data pointer - void setUserPointer(void* userPtr) - { - m_userPointer = userPtr; - } - - void* getUserPointer() const - { - return m_userPointer; - } - }; #endif //COLLISION_SHAPE_H diff --git a/extern/bullet2/src/BulletCollision/CollisionShapes/btCompoundShape.cpp b/extern/bullet2/src/BulletCollision/CollisionShapes/btCompoundShape.cpp index 740f1783630..a4712b3e925 100644 --- a/extern/bullet2/src/BulletCollision/CollisionShapes/btCompoundShape.cpp +++ b/extern/bullet2/src/BulletCollision/CollisionShapes/btCompoundShape.cpp @@ -35,15 +35,8 @@ btCompoundShape::~btCompoundShape() void btCompoundShape::addChildShape(const btTransform& localTransform,btCollisionShape* shape) { - //m_childTransforms.push_back(localTransform); - //m_childShapes.push_back(shape); - btCompoundShapeChild child; - child.m_transform = localTransform; - child.m_childShape = shape; - child.m_childShapeType = shape->getShapeType(); - child.m_childMargin = shape->getMargin(); - - m_children.push_back(child); + m_childTransforms.push_back(localTransform); + m_childShapes.push_back(shape); //extend the local aabbMin/aabbMax btVector3 localAabbMin,localAabbMax; @@ -62,53 +55,9 @@ void btCompoundShape::addChildShape(const btTransform& localTransform,btCollisio } } -void btCompoundShape::removeChildShape(btCollisionShape* shape) -{ - bool done_removing; - - // Find the children containing the shape specified, and remove those children. - do - { - done_removing = true; - - for(int i = 0; i < m_children.size(); i++) - { - if(m_children[i].m_childShape == shape) - { - m_children.remove(m_children[i]); - done_removing = false; // Do another iteration pass after removing from the vector - break; - } - } - } - while (!done_removing); - - recalculateLocalAabb(); -} -void btCompoundShape::recalculateLocalAabb() -{ - // Recalculate the local aabb - // Brute force, it iterates over all the shapes left. - m_localAabbMin = btVector3(btScalar(1e30),btScalar(1e30),btScalar(1e30)); - m_localAabbMax = btVector3(btScalar(-1e30),btScalar(-1e30),btScalar(-1e30)); - - //extend the local aabbMin/aabbMax - for (int j = 0; j < m_children.size(); j++) - { - btVector3 localAabbMin,localAabbMax; - m_children[j].m_childShape->getAabb(m_children[j].m_transform, localAabbMin, localAabbMax); - for (int i=0;i<3;i++) - { - if (m_localAabbMin[i] > localAabbMin[i]) - m_localAabbMin[i] = localAabbMin[i]; - if (m_localAabbMax[i] < localAabbMax[i]) - m_localAabbMax[i] = localAabbMax[i]; - } - } -} - - ///getAabb's default implementation is brute force, expected derived classes to implement a fast dedicated version + + ///getAabb's default implementation is brute force, expected derived classes to implement a fast dedicated version void btCompoundShape::getAabb(const btTransform& trans,btVector3& aabbMin,btVector3& aabbMax) const { btVector3 localHalfExtents = btScalar(0.5)*(m_localAabbMax-m_localAabbMin); @@ -127,7 +76,7 @@ void btCompoundShape::getAabb(const btTransform& trans,btVector3& aabbMin,btVect aabbMax = center + extent; } -void btCompoundShape::calculateLocalInertia(btScalar mass,btVector3& inertia) const +void btCompoundShape::calculateLocalInertia(btScalar mass,btVector3& inertia) { //approximation: take the inertia from the aabb for now btTransform ident; diff --git a/extern/bullet2/src/BulletCollision/CollisionShapes/btCompoundShape.h b/extern/bullet2/src/BulletCollision/CollisionShapes/btCompoundShape.h index f77e4b59558..86dc1f80947 100644 --- a/extern/bullet2/src/BulletCollision/CollisionShapes/btCompoundShape.h +++ b/extern/bullet2/src/BulletCollision/CollisionShapes/btCompoundShape.h @@ -18,95 +18,58 @@ subject to the following restrictions: #include "btCollisionShape.h" -#include "LinearMath/btVector3.h" -#include "LinearMath/btTransform.h" -#include "LinearMath/btMatrix3x3.h" +#include "../../LinearMath/btVector3.h" +#include "../../LinearMath/btTransform.h" +#include "../../LinearMath/btMatrix3x3.h" #include "btCollisionMargin.h" -#include "LinearMath/btAlignedObjectArray.h" +#include "../../LinearMath/btAlignedObjectArray.h" class btOptimizedBvh; - -ATTRIBUTE_ALIGNED16(struct) btCompoundShapeChild -{ - BT_DECLARE_ALIGNED_ALLOCATOR(); - - btTransform m_transform; - btCollisionShape* m_childShape; - int m_childShapeType; - btScalar m_childMargin; -}; - -SIMD_FORCE_INLINE bool operator==(const btCompoundShapeChild& c1, const btCompoundShapeChild& c2) -{ - return ( c1.m_transform == c2.m_transform && - c1.m_childShape == c2.m_childShape && - c1.m_childShapeType == c2.m_childShapeType && - c1.m_childMargin == c2.m_childMargin ); -} - /// btCompoundShape allows to store multiple other btCollisionShapes -/// This allows for moving concave collision objects. This is more general then the static concave btBvhTriangleMeshShape. -ATTRIBUTE_ALIGNED16(class) btCompoundShape : public btCollisionShape +/// This allows for concave collision objects. This is more general then the Static Concave btTriangleMeshShape. +class btCompoundShape : public btCollisionShape { - //btAlignedObjectArray m_childTransforms; - //btAlignedObjectArray m_childShapes; - btAlignedObjectArray m_children; + btAlignedObjectArray m_childTransforms; + btAlignedObjectArray m_childShapes; btVector3 m_localAabbMin; btVector3 m_localAabbMax; btOptimizedBvh* m_aabbTree; public: - BT_DECLARE_ALIGNED_ALLOCATOR(); - btCompoundShape(); virtual ~btCompoundShape(); void addChildShape(const btTransform& localTransform,btCollisionShape* shape); - /** Remove all children shapes that contain the specified shape. */ - virtual void removeChildShape(btCollisionShape* shape); - - - - int getNumChildShapes() const { - return int (m_children.size()); + return int (m_childShapes.size()); } btCollisionShape* getChildShape(int index) { - return m_children[index].m_childShape; + return m_childShapes[index]; } const btCollisionShape* getChildShape(int index) const { - return m_children[index].m_childShape; + return m_childShapes[index]; } - btTransform getChildTransform(int index) + btTransform& getChildTransform(int index) { - return m_children[index].m_transform; + return m_childTransforms[index]; } - const btTransform getChildTransform(int index) const + const btTransform& getChildTransform(int index) const { - return m_children[index].m_transform; - } - - - btCompoundShapeChild* getChildList() - { - return &m_children[0]; + return m_childTransforms[index]; } ///getAabb's default implementation is brute force, expected derived classes to implement a fast dedicated version - virtual void getAabb(const btTransform& t,btVector3& aabbMin,btVector3& aabbMax) const; - - /** Re-calculate the local Aabb. Is called at the end of removeChildShapes. - Use this yourself if you modify the children or their transforms. */ - virtual void recalculateLocalAabb(); + void getAabb(const btTransform& t,btVector3& aabbMin,btVector3& aabbMax) const; + virtual void setLocalScaling(const btVector3& scaling) { @@ -117,7 +80,7 @@ public: return m_localScaling; } - virtual void calculateLocalInertia(btScalar mass,btVector3& inertia) const; + virtual void calculateLocalInertia(btScalar mass,btVector3& inertia); virtual int getShapeType() const { return COMPOUND_SHAPE_PROXYTYPE;} @@ -129,7 +92,7 @@ public: { return m_collisionMargin; } - virtual const char* getName()const + virtual char* getName()const { return "Compound"; } diff --git a/extern/bullet2/src/BulletCollision/CollisionShapes/btConcaveShape.h b/extern/bullet2/src/BulletCollision/CollisionShapes/btConcaveShape.h index f3f57206ab7..73f974e4ee9 100644 --- a/extern/bullet2/src/BulletCollision/CollisionShapes/btConcaveShape.h +++ b/extern/bullet2/src/BulletCollision/CollisionShapes/btConcaveShape.h @@ -17,12 +17,12 @@ subject to the following restrictions: #define CONCAVE_SHAPE_H #include "btCollisionShape.h" -#include "BulletCollision/BroadphaseCollision/btBroadphaseProxy.h" // for the types +#include "../BroadphaseCollision/btBroadphaseProxy.h" // for the types #include "btTriangleCallback.h" -///The btConcaveShape class provides an interface for non-moving (static) concave shapes. -///It has been implemented by the btStaticPlaneShape, btBvhTriangleMeshShape and btHeightfieldTerrainShape. +///Concave shape proves an interface concave shapes that can produce triangles that overlapping a given AABB. +///Static triangle mesh, infinite plane, height field/landscapes are example that implement this interface. class btConcaveShape : public btCollisionShape { protected: diff --git a/extern/bullet2/src/BulletCollision/CollisionShapes/btConeShape.h b/extern/bullet2/src/BulletCollision/CollisionShapes/btConeShape.h index 685369742e4..3ccda5b12c6 100644 --- a/extern/bullet2/src/BulletCollision/CollisionShapes/btConeShape.h +++ b/extern/bullet2/src/BulletCollision/CollisionShapes/btConeShape.h @@ -16,11 +16,11 @@ subject to the following restrictions: #ifndef CONE_MINKOWSKI_H #define CONE_MINKOWSKI_H -#include "btConvexInternalShape.h" -#include "BulletCollision/BroadphaseCollision/btBroadphaseProxy.h" // for the types +#include "btConvexShape.h" +#include "../BroadphaseCollision/btBroadphaseProxy.h" // for the types -///The btConeShape implements a cone shape primitive, centered around the origin and aligned with the Y axis. The btConeShapeX is aligned around the X axis and btConeShapeZ around the Z axis. -class btConeShape : public btConvexInternalShape +///btConeShape implements a Cone shape, around the Y axis +class btConeShape : public btConvexShape { @@ -42,7 +42,7 @@ public: btScalar getHeight() const { return m_height;} - virtual void calculateLocalInertia(btScalar mass,btVector3& inertia) const + virtual void calculateLocalInertia(btScalar mass,btVector3& inertia) { btTransform identity; identity.setIdentity(); @@ -72,7 +72,7 @@ public: virtual int getShapeType() const { return CONE_SHAPE_PROXYTYPE; } - virtual const char* getName()const + virtual char* getName()const { return "Cone"; } diff --git a/extern/bullet2/src/BulletCollision/CollisionShapes/btConvexHullShape.h b/extern/bullet2/src/BulletCollision/CollisionShapes/btConvexHullShape.h index c029ca19403..3fd5e382525 100644 --- a/extern/bullet2/src/BulletCollision/CollisionShapes/btConvexHullShape.h +++ b/extern/bullet2/src/BulletCollision/CollisionShapes/btConvexHullShape.h @@ -17,17 +17,18 @@ subject to the following restrictions: #define CONVEX_HULL_SHAPE_H #include "btPolyhedralConvexShape.h" -#include "BulletCollision/BroadphaseCollision/btBroadphaseProxy.h" // for the types -#include "LinearMath/btAlignedObjectArray.h" +#include "../BroadphaseCollision/btBroadphaseProxy.h" // for the types +#include "../../LinearMath/btAlignedObjectArray.h" -///The btConvexHullShape implements an implicit convex hull of an array of vertices. -///Bullet provides a general and fast collision detector for convex shapes based on GJK and EPA using localGetSupportingVertex. +///ConvexHullShape implements an implicit (getSupportingVertex) Convex Hull of a Point Cloud (vertices) +///No connectivity is needed. localGetSupportingVertex iterates linearly though all vertices. +///on modern hardware, due to cache coherency this isn't that bad. Complex algorithms tend to trash the cash. +///(memory is much slower then the cpu) ATTRIBUTE_ALIGNED16(class) btConvexHullShape : public btPolyhedralConvexShape { btAlignedObjectArray m_points; public: - BT_DECLARE_ALIGNED_ALLOCATOR(); ///this constructor optionally takes in a pointer to points. Each point is assumed to be 3 consecutive btScalar (x,y,z), the striding defines the number of bytes between each point, in memory. @@ -42,12 +43,7 @@ public: return &m_points[0]; } - const btPoint3* getPoints() const - { - return &m_points[0]; - } - - int getNumPoints() const + int getNumPoints() { return m_points.size(); } @@ -60,7 +56,7 @@ public: virtual int getShapeType()const { return CONVEX_HULL_SHAPE_PROXYTYPE; } //debugging - virtual const char* getName()const {return "Convex";} + virtual char* getName()const {return "Convex";} virtual int getNumVertices() const; diff --git a/extern/bullet2/src/BulletCollision/CollisionShapes/btConvexInternalShape.cpp b/extern/bullet2/src/BulletCollision/CollisionShapes/btConvexInternalShape.cpp deleted file mode 100644 index f828d28e18c..00000000000 --- a/extern/bullet2/src/BulletCollision/CollisionShapes/btConvexInternalShape.cpp +++ /dev/null @@ -1,78 +0,0 @@ -/* -Bullet Continuous Collision Detection and Physics Library -Copyright (c) 2003-2006 Erwin Coumans http://continuousphysics.com/Bullet/ - -This software is provided 'as-is', without any express or implied warranty. -In no event will the authors be held liable for any damages arising from the use of this software. -Permission is granted to anyone to use this software for any purpose, -including commercial applications, and to alter it and redistribute it freely, -subject to the following restrictions: - -1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. -2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. -3. This notice may not be removed or altered from any source distribution. -*/ - - -#include "btConvexInternalShape.h" - - -btConvexInternalShape::btConvexInternalShape() -: m_localScaling(btScalar(1.),btScalar(1.),btScalar(1.)), -m_collisionMargin(CONVEX_DISTANCE_MARGIN) -{ -} - - -void btConvexInternalShape::setLocalScaling(const btVector3& scaling) -{ - m_localScaling = scaling; -} - - - -void btConvexInternalShape::getAabbSlow(const btTransform& trans,btVector3&minAabb,btVector3&maxAabb) const -{ - - btScalar margin = getMargin(); - for (int i=0;i<3;i++) - { - btVector3 vec(btScalar(0.),btScalar(0.),btScalar(0.)); - vec[i] = btScalar(1.); - - btVector3 sv = localGetSupportingVertex(vec*trans.getBasis()); - - btVector3 tmp = trans(sv); - maxAabb[i] = tmp[i]+margin; - vec[i] = btScalar(-1.); - tmp = trans(localGetSupportingVertex(vec*trans.getBasis())); - minAabb[i] = tmp[i]-margin; - } -}; - - -btVector3 btConvexInternalShape::localGetSupportingVertex(const btVector3& vec)const -{ -#ifndef __SPU__ - - btVector3 supVertex = localGetSupportingVertexWithoutMargin(vec); - - if ( getMargin()!=btScalar(0.) ) - { - btVector3 vecnorm = vec; - if (vecnorm .length2() < (SIMD_EPSILON*SIMD_EPSILON)) - { - vecnorm.setValue(btScalar(-1.),btScalar(-1.),btScalar(-1.)); - } - vecnorm.normalize(); - supVertex+= getMargin() * vecnorm; - } - return supVertex; - -#else - return btVector3(0,0,0); -#endif //__SPU__ - - } - - diff --git a/extern/bullet2/src/BulletCollision/CollisionShapes/btConvexInternalShape.h b/extern/bullet2/src/BulletCollision/CollisionShapes/btConvexInternalShape.h deleted file mode 100644 index 9388ccf31f2..00000000000 --- a/extern/bullet2/src/BulletCollision/CollisionShapes/btConvexInternalShape.h +++ /dev/null @@ -1,98 +0,0 @@ - -#ifndef BT_CONVEX_INTERNAL_SHAPE_H -#define BT_CONVEX_INTERNAL_SHAPE_H - -#include "btConvexShape.h" - -///The btConvexInternalShape is an internal base class, shared by most convex shape implementations. -class btConvexInternalShape : public btConvexShape -{ - - protected: - - //local scaling. collisionMargin is not scaled ! - btVector3 m_localScaling; - - btVector3 m_implicitShapeDimensions; - - btScalar m_collisionMargin; - - btScalar m_padding; - -public: - - btConvexInternalShape(); - - virtual ~btConvexInternalShape() - { - - } - - - virtual btVector3 localGetSupportingVertex(const btVector3& vec)const; -#ifndef __SPU__ - virtual btVector3 localGetSupportingVertexWithoutMargin(const btVector3& vec) const= 0; - - //notice that the vectors should be unit length - virtual void batchedUnitVectorGetSupportingVertexWithoutMargin(const btVector3* vectors,btVector3* supportVerticesOut,int numVectors) const= 0; -#endif //#ifndef __SPU__ - - const btVector3& getImplicitShapeDimensions() const - { - return m_implicitShapeDimensions; - } - - ///getAabb's default implementation is brute force, expected derived classes to implement a fast dedicated version - void getAabb(const btTransform& t,btVector3& aabbMin,btVector3& aabbMax) const - { - getAabbSlow(t,aabbMin,aabbMax); - } - - - - virtual void getAabbSlow(const btTransform& t,btVector3& aabbMin,btVector3& aabbMax) const; - - - virtual void setLocalScaling(const btVector3& scaling); - virtual const btVector3& getLocalScaling() const - { - return m_localScaling; - } - - const btVector3& getLocalScalingNV() const - { - return m_localScaling; - } - - virtual void setMargin(btScalar margin) - { - m_collisionMargin = margin; - } - virtual btScalar getMargin() const - { - return m_collisionMargin; - } - - btScalar getMarginNV() const - { - return m_collisionMargin; - } - - virtual int getNumPreferredPenetrationDirections() const - { - return 0; - } - - virtual void getPreferredPenetrationDirection(int index, btVector3& penetrationVector) const - { - (void)penetrationVector; - (void)index; - btAssert(0); - } - - - -}; - - -#endif //BT_CONVEX_INTERNAL_SHAPE_H diff --git a/extern/bullet2/src/BulletCollision/CollisionShapes/btConvexShape.cpp b/extern/bullet2/src/BulletCollision/CollisionShapes/btConvexShape.cpp index 7afcccf8b03..7edf1ea6db8 100644 --- a/extern/bullet2/src/BulletCollision/CollisionShapes/btConvexShape.cpp +++ b/extern/bullet2/src/BulletCollision/CollisionShapes/btConvexShape.cpp @@ -16,3 +16,62 @@ subject to the following restrictions: #include "btConvexShape.h" +btConvexShape::btConvexShape() +: m_localScaling(btScalar(1.),btScalar(1.),btScalar(1.)), +m_collisionMargin(CONVEX_DISTANCE_MARGIN) +{ +} + + +void btConvexShape::setLocalScaling(const btVector3& scaling) +{ + m_localScaling = scaling; +} + + + +void btConvexShape::getAabbSlow(const btTransform& trans,btVector3&minAabb,btVector3&maxAabb) const +{ + + btScalar margin = getMargin(); + for (int i=0;i<3;i++) + { + btVector3 vec(btScalar(0.),btScalar(0.),btScalar(0.)); + vec[i] = btScalar(1.); + + btVector3 sv = localGetSupportingVertex(vec*trans.getBasis()); + + btVector3 tmp = trans(sv); + maxAabb[i] = tmp[i]+margin; + vec[i] = btScalar(-1.); + tmp = trans(localGetSupportingVertex(vec*trans.getBasis())); + minAabb[i] = tmp[i]-margin; + } +}; + + +btVector3 btConvexShape::localGetSupportingVertex(const btVector3& vec)const +{ +#ifndef __SPU__ + + btVector3 supVertex = localGetSupportingVertexWithoutMargin(vec); + + if ( getMargin()!=btScalar(0.) ) + { + btVector3 vecnorm = vec; + if (vecnorm .length2() < (SIMD_EPSILON*SIMD_EPSILON)) + { + vecnorm.setValue(btScalar(-1.),btScalar(-1.),btScalar(-1.)); + } + vecnorm.normalize(); + supVertex+= getMargin() * vecnorm; + } + return supVertex; + +#else + return btVector3(0,0,0); +#endif //__SPU__ + + } + + diff --git a/extern/bullet2/src/BulletCollision/CollisionShapes/btConvexShape.h b/extern/bullet2/src/BulletCollision/CollisionShapes/btConvexShape.h index e4eb7f6dbf6..746f383dfc7 100644 --- a/extern/bullet2/src/BulletCollision/CollisionShapes/btConvexShape.h +++ b/extern/bullet2/src/BulletCollision/CollisionShapes/btConvexShape.h @@ -18,25 +18,37 @@ subject to the following restrictions: #include "btCollisionShape.h" -#include "LinearMath/btVector3.h" -#include "LinearMath/btTransform.h" -#include "LinearMath/btMatrix3x3.h" +#include "../../LinearMath/btVector3.h" +#include "../../LinearMath/btTransform.h" +#include "../../LinearMath/btMatrix3x3.h" #include "btCollisionMargin.h" -#include "LinearMath/btAlignedAllocator.h" //todo: get rid of this btConvexCastResult thing! struct btConvexCastResult; #define MAX_PREFERRED_PENETRATION_DIRECTIONS 10 -/// The btConvexShape is an abstract shape interface, implemented by all convex shapes such as btBoxShape, btConvexHullShape etc. -/// It describes general convex shapes using the localGetSupportingVertex interface, used by collision detectors such as btGjkPairDetector. +/// btConvexShape is an abstract shape interface. +/// The explicit part provides plane-equations, the implicit part provides GetClosestPoint interface. +/// used in combination with GJK or btConvexCast ATTRIBUTE_ALIGNED16(class) btConvexShape : public btCollisionShape { +protected: + + //local scaling. collisionMargin is not scaled ! + btVector3 m_localScaling; + + btVector3 m_implicitShapeDimensions; + + btScalar m_collisionMargin; + + btScalar m_padding[2]; + + + public: - - BT_DECLARE_ALIGNED_ALLOCATOR(); + btConvexShape(); virtual ~btConvexShape() { @@ -44,7 +56,7 @@ public: } - virtual btVector3 localGetSupportingVertex(const btVector3& vec)const =0; + virtual btVector3 localGetSupportingVertex(const btVector3& vec)const; #ifndef __SPU__ virtual btVector3 localGetSupportingVertexWithoutMargin(const btVector3& vec) const= 0; @@ -52,24 +64,63 @@ public: virtual void batchedUnitVectorGetSupportingVertexWithoutMargin(const btVector3* vectors,btVector3* supportVerticesOut,int numVectors) const= 0; #endif //#ifndef __SPU__ + const btVector3& getImplicitShapeDimensions() const + { + return m_implicitShapeDimensions; + } ///getAabb's default implementation is brute force, expected derived classes to implement a fast dedicated version - void getAabb(const btTransform& t,btVector3& aabbMin,btVector3& aabbMax) const =0; + void getAabb(const btTransform& t,btVector3& aabbMin,btVector3& aabbMax) const + { + getAabbSlow(t,aabbMin,aabbMax); + } - virtual void getAabbSlow(const btTransform& t,btVector3& aabbMin,btVector3& aabbMax) const =0; - virtual void setLocalScaling(const btVector3& scaling) =0; - virtual const btVector3& getLocalScaling() const =0; - - virtual void setMargin(btScalar margin)=0; - - virtual btScalar getMargin() const=0; - - virtual int getNumPreferredPenetrationDirections() const=0; - virtual void getPreferredPenetrationDirection(int index, btVector3& penetrationVector) const=0; + virtual void getAabbSlow(const btTransform& t,btVector3& aabbMin,btVector3& aabbMax) const; -}; + + virtual void setLocalScaling(const btVector3& scaling); + virtual const btVector3& getLocalScaling() const + { + return m_localScaling; + } + + const btVector3& getLocalScalingNV() const + { + return m_localScaling; + } + + virtual void setMargin(btScalar margin) + { + m_collisionMargin = margin; + } + virtual btScalar getMargin() const + { + return m_collisionMargin; + } + + btScalar getMarginNV() const + { + return m_collisionMargin; + } + + virtual int getNumPreferredPenetrationDirections() const + { + return 0; + } + + virtual void getPreferredPenetrationDirection(int index, btVector3& penetrationVector) const + { + (void)penetrationVector; + (void)index; + btAssert(0); + } + + + +} +; diff --git a/extern/bullet2/src/BulletCollision/CollisionShapes/btConvexTriangleMeshShape.cpp b/extern/bullet2/src/BulletCollision/CollisionShapes/btConvexTriangleMeshShape.cpp index f1682aaf65b..6941030b15f 100644 --- a/extern/bullet2/src/BulletCollision/CollisionShapes/btConvexTriangleMeshShape.cpp +++ b/extern/bullet2/src/BulletCollision/CollisionShapes/btConvexTriangleMeshShape.cpp @@ -19,11 +19,10 @@ subject to the following restrictions: #include "BulletCollision/CollisionShapes/btStridingMeshInterface.h" -btConvexTriangleMeshShape ::btConvexTriangleMeshShape (btStridingMeshInterface* meshInterface, bool calcAabb) +btConvexTriangleMeshShape ::btConvexTriangleMeshShape (btStridingMeshInterface* meshInterface) :m_stridingMesh(meshInterface) { - if ( calcAabb ) - recalcLocalAabb(); + recalcLocalAabb(); } diff --git a/extern/bullet2/src/BulletCollision/CollisionShapes/btConvexTriangleMeshShape.h b/extern/bullet2/src/BulletCollision/CollisionShapes/btConvexTriangleMeshShape.h index 01eecf27811..34ee7af744c 100644 --- a/extern/bullet2/src/BulletCollision/CollisionShapes/btConvexTriangleMeshShape.h +++ b/extern/bullet2/src/BulletCollision/CollisionShapes/btConvexTriangleMeshShape.h @@ -3,24 +3,20 @@ #include "btPolyhedralConvexShape.h" -#include "BulletCollision/BroadphaseCollision/btBroadphaseProxy.h" // for the types +#include "../BroadphaseCollision/btBroadphaseProxy.h" // for the types -/// The btConvexTriangleMeshShape is a convex hull of a triangle mesh, but the performance is not as good as btConvexHullShape. -/// A small benefit of this class is that it uses the btStridingMeshInterface, so you can avoid the duplication of the triangle mesh data. Nevertheless, most users should use the much better performing btConvexHullShape instead. +/// btConvexTriangleMeshShape is a convex hull of a triangle mesh. If you just have a point cloud, you can use btConvexHullShape instead. +/// It uses the btStridingMeshInterface instead of a point cloud. This can avoid the duplication of the triangle mesh data. class btConvexTriangleMeshShape : public btPolyhedralConvexShape { class btStridingMeshInterface* m_stridingMesh; public: - btConvexTriangleMeshShape(btStridingMeshInterface* meshInterface, bool calcAabb = true); + btConvexTriangleMeshShape(btStridingMeshInterface* meshInterface); - class btStridingMeshInterface* getMeshInterface() - { - return m_stridingMesh; - } - const class btStridingMeshInterface* getMeshInterface() const + class btStridingMeshInterface* getStridingMesh() { return m_stridingMesh; } @@ -32,7 +28,7 @@ public: virtual int getShapeType()const { return CONVEX_TRIANGLEMESH_SHAPE_PROXYTYPE; } //debugging - virtual const char* getName()const {return "ConvexTrimesh";} + virtual char* getName()const {return "ConvexTrimesh";} virtual int getNumVertices() const; virtual int getNumEdges() const; @@ -53,4 +49,3 @@ public: #endif //CONVEX_TRIANGLEMESH_SHAPE_H - diff --git a/extern/bullet2/src/BulletCollision/CollisionShapes/btCylinderShape.cpp b/extern/bullet2/src/BulletCollision/CollisionShapes/btCylinderShape.cpp index 3afef1c7550..1666afb3b88 100644 --- a/extern/bullet2/src/BulletCollision/CollisionShapes/btCylinderShape.cpp +++ b/extern/bullet2/src/BulletCollision/CollisionShapes/btCylinderShape.cpp @@ -45,7 +45,7 @@ void btCylinderShape::getAabb(const btTransform& t,btVector3& aabbMin,btVector3& } -SIMD_FORCE_INLINE btVector3 CylinderLocalSupportX(const btVector3& halfExtents,const btVector3& v) +inline btVector3 CylinderLocalSupportX(const btVector3& halfExtents,const btVector3& v) { const int cylinderUpAxis = 0; const int XX = 1; @@ -163,24 +163,24 @@ const int ZZ = 1; btVector3 btCylinderShapeX::localGetSupportingVertexWithoutMargin(const btVector3& vec)const { - return CylinderLocalSupportX(getHalfExtentsWithoutMargin(),vec); + return CylinderLocalSupportX(getHalfExtents(),vec); } btVector3 btCylinderShapeZ::localGetSupportingVertexWithoutMargin(const btVector3& vec)const { - return CylinderLocalSupportZ(getHalfExtentsWithoutMargin(),vec); + return CylinderLocalSupportZ(getHalfExtents(),vec); } btVector3 btCylinderShape::localGetSupportingVertexWithoutMargin(const btVector3& vec)const { - return CylinderLocalSupportY(getHalfExtentsWithoutMargin(),vec); + return CylinderLocalSupportY(getHalfExtents(),vec); } void btCylinderShape::batchedUnitVectorGetSupportingVertexWithoutMargin(const btVector3* vectors,btVector3* supportVerticesOut,int numVectors) const { for (int i=0;i=0); btAssert(y>=0); - btAssert(xstartX) startX = quantizedAabbMin[1]; @@ -244,10 +243,10 @@ void btHeightfieldTerrainShape::processAllTriangles(btTriangleCallback* callback } case 1: { - quantizedAabbMin[0]+=m_heightStickWidth/2-1; - quantizedAabbMax[0]+=m_heightStickWidth/2+1; - quantizedAabbMin[2]+=m_heightStickLength/2-1; - quantizedAabbMax[2]+=m_heightStickLength/2+1; + quantizedAabbMin[0]+=m_width/2-1; + quantizedAabbMax[0]+=m_width/2+1; + quantizedAabbMin[2]+=m_length/2-1; + quantizedAabbMax[2]+=m_length/2+1; if (quantizedAabbMin[0]>startX) startX = quantizedAabbMin[0]; @@ -261,10 +260,10 @@ void btHeightfieldTerrainShape::processAllTriangles(btTriangleCallback* callback }; case 2: { - quantizedAabbMin[0]+=m_heightStickWidth/2-1; - quantizedAabbMax[0]+=m_heightStickWidth/2+1; - quantizedAabbMin[1]+=m_heightStickLength/2-1; - quantizedAabbMax[1]+=m_heightStickLength/2+1; + quantizedAabbMin[0]+=m_width/2-1; + quantizedAabbMax[0]+=m_width/2+1; + quantizedAabbMin[1]+=m_length/2-1; + quantizedAabbMax[1]+=m_length/2+1; if (quantizedAabbMin[0]>startX) startX = quantizedAabbMin[0]; @@ -291,7 +290,7 @@ void btHeightfieldTerrainShape::processAllTriangles(btTriangleCallback* callback for(int x=startX; xlocalGetSupportingVertexWithoutMargin(-vec*m_transA.getBasis())); + btVector3 supVertexA = m_transA(m_shapeA->localGetSupportingVertexWithoutMargin(vec*m_transA.getBasis())); btVector3 supVertexB = m_transB(m_shapeB->localGetSupportingVertexWithoutMargin(vec*m_transB.getBasis())); - return supVertexA - supVertexB; + return supVertexA + supVertexB; } void btMinkowskiSumShape::batchedUnitVectorGetSupportingVertexWithoutMargin(const btVector3* vectors,btVector3* supportVerticesOut,int numVectors) const @@ -49,7 +49,7 @@ btScalar btMinkowskiSumShape::getMargin() const } -void btMinkowskiSumShape::calculateLocalInertia(btScalar mass,btVector3& inertia) const +void btMinkowskiSumShape::calculateLocalInertia(btScalar mass,btVector3& inertia) { (void)mass; btAssert(0); diff --git a/extern/bullet2/src/BulletCollision/CollisionShapes/btMinkowskiSumShape.h b/extern/bullet2/src/BulletCollision/CollisionShapes/btMinkowskiSumShape.h index f9c8427c2f3..198faaff9f9 100644 --- a/extern/bullet2/src/BulletCollision/CollisionShapes/btMinkowskiSumShape.h +++ b/extern/bullet2/src/BulletCollision/CollisionShapes/btMinkowskiSumShape.h @@ -16,11 +16,11 @@ subject to the following restrictions: #ifndef MINKOWSKI_SUM_SHAPE_H #define MINKOWSKI_SUM_SHAPE_H -#include "btConvexInternalShape.h" -#include "BulletCollision/BroadphaseCollision/btBroadphaseProxy.h" // for the types +#include "btConvexShape.h" +#include "../BroadphaseCollision/btBroadphaseProxy.h" // for the types -/// The btMinkowskiSumShape is only for advanced users. This shape represents implicit based minkowski sum of two convex implicit shapes. -class btMinkowskiSumShape : public btConvexInternalShape +/// btMinkowskiSumShape represents implicit (getSupportingVertex) based minkowski sum of two convex implicit shapes. +class btMinkowskiSumShape : public btConvexShape { btTransform m_transA; @@ -37,7 +37,7 @@ public: virtual void batchedUnitVectorGetSupportingVertexWithoutMargin(const btVector3* vectors,btVector3* supportVerticesOut,int numVectors) const; - virtual void calculateLocalInertia(btScalar mass,btVector3& inertia) const; + virtual void calculateLocalInertia(btScalar mass,btVector3& inertia); void setTransformA(const btTransform& transA) { m_transA = transA;} void setTransformB(const btTransform& transB) { m_transB = transB;} @@ -53,7 +53,7 @@ public: const btConvexShape* getShapeA() const { return m_shapeA;} const btConvexShape* getShapeB() const { return m_shapeB;} - virtual const char* getName()const + virtual char* getName()const { return "MinkowskiSum"; } diff --git a/extern/bullet2/src/BulletCollision/CollisionShapes/btMultiSphereShape.cpp b/extern/bullet2/src/BulletCollision/CollisionShapes/btMultiSphereShape.cpp index c709205efc2..6015a618082 100644 --- a/extern/bullet2/src/BulletCollision/CollisionShapes/btMultiSphereShape.cpp +++ b/extern/bullet2/src/BulletCollision/CollisionShapes/btMultiSphereShape.cpp @@ -47,7 +47,7 @@ btMultiSphereShape::btMultiSphereShape (const btVector3& inertiaHalfExtents,cons btVector3 vec = vec0; btScalar lenSqr = vec.length2(); - if (lenSqr < (SIMD_EPSILON*SIMD_EPSILON)) + if (lenSqr < btScalar(0.0001)) { vec.setValue(1,0,0); } else @@ -116,7 +116,7 @@ btMultiSphereShape::btMultiSphereShape (const btVector3& inertiaHalfExtents,cons -void btMultiSphereShape::calculateLocalInertia(btScalar mass,btVector3& inertia) const +void btMultiSphereShape::calculateLocalInertia(btScalar mass,btVector3& inertia) { //as an approximation, take the inertia of the box that bounds the spheres diff --git a/extern/bullet2/src/BulletCollision/CollisionShapes/btMultiSphereShape.h b/extern/bullet2/src/BulletCollision/CollisionShapes/btMultiSphereShape.h index 45968f3947f..1897b474057 100644 --- a/extern/bullet2/src/BulletCollision/CollisionShapes/btMultiSphereShape.h +++ b/extern/bullet2/src/BulletCollision/CollisionShapes/btMultiSphereShape.h @@ -16,14 +16,13 @@ subject to the following restrictions: #ifndef MULTI_SPHERE_MINKOWSKI_H #define MULTI_SPHERE_MINKOWSKI_H -#include "btConvexInternalShape.h" -#include "BulletCollision/BroadphaseCollision/btBroadphaseProxy.h" // for the types +#include "btConvexShape.h" +#include "../BroadphaseCollision/btBroadphaseProxy.h" // for the types #define MAX_NUM_SPHERES 5 -///The btMultiSphereShape represents the convex hull of a collection of spheres. You can create special capsules or other smooth volumes. -///It is possible to animate the spheres for deformation. -class btMultiSphereShape : public btConvexInternalShape +///btMultiSphereShape represents implicit convex hull of a collection of spheres (using getSupportingVertex) +class btMultiSphereShape : public btConvexShape { @@ -40,7 +39,7 @@ public: btMultiSphereShape (const btVector3& inertiaHalfExtents,const btVector3* positions,const btScalar* radi,int numSpheres); ///CollisionShape Interface - virtual void calculateLocalInertia(btScalar mass,btVector3& inertia) const; + virtual void calculateLocalInertia(btScalar mass,btVector3& inertia); /// btConvexShape Interface virtual btVector3 localGetSupportingVertexWithoutMargin(const btVector3& vec)const; @@ -64,7 +63,7 @@ public: virtual int getShapeType() const { return MULTI_SPHERE_SHAPE_PROXYTYPE; } - virtual const char* getName()const + virtual char* getName()const { return "MultiSphere"; } diff --git a/extern/bullet2/src/BulletCollision/CollisionShapes/btMultimaterialTriangleMeshShape.cpp b/extern/bullet2/src/BulletCollision/CollisionShapes/btMultimaterialTriangleMeshShape.cpp deleted file mode 100644 index fc47e86411d..00000000000 --- a/extern/bullet2/src/BulletCollision/CollisionShapes/btMultimaterialTriangleMeshShape.cpp +++ /dev/null @@ -1,45 +0,0 @@ -/* -Bullet Continuous Collision Detection and Physics Library -Copyright (c) 2003-2008 Erwin Coumans http://continuousphysics.com/Bullet/ - -This software is provided 'as-is', without any express or implied warranty. -In no event will the authors be held liable for any damages arising from the use of this software. -Permission is granted to anyone to use this software for any purpose, -including commercial applications, and to alter it and redistribute it freely, -subject to the following restrictions: - -1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. -2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. -3. This notice may not be removed or altered from any source distribution. -*/ - -/// This file was created by Alex Silverman - -#include "BulletCollision/CollisionShapes/btMultimaterialTriangleMeshShape.h" -#include "BulletCollision/CollisionShapes/btTriangleIndexVertexMaterialArray.h" -//#include "BulletCollision/CollisionShapes/btOptimizedBvh.h" - - -///Obtains the material for a specific triangle -const btMaterial * btMultimaterialTriangleMeshShape::getMaterialProperties(int partID, int triIndex) -{ - const unsigned char * materialBase = 0; - int numMaterials; - PHY_ScalarType materialType; - int materialStride; - const unsigned char * triangleMaterialBase = 0; - int numTriangles; - int triangleMaterialStride; - PHY_ScalarType triangleType; - - ((btTriangleIndexVertexMaterialArray*)m_meshInterface)->getLockedReadOnlyMaterialBase(&materialBase, numMaterials, materialType, materialStride, - &triangleMaterialBase, numTriangles, triangleMaterialStride, triangleType, partID); - - // return the pointer to the place with the friction for the triangle - // TODO: This depends on whether it's a moving mesh or not - // BUG IN GIMPACT - //return (btScalar*)(&materialBase[triangleMaterialBase[(triIndex-1) * triangleMaterialStride] * materialStride]); - int * matInd = (int *)(&(triangleMaterialBase[(triIndex * triangleMaterialStride)])); - btMaterial *matVal = (btMaterial *)(&(materialBase[*matInd * materialStride])); - return (matVal); -} diff --git a/extern/bullet2/src/BulletCollision/CollisionShapes/btMultimaterialTriangleMeshShape.h b/extern/bullet2/src/BulletCollision/CollisionShapes/btMultimaterialTriangleMeshShape.h deleted file mode 100644 index 2f108020cdf..00000000000 --- a/extern/bullet2/src/BulletCollision/CollisionShapes/btMultimaterialTriangleMeshShape.h +++ /dev/null @@ -1,124 +0,0 @@ -/* -Bullet Continuous Collision Detection and Physics Library -Copyright (c) 2003-2008 Erwin Coumans http://continuousphysics.com/Bullet/ - -This software is provided 'as-is', without any express or implied warranty. -In no event will the authors be held liable for any damages arising from the use of this software. -Permission is granted to anyone to use this software for any purpose, -including commercial applications, and to alter it and redistribute it freely, -subject to the following restrictions: - -1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. -2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. -3. This notice may not be removed or altered from any source distribution. -*/ - -/// This file was created by Alex Silverman - -#ifndef BVH_TRIANGLE_MATERIAL_MESH_SHAPE_H -#define BVH_TRIANGLE_MATERIAL_MESH_SHAPE_H - -#include "btBvhTriangleMeshShape.h" -#include "btMaterial.h" - -///The BvhTriangleMaterialMeshShape extends the btBvhTriangleMeshShape. Its main contribution is the interface into a material array, which allows per-triangle friction and restitution. -ATTRIBUTE_ALIGNED16(class) btMultimaterialTriangleMeshShape : public btBvhTriangleMeshShape -{ - btAlignedObjectArray m_materialList; - int ** m_triangleMaterials; - -public: - - BT_DECLARE_ALIGNED_ALLOCATOR(); - - btMultimaterialTriangleMeshShape(): btBvhTriangleMeshShape() {} - btMultimaterialTriangleMeshShape(btStridingMeshInterface* meshInterface, bool useQuantizedAabbCompression, bool buildBvh = true): - btBvhTriangleMeshShape(meshInterface, useQuantizedAabbCompression, buildBvh) - { - btVector3 m_triangle[3]; - const unsigned char *vertexbase; - int numverts; - PHY_ScalarType type; - int stride; - const unsigned char *indexbase; - int indexstride; - int numfaces; - PHY_ScalarType indicestype; - - //m_materialLookup = (int**)(btAlignedAlloc(sizeof(int*) * meshInterface->getNumSubParts(), 16)); - - for(int i = 0; i < meshInterface->getNumSubParts(); i++) - { - m_meshInterface->getLockedReadOnlyVertexIndexBase( - &vertexbase, - numverts, - type, - stride, - &indexbase, - indexstride, - numfaces, - indicestype, - i); - //m_materialLookup[i] = (int*)(btAlignedAlloc(sizeof(int) * numfaces, 16)); - } - } - - ///optionally pass in a larger bvh aabb, used for quantization. This allows for deformations within this aabb - btMultimaterialTriangleMeshShape(btStridingMeshInterface* meshInterface, bool useQuantizedAabbCompression,const btVector3& bvhAabbMin,const btVector3& bvhAabbMax, bool buildBvh = true): - btBvhTriangleMeshShape(meshInterface, useQuantizedAabbCompression, bvhAabbMin, bvhAabbMax, buildBvh) - { - btVector3 m_triangle[3]; - const unsigned char *vertexbase; - int numverts; - PHY_ScalarType type; - int stride; - const unsigned char *indexbase; - int indexstride; - int numfaces; - PHY_ScalarType indicestype; - - //m_materialLookup = (int**)(btAlignedAlloc(sizeof(int*) * meshInterface->getNumSubParts(), 16)); - - for(int i = 0; i < meshInterface->getNumSubParts(); i++) - { - m_meshInterface->getLockedReadOnlyVertexIndexBase( - &vertexbase, - numverts, - type, - stride, - &indexbase, - indexstride, - numfaces, - indicestype, - i); - //m_materialLookup[i] = (int*)(btAlignedAlloc(sizeof(int) * numfaces * 2, 16)); - } - } - - virtual ~btMultimaterialTriangleMeshShape() - { -/* - for(int i = 0; i < m_meshInterface->getNumSubParts(); i++) - { - btAlignedFree(m_materialValues[i]); - m_materialLookup[i] = NULL; - } - btAlignedFree(m_materialValues); - m_materialLookup = NULL; -*/ - } - virtual int getShapeType() const - { - return MULTIMATERIAL_TRIANGLE_MESH_PROXYTYPE; - } - - //debugging - virtual const char* getName()const {return "MULTIMATERIALTRIANGLEMESH";} - - ///Obtains the material for a specific triangle - const btMaterial * getMaterialProperties(int partID, int triIndex); - -} -; - -#endif //BVH_TRIANGLE_MATERIAL_MESH_SHAPE_H diff --git a/extern/bullet2/src/BulletCollision/CollisionShapes/btOptimizedBvh.cpp b/extern/bullet2/src/BulletCollision/CollisionShapes/btOptimizedBvh.cpp index 9b78fc0f7c2..44438a24455 100644 --- a/extern/bullet2/src/BulletCollision/CollisionShapes/btOptimizedBvh.cpp +++ b/extern/bullet2/src/BulletCollision/CollisionShapes/btOptimizedBvh.cpp @@ -19,12 +19,13 @@ subject to the following restrictions: #include "LinearMath/btIDebugDraw.h" -btOptimizedBvh::btOptimizedBvh() -{ -} -btOptimizedBvh::~btOptimizedBvh() -{ +btOptimizedBvh::btOptimizedBvh() : m_useQuantization(false), + m_traversalMode(TRAVERSAL_STACKLESS_CACHE_FRIENDLY) + //m_traversalMode(TRAVERSAL_STACKLESS) + //m_traversalMode(TRAVERSAL_RECURSIVE) +{ + } @@ -79,7 +80,7 @@ void btOptimizedBvh::build(btStridingMeshInterface* triangles, bool useQuantized struct QuantizedNodeTriangleCallback : public btInternalTriangleIndexCallback { QuantizedNodeArray& m_triangleNodes; - const btQuantizedBvh* m_optimizedTree; // for quantization + const btOptimizedBvh* m_optimizedTree; // for quantization QuantizedNodeTriangleCallback& operator=(QuantizedNodeTriangleCallback& other) { @@ -88,16 +89,14 @@ void btOptimizedBvh::build(btStridingMeshInterface* triangles, bool useQuantized return *this; } - QuantizedNodeTriangleCallback(QuantizedNodeArray& triangleNodes,const btQuantizedBvh* tree) + QuantizedNodeTriangleCallback(QuantizedNodeArray& triangleNodes,const btOptimizedBvh* tree) :m_triangleNodes(triangleNodes),m_optimizedTree(tree) { } virtual void internalProcessTriangleIndex(btVector3* triangle,int partId,int triangleIndex) { - // The partId and triangle index must fit in the same (positive) integer - btAssert(partId < (1<=0); @@ -112,29 +111,10 @@ void btOptimizedBvh::build(btStridingMeshInterface* triangles, bool useQuantized aabbMin.setMin(triangle[2]); aabbMax.setMax(triangle[2]); - //PCK: add these checks for zero dimensions of aabb - const btScalar MIN_AABB_DIMENSION = btScalar(0.002); - const btScalar MIN_AABB_HALF_DIMENSION = btScalar(0.001); - if (aabbMax.x() - aabbMin.x() < MIN_AABB_DIMENSION) - { - aabbMax.setX(aabbMax.x() + MIN_AABB_HALF_DIMENSION); - aabbMin.setX(aabbMin.x() - MIN_AABB_HALF_DIMENSION); - } - if (aabbMax.y() - aabbMin.y() < MIN_AABB_DIMENSION) - { - aabbMax.setY(aabbMax.y() + MIN_AABB_HALF_DIMENSION); - aabbMin.setY(aabbMin.y() - MIN_AABB_HALF_DIMENSION); - } - if (aabbMax.z() - aabbMin.z() < MIN_AABB_DIMENSION) - { - aabbMax.setZ(aabbMax.z() + MIN_AABB_HALF_DIMENSION); - aabbMin.setZ(aabbMin.z() - MIN_AABB_HALF_DIMENSION); - } + m_optimizedTree->quantizeWithClamp(&node.m_quantizedAabbMin[0],aabbMin); + m_optimizedTree->quantizeWithClamp(&node.m_quantizedAabbMax[0],aabbMax); - m_optimizedTree->quantize(&node.m_quantizedAabbMin[0],aabbMin,0); - m_optimizedTree->quantize(&node.m_quantizedAabbMax[0],aabbMax,1); - - node.m_escapeIndexOrTriangleIndex = (partId<<(31-MAX_NUM_PARTS_IN_BITS)) | triangleIndex; + node.m_escapeIndexOrTriangleIndex = triangleIndex; m_triangleNodes.push_back(node); } @@ -190,45 +170,10 @@ void btOptimizedBvh::build(btStridingMeshInterface* triangles, bool useQuantized subtree.m_rootNodeIndex = 0; subtree.m_subtreeSize = m_quantizedContiguousNodes[0].isLeafNode() ? 1 : m_quantizedContiguousNodes[0].getEscapeIndex(); } - - //PCK: update the copy of the size - m_subtreeHeaderCount = m_SubtreeHeaders.size(); - - //PCK: clear m_quantizedLeafNodes and m_leafNodes, they are temporary - m_quantizedLeafNodes.clear(); - m_leafNodes.clear(); } - -void btOptimizedBvh::refit(btStridingMeshInterface* meshInterface,const btVector3& aabbMin,const btVector3& aabbMax) -{ - if (m_useQuantization) - { - - setQuantizationValues(aabbMin,aabbMax); - - updateBvhNodes(meshInterface,0,m_curNodeIndex,0); - - ///now update all subtree headers - - int i; - for (i=0;im_SubtreeHeaders.size();i++) { btBvhSubtreeInfo& subtree = m_SubtreeHeaders[i]; - //PCK: unsigned instead of bool - unsigned overlap = testQuantizedAabbAgainstQuantizedAabb(quantizedQueryAabbMin,quantizedQueryAabbMax,subtree.m_quantizedAabbMin,subtree.m_quantizedAabbMax); - if (overlap != 0) + bool overlap = testQuantizedAabbAgainstQuantizedAabb(quantizedQueryAabbMin,quantizedQueryAabbMax,subtree.m_quantizedAabbMin,subtree.m_quantizedAabbMax); + if (overlap) { updateBvhNodes(meshInterface,subtree.m_rootNodeIndex,subtree.m_rootNodeIndex+subtree.m_subtreeSize,i); @@ -268,23 +212,36 @@ void btOptimizedBvh::refitPartial(btStridingMeshInterface* meshInterface,const b } +///just for debugging, to visualize the individual patches/subtrees +#ifdef DEBUG_PATCH_COLORS +btVector3 color[4]= +{ + btVector3(255,0,0), + btVector3(0,255,0), + btVector3(0,0,255), + btVector3(0,255,255) +}; +#endif //DEBUG_PATCH_COLORS + + void btOptimizedBvh::updateBvhNodes(btStridingMeshInterface* meshInterface,int firstNode,int endNode,int index) { (void)index; btAssert(m_useQuantization); - int curNodeSubPart=-1; + int nodeSubPart=0; //get access info to trianglemesh data - const unsigned char *vertexbase = 0; - int numverts = 0; - PHY_ScalarType type = PHY_INTEGER; - int stride = 0; - const unsigned char *indexbase = 0; - int indexstride = 0; - int numfaces = 0; - PHY_ScalarType indicestype = PHY_INTEGER; + const unsigned char *vertexbase; + int numverts; + PHY_ScalarType type; + int stride; + const unsigned char *indexbase; + int indexstride; + int numfaces; + PHY_ScalarType indicestype; + meshInterface->getLockedReadOnlyVertexIndexBase(&vertexbase,numverts, type,stride,&indexbase,indexstride,numfaces,indicestype,nodeSubPart); btVector3 triangleVerts[3]; btVector3 aabbMin,aabbMax; @@ -299,24 +256,16 @@ void btOptimizedBvh::updateBvhNodes(btStridingMeshInterface* meshInterface,int f if (curNode.isLeafNode()) { //recalc aabb from triangle data - int nodeSubPart = curNode.getPartId(); int nodeTriangleIndex = curNode.getTriangleIndex(); - if (nodeSubPart != curNodeSubPart) - { - if (curNodeSubPart >= 0) - meshInterface->unLockReadOnlyVertexBase(curNodeSubPart); - meshInterface->getLockedReadOnlyVertexIndexBase(&vertexbase,numverts, type,stride,&indexbase,indexstride,numfaces,indicestype,nodeSubPart); - btAssert(indicestype==PHY_INTEGER||indicestype==PHY_SHORT); - } //triangles->getLockedReadOnlyVertexIndexBase(vertexBase,numVerts, - unsigned int* gfxbase = (unsigned int*)(indexbase+nodeTriangleIndex*indexstride); + int* gfxbase = (int*)(indexbase+nodeTriangleIndex*indexstride); for (int j=2;j>=0;j--) { - int graphicsindex = indicestype==PHY_SHORT?((unsigned short*)gfxbase)[j]:gfxbase[j]; + int graphicsindex = gfxbase[j]; btScalar* graphicsbase = (btScalar*)(vertexbase+graphicsindex*stride); #ifdef DEBUG_PATCH_COLORS btVector3 mycolor = color[index&3]; @@ -343,8 +292,8 @@ void btOptimizedBvh::updateBvhNodes(btStridingMeshInterface* meshInterface,int f aabbMin.setMin(triangleVerts[2]); aabbMax.setMax(triangleVerts[2]); - quantize(&curNode.m_quantizedAabbMin[0],aabbMin,0); - quantize(&curNode.m_quantizedAabbMax[0],aabbMax,1); + quantizeWithClamp(&curNode.m_quantizedAabbMin[0],aabbMin); + quantizeWithClamp(&curNode.m_quantizedAabbMax[0],aabbMax); } else { @@ -372,17 +321,525 @@ void btOptimizedBvh::updateBvhNodes(btStridingMeshInterface* meshInterface,int f } - if (curNodeSubPart >= 0) - meshInterface->unLockReadOnlyVertexBase(curNodeSubPart); + meshInterface->unLockReadOnlyVertexBase(nodeSubPart); } -///deSerializeInPlace loads and initializes a BVH from a buffer in memory 'in place' -btOptimizedBvh* btOptimizedBvh::deSerializeInPlace(void *i_alignedDataBuffer, unsigned int i_dataBufferSize, bool i_swapEndian) +void btOptimizedBvh::setQuantizationValues(const btVector3& bvhAabbMin,const btVector3& bvhAabbMax,btScalar quantizationMargin) { - btQuantizedBvh* bvh = btQuantizedBvh::deSerializeInPlace(i_alignedDataBuffer,i_dataBufferSize,i_swapEndian); - - //we don't add additional data so just do a static upcast - return static_cast(bvh); + //enlarge the AABB to avoid division by zero when initializing the quantization values + btVector3 clampValue(quantizationMargin,quantizationMargin,quantizationMargin); + m_bvhAabbMin = bvhAabbMin - clampValue; + m_bvhAabbMax = bvhAabbMax + clampValue; + btVector3 aabbSize = m_bvhAabbMax - m_bvhAabbMin; + m_bvhQuantization = btVector3(btScalar(65535.0),btScalar(65535.0),btScalar(65535.0)) / aabbSize; +} + + +void btOptimizedBvh::refit(btStridingMeshInterface* meshInterface) +{ + if (m_useQuantization) + { + //calculate new aabb + btVector3 aabbMin,aabbMax; + meshInterface->calculateAabbBruteForce(aabbMin,aabbMax); + + setQuantizationValues(aabbMin,aabbMax); + + updateBvhNodes(meshInterface,0,m_curNodeIndex,0); + + ///now update all subtree headers + + int i; + for (i=0;i gMaxStackDepth) + gMaxStackDepth = gStackDepth; +#endif //DEBUG_TREE_BUILDING + + + int splitAxis, splitIndex, i; + int numIndices =endIndex-startIndex; + int curIndex = m_curNodeIndex; + + assert(numIndices>0); + + if (numIndices==1) + { +#ifdef DEBUG_TREE_BUILDING + gStackDepth--; +#endif //DEBUG_TREE_BUILDING + + assignInternalNodeFromLeafNode(m_curNodeIndex,startIndex); + + m_curNodeIndex++; + return; + } + //calculate Best Splitting Axis and where to split it. Sort the incoming 'leafNodes' array within range 'startIndex/endIndex'. + + splitAxis = calcSplittingAxis(startIndex,endIndex); + + splitIndex = sortAndCalcSplittingIndex(startIndex,endIndex,splitAxis); + + int internalNodeIndex = m_curNodeIndex; + + setInternalNodeAabbMax(m_curNodeIndex,btVector3(btScalar(-1e30),btScalar(-1e30),btScalar(-1e30))); + setInternalNodeAabbMin(m_curNodeIndex,btVector3(btScalar(1e30),btScalar(1e30),btScalar(1e30))); + + for (i=startIndex;im_escapeIndex; + + int leftChildNodexIndex = m_curNodeIndex; + + //build left child tree + buildTree(startIndex,splitIndex); + + int rightChildNodexIndex = m_curNodeIndex; + //build right child tree + buildTree(splitIndex,endIndex); + +#ifdef DEBUG_TREE_BUILDING + gStackDepth--; +#endif //DEBUG_TREE_BUILDING + + int escapeIndex = m_curNodeIndex - curIndex; + + if (m_useQuantization) + { + //escapeIndex is the number of nodes of this subtree + const int sizeQuantizedNode =sizeof(btQuantizedBvhNode); + const int treeSizeInBytes = escapeIndex * sizeQuantizedNode; + if (treeSizeInBytes > MAX_SUBTREE_SIZE_IN_BYTES) + { + updateSubtreeHeaders(leftChildNodexIndex,rightChildNodexIndex); + } + } + + setInternalNodeEscapeIndex(internalNodeIndex,escapeIndex); + +} + +void btOptimizedBvh::updateSubtreeHeaders(int leftChildNodexIndex,int rightChildNodexIndex) +{ + btAssert(m_useQuantization); + + btQuantizedBvhNode& leftChildNode = m_quantizedContiguousNodes[leftChildNodexIndex]; + int leftSubTreeSize = leftChildNode.isLeafNode() ? 1 : leftChildNode.getEscapeIndex(); + int leftSubTreeSizeInBytes = leftSubTreeSize * sizeof(btQuantizedBvhNode); + + btQuantizedBvhNode& rightChildNode = m_quantizedContiguousNodes[rightChildNodexIndex]; + int rightSubTreeSize = rightChildNode.isLeafNode() ? 1 : rightChildNode.getEscapeIndex(); + int rightSubTreeSizeInBytes = rightSubTreeSize * sizeof(btQuantizedBvhNode); + + if(leftSubTreeSizeInBytes <= MAX_SUBTREE_SIZE_IN_BYTES) + { + btBvhSubtreeInfo& subtree = m_SubtreeHeaders.expand(); + subtree.setAabbFromQuantizeNode(leftChildNode); + subtree.m_rootNodeIndex = leftChildNodexIndex; + subtree.m_subtreeSize = leftSubTreeSize; + } + + if(rightSubTreeSizeInBytes <= MAX_SUBTREE_SIZE_IN_BYTES) + { + btBvhSubtreeInfo& subtree = m_SubtreeHeaders.expand(); + subtree.setAabbFromQuantizeNode(rightChildNode); + subtree.m_rootNodeIndex = rightChildNodexIndex; + subtree.m_subtreeSize = rightSubTreeSize; + } +} + + +int btOptimizedBvh::sortAndCalcSplittingIndex(int startIndex,int endIndex,int splitAxis) +{ + int i; + int splitIndex =startIndex; + int numIndices = endIndex - startIndex; + btScalar splitValue; + + btVector3 means(btScalar(0.),btScalar(0.),btScalar(0.)); + for (i=startIndex;i splitValue) + { + //swap + swapLeafNodes(i,splitIndex); + splitIndex++; + } + } + + //if the splitIndex causes unbalanced trees, fix this by using the center in between startIndex and endIndex + //otherwise the tree-building might fail due to stack-overflows in certain cases. + //unbalanced1 is unsafe: it can cause stack overflows + //bool unbalanced1 = ((splitIndex==startIndex) || (splitIndex == (endIndex-1))); + + //unbalanced2 should work too: always use center (perfect balanced trees) + //bool unbalanced2 = true; + + //this should be safe too: + int rangeBalancedIndices = numIndices/3; + bool unbalanced = ((splitIndex<=(startIndex+rangeBalancedIndices)) || (splitIndex >=(endIndex-1-rangeBalancedIndices))); + + if (unbalanced) + { + splitIndex = startIndex+ (numIndices>>1); + } + + bool unbal = (splitIndex==startIndex) || (splitIndex == (endIndex)); + btAssert(!unbal); + + return splitIndex; +} + + +int btOptimizedBvh::calcSplittingAxis(int startIndex,int endIndex) +{ + int i; + + btVector3 means(btScalar(0.),btScalar(0.),btScalar(0.)); + btVector3 variance(btScalar(0.),btScalar(0.),btScalar(0.)); + int numIndices = endIndex-startIndex; + + for (i=startIndex;im_aabbMinOrg,rootNode->m_aabbMaxOrg); + isLeafNode = rootNode->m_escapeIndex == -1; + + if (isLeafNode && aabbOverlap) + { + nodeCallback->processNode(rootNode->m_subPart,rootNode->m_triangleIndex); + } + + if (aabbOverlap || isLeafNode) + { + rootNode++; + curIndex++; + } else + { + escapeIndex = rootNode->m_escapeIndex; + rootNode += escapeIndex; + curIndex += escapeIndex; + } + } + if (maxIterations < walkIterations) + maxIterations = walkIterations; + +} + +/* +///this was the original recursive traversal, before we optimized towards stackless traversal +void btOptimizedBvh::walkTree(btOptimizedBvhNode* rootNode,btNodeOverlapCallback* nodeCallback,const btVector3& aabbMin,const btVector3& aabbMax) const +{ + bool isLeafNode, aabbOverlap = TestAabbAgainstAabb2(aabbMin,aabbMax,rootNode->m_aabbMin,rootNode->m_aabbMax); + if (aabbOverlap) + { + isLeafNode = (!rootNode->m_leftChild && !rootNode->m_rightChild); + if (isLeafNode) + { + nodeCallback->processNode(rootNode); + } else + { + walkTree(rootNode->m_leftChild,nodeCallback,aabbMin,aabbMax); + walkTree(rootNode->m_rightChild,nodeCallback,aabbMin,aabbMax); + } + } + +} +*/ + +void btOptimizedBvh::walkRecursiveQuantizedTreeAgainstQueryAabb(const btQuantizedBvhNode* currentNode,btNodeOverlapCallback* nodeCallback,unsigned short int* quantizedQueryAabbMin,unsigned short int* quantizedQueryAabbMax) const +{ + btAssert(m_useQuantization); + + bool aabbOverlap, isLeafNode; + + aabbOverlap = testQuantizedAabbAgainstQuantizedAabb(quantizedQueryAabbMin,quantizedQueryAabbMax,currentNode->m_quantizedAabbMin,currentNode->m_quantizedAabbMax); + isLeafNode = currentNode->isLeafNode(); + + if (aabbOverlap) + { + if (isLeafNode) + { + nodeCallback->processNode(0,currentNode->getTriangleIndex()); + } else + { + //process left and right children + const btQuantizedBvhNode* leftChildNode = currentNode+1; + walkRecursiveQuantizedTreeAgainstQueryAabb(leftChildNode,nodeCallback,quantizedQueryAabbMin,quantizedQueryAabbMax); + + const btQuantizedBvhNode* rightChildNode = leftChildNode->isLeafNode() ? leftChildNode+1:leftChildNode+leftChildNode->getEscapeIndex(); + walkRecursiveQuantizedTreeAgainstQueryAabb(rightChildNode,nodeCallback,quantizedQueryAabbMin,quantizedQueryAabbMax); + } + } +} + + + + + + + +void btOptimizedBvh::walkStacklessQuantizedTree(btNodeOverlapCallback* nodeCallback,unsigned short int* quantizedQueryAabbMin,unsigned short int* quantizedQueryAabbMax,int startNodeIndex,int endNodeIndex) const +{ + btAssert(m_useQuantization); + + int curIndex = startNodeIndex; + int walkIterations = 0; + int subTreeSize = endNodeIndex - startNodeIndex; + + const btQuantizedBvhNode* rootNode = &m_quantizedContiguousNodes[startNodeIndex]; + int escapeIndex; + + bool aabbOverlap, isLeafNode; + + while (curIndex < endNodeIndex) + { + +//#define VISUALLY_ANALYZE_BVH 1 +#ifdef VISUALLY_ANALYZE_BVH + //some code snippet to debugDraw aabb, to visually analyze bvh structure + static int drawPatch = 0; + //need some global access to a debugDrawer + extern btIDebugDraw* debugDrawerPtr; + if (curIndex==drawPatch) + { + btVector3 aabbMin,aabbMax; + aabbMin = unQuantize(rootNode->m_quantizedAabbMin); + aabbMax = unQuantize(rootNode->m_quantizedAabbMax); + btVector3 color(1,0,0); + debugDrawerPtr->drawAabb(aabbMin,aabbMax,color); + } +#endif//VISUALLY_ANALYZE_BVH + + //catch bugs in tree data + assert (walkIterations < subTreeSize); + + walkIterations++; + aabbOverlap = testQuantizedAabbAgainstQuantizedAabb(quantizedQueryAabbMin,quantizedQueryAabbMax,rootNode->m_quantizedAabbMin,rootNode->m_quantizedAabbMax); + isLeafNode = rootNode->isLeafNode(); + + if (isLeafNode && aabbOverlap) + { + nodeCallback->processNode(0,rootNode->getTriangleIndex()); + } + + if (aabbOverlap || isLeafNode) + { + rootNode++; + curIndex++; + } else + { + escapeIndex = rootNode->getEscapeIndex(); + rootNode += escapeIndex; + curIndex += escapeIndex; + } + } + if (maxIterations < walkIterations) + maxIterations = walkIterations; + +} + +//This traversal can be called from Playstation 3 SPU +void btOptimizedBvh::walkStacklessQuantizedTreeCacheFriendly(btNodeOverlapCallback* nodeCallback,unsigned short int* quantizedQueryAabbMin,unsigned short int* quantizedQueryAabbMax) const +{ + btAssert(m_useQuantization); + + int i; + + + for (i=0;im_SubtreeHeaders.size();i++) + { + const btBvhSubtreeInfo& subtree = m_SubtreeHeaders[i]; + + bool overlap = testQuantizedAabbAgainstQuantizedAabb(quantizedQueryAabbMin,quantizedQueryAabbMax,subtree.m_quantizedAabbMin,subtree.m_quantizedAabbMax); + if (overlap) + { + walkStacklessQuantizedTree(nodeCallback,quantizedQueryAabbMin,quantizedQueryAabbMax, + subtree.m_rootNodeIndex, + subtree.m_rootNodeIndex+subtree.m_subtreeSize); + } + } +} + + + + +void btOptimizedBvh::reportSphereOverlappingNodex(btNodeOverlapCallback* nodeCallback,const btVector3& aabbMin,const btVector3& aabbMax) const +{ + (void)nodeCallback; + (void)aabbMin; + (void)aabbMax; + //not yet, please use aabb + btAssert(0); +} + + +void btOptimizedBvh::quantizeWithClamp(unsigned short* out, const btVector3& point) const +{ + + btAssert(m_useQuantization); + + btVector3 clampedPoint(point); + clampedPoint.setMax(m_bvhAabbMin); + clampedPoint.setMin(m_bvhAabbMax); + + btVector3 v = (clampedPoint - m_bvhAabbMin) * m_bvhQuantization; + out[0] = (unsigned short)(v.getX()+0.5f); + out[1] = (unsigned short)(v.getY()+0.5f); + out[2] = (unsigned short)(v.getZ()+0.5f); +} + +btVector3 btOptimizedBvh::unQuantize(const unsigned short* vecIn) const +{ + btVector3 vecOut; + vecOut.setValue( + (btScalar)(vecIn[0]) / (m_bvhQuantization.getX()), + (btScalar)(vecIn[1]) / (m_bvhQuantization.getY()), + (btScalar)(vecIn[2]) / (m_bvhQuantization.getZ())); + vecOut += m_bvhAabbMin; + return vecOut; +} + + +void btOptimizedBvh::swapLeafNodes(int i,int splitIndex) +{ + if (m_useQuantization) + { + btQuantizedBvhNode tmp = m_quantizedLeafNodes[i]; + m_quantizedLeafNodes[i] = m_quantizedLeafNodes[splitIndex]; + m_quantizedLeafNodes[splitIndex] = tmp; + } else + { + btOptimizedBvhNode tmp = m_leafNodes[i]; + m_leafNodes[i] = m_leafNodes[splitIndex]; + m_leafNodes[splitIndex] = tmp; + } +} + +void btOptimizedBvh::assignInternalNodeFromLeafNode(int internalNode,int leafNodeIndex) +{ + if (m_useQuantization) + { + m_quantizedContiguousNodes[internalNode] = m_quantizedLeafNodes[leafNodeIndex]; + } else + { + m_contiguousNodes[internalNode] = m_leafNodes[leafNodeIndex]; + } } diff --git a/extern/bullet2/src/BulletCollision/CollisionShapes/btOptimizedBvh.h b/extern/bullet2/src/BulletCollision/CollisionShapes/btOptimizedBvh.h index d7536417d7e..d5159586344 100644 --- a/extern/bullet2/src/BulletCollision/CollisionShapes/btOptimizedBvh.h +++ b/extern/bullet2/src/BulletCollision/CollisionShapes/btOptimizedBvh.h @@ -16,48 +16,315 @@ subject to the following restrictions: #ifndef OPTIMIZED_BVH_H #define OPTIMIZED_BVH_H -#include "BulletCollision/BroadphaseCollision/btQuantizedBvh.h" + +#include "../../LinearMath/btVector3.h" + + +//http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vclang/html/vclrf__m128.asp + + class btStridingMeshInterface; +//Note: currently we have 16 bytes per quantized node +#define MAX_SUBTREE_SIZE_IN_BYTES 2048 -///The btOptimizedBvh extends the btQuantizedBvh to create AABB tree for triangle meshes, through the btStridingMeshInterface. -ATTRIBUTE_ALIGNED16(class) btOptimizedBvh : public btQuantizedBvh + +///btQuantizedBvhNode is a compressed aabb node, 16 bytes. +///Node can be used for leafnode or internal node. Leafnodes can point to 32-bit triangle index (non-negative range). +ATTRIBUTE_ALIGNED16 (struct) btQuantizedBvhNode { + //12 bytes + unsigned short int m_quantizedAabbMin[3]; + unsigned short int m_quantizedAabbMax[3]; + //4 bytes + int m_escapeIndexOrTriangleIndex; + + bool isLeafNode() const + { + //skipindex is negative (internal node), triangleindex >=0 (leafnode) + return (m_escapeIndexOrTriangleIndex >= 0); + } + int getEscapeIndex() const + { + btAssert(!isLeafNode()); + return -m_escapeIndexOrTriangleIndex; + } + int getTriangleIndex() const + { + btAssert(isLeafNode()); + return m_escapeIndexOrTriangleIndex; + } +} +; + +/// btOptimizedBvhNode contains both internal and leaf node information. +/// Total node size is 44 bytes / node. You can use the compressed version of 16 bytes. +ATTRIBUTE_ALIGNED16 (struct) btOptimizedBvhNode +{ + //32 bytes + btVector3 m_aabbMinOrg; + btVector3 m_aabbMaxOrg; + + //4 + int m_escapeIndex; + + //8 + //for child nodes + int m_subPart; + int m_triangleIndex; + int m_padding[5];//bad, due to alignment + + +}; + + +///btBvhSubtreeInfo provides info to gather a subtree of limited size +ATTRIBUTE_ALIGNED16(class) btBvhSubtreeInfo +{ public: - BT_DECLARE_ALIGNED_ALLOCATOR(); + //12 bytes + unsigned short int m_quantizedAabbMin[3]; + unsigned short int m_quantizedAabbMax[3]; + //4 bytes, points to the root of the subtree + int m_rootNodeIndex; + //4 bytes + int m_subtreeSize; + int m_padding[3]; + + + void setAabbFromQuantizeNode(const btQuantizedBvhNode& quantizedNode) + { + m_quantizedAabbMin[0] = quantizedNode.m_quantizedAabbMin[0]; + m_quantizedAabbMin[1] = quantizedNode.m_quantizedAabbMin[1]; + m_quantizedAabbMin[2] = quantizedNode.m_quantizedAabbMin[2]; + m_quantizedAabbMax[0] = quantizedNode.m_quantizedAabbMax[0]; + m_quantizedAabbMax[1] = quantizedNode.m_quantizedAabbMax[1]; + m_quantizedAabbMax[2] = quantizedNode.m_quantizedAabbMax[2]; + } +} +; + + +class btNodeOverlapCallback +{ +public: + virtual ~btNodeOverlapCallback() {}; + + virtual void processNode(int subPart, int triangleIndex) = 0; +}; + +#include "../../LinearMath/btAlignedAllocator.h" +#include "../../LinearMath/btAlignedObjectArray.h" + + + +///for code readability: +typedef btAlignedObjectArray NodeArray; +typedef btAlignedObjectArray QuantizedNodeArray; +typedef btAlignedObjectArray BvhSubtreeInfoArray; + + +///OptimizedBvh store an AABB tree that can be quickly traversed on CPU (and SPU,GPU in future) +ATTRIBUTE_ALIGNED16(class) btOptimizedBvh +{ + NodeArray m_leafNodes; + NodeArray m_contiguousNodes; + + QuantizedNodeArray m_quantizedLeafNodes; + + QuantizedNodeArray m_quantizedContiguousNodes; + + int m_curNodeIndex; + + + //quantization data + bool m_useQuantization; + btVector3 m_bvhAabbMin; + btVector3 m_bvhAabbMax; + btVector3 m_bvhQuantization; + + enum btTraversalMode + { + TRAVERSAL_STACKLESS = 0, + TRAVERSAL_STACKLESS_CACHE_FRIENDLY, + TRAVERSAL_RECURSIVE + }; + + btTraversalMode m_traversalMode; + + + + + BvhSubtreeInfoArray m_SubtreeHeaders; + + + ///two versions, one for quantized and normal nodes. This allows code-reuse while maintaining readability (no template/macro!) + ///this might be refactored into a virtual, it is usually not calculated at run-time + void setInternalNodeAabbMin(int nodeIndex, const btVector3& aabbMin) + { + if (m_useQuantization) + { + quantizeWithClamp(&m_quantizedContiguousNodes[nodeIndex].m_quantizedAabbMin[0] ,aabbMin); + } else + { + m_contiguousNodes[nodeIndex].m_aabbMinOrg = aabbMin; + + } + } + void setInternalNodeAabbMax(int nodeIndex,const btVector3& aabbMax) + { + if (m_useQuantization) + { + quantizeWithClamp(&m_quantizedContiguousNodes[nodeIndex].m_quantizedAabbMax[0],aabbMax); + } else + { + m_contiguousNodes[nodeIndex].m_aabbMaxOrg = aabbMax; + } + } + + btVector3 getAabbMin(int nodeIndex) const + { + if (m_useQuantization) + { + return unQuantize(&m_quantizedLeafNodes[nodeIndex].m_quantizedAabbMin[0]); + } + //non-quantized + return m_leafNodes[nodeIndex].m_aabbMinOrg; + + } + btVector3 getAabbMax(int nodeIndex) const + { + if (m_useQuantization) + { + return unQuantize(&m_quantizedLeafNodes[nodeIndex].m_quantizedAabbMax[0]); + } + //non-quantized + return m_leafNodes[nodeIndex].m_aabbMaxOrg; + + } + + void setQuantizationValues(const btVector3& bvhAabbMin,const btVector3& bvhAabbMax,btScalar quantizationMargin=btScalar(1.0)); + + void setInternalNodeEscapeIndex(int nodeIndex, int escapeIndex) + { + if (m_useQuantization) + { + m_quantizedContiguousNodes[nodeIndex].m_escapeIndexOrTriangleIndex = -escapeIndex; + } + else + { + m_contiguousNodes[nodeIndex].m_escapeIndex = escapeIndex; + } + + } + + void mergeInternalNodeAabb(int nodeIndex,const btVector3& newAabbMin,const btVector3& newAabbMax) + { + if (m_useQuantization) + { + unsigned short int quantizedAabbMin[3]; + unsigned short int quantizedAabbMax[3]; + quantizeWithClamp(quantizedAabbMin,newAabbMin); + quantizeWithClamp(quantizedAabbMax,newAabbMax); + for (int i=0;i<3;i++) + { + if (m_quantizedContiguousNodes[nodeIndex].m_quantizedAabbMin[i] > quantizedAabbMin[i]) + m_quantizedContiguousNodes[nodeIndex].m_quantizedAabbMin[i] = quantizedAabbMin[i]; + + if (m_quantizedContiguousNodes[nodeIndex].m_quantizedAabbMax[i] < quantizedAabbMax[i]) + m_quantizedContiguousNodes[nodeIndex].m_quantizedAabbMax[i] = quantizedAabbMax[i]; + + } + } else + { + //non-quantized + m_contiguousNodes[nodeIndex].m_aabbMinOrg.setMin(newAabbMin); + m_contiguousNodes[nodeIndex].m_aabbMaxOrg.setMax(newAabbMax); + } + } + + void swapLeafNodes(int firstIndex,int secondIndex); + + void assignInternalNodeFromLeafNode(int internalNode,int leafNodeIndex); protected: -public: + + void buildTree (int startIndex,int endIndex); + + int calcSplittingAxis(int startIndex,int endIndex); + + int sortAndCalcSplittingIndex(int startIndex,int endIndex,int splitAxis); + + void walkStacklessTree(btNodeOverlapCallback* nodeCallback,const btVector3& aabbMin,const btVector3& aabbMax) const; + + void walkStacklessQuantizedTree(btNodeOverlapCallback* nodeCallback,unsigned short int* quantizedQueryAabbMin,unsigned short int* quantizedQueryAabbMax,int startNodeIndex,int endNodeIndex) const; + + ///tree traversal designed for small-memory processors like PS3 SPU + void walkStacklessQuantizedTreeCacheFriendly(btNodeOverlapCallback* nodeCallback,unsigned short int* quantizedQueryAabbMin,unsigned short int* quantizedQueryAabbMax) const; + + ///use the 16-byte stackless 'skipindex' node tree to do a recursive traversal + void walkRecursiveQuantizedTreeAgainstQueryAabb(const btQuantizedBvhNode* currentNode,btNodeOverlapCallback* nodeCallback,unsigned short int* quantizedQueryAabbMin,unsigned short int* quantizedQueryAabbMax) const; + + ///use the 16-byte stackless 'skipindex' node tree to do a recursive traversal + void walkRecursiveQuantizedTreeAgainstQuantizedTree(const btQuantizedBvhNode* treeNodeA,const btQuantizedBvhNode* treeNodeB,btNodeOverlapCallback* nodeCallback) const; + + + inline bool testQuantizedAabbAgainstQuantizedAabb(unsigned short int* aabbMin1,unsigned short int* aabbMax1,const unsigned short int* aabbMin2,const unsigned short int* aabbMax2) const + { + bool overlap = true; + overlap = (aabbMin1[0] > aabbMax2[0] || aabbMax1[0] < aabbMin2[0]) ? false : overlap; + overlap = (aabbMin1[2] > aabbMax2[2] || aabbMax1[2] < aabbMin2[2]) ? false : overlap; + overlap = (aabbMin1[1] > aabbMax2[1] || aabbMax1[1] < aabbMin2[1]) ? false : overlap; + return overlap; + } + + void updateSubtreeHeaders(int leftChildNodexIndex,int rightChildNodexIndex); + +public: btOptimizedBvh(); virtual ~btOptimizedBvh(); void build(btStridingMeshInterface* triangles,bool useQuantizedAabbCompression, const btVector3& bvhAabbMin, const btVector3& bvhAabbMax); - void refit(btStridingMeshInterface* triangles,const btVector3& aabbMin,const btVector3& aabbMax); + void reportAabbOverlappingNodex(btNodeOverlapCallback* nodeCallback,const btVector3& aabbMin,const btVector3& aabbMax) const; + + void reportSphereOverlappingNodex(btNodeOverlapCallback* nodeCallback,const btVector3& aabbMin,const btVector3& aabbMax) const; + + void quantizeWithClamp(unsigned short* out, const btVector3& point) const; + + btVector3 unQuantize(const unsigned short* vecIn) const; + + ///setTraversalMode let's you choose between stackless, recursive or stackless cache friendly tree traversal. Note this is only implemented for quantized trees. + void setTraversalMode(btTraversalMode traversalMode) + { + m_traversalMode = traversalMode; + } + + void refit(btStridingMeshInterface* triangles); void refitPartial(btStridingMeshInterface* triangles,const btVector3& aabbMin, const btVector3& aabbMax); void updateBvhNodes(btStridingMeshInterface* meshInterface,int firstNode,int endNode,int index); - /// Data buffer MUST be 16 byte aligned - virtual bool serialize(void *o_alignedDataBuffer, unsigned i_dataBufferSize, bool i_swapEndian) - { - return btQuantizedBvh::serialize(o_alignedDataBuffer,i_dataBufferSize,i_swapEndian); + QuantizedNodeArray& getQuantizedNodeArray() + { + return m_quantizedContiguousNodes; } - ///deSerializeInPlace loads and initializes a BVH from a buffer in memory 'in place' - static btOptimizedBvh *deSerializeInPlace(void *i_alignedDataBuffer, unsigned int i_dataBufferSize, bool i_swapEndian); + BvhSubtreeInfoArray& getSubtreeInfoArray() + { + return m_SubtreeHeaders; + } - -}; +} +; #endif //OPTIMIZED_BVH_H - diff --git a/extern/bullet2/src/BulletCollision/CollisionShapes/btPolyhedralConvexShape.cpp b/extern/bullet2/src/BulletCollision/CollisionShapes/btPolyhedralConvexShape.cpp index 71c3af38a02..bbc4ba62af6 100644 --- a/extern/bullet2/src/BulletCollision/CollisionShapes/btPolyhedralConvexShape.cpp +++ b/extern/bullet2/src/BulletCollision/CollisionShapes/btPolyhedralConvexShape.cpp @@ -13,7 +13,7 @@ subject to the following restrictions: 3. This notice may not be removed or altered from any source distribution. */ -#include "BulletCollision/CollisionShapes/btPolyhedralConvexShape.h" +#include btPolyhedralConvexShape::btPolyhedralConvexShape() :m_localAabbMin(1,1,1), @@ -95,7 +95,7 @@ void btPolyhedralConvexShape::batchedUnitVectorGetSupportingVertexWithoutMargin( -void btPolyhedralConvexShape::calculateLocalInertia(btScalar mass,btVector3& inertia) const +void btPolyhedralConvexShape::calculateLocalInertia(btScalar mass,btVector3& inertia) { //not yet, return box inertia @@ -128,46 +128,10 @@ void btPolyhedralConvexShape::getAabb(const btTransform& trans,btVector3& aabbMi -void btPolyhedralConvexShape::setLocalScaling(const btVector3& scaling) -{ - btConvexInternalShape::setLocalScaling(scaling); - recalcLocalAabb(); -} void btPolyhedralConvexShape::recalcLocalAabb() { m_isLocalAabbValid = true; - - #if 1 - static const btVector3 _directions[] = - { - btVector3( 1., 0., 0.), - btVector3( 0., 1., 0.), - btVector3( 0., 0., 1.), - btVector3( -1., 0., 0.), - btVector3( 0., -1., 0.), - btVector3( 0., 0., -1.) - }; - - btVector3 _supporting[] = - { - btVector3( 0., 0., 0.), - btVector3( 0., 0., 0.), - btVector3( 0., 0., 0.), - btVector3( 0., 0., 0.), - btVector3( 0., 0., 0.), - btVector3( 0., 0., 0.) - }; - - batchedUnitVectorGetSupportingVertexWithoutMargin(_directions, _supporting, 6); - - for ( int i = 0; i < 3; ++i ) - { - m_localAabbMax[i] = _supporting[i][i] + m_collisionMargin; - m_localAabbMin[i] = _supporting[i + 3][i] - m_collisionMargin; - } - - #else for (int i=0;i<3;i++) { @@ -179,8 +143,6 @@ void btPolyhedralConvexShape::recalcLocalAabb() tmp = localGetSupportingVertex(vec); m_localAabbMin[i] = tmp[i]-m_collisionMargin; } - #endif } - diff --git a/extern/bullet2/src/BulletCollision/CollisionShapes/btPolyhedralConvexShape.h b/extern/bullet2/src/BulletCollision/CollisionShapes/btPolyhedralConvexShape.h index 0d55e4fe92c..c35f7512663 100644 --- a/extern/bullet2/src/BulletCollision/CollisionShapes/btPolyhedralConvexShape.h +++ b/extern/bullet2/src/BulletCollision/CollisionShapes/btPolyhedralConvexShape.h @@ -16,13 +16,13 @@ subject to the following restrictions: #ifndef BU_SHAPE #define BU_SHAPE -#include "LinearMath/btPoint3.h" -#include "LinearMath/btMatrix3x3.h" -#include "btConvexInternalShape.h" +#include "../../LinearMath/btPoint3.h" +#include "../../LinearMath/btMatrix3x3.h" +#include "btConvexShape.h" -///The btPolyhedralConvexShape is an internal interface class for polyhedral convex shapes. -class btPolyhedralConvexShape : public btConvexInternalShape +///PolyhedralConvexShape is an interface class for feature based (vertex/edge/face) convex shapes. +class btPolyhedralConvexShape : public btConvexShape { protected: @@ -38,7 +38,7 @@ public: virtual btVector3 localGetSupportingVertexWithoutMargin(const btVector3& vec)const; virtual void batchedUnitVectorGetSupportingVertexWithoutMargin(const btVector3* vectors,btVector3* supportVerticesOut,int numVectors) const; - virtual void calculateLocalInertia(btScalar mass,btVector3& inertia) const; + virtual void calculateLocalInertia(btScalar mass,btVector3& inertia); inline void getNonvirtualAabb(const btTransform& trans,btVector3& aabbMin,btVector3& aabbMax, btScalar margin) const @@ -73,8 +73,6 @@ public: virtual void getAabb(const btTransform& t,btVector3& aabbMin,btVector3& aabbMax) const; - virtual void setLocalScaling(const btVector3& scaling); - void recalcLocalAabb(); virtual int getNumVertices() const = 0 ; diff --git a/extern/bullet2/src/BulletCollision/CollisionShapes/btShapeHull.cpp b/extern/bullet2/src/BulletCollision/CollisionShapes/btShapeHull.cpp deleted file mode 100644 index a87b87f1a6f..00000000000 --- a/extern/bullet2/src/BulletCollision/CollisionShapes/btShapeHull.cpp +++ /dev/null @@ -1,164 +0,0 @@ -/* -btbtShapeHull implemented by John McCutchan. - -Bullet Continuous Collision Detection and Physics Library -Copyright (c) 2003-2008 Erwin Coumans http://bulletphysics.com - -This software is provided 'as-is', without any express or implied warranty. -In no event will the authors be held liable for any damages arising from the use of this software. -Permission is granted to anyone to use this software for any purpose, -including commercial applications, and to alter it and redistribute it freely, -subject to the following restrictions: - -1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. -2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. -3. This notice may not be removed or altered from any source distribution. -*/ - -#include "btShapeHull.h" -#include "LinearMath/btConvexHull.h" - -#define NUM_UNITSPHERE_POINTS 42 - -static btVector3 btUnitSpherePoints[NUM_UNITSPHERE_POINTS+MAX_PREFERRED_PENETRATION_DIRECTIONS*2] = -{ - btVector3(btScalar(0.000000) , btScalar(-0.000000),btScalar(-1.000000)), - btVector3(btScalar(0.723608) , btScalar(-0.525725),btScalar(-0.447219)), - btVector3(btScalar(-0.276388) , btScalar(-0.850649),btScalar(-0.447219)), - btVector3(btScalar(-0.894426) , btScalar(-0.000000),btScalar(-0.447216)), - btVector3(btScalar(-0.276388) , btScalar(0.850649),btScalar(-0.447220)), - btVector3(btScalar(0.723608) , btScalar(0.525725),btScalar(-0.447219)), - btVector3(btScalar(0.276388) , btScalar(-0.850649),btScalar(0.447220)), - btVector3(btScalar(-0.723608) , btScalar(-0.525725),btScalar(0.447219)), - btVector3(btScalar(-0.723608) , btScalar(0.525725),btScalar(0.447219)), - btVector3(btScalar(0.276388) , btScalar(0.850649),btScalar(0.447219)), - btVector3(btScalar(0.894426) , btScalar(0.000000),btScalar(0.447216)), - btVector3(btScalar(-0.000000) , btScalar(0.000000),btScalar(1.000000)), - btVector3(btScalar(0.425323) , btScalar(-0.309011),btScalar(-0.850654)), - btVector3(btScalar(-0.162456) , btScalar(-0.499995),btScalar(-0.850654)), - btVector3(btScalar(0.262869) , btScalar(-0.809012),btScalar(-0.525738)), - btVector3(btScalar(0.425323) , btScalar(0.309011),btScalar(-0.850654)), - btVector3(btScalar(0.850648) , btScalar(-0.000000),btScalar(-0.525736)), - btVector3(btScalar(-0.525730) , btScalar(-0.000000),btScalar(-0.850652)), - btVector3(btScalar(-0.688190) , btScalar(-0.499997),btScalar(-0.525736)), - btVector3(btScalar(-0.162456) , btScalar(0.499995),btScalar(-0.850654)), - btVector3(btScalar(-0.688190) , btScalar(0.499997),btScalar(-0.525736)), - btVector3(btScalar(0.262869) , btScalar(0.809012),btScalar(-0.525738)), - btVector3(btScalar(0.951058) , btScalar(0.309013),btScalar(0.000000)), - btVector3(btScalar(0.951058) , btScalar(-0.309013),btScalar(0.000000)), - btVector3(btScalar(0.587786) , btScalar(-0.809017),btScalar(0.000000)), - btVector3(btScalar(0.000000) , btScalar(-1.000000),btScalar(0.000000)), - btVector3(btScalar(-0.587786) , btScalar(-0.809017),btScalar(0.000000)), - btVector3(btScalar(-0.951058) , btScalar(-0.309013),btScalar(-0.000000)), - btVector3(btScalar(-0.951058) , btScalar(0.309013),btScalar(-0.000000)), - btVector3(btScalar(-0.587786) , btScalar(0.809017),btScalar(-0.000000)), - btVector3(btScalar(-0.000000) , btScalar(1.000000),btScalar(-0.000000)), - btVector3(btScalar(0.587786) , btScalar(0.809017),btScalar(-0.000000)), - btVector3(btScalar(0.688190) , btScalar(-0.499997),btScalar(0.525736)), - btVector3(btScalar(-0.262869) , btScalar(-0.809012),btScalar(0.525738)), - btVector3(btScalar(-0.850648) , btScalar(0.000000),btScalar(0.525736)), - btVector3(btScalar(-0.262869) , btScalar(0.809012),btScalar(0.525738)), - btVector3(btScalar(0.688190) , btScalar(0.499997),btScalar(0.525736)), - btVector3(btScalar(0.525730) , btScalar(0.000000),btScalar(0.850652)), - btVector3(btScalar(0.162456) , btScalar(-0.499995),btScalar(0.850654)), - btVector3(btScalar(-0.425323) , btScalar(-0.309011),btScalar(0.850654)), - btVector3(btScalar(-0.425323) , btScalar(0.309011),btScalar(0.850654)), - btVector3(btScalar(0.162456) , btScalar(0.499995),btScalar(0.850654)) -}; - -btShapeHull::btShapeHull (const btConvexShape* shape) -{ - m_shape = shape; - m_vertices.clear (); - m_indices.clear(); - m_numIndices = 0; -} - -btShapeHull::~btShapeHull () -{ - m_indices.clear(); - m_vertices.clear (); -} - -bool -btShapeHull::buildHull (btScalar /*margin*/) -{ - int numSampleDirections = NUM_UNITSPHERE_POINTS; - { - int numPDA = m_shape->getNumPreferredPenetrationDirections(); - if (numPDA) - { - for (int i=0;igetPreferredPenetrationDirection(i,norm); - btUnitSpherePoints[numSampleDirections] = norm; - numSampleDirections++; - } - } - } - - btVector3 supportPoints[NUM_UNITSPHERE_POINTS+MAX_PREFERRED_PENETRATION_DIRECTIONS*2]; - int i; - for (i = 0; i < numSampleDirections; i++) - { - supportPoints[i] = m_shape->localGetSupportingVertex(btUnitSpherePoints[i]); - } - - HullDesc hd; - hd.mFlags = QF_TRIANGLES; - hd.mVcount = static_cast(numSampleDirections); - -#ifdef BT_USE_DOUBLE_PRECISION - hd.mVertices = &supportPoints[0]; - hd.mVertexStride = sizeof(btVector3); -#else - hd.mVertices = &supportPoints[0]; - hd.mVertexStride = sizeof (btVector3); -#endif - - HullLibrary hl; - HullResult hr; - if (hl.CreateConvexHull (hd, hr) == QE_FAIL) - { - return false; - } - - m_vertices.resize (static_cast(hr.mNumOutputVertices)); - - - for (i = 0; i < static_cast(hr.mNumOutputVertices); i++) - { - m_vertices[i] = hr.m_OutputVertices[i]; - } - m_numIndices = hr.mNumIndices; - m_indices.resize(static_cast(m_numIndices)); - for (i = 0; i < static_cast(m_numIndices); i++) - { - m_indices[i] = hr.m_Indices[i]; - } - - // free temporary hull result that we just copied - hl.ReleaseResult (hr); - - return true; -} - -int -btShapeHull::numTriangles () const -{ - return static_cast(m_numIndices / 3); -} - -int -btShapeHull::numVertices () const -{ - return m_vertices.size (); -} - -int -btShapeHull::numIndices () const -{ - return static_cast(m_numIndices); -} - diff --git a/extern/bullet2/src/BulletCollision/CollisionShapes/btShapeHull.h b/extern/bullet2/src/BulletCollision/CollisionShapes/btShapeHull.h deleted file mode 100644 index 583c6b99eb6..00000000000 --- a/extern/bullet2/src/BulletCollision/CollisionShapes/btShapeHull.h +++ /dev/null @@ -1,56 +0,0 @@ -/* -btShapeHull implemented by John McCutchan. - -Bullet Continuous Collision Detection and Physics Library -Copyright (c) 2003-2008 Erwin Coumans http://continuousphysics.com/Bullet/ - -This software is provided 'as-is', without any express or implied warranty. -In no event will the authors be held liable for any damages arising from the use of this software. -Permission is granted to anyone to use this software for any purpose, -including commercial applications, and to alter it and redistribute it freely, -subject to the following restrictions: - -1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. -2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. -3. This notice may not be removed or altered from any source distribution. -*/ - -#ifndef _SHAPE_HULL_H -#define _SHAPE_HULL_H - -#include "LinearMath/btAlignedObjectArray.h" -#include "BulletCollision/CollisionShapes/btConvexShape.h" - - -///The btShapeHull class takes a btConvexShape, builds a simplified convex hull using btConvexHull and provides triangle indices and vertices. -///It can be useful for to simplify a complex convex object and for visualization of a non-polyhedral convex object. -///It approximates the convex hull using the supporting vertex of 42 directions. -class btShapeHull -{ -public: - btShapeHull (const btConvexShape* shape); - ~btShapeHull (); - - bool buildHull (btScalar margin); - - int numTriangles () const; - int numVertices () const; - int numIndices () const; - - const btVector3* getVertexPointer() const - { - return &m_vertices[0]; - } - const unsigned int* getIndexPointer() const - { - return &m_indices[0]; - } - -protected: - btAlignedObjectArray m_vertices; - btAlignedObjectArray m_indices; - unsigned int m_numIndices; - const btConvexShape* m_shape; -}; - -#endif //_SHAPE_HULL_H diff --git a/extern/bullet2/src/BulletCollision/CollisionShapes/btSphereShape.cpp b/extern/bullet2/src/BulletCollision/CollisionShapes/btSphereShape.cpp index 15cfe432e27..ca65dd03f3e 100644 --- a/extern/bullet2/src/BulletCollision/CollisionShapes/btSphereShape.cpp +++ b/extern/bullet2/src/BulletCollision/CollisionShapes/btSphereShape.cpp @@ -68,7 +68,7 @@ void btSphereShape::getAabb(const btTransform& t,btVector3& aabbMin,btVector3& a -void btSphereShape::calculateLocalInertia(btScalar mass,btVector3& inertia) const +void btSphereShape::calculateLocalInertia(btScalar mass,btVector3& inertia) { btScalar elem = btScalar(0.4) * mass * getMargin()*getMargin(); inertia.setValue(elem,elem,elem); diff --git a/extern/bullet2/src/BulletCollision/CollisionShapes/btSphereShape.h b/extern/bullet2/src/BulletCollision/CollisionShapes/btSphereShape.h index 83421d69e0d..66521664087 100644 --- a/extern/bullet2/src/BulletCollision/CollisionShapes/btSphereShape.h +++ b/extern/bullet2/src/BulletCollision/CollisionShapes/btSphereShape.h @@ -16,17 +16,15 @@ subject to the following restrictions: #ifndef SPHERE_MINKOWSKI_H #define SPHERE_MINKOWSKI_H -#include "btConvexInternalShape.h" -#include "BulletCollision/BroadphaseCollision/btBroadphaseProxy.h" // for the types +#include "btConvexShape.h" +#include "../BroadphaseCollision/btBroadphaseProxy.h" // for the types -///The btSphereShape implements an implicit sphere, centered around a local origin with radius. -ATTRIBUTE_ALIGNED16(class) btSphereShape : public btConvexInternalShape +///btSphereShape implements an implicit (getSupportingVertex) Sphere +ATTRIBUTE_ALIGNED16(class) btSphereShape : public btConvexShape { public: - BT_DECLARE_ALIGNED_ALLOCATOR(); - btSphereShape (btScalar radius); @@ -36,26 +34,26 @@ public: virtual void batchedUnitVectorGetSupportingVertexWithoutMargin(const btVector3* vectors,btVector3* supportVerticesOut,int numVectors) const; - virtual void calculateLocalInertia(btScalar mass,btVector3& inertia) const; + virtual void calculateLocalInertia(btScalar mass,btVector3& inertia); virtual void getAabb(const btTransform& t,btVector3& aabbMin,btVector3& aabbMax) const; virtual int getShapeType() const { return SPHERE_SHAPE_PROXYTYPE; } - btScalar getRadius() const { return m_implicitShapeDimensions.getX() * m_localScaling.getX();} + btScalar getRadius() const { return m_implicitShapeDimensions.getX();} //debugging - virtual const char* getName()const {return "SPHERE";} + virtual char* getName()const {return "SPHERE";} virtual void setMargin(btScalar margin) { - btConvexInternalShape::setMargin(margin); + btConvexShape::setMargin(margin); } virtual btScalar getMargin() const { //to improve gjk behaviour, use radius+margin as the full margin, so never get into the penetration case //this means, non-uniform scaling is not supported anymore - return getRadius(); + return m_localScaling.getX() * getRadius() + btConvexShape::getMargin(); } diff --git a/extern/bullet2/src/BulletCollision/CollisionShapes/btStaticPlaneShape.cpp b/extern/bullet2/src/BulletCollision/CollisionShapes/btStaticPlaneShape.cpp index 3c98ca08ddc..4fbaafa1b93 100644 --- a/extern/bullet2/src/BulletCollision/CollisionShapes/btStaticPlaneShape.cpp +++ b/extern/bullet2/src/BulletCollision/CollisionShapes/btStaticPlaneShape.cpp @@ -19,11 +19,10 @@ subject to the following restrictions: btStaticPlaneShape::btStaticPlaneShape(const btVector3& planeNormal,btScalar planeConstant) -:m_planeNormal(planeNormal.normalized()), +:m_planeNormal(planeNormal), m_planeConstant(planeConstant), m_localScaling(btScalar(0.),btScalar(0.),btScalar(0.)) { - // btAssert( btFuzzyZero(m_planeNormal.length() - btScalar(1.)) ); } @@ -87,7 +86,7 @@ void btStaticPlaneShape::processAllTriangles(btTriangleCallback* callback,const } -void btStaticPlaneShape::calculateLocalInertia(btScalar mass,btVector3& inertia) const +void btStaticPlaneShape::calculateLocalInertia(btScalar mass,btVector3& inertia) { (void)mass; diff --git a/extern/bullet2/src/BulletCollision/CollisionShapes/btStaticPlaneShape.h b/extern/bullet2/src/BulletCollision/CollisionShapes/btStaticPlaneShape.h index ddebca73dea..f59cc0c3347 100644 --- a/extern/bullet2/src/BulletCollision/CollisionShapes/btStaticPlaneShape.h +++ b/extern/bullet2/src/BulletCollision/CollisionShapes/btStaticPlaneShape.h @@ -19,7 +19,8 @@ subject to the following restrictions: #include "btConcaveShape.h" -///The btStaticPlaneShape simulates an infinite non-moving (static) collision plane. +///StaticPlaneShape simulates an 'infinite' plane by dynamically reporting triangles approximated by intersection of the plane with the AABB. +///Assumed is that the other objects is not also infinite, so a reasonable sized AABB. class btStaticPlaneShape : public btConcaveShape { protected: @@ -45,23 +46,14 @@ public: virtual void processAllTriangles(btTriangleCallback* callback,const btVector3& aabbMin,const btVector3& aabbMax) const; - virtual void calculateLocalInertia(btScalar mass,btVector3& inertia) const; + virtual void calculateLocalInertia(btScalar mass,btVector3& inertia); virtual void setLocalScaling(const btVector3& scaling); virtual const btVector3& getLocalScaling() const; - const btVector3& getPlaneNormal() const - { - return m_planeNormal; - } - - const btScalar& getPlaneConstant() const - { - return m_planeConstant; - } //debugging - virtual const char* getName()const {return "STATICPLANE";} + virtual char* getName()const {return "STATICPLANE";} }; diff --git a/extern/bullet2/src/BulletCollision/CollisionShapes/btStridingMeshInterface.cpp b/extern/bullet2/src/BulletCollision/CollisionShapes/btStridingMeshInterface.cpp index 752a5fc1dfa..03ca1ae7736 100644 --- a/extern/bullet2/src/BulletCollision/CollisionShapes/btStridingMeshInterface.cpp +++ b/extern/bullet2/src/BulletCollision/CollisionShapes/btStridingMeshInterface.cpp @@ -51,7 +51,7 @@ void btStridingMeshInterface::InternalProcessAllTriangles(btInternalTriangleInde { for (gfxindex=0;gfxindexprocessAllTriangles(&triBuf,aabbMin, aabbMax); +// for (int i=0;iprocessAllTriangles(&triBuf,aabbMin, aabbMax); -/// for (int i=0;i IndexedMeshArray; -///The btTriangleIndexVertexArray allows to access multiple triangle meshes, by indexing into existing triangle/index arrays. +///TriangleIndexVertexArray allows to use multiple meshes, by indexing into existing triangle/index arrays. ///Additional meshes can be added using addIndexedMesh ///No duplcate is made of the vertex/index data, it only indexes into external vertex/index arrays. ///So keep those arrays around during the lifetime of this btTriangleIndexVertexArray. ATTRIBUTE_ALIGNED16( class) btTriangleIndexVertexArray : public btStridingMeshInterface { -protected: IndexedMeshArray m_indexedMeshes; - int m_pad[2]; - int m_hasAabb; // using int instead of bool to maintain alignment - btVector3 m_aabbMin; - btVector3 m_aabbMax; + int m_pad[3]; + public: - BT_DECLARE_ALIGNED_ALLOCATOR(); - - btTriangleIndexVertexArray() : m_hasAabb(0) + btTriangleIndexVertexArray() { } - virtual ~btTriangleIndexVertexArray(); - //just to be backwards compatible - btTriangleIndexVertexArray(int numTriangles,int* triangleIndexBase,int triangleIndexStride,int numVertices,btScalar* vertexBase,int vertexStride); + btTriangleIndexVertexArray(int numTriangleIndices,int* triangleIndexBase,int triangleIndexStride,int numVertices,btScalar* vertexBase,int vertexStride); - void addIndexedMesh(const btIndexedMesh& mesh, PHY_ScalarType indexType = PHY_INTEGER) + void addIndexedMesh(const btIndexedMesh& mesh) { m_indexedMeshes.push_back(mesh); - m_indexedMeshes[m_indexedMeshes.size()-1].m_indexType = indexType; } @@ -105,10 +91,6 @@ public: virtual void preallocateVertices(int numverts){(void) numverts;} virtual void preallocateIndices(int numindices){(void) numindices;} - virtual bool hasPremadeAabb() const; - virtual void setPremadeAabb(const btVector3& aabbMin, const btVector3& aabbMax ); - virtual void getPremadeAabb(btVector3* aabbMin, btVector3* aabbMax ) const; - } ; diff --git a/extern/bullet2/src/BulletCollision/CollisionShapes/btTriangleIndexVertexMaterialArray.cpp b/extern/bullet2/src/BulletCollision/CollisionShapes/btTriangleIndexVertexMaterialArray.cpp deleted file mode 100644 index 492854ff646..00000000000 --- a/extern/bullet2/src/BulletCollision/CollisionShapes/btTriangleIndexVertexMaterialArray.cpp +++ /dev/null @@ -1,86 +0,0 @@ -/* -Bullet Continuous Collision Detection and Physics Library -Copyright (c) 2003-2006 Erwin Coumans http://continuousphysics.com/Bullet/ - -This software is provided 'as-is', without any express or implied warranty. -In no event will the authors be held liable for any damages arising from the use of this software. -Permission is granted to anyone to use this software for any purpose, -including commercial applications, and to alter it and redistribute it freely, -subject to the following restrictions: - -1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. -2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. -3. This notice may not be removed or altered from any source distribution. -*/ - -///This file was created by Alex Silverman - -#include "btTriangleIndexVertexMaterialArray.h" - -btTriangleIndexVertexMaterialArray::btTriangleIndexVertexMaterialArray(int numTriangles,int* triangleIndexBase,int triangleIndexStride, - int numVertices,btScalar* vertexBase,int vertexStride, - int numMaterials, unsigned char* materialBase, int materialStride, - int* triangleMaterialsBase, int materialIndexStride) : -btTriangleIndexVertexArray(numTriangles, triangleIndexBase, triangleIndexStride, numVertices, vertexBase, vertexStride) -{ - btMaterialProperties mat; - - mat.m_numMaterials = numMaterials; - mat.m_materialBase = materialBase; - mat.m_materialStride = materialStride; -#ifdef BT_USE_DOUBLE_PRECISION - mat.m_materialType = PHY_DOUBLE; -#else - mat.m_materialType = PHY_FLOAT; -#endif - - mat.m_numTriangles = numTriangles; - mat.m_triangleMaterialsBase = (unsigned char *)triangleMaterialsBase; - mat.m_triangleMaterialStride = materialIndexStride; - mat.m_triangleType = PHY_INTEGER; - - addMaterialProperties(mat); -} - - -void btTriangleIndexVertexMaterialArray::getLockedMaterialBase(unsigned char **materialBase, int& numMaterials, PHY_ScalarType& materialType, int& materialStride, - unsigned char ** triangleMaterialBase, int& numTriangles, int& triangleMaterialStride, PHY_ScalarType& triangleType, int subpart) -{ - btAssert(subpart< getNumSubParts() ); - - btMaterialProperties& mats = m_materials[subpart]; - - numMaterials = mats.m_numMaterials; - (*materialBase) = (unsigned char *) mats.m_materialBase; -#ifdef BT_USE_DOUBLE_PRECISION - materialType = PHY_DOUBLE; -#else - materialType = PHY_FLOAT; -#endif - materialStride = mats.m_materialStride; - - numTriangles = mats.m_numTriangles; - (*triangleMaterialBase) = (unsigned char *)mats.m_triangleMaterialsBase; - triangleMaterialStride = mats.m_triangleMaterialStride; - triangleType = mats.m_triangleType; -} - -void btTriangleIndexVertexMaterialArray::getLockedReadOnlyMaterialBase(const unsigned char **materialBase, int& numMaterials, PHY_ScalarType& materialType, int& materialStride, - const unsigned char ** triangleMaterialBase, int& numTriangles, int& triangleMaterialStride, PHY_ScalarType& triangleType, int subpart) -{ - btMaterialProperties& mats = m_materials[subpart]; - - numMaterials = mats.m_numMaterials; - (*materialBase) = (const unsigned char *) mats.m_materialBase; -#ifdef BT_USE_DOUBLE_PRECISION - materialType = PHY_DOUBLE; -#else - materialType = PHY_FLOAT; -#endif - materialStride = mats.m_materialStride; - - numTriangles = mats.m_numTriangles; - (*triangleMaterialBase) = (const unsigned char *)mats.m_triangleMaterialsBase; - triangleMaterialStride = mats.m_triangleMaterialStride; - triangleType = mats.m_triangleType; -} diff --git a/extern/bullet2/src/BulletCollision/CollisionShapes/btTriangleIndexVertexMaterialArray.h b/extern/bullet2/src/BulletCollision/CollisionShapes/btTriangleIndexVertexMaterialArray.h deleted file mode 100644 index 69a2e631458..00000000000 --- a/extern/bullet2/src/BulletCollision/CollisionShapes/btTriangleIndexVertexMaterialArray.h +++ /dev/null @@ -1,84 +0,0 @@ -/* -Bullet Continuous Collision Detection and Physics Library -Copyright (c) 2003-2006 Erwin Coumans http://continuousphysics.com/Bullet/ - -This software is provided 'as-is', without any express or implied warranty. -In no event will the authors be held liable for any damages arising from the use of this software. -Permission is granted to anyone to use this software for any purpose, -including commercial applications, and to alter it and redistribute it freely, -subject to the following restrictions: - -1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. -2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. -3. This notice may not be removed or altered from any source distribution. -*/ - -///This file was created by Alex Silverman - -#ifndef BT_MULTIMATERIAL_TRIANGLE_INDEX_VERTEX_ARRAY_H -#define BT_MULTIMATERIAL_TRIANGLE_INDEX_VERTEX_ARRAY_H - -#include "btTriangleIndexVertexArray.h" - - -ATTRIBUTE_ALIGNED16( struct) btMaterialProperties -{ - ///m_materialBase ==========> 2 btScalar values make up one material, friction then restitution - int m_numMaterials; - const unsigned char * m_materialBase; - int m_materialStride; - PHY_ScalarType m_materialType; - ///m_numTriangles <=========== This exists in the btIndexedMesh object for the same subpart, but since we're - /// padding the structure, it can be reproduced at no real cost - ///m_triangleMaterials =====> 1 integer value makes up one entry - /// eg: m_triangleMaterials[1] = 5; // This will set triangle 2 to use material 5 - int m_numTriangles; - const unsigned char * m_triangleMaterialsBase; - int m_triangleMaterialStride; - ///m_triangleType <========== Automatically set in addMaterialProperties - PHY_ScalarType m_triangleType; -}; - -typedef btAlignedObjectArray MaterialArray; - -///Teh btTriangleIndexVertexMaterialArray is built on TriangleIndexVertexArray -///The addition of a material array allows for the utilization of the partID and -///triangleIndex that are returned in the ContactAddedCallback. As with -///TriangleIndexVertexArray, no duplicate is made of the material data, so it -///is the users responsibility to maintain the array during the lifetime of the -///TriangleIndexVertexMaterialArray. -ATTRIBUTE_ALIGNED16(class) btTriangleIndexVertexMaterialArray : public btTriangleIndexVertexArray -{ -protected: - MaterialArray m_materials; - -public: - BT_DECLARE_ALIGNED_ALLOCATOR(); - - btTriangleIndexVertexMaterialArray() - { - } - - btTriangleIndexVertexMaterialArray(int numTriangles,int* triangleIndexBase,int triangleIndexStride, - int numVertices,btScalar* vertexBase,int vertexStride, - int numMaterials, unsigned char* materialBase, int materialStride, - int* triangleMaterialsBase, int materialIndexStride); - - virtual ~btTriangleIndexVertexMaterialArray() {} - - void addMaterialProperties(const btMaterialProperties& mat, PHY_ScalarType triangleType = PHY_INTEGER) - { - m_materials.push_back(mat); - m_materials[m_materials.size()-1].m_triangleType = triangleType; - } - - virtual void getLockedMaterialBase(unsigned char **materialBase, int& numMaterials, PHY_ScalarType& materialType, int& materialStride, - unsigned char ** triangleMaterialBase, int& numTriangles, int& triangleMaterialStride, PHY_ScalarType& triangleType ,int subpart = 0); - - virtual void getLockedReadOnlyMaterialBase(const unsigned char **materialBase, int& numMaterials, PHY_ScalarType& materialType, int& materialStride, - const unsigned char ** triangleMaterialBase, int& numTriangles, int& triangleMaterialStride, PHY_ScalarType& triangleType, int subpart = 0); - -} -; - -#endif //BT_MULTIMATERIAL_TRIANGLE_INDEX_VERTEX_ARRAY_H diff --git a/extern/bullet2/src/BulletCollision/CollisionShapes/btTriangleMesh.cpp b/extern/bullet2/src/BulletCollision/CollisionShapes/btTriangleMesh.cpp index bcea97052d6..98c54ef45f8 100644 --- a/extern/bullet2/src/BulletCollision/CollisionShapes/btTriangleMesh.cpp +++ b/extern/bullet2/src/BulletCollision/CollisionShapes/btTriangleMesh.cpp @@ -14,102 +14,47 @@ subject to the following restrictions: */ #include "btTriangleMesh.h" +#include - -btTriangleMesh::btTriangleMesh (bool use32bitIndices,bool use4componentVertices) -:m_use32bitIndices(use32bitIndices), -m_use4componentVertices(use4componentVertices) +btTriangleMesh::btTriangleMesh () { - btIndexedMesh meshIndex; - meshIndex.m_numTriangles = 0; - meshIndex.m_numVertices = 0; - meshIndex.m_indexType = PHY_INTEGER; - meshIndex.m_triangleIndexBase = 0; - meshIndex.m_triangleIndexStride = 3*sizeof(int); - meshIndex.m_vertexBase = 0; - meshIndex.m_vertexStride = sizeof(btVector3); - m_indexedMeshes.push_back(meshIndex); - - if (m_use32bitIndices) - { - m_indexedMeshes[0].m_numTriangles = m_32bitIndices.size()/3; - m_indexedMeshes[0].m_triangleIndexBase = (unsigned char*) &m_32bitIndices[0]; - m_indexedMeshes[0].m_indexType = PHY_INTEGER; - m_indexedMeshes[0].m_triangleIndexStride = 3*sizeof(int); - } else - { - m_indexedMeshes[0].m_numTriangles = m_16bitIndices.size()/3; - m_indexedMeshes[0].m_triangleIndexBase = (unsigned char*) &m_16bitIndices[0]; - m_indexedMeshes[0].m_indexType = PHY_SHORT; - m_indexedMeshes[0].m_triangleIndexStride = 3*sizeof(short int); - } - - if (m_use4componentVertices) - { - m_indexedMeshes[0].m_numVertices = m_4componentVertices.size(); - m_indexedMeshes[0].m_vertexBase = (unsigned char*)&m_4componentVertices[0]; - m_indexedMeshes[0].m_vertexStride = sizeof(btVector3); - } else - { - m_indexedMeshes[0].m_numVertices = m_3componentVertices.size()/3; - m_indexedMeshes[0].m_vertexBase = (unsigned char*)&m_3componentVertices[0]; - m_indexedMeshes[0].m_vertexStride = 3*sizeof(btScalar); - } - } - -void btTriangleMesh::addTriangle(const btVector3& vertex0,const btVector3& vertex1,const btVector3& vertex2) +void btTriangleMesh::getLockedVertexIndexBase(unsigned char **vertexbase, int& numverts,PHY_ScalarType& type, int& stride,unsigned char **indexbase,int & indexstride,int& numfaces,PHY_ScalarType& indicestype,int subpart) { - m_indexedMeshes[0].m_numTriangles++; - m_indexedMeshes[0].m_numVertices+=3; + (void)subpart; + numverts = m_vertices.size(); + *vertexbase = (unsigned char*)&m_vertices[0]; + type = PHY_FLOAT; + stride = sizeof(btVector3); - if (m_use4componentVertices) - { - m_4componentVertices.push_back(vertex0); - m_4componentVertices.push_back(vertex1); - m_4componentVertices.push_back(vertex2); - m_indexedMeshes[0].m_vertexBase = (unsigned char*)&m_4componentVertices[0]; - } else - { - m_3componentVertices.push_back(vertex0.getX()); - m_3componentVertices.push_back(vertex0.getY()); - m_3componentVertices.push_back(vertex0.getZ()); + numfaces = m_indices.size()/3; + *indexbase = (unsigned char*) &m_indices[0]; + indicestype = PHY_INTEGER; + indexstride = 3*sizeof(int); - m_3componentVertices.push_back(vertex1.getX()); - m_3componentVertices.push_back(vertex1.getY()); - m_3componentVertices.push_back(vertex1.getZ()); - - m_3componentVertices.push_back(vertex2.getX()); - m_3componentVertices.push_back(vertex2.getY()); - m_3componentVertices.push_back(vertex2.getZ()); - m_indexedMeshes[0].m_vertexBase = (unsigned char*)&m_3componentVertices[0]; - } - - if (m_use32bitIndices) - { - int curIndex = m_32bitIndices.size(); - m_32bitIndices.push_back(curIndex++); - m_32bitIndices.push_back(curIndex++); - m_32bitIndices.push_back(curIndex++); - m_indexedMeshes[0].m_triangleIndexBase = (unsigned char*) &m_32bitIndices[0]; - } else - { - short curIndex = static_cast(m_16bitIndices.size()); - m_16bitIndices.push_back(curIndex++); - m_16bitIndices.push_back(curIndex++); - m_16bitIndices.push_back(curIndex++); - m_indexedMeshes[0].m_triangleIndexBase = (unsigned char*) &m_16bitIndices[0]; - } } -int btTriangleMesh::getNumTriangles() const +void btTriangleMesh::getLockedReadOnlyVertexIndexBase(const unsigned char **vertexbase, int& numverts,PHY_ScalarType& type, int& stride,const unsigned char **indexbase,int & indexstride,int& numfaces,PHY_ScalarType& indicestype,int subpart) const { - if (m_use32bitIndices) - { - return m_32bitIndices.size() / 3; - } - return m_16bitIndices.size() / 3; + (void)subpart; + numverts = m_vertices.size(); + *vertexbase = (unsigned char*)&m_vertices[0]; + type = PHY_FLOAT; + stride = sizeof(btVector3); + + numfaces = m_indices.size()/3; + *indexbase = (unsigned char*) &m_indices[0]; + indicestype = PHY_INTEGER; + indexstride = 3*sizeof(int); + +} + + + +int btTriangleMesh::getNumSubParts() const +{ + return 1; } diff --git a/extern/bullet2/src/BulletCollision/CollisionShapes/btTriangleMesh.h b/extern/bullet2/src/BulletCollision/CollisionShapes/btTriangleMesh.h index e4d41d5ede0..525f5336b48 100644 --- a/extern/bullet2/src/BulletCollision/CollisionShapes/btTriangleMesh.h +++ b/extern/bullet2/src/BulletCollision/CollisionShapes/btTriangleMesh.h @@ -17,42 +17,54 @@ subject to the following restrictions: #ifndef TRIANGLE_MESH_H #define TRIANGLE_MESH_H -#include "btTriangleIndexVertexArray.h" -#include "LinearMath/btVector3.h" -#include "LinearMath/btAlignedObjectArray.h" +#include "btStridingMeshInterface.h" +#include "../../LinearMath/btVector3.h" +#include "../../LinearMath/btAlignedObjectArray.h" -///The btTriangleMesh class is a convenience class derived from btTriangleIndexVertexArray, that provides storage for a concave triangle mesh. It can be used as data for the btBvhTriangleMeshShape. -///It allows either 32bit or 16bit indices, and 4 (x-y-z-w) or 3 (x-y-z) component vertices. -///If you want to share triangle/index data between graphics mesh and collision mesh (btBvhTriangleMeshShape), you can directly use btTriangleIndexVertexArray or derive your own class from btStridingMeshInterface. -///Performance of btTriangleMesh and btTriangleIndexVertexArray used in a btBvhTriangleMeshShape is the same. -class btTriangleMesh : public btTriangleIndexVertexArray +///TriangleMesh provides storage for a concave triangle mesh. It can be used as data for the btTriangleMeshShape. +class btTriangleMesh : public btStridingMeshInterface { - btAlignedObjectArray m_4componentVertices; - btAlignedObjectArray m_3componentVertices; - - btAlignedObjectArray m_32bitIndices; - btAlignedObjectArray m_16bitIndices; - bool m_use32bitIndices; - bool m_use4componentVertices; - + btAlignedObjectArray m_vertices; + btAlignedObjectArray m_indices; public: - btTriangleMesh (bool use32bitIndices=true,bool use4componentVertices=true); + btTriangleMesh (); - bool getUse32bitIndices() const + void addTriangle(const btVector3& vertex0,const btVector3& vertex1,const btVector3& vertex2) { - return m_use32bitIndices; + int curIndex = m_indices.size(); + m_vertices.push_back(vertex0); + m_vertices.push_back(vertex1); + m_vertices.push_back(vertex2); + + m_indices.push_back(curIndex++); + m_indices.push_back(curIndex++); + m_indices.push_back(curIndex++); } - bool getUse4componentVertices() const + int getNumTriangles() const { - return m_use4componentVertices; + return m_indices.size() / 3; } - - void addTriangle(const btVector3& vertex0,const btVector3& vertex1,const btVector3& vertex2); - - int getNumTriangles() const; + + +//StridingMeshInterface interface implementation + + virtual void getLockedVertexIndexBase(unsigned char **vertexbase, int& numverts,PHY_ScalarType& type, int& stride,unsigned char **indexbase,int & indexstride,int& numfaces,PHY_ScalarType& indicestype,int subpart=0); + + virtual void getLockedReadOnlyVertexIndexBase(const unsigned char **vertexbase, int& numverts,PHY_ScalarType& type, int& stride,const unsigned char **indexbase,int & indexstride,int& numfaces,PHY_ScalarType& indicestype,int subpart=0) const; + + /// unLockVertexBase finishes the access to a subpart of the triangle mesh + /// make a call to unLockVertexBase when the read and write access (using getLockedVertexIndexBase) is finished + virtual void unLockVertexBase(int subpart) {(void) subpart;} + + virtual void unLockReadOnlyVertexBase(int subpart) const { (void) subpart;} + + /// getNumSubParts returns the number of seperate subparts + /// each subpart has a continuous array of vertices and indices + virtual int getNumSubParts() const; + virtual void preallocateVertices(int numverts){(void) numverts;} virtual void preallocateIndices(int numindices){(void) numindices;} diff --git a/extern/bullet2/src/BulletCollision/CollisionShapes/btTriangleMeshShape.cpp b/extern/bullet2/src/BulletCollision/CollisionShapes/btTriangleMeshShape.cpp index cd0a00bbd6f..ed81897b515 100644 --- a/extern/bullet2/src/BulletCollision/CollisionShapes/btTriangleMeshShape.cpp +++ b/extern/bullet2/src/BulletCollision/CollisionShapes/btTriangleMeshShape.cpp @@ -20,18 +20,12 @@ subject to the following restrictions: #include "LinearMath/btAabbUtil2.h" #include "BulletCollision/CollisionShapes/btCollisionMargin.h" +#include "stdio.h" btTriangleMeshShape::btTriangleMeshShape(btStridingMeshInterface* meshInterface) : m_meshInterface(meshInterface) { - if(meshInterface->hasPremadeAabb()) - { - meshInterface->getPremadeAabb(&m_localAabbMin, &m_localAabbMax); - } - else - { - recalcLocalAabb(); - } + recalcLocalAabb(); } @@ -144,7 +138,6 @@ const btVector3& btTriangleMeshShape::getLocalScaling() const //#define DEBUG_TRIANGLE_MESH - void btTriangleMeshShape::processAllTriangles(btTriangleCallback* callback,const btVector3& aabbMin,const btVector3& aabbMax) const { struct FilteredCallback : public btInternalTriangleIndexCallback @@ -181,7 +174,8 @@ void btTriangleMeshShape::processAllTriangles(btTriangleCallback* callback,const -void btTriangleMeshShape::calculateLocalInertia(btScalar mass,btVector3& inertia) const + +void btTriangleMeshShape::calculateLocalInertia(btScalar mass,btVector3& inertia) { (void)mass; //moving concave objects not supported diff --git a/extern/bullet2/src/BulletCollision/CollisionShapes/btTriangleMeshShape.h b/extern/bullet2/src/BulletCollision/CollisionShapes/btTriangleMeshShape.h index 9fba77cb547..e6173e47640 100644 --- a/extern/bullet2/src/BulletCollision/CollisionShapes/btTriangleMeshShape.h +++ b/extern/bullet2/src/BulletCollision/CollisionShapes/btTriangleMeshShape.h @@ -20,19 +20,17 @@ subject to the following restrictions: #include "btStridingMeshInterface.h" -///The btTriangleMeshShape is an internal concave triangle mesh interface. Don't use this class directly, use btBvhTriangleMeshShape instead. +///Concave triangle mesh. Uses an interface to access the triangles to allow for sharing graphics/physics triangles. class btTriangleMeshShape : public btConcaveShape { protected: btVector3 m_localAabbMin; btVector3 m_localAabbMax; btStridingMeshInterface* m_meshInterface; - - ///btTriangleMeshShape constructor has been disabled/protected, so that users will not mistakenly use this class. - ///Don't use btTriangleMeshShape but use btBvhTriangleMeshShape instead! - btTriangleMeshShape(btStridingMeshInterface* meshInterface); + public: + btTriangleMeshShape(btStridingMeshInterface* meshInterface); virtual ~btTriangleMeshShape(); @@ -46,11 +44,16 @@ public: void recalcLocalAabb(); + virtual int getShapeType() const + { + return TRIANGLE_MESH_SHAPE_PROXYTYPE; + } + virtual void getAabb(const btTransform& t,btVector3& aabbMin,btVector3& aabbMax) const; virtual void processAllTriangles(btTriangleCallback* callback,const btVector3& aabbMin,const btVector3& aabbMax) const; - virtual void calculateLocalInertia(btScalar mass,btVector3& inertia) const; + virtual void calculateLocalInertia(btScalar mass,btVector3& inertia); virtual void setLocalScaling(const btVector3& scaling); virtual const btVector3& getLocalScaling() const; @@ -67,7 +70,7 @@ public: //debugging - virtual const char* getName()const {return "TRIANGLEMESH";} + virtual char* getName()const {return "TRIANGLEMESH";} }; diff --git a/extern/bullet2/src/BulletCollision/CollisionShapes/btTriangleShape.h b/extern/bullet2/src/BulletCollision/CollisionShapes/btTriangleShape.h index ba7aa0c32a0..c2e240c051c 100644 --- a/extern/bullet2/src/BulletCollision/CollisionShapes/btTriangleShape.h +++ b/extern/bullet2/src/BulletCollision/CollisionShapes/btTriangleShape.h @@ -27,6 +27,7 @@ public: btVector3 m_vertices1[3]; + virtual int getNumVertices() const { return 3; @@ -83,13 +84,14 @@ public: - btTriangleShape(const btVector3& p0,const btVector3& p1,const btVector3& p2) - { - m_vertices1[0] = p0; - m_vertices1[1] = p1; - m_vertices1[2] = p2; - } + btTriangleShape(const btVector3& p0,const btVector3& p1,const btVector3& p2) + { + m_vertices1[0] = p0; + m_vertices1[1] = p1; + m_vertices1[2] = p2; + } + virtual void getPlane(btVector3& planeNormal,btPoint3& planeSupport,int i) const { @@ -114,7 +116,7 @@ public: planeSupport = m_vertices1[0]; } - virtual void calculateLocalInertia(btScalar mass,btVector3& inertia) const + virtual void calculateLocalInertia(btScalar mass,btVector3& inertia) { (void)mass; btAssert(0); @@ -153,7 +155,7 @@ public: return false; } //debugging - virtual const char* getName()const + virtual char* getName()const { return "Triangle"; } diff --git a/extern/bullet2/src/BulletCollision/CollisionShapes/btUniformScalingShape.cpp b/extern/bullet2/src/BulletCollision/CollisionShapes/btUniformScalingShape.cpp deleted file mode 100644 index ef340286cb0..00000000000 --- a/extern/bullet2/src/BulletCollision/CollisionShapes/btUniformScalingShape.cpp +++ /dev/null @@ -1,114 +0,0 @@ -/* -Bullet Continuous Collision Detection and Physics Library -Copyright (c) 2003-2007 Erwin Coumans http://continuousphysics.com/Bullet/ - -This software is provided 'as-is', without any express or implied warranty. -In no event will the authors be held liable for any damages arising from the use of this software. -Permission is granted to anyone to use this software for any purpose, -including commercial applications, and to alter it and redistribute it freely, -subject to the following restrictions: - -1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. -2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. -3. This notice may not be removed or altered from any source distribution. -*/ - -#include "btUniformScalingShape.h" - -btUniformScalingShape::btUniformScalingShape( btConvexShape* convexChildShape,btScalar uniformScalingFactor): -m_childConvexShape(convexChildShape), -m_uniformScalingFactor(uniformScalingFactor) -{ -} - -btUniformScalingShape::~btUniformScalingShape() -{ -} - - -btVector3 btUniformScalingShape::localGetSupportingVertexWithoutMargin(const btVector3& vec)const -{ - btVector3 tmpVertex; - tmpVertex = m_childConvexShape->localGetSupportingVertexWithoutMargin(vec); - return tmpVertex*m_uniformScalingFactor; -} - -void btUniformScalingShape::batchedUnitVectorGetSupportingVertexWithoutMargin(const btVector3* vectors,btVector3* supportVerticesOut,int numVectors) const -{ - m_childConvexShape->batchedUnitVectorGetSupportingVertexWithoutMargin(vectors,supportVerticesOut,numVectors); - int i; - for (i=0;ilocalGetSupportingVertex(vec); - return tmpVertex*m_uniformScalingFactor; -} - - -void btUniformScalingShape::calculateLocalInertia(btScalar mass,btVector3& inertia) const -{ - - ///this linear upscaling is not realistic, but we don't deal with large mass ratios... - btVector3 tmpInertia; - m_childConvexShape->calculateLocalInertia(mass,tmpInertia); - inertia = tmpInertia * m_uniformScalingFactor; -} - - - ///getAabb's default implementation is brute force, expected derived classes to implement a fast dedicated version -void btUniformScalingShape::getAabb(const btTransform& t,btVector3& aabbMin,btVector3& aabbMax) const -{ - m_childConvexShape->getAabb(t,aabbMin,aabbMax); - btVector3 aabbCenter = (aabbMax+aabbMin)*btScalar(0.5); - btVector3 scaledAabbHalfExtends = (aabbMax-aabbMin)*btScalar(0.5)*m_uniformScalingFactor; - - aabbMin = aabbCenter - scaledAabbHalfExtends; - aabbMax = aabbCenter + scaledAabbHalfExtends; - -} - -void btUniformScalingShape::getAabbSlow(const btTransform& t,btVector3& aabbMin,btVector3& aabbMax) const -{ - m_childConvexShape->getAabbSlow(t,aabbMin,aabbMax); - btVector3 aabbCenter = (aabbMax+aabbMin)*btScalar(0.5); - btVector3 scaledAabbHalfExtends = (aabbMax-aabbMin)*btScalar(0.5)*m_uniformScalingFactor; - - aabbMin = aabbCenter - scaledAabbHalfExtends; - aabbMax = aabbCenter + scaledAabbHalfExtends; -} - -void btUniformScalingShape::setLocalScaling(const btVector3& scaling) -{ - m_childConvexShape->setLocalScaling(scaling); -} - -const btVector3& btUniformScalingShape::getLocalScaling() const -{ - return m_childConvexShape->getLocalScaling(); -} - -void btUniformScalingShape::setMargin(btScalar margin) -{ - m_childConvexShape->setMargin(margin); -} -btScalar btUniformScalingShape::getMargin() const -{ - return m_childConvexShape->getMargin() * m_uniformScalingFactor; -} - -int btUniformScalingShape::getNumPreferredPenetrationDirections() const -{ - return m_childConvexShape->getNumPreferredPenetrationDirections(); -} - -void btUniformScalingShape::getPreferredPenetrationDirection(int index, btVector3& penetrationVector) const -{ - m_childConvexShape->getPreferredPenetrationDirection(index,penetrationVector); -} diff --git a/extern/bullet2/src/BulletCollision/CollisionShapes/btUniformScalingShape.h b/extern/bullet2/src/BulletCollision/CollisionShapes/btUniformScalingShape.h deleted file mode 100644 index 1e17fc8e198..00000000000 --- a/extern/bullet2/src/BulletCollision/CollisionShapes/btUniformScalingShape.h +++ /dev/null @@ -1,88 +0,0 @@ -/* -Bullet Continuous Collision Detection and Physics Library -Copyright (c) 2003-2006 Erwin Coumans http://continuousphysics.com/Bullet/ - -This software is provided 'as-is', without any express or implied warranty. -In no event will the authors be held liable for any damages arising from the use of this software. -Permission is granted to anyone to use this software for any purpose, -including commercial applications, and to alter it and redistribute it freely, -subject to the following restrictions: - -1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. -2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. -3. This notice may not be removed or altered from any source distribution. -*/ - -#ifndef BT_UNIFORM_SCALING_SHAPE_H -#define BT_UNIFORM_SCALING_SHAPE_H - -#include "btConvexShape.h" -#include "BulletCollision/BroadphaseCollision/btBroadphaseProxy.h" // for the types - -///The btUniformScalingShape allows to re-use uniform scaled instances of btConvexShape in a memory efficient way. -///Istead of using btUniformScalingShape, it is better to use the non-uniform setLocalScaling method on convex shapes that implement it. -class btUniformScalingShape : public btConvexShape -{ - btConvexShape* m_childConvexShape; - - btScalar m_uniformScalingFactor; - - public: - - btUniformScalingShape( btConvexShape* convexChildShape, btScalar uniformScalingFactor); - - virtual ~btUniformScalingShape(); - - virtual btVector3 localGetSupportingVertexWithoutMargin(const btVector3& vec)const; - - virtual btVector3 localGetSupportingVertex(const btVector3& vec)const; - - virtual void batchedUnitVectorGetSupportingVertexWithoutMargin(const btVector3* vectors,btVector3* supportVerticesOut,int numVectors) const; - - virtual void calculateLocalInertia(btScalar mass,btVector3& inertia) const; - - btScalar getUniformScalingFactor() const - { - return m_uniformScalingFactor; - } - - btConvexShape* getChildShape() - { - return m_childConvexShape; - } - - const btConvexShape* getChildShape() const - { - return m_childConvexShape; - } - - virtual const char* getName()const - { - return "UniformScalingShape"; - } - - virtual int getShapeType() const { return UNIFORM_SCALING_SHAPE_PROXYTYPE; } - - - /////////////////////////// - - - ///getAabb's default implementation is brute force, expected derived classes to implement a fast dedicated version - void getAabb(const btTransform& t,btVector3& aabbMin,btVector3& aabbMax) const; - - virtual void getAabbSlow(const btTransform& t,btVector3& aabbMin,btVector3& aabbMax) const; - - virtual void setLocalScaling(const btVector3& scaling) ; - virtual const btVector3& getLocalScaling() const ; - - virtual void setMargin(btScalar margin); - virtual btScalar getMargin() const; - - virtual int getNumPreferredPenetrationDirections() const; - - virtual void getPreferredPenetrationDirection(int index, btVector3& penetrationVector) const; - - -}; - -#endif //BT_UNIFORM_SCALING_SHAPE_H diff --git a/extern/bullet2/src/BulletCollision/NarrowPhaseCollision/btContinuousConvexCollision.cpp b/extern/bullet2/src/BulletCollision/NarrowPhaseCollision/btContinuousConvexCollision.cpp index 6551cfb92fe..2c565734e97 100644 --- a/extern/bullet2/src/BulletCollision/NarrowPhaseCollision/btContinuousConvexCollision.cpp +++ b/extern/bullet2/src/BulletCollision/NarrowPhaseCollision/btContinuousConvexCollision.cpp @@ -16,6 +16,7 @@ subject to the following restrictions: #include "btContinuousConvexCollision.h" #include "BulletCollision/CollisionShapes/btConvexShape.h" +#include "BulletCollision/CollisionShapes/btMinkowskiSumShape.h" #include "BulletCollision/NarrowPhaseCollision/btSimplexSolverInterface.h" #include "LinearMath/btTransformUtil.h" #include "BulletCollision/CollisionShapes/btSphereShape.h" @@ -25,7 +26,7 @@ subject to the following restrictions: -btContinuousConvexCollision::btContinuousConvexCollision ( const btConvexShape* convexA,const btConvexShape* convexB,btSimplexSolverInterface* simplexSolver, btConvexPenetrationDepthSolver* penetrationDepthSolver) +btContinuousConvexCollision::btContinuousConvexCollision ( btConvexShape* convexA,btConvexShape* convexB,btSimplexSolverInterface* simplexSolver, btConvexPenetrationDepthSolver* penetrationDepthSolver) :m_simplexSolver(simplexSolver), m_penetrationDepthSolver(penetrationDepthSolver), m_convexA(convexA),m_convexB(convexB) @@ -34,7 +35,7 @@ m_convexA(convexA),m_convexB(convexB) /// This maximum should not be necessary. It allows for untested/degenerate cases in production code. /// You don't want your game ever to lock-up. -#define MAX_ITERATIONS 64 +#define MAX_ITERATIONS 1000 bool btContinuousConvexCollision::calcTimeOfImpact( const btTransform& fromA, @@ -51,18 +52,10 @@ bool btContinuousConvexCollision::calcTimeOfImpact( btTransformUtil::calculateVelocity(fromA,toA,btScalar(1.),linVelA,angVelA); btTransformUtil::calculateVelocity(fromB,toB,btScalar(1.),linVelB,angVelB); - btScalar boundingRadiusA = m_convexA->getAngularMotionDisc(); btScalar boundingRadiusB = m_convexB->getAngularMotionDisc(); btScalar maxAngularProjectedVelocity = angVelA.length() * boundingRadiusA + angVelB.length() * boundingRadiusB; - btVector3 relLinVel = (linVelB-linVelA); - - btScalar relLinVelocLength = (linVelB-linVelA).length(); - - if ((relLinVelocLength+maxAngularProjectedVelocity) == 0.f) - return false; - btScalar radius = btScalar(0.001); @@ -100,7 +93,7 @@ bool btContinuousConvexCollision::calcTimeOfImpact( btGjkPairDetector::ClosestPointInput input; //we don't use margins during CCD - // gjk.setIgnoreMargin(true); + gjk.setIgnoreMargin(true); input.m_transformA = fromA; input.m_transformB = fromB; @@ -115,31 +108,25 @@ bool btContinuousConvexCollision::calcTimeOfImpact( btScalar dist; dist = pointCollector1.m_distance; n = pointCollector1.m_normalOnBInWorld; - - btScalar projectedLinearVelocity = relLinVel.dot(n); //not close enough while (dist > radius) { numIter++; if (numIter > maxIter) - { return false; //todo: report a failure - } - btScalar dLambda = btScalar(0.); - projectedLinearVelocity = relLinVel.dot(n); + btScalar dLambda = btScalar(0.); //calculate safe moving fraction from distance / (linear+rotational velocity) //btScalar clippedDist = GEN_min(angularConservativeRadius,dist); //btScalar clippedDist = dist; + btScalar projectedLinearVelocity = (linVelB-linVelA).dot(n); dLambda = dist / (projectedLinearVelocity+ maxAngularProjectedVelocity); - - lambda = lambda + dLambda; if (lambda > btScalar(1.)) @@ -148,14 +135,9 @@ bool btContinuousConvexCollision::calcTimeOfImpact( if (lambda < btScalar(0.)) return false; - //todo: next check with relative epsilon if (lambda <= lastLambda) - { - return false; - //n.setValue(0,0,0); break; - } lastLambda = lambda; @@ -181,13 +163,11 @@ bool btContinuousConvexCollision::calcTimeOfImpact( { //degenerate ?! result.m_fraction = lastLambda; - n = pointCollector.m_normalOnBInWorld; - result.m_normal=n;//.setValue(1,1,1);// = n; - result.m_hitPoint = pointCollector.m_pointInWorld; + result.m_normal = n; return true; } c = pointCollector.m_pointInWorld; - n = pointCollector.m_normalOnBInWorld; + dist = pointCollector.m_distance; } else { @@ -197,13 +177,8 @@ bool btContinuousConvexCollision::calcTimeOfImpact( } - //don't report time of impact for motion away from the contact normal (or causes minor penetration) - if ((projectedLinearVelocity+ maxAngularProjectedVelocity)<=result.m_allowedPenetration)//SIMD_EPSILON) - return false; - result.m_fraction = lambda; result.m_normal = n; - result.m_hitPoint = c; return true; } diff --git a/extern/bullet2/src/BulletCollision/NarrowPhaseCollision/btContinuousConvexCollision.h b/extern/bullet2/src/BulletCollision/NarrowPhaseCollision/btContinuousConvexCollision.h index 28c2b4d6156..9901bab4b45 100644 --- a/extern/bullet2/src/BulletCollision/NarrowPhaseCollision/btContinuousConvexCollision.h +++ b/extern/bullet2/src/BulletCollision/NarrowPhaseCollision/btContinuousConvexCollision.h @@ -30,13 +30,13 @@ class btContinuousConvexCollision : public btConvexCast { btSimplexSolverInterface* m_simplexSolver; btConvexPenetrationDepthSolver* m_penetrationDepthSolver; - const btConvexShape* m_convexA; - const btConvexShape* m_convexB; + btConvexShape* m_convexA; + btConvexShape* m_convexB; public: - btContinuousConvexCollision (const btConvexShape* shapeA,const btConvexShape* shapeB ,btSimplexSolverInterface* simplexSolver,btConvexPenetrationDepthSolver* penetrationDepthSolver); + btContinuousConvexCollision (btConvexShape* shapeA,btConvexShape* shapeB ,btSimplexSolverInterface* simplexSolver,btConvexPenetrationDepthSolver* penetrationDepthSolver); virtual bool calcTimeOfImpact( const btTransform& fromA, diff --git a/extern/bullet2/src/BulletCollision/NarrowPhaseCollision/btConvexCast.h b/extern/bullet2/src/BulletCollision/NarrowPhaseCollision/btConvexCast.h index 0edf4dcd496..3101b59993d 100644 --- a/extern/bullet2/src/BulletCollision/NarrowPhaseCollision/btConvexCast.h +++ b/extern/bullet2/src/BulletCollision/NarrowPhaseCollision/btConvexCast.h @@ -17,11 +17,11 @@ subject to the following restrictions: #ifndef CONVEX_CAST_H #define CONVEX_CAST_H -#include "LinearMath/btTransform.h" -#include "LinearMath/btVector3.h" -#include "LinearMath/btScalar.h" +#include "../../LinearMath/btTransform.h" +#include "../../LinearMath/btVector3.h" +#include "../../LinearMath/btScalar.h" class btMinkowskiSumShape; -#include "LinearMath/btIDebugDraw.h" +#include "../../LinearMath/btIDebugDraw.h" /// btConvexCast is an interface for Casting class btConvexCast @@ -42,21 +42,19 @@ public: CastResult() :m_fraction(btScalar(1e30)), - m_debugDrawer(0), - m_allowedPenetration(btScalar(0)) + m_debugDrawer(0) { } virtual ~CastResult() {}; + btVector3 m_normal; + btScalar m_fraction; btTransform m_hitTransformA; btTransform m_hitTransformB; - btVector3 m_normal; - btVector3 m_hitPoint; - btScalar m_fraction; //input and output + btIDebugDraw* m_debugDrawer; - btScalar m_allowedPenetration; }; diff --git a/extern/bullet2/src/BulletCollision/NarrowPhaseCollision/btConvexPenetrationDepthSolver.h b/extern/bullet2/src/BulletCollision/NarrowPhaseCollision/btConvexPenetrationDepthSolver.h index 99690921317..7caeba4be45 100644 --- a/extern/bullet2/src/BulletCollision/NarrowPhaseCollision/btConvexPenetrationDepthSolver.h +++ b/extern/bullet2/src/BulletCollision/NarrowPhaseCollision/btConvexPenetrationDepthSolver.h @@ -21,7 +21,7 @@ class btStackAlloc; class btVector3; #include "btSimplexSolverInterface.h" class btConvexShape; -#include "LinearMath/btPoint3.h" +#include "../../LinearMath/btPoint3.h" class btTransform; ///ConvexPenetrationDepthSolver provides an interface for penetration depth calculation. @@ -31,7 +31,7 @@ public: virtual ~btConvexPenetrationDepthSolver() {}; virtual bool calcPenDepth( btSimplexSolverInterface& simplexSolver, - const btConvexShape* convexA,const btConvexShape* convexB, + btConvexShape* convexA,btConvexShape* convexB, const btTransform& transA,const btTransform& transB, btVector3& v, btPoint3& pa, btPoint3& pb, class btIDebugDraw* debugDraw,btStackAlloc* stackAlloc diff --git a/extern/bullet2/src/BulletCollision/NarrowPhaseCollision/btDiscreteCollisionDetectorInterface.h b/extern/bullet2/src/BulletCollision/NarrowPhaseCollision/btDiscreteCollisionDetectorInterface.h index db797d5141f..15000c1ab61 100644 --- a/extern/bullet2/src/BulletCollision/NarrowPhaseCollision/btDiscreteCollisionDetectorInterface.h +++ b/extern/bullet2/src/BulletCollision/NarrowPhaseCollision/btDiscreteCollisionDetectorInterface.h @@ -16,8 +16,8 @@ subject to the following restrictions: #ifndef DISCRETE_COLLISION_DETECTOR1_INTERFACE_H #define DISCRETE_COLLISION_DETECTOR1_INTERFACE_H -#include "LinearMath/btTransform.h" -#include "LinearMath/btVector3.h" +#include "../../LinearMath/btTransform.h" +#include "../../LinearMath/btVector3.h" class btStackAlloc; /// This interface is made to be used by an iterative approach to do TimeOfImpact calculations @@ -58,7 +58,7 @@ struct btDiscreteCollisionDetectorInterface // give either closest points (distance > 0) or penetration (distance) // the normal always points from B towards A // - virtual void getClosestPoints(const ClosestPointInput& input,Result& output,class btIDebugDraw* debugDraw,bool swapResults=false) = 0; + virtual void getClosestPoints(const ClosestPointInput& input,Result& output,class btIDebugDraw* debugDraw) = 0; }; diff --git a/extern/bullet2/src/BulletCollision/NarrowPhaseCollision/btGjkConvexCast.cpp b/extern/bullet2/src/BulletCollision/NarrowPhaseCollision/btGjkConvexCast.cpp index bef697a0a11..93edffeafd6 100644 --- a/extern/bullet2/src/BulletCollision/NarrowPhaseCollision/btGjkConvexCast.cpp +++ b/extern/bullet2/src/BulletCollision/NarrowPhaseCollision/btGjkConvexCast.cpp @@ -17,17 +17,12 @@ subject to the following restrictions: #include "btGjkConvexCast.h" #include "BulletCollision/CollisionShapes/btSphereShape.h" +#include "BulletCollision/CollisionShapes/btMinkowskiSumShape.h" #include "btGjkPairDetector.h" #include "btPointCollector.h" -#include "LinearMath/btTransformUtil.h" -#ifdef BT_USE_DOUBLE_PRECISION -#define MAX_ITERATIONS 64 -#else -#define MAX_ITERATIONS 32 -#endif -btGjkConvexCast::btGjkConvexCast(const btConvexShape* convexA,const btConvexShape* convexB,btSimplexSolverInterface* simplexSolver) +btGjkConvexCast::btGjkConvexCast(btConvexShape* convexA,btConvexShape* convexB,btSimplexSolverInterface* simplexSolver) :m_simplexSolver(simplexSolver), m_convexA(convexA), m_convexB(convexB) @@ -43,113 +38,120 @@ bool btGjkConvexCast::calcTimeOfImpact( { - m_simplexSolver->reset(); + btMinkowskiSumShape combi(m_convexA,m_convexB); + btMinkowskiSumShape* convex = &combi; - /// compute linear velocity for this interval, to interpolate - //assume no rotation/angular velocity, assert here? - btVector3 linVelA,linVelB; - linVelA = toA.getOrigin()-fromA.getOrigin(); - linVelB = toB.getOrigin()-fromB.getOrigin(); + btTransform rayFromLocalA; + btTransform rayToLocalA; + + rayFromLocalA = fromA.inverse()* fromB; + rayToLocalA = toA.inverse()* toB; + + + btTransform trA,trB; + trA = btTransform(fromA); + trB = btTransform(fromB); + trA.setOrigin(btPoint3(0,0,0)); + trB.setOrigin(btPoint3(0,0,0)); + + convex->setTransformA(trA); + convex->setTransformB(trB); + + + + + btScalar radius = btScalar(0.01); - btScalar radius = btScalar(0.001); btScalar lambda = btScalar(0.); - btVector3 v(1,0,0); - - int maxIter = MAX_ITERATIONS; - + btVector3 s = rayFromLocalA.getOrigin(); + btVector3 r = rayToLocalA.getOrigin()-rayFromLocalA.getOrigin(); + btVector3 x = s; btVector3 n; - n.setValue(btScalar(0.),btScalar(0.),btScalar(0.)); + n.setValue(0,0,0); bool hasResult = false; btVector3 c; - btVector3 r = (linVelA-linVelB); btScalar lastLambda = lambda; - //btScalar epsilon = btScalar(0.001); - int numIter = 0; //first solution, using GJK + //no penetration support for now, perhaps pass a pointer when we really want it + btConvexPenetrationDepthSolver* penSolverPtr = 0; btTransform identityTrans; identityTrans.setIdentity(); + btSphereShape raySphere(btScalar(0.0)); + raySphere.setMargin(btScalar(0.)); -// result.drawCoordSystem(sphereTr); + btTransform sphereTr; + sphereTr.setIdentity(); + sphereTr.setOrigin( rayFromLocalA.getOrigin()); - btPointCollector pointCollector; + result.drawCoordSystem(sphereTr); + { + btPointCollector pointCollector1; + btGjkPairDetector gjk(&raySphere,convex,m_simplexSolver,penSolverPtr); - - btGjkPairDetector gjk(m_convexA,m_convexB,m_simplexSolver,0);//m_penetrationDepthSolver); - btGjkPairDetector::ClosestPointInput input; + btGjkPairDetector::ClosestPointInput input; + input.m_transformA = sphereTr; + input.m_transformB = identityTrans; + gjk.getClosestPoints(input,pointCollector1,0); - //we don't use margins during CCD - // gjk.setIgnoreMargin(true); + hasResult = pointCollector1.m_hasResult; + c = pointCollector1.m_pointInWorld; + n = pointCollector1.m_normalOnBInWorld; + } - input.m_transformA = fromA; - input.m_transformB = fromB; - gjk.getClosestPoints(input,pointCollector,0); - - hasResult = pointCollector.m_hasResult; - c = pointCollector.m_pointInWorld; + if (hasResult) { btScalar dist; - dist = pointCollector.m_distance; - n = pointCollector.m_normalOnBInWorld; - - + dist = (c-x).length(); + if (dist < radius) + { + //penetration + lastLambda = btScalar(1.); + } //not close enough while (dist > radius) { - numIter++; - if (numIter > maxIter) - { - return false; //todo: report a failure - } - btScalar dLambda = btScalar(0.); - - btScalar projectedLinearVelocity = r.dot(n); - dLambda = dist / (projectedLinearVelocity); + n = x - c; + btScalar nDotr = n.dot(r); - lambda = lambda - dLambda; - - if (lambda > btScalar(1.)) + if (nDotr >= -(SIMD_EPSILON*SIMD_EPSILON)) return false; - - if (lambda < btScalar(0.)) - return false; - - //todo: next check with relative epsilon + + lambda = lambda - n.dot(n) / nDotr; if (lambda <= lastLambda) - { - return false; - //n.setValue(0,0,0); break; - } + lastLambda = lambda; - //interpolate to next lambda - result.DebugDraw( lambda ); - input.m_transformA.getOrigin().setInterpolate3(fromA.getOrigin(),toA.getOrigin(),lambda); - input.m_transformB.getOrigin().setInterpolate3(fromB.getOrigin(),toB.getOrigin(),lambda); - + x = s + lambda * r; + + sphereTr.setOrigin( x ); + result.drawCoordSystem(sphereTr); + btPointCollector pointCollector; + btGjkPairDetector gjk(&raySphere,convex,m_simplexSolver,penSolverPtr); + btGjkPairDetector::ClosestPointInput input; + input.m_transformA = sphereTr; + input.m_transformB = identityTrans; gjk.getClosestPoints(input,pointCollector,0); if (pointCollector.m_hasResult) { if (pointCollector.m_distance < btScalar(0.)) { + //degeneracy, report a hit result.m_fraction = lastLambda; - n = pointCollector.m_normalOnBInWorld; - result.m_normal=n; - result.m_hitPoint = pointCollector.m_pointInWorld; + result.m_normal = n; return true; } - c = pointCollector.m_pointInWorld; - n = pointCollector.m_normalOnBInWorld; - dist = pointCollector.m_distance; + c = pointCollector.m_pointInWorld; + dist = (c-x).length(); } else { //?? @@ -158,19 +160,15 @@ bool btGjkConvexCast::calcTimeOfImpact( } - //is n normalized? - //don't report time of impact for motion away from the contact normal (or causes minor penetration) - if (n.dot(r)>=-result.m_allowedPenetration) - return false; - - result.m_fraction = lambda; - result.m_normal = n; - result.m_hitPoint = c; - return true; + if (lastLambda < btScalar(1.)) + { + + result.m_fraction = lastLambda; + result.m_normal = n; + return true; + } } return false; - - } diff --git a/extern/bullet2/src/BulletCollision/NarrowPhaseCollision/btGjkConvexCast.h b/extern/bullet2/src/BulletCollision/NarrowPhaseCollision/btGjkConvexCast.h index a977c9e83f7..3905c45e6d6 100644 --- a/extern/bullet2/src/BulletCollision/NarrowPhaseCollision/btGjkConvexCast.h +++ b/extern/bullet2/src/BulletCollision/NarrowPhaseCollision/btGjkConvexCast.h @@ -18,9 +18,9 @@ subject to the following restrictions: #ifndef GJK_CONVEX_CAST_H #define GJK_CONVEX_CAST_H -#include "BulletCollision/CollisionShapes/btCollisionMargin.h" +#include "../CollisionShapes/btCollisionMargin.h" -#include "LinearMath/btVector3.h" +#include "../../LinearMath/btVector3.h" #include "btConvexCast.h" class btConvexShape; class btMinkowskiSumShape; @@ -30,12 +30,12 @@ class btMinkowskiSumShape; class btGjkConvexCast : public btConvexCast { btSimplexSolverInterface* m_simplexSolver; - const btConvexShape* m_convexA; - const btConvexShape* m_convexB; + btConvexShape* m_convexA; + btConvexShape* m_convexB; public: - btGjkConvexCast(const btConvexShape* convexA,const btConvexShape* convexB,btSimplexSolverInterface* simplexSolver); + btGjkConvexCast(btConvexShape* convexA,btConvexShape* convexB,btSimplexSolverInterface* simplexSolver); /// cast a convex against another convex object virtual bool calcTimeOfImpact( diff --git a/extern/bullet2/src/BulletCollision/NarrowPhaseCollision/btGjkEpa.cpp b/extern/bullet2/src/BulletCollision/NarrowPhaseCollision/btGjkEpa.cpp index 36cdeeaefdb..8abdfdbb7e5 100644 --- a/extern/bullet2/src/BulletCollision/NarrowPhaseCollision/btGjkEpa.cpp +++ b/extern/bullet2/src/BulletCollision/NarrowPhaseCollision/btGjkEpa.cpp @@ -26,7 +26,7 @@ Nov.2006 #include "btGjkEpa.h" #include //for memset -#include "LinearMath/btStackAlloc.h" +#include #if defined(DEBUG) || defined (_DEBUG) #include //for debug printf @@ -580,8 +580,8 @@ using namespace gjkepa_impl; // -bool btGjkEpaSolver::Collide(const btConvexShape *shape0,const btTransform &wtrs0, - const btConvexShape *shape1,const btTransform &wtrs1, +bool btGjkEpaSolver::Collide(btConvexShape *shape0,const btTransform &wtrs0, + btConvexShape *shape1,const btTransform &wtrs1, btScalar radialmargin, btStackAlloc* stackAlloc, sResults& results) @@ -602,13 +602,13 @@ GJK gjk(stackAlloc, wtrs1.getBasis(),wtrs1.getOrigin(),shape1, radialmargin+EPA_accuracy); const Z collide(gjk.SearchOrigin()); -results.gjk_iterations = static_cast(gjk.iterations+1); +results.gjk_iterations = gjk.iterations+1; if(collide) { /* Then EPA for penetration depth */ EPA epa(&gjk); const F pd(epa.EvaluatePD()); - results.epa_iterations = static_cast(epa.iterations+1); + results.epa_iterations = epa.iterations+1; if(pd>0) { results.status = sResults::Penetrating; diff --git a/extern/bullet2/src/BulletCollision/NarrowPhaseCollision/btGjkEpa.h b/extern/bullet2/src/BulletCollision/NarrowPhaseCollision/btGjkEpa.h index 1c256f41939..759b30bb17f 100644 --- a/extern/bullet2/src/BulletCollision/NarrowPhaseCollision/btGjkEpa.h +++ b/extern/bullet2/src/BulletCollision/NarrowPhaseCollision/btGjkEpa.h @@ -21,7 +21,7 @@ Nov.2006 #ifndef _05E48D53_04E0_49ad_BB0A_D74FE62E7366_ #define _05E48D53_04E0_49ad_BB0A_D74FE62E7366_ -#include "BulletCollision/CollisionShapes/btConvexShape.h" +#include "../CollisionShapes/btConvexShape.h" class btStackAlloc; @@ -35,7 +35,7 @@ struct sResults Separated, /* Shapes doesnt penetrate */ Penetrating, /* Shapes are penetrating */ GJK_Failed, /* GJK phase fail, no big issue, shapes are probably just 'touching' */ - EPA_Failed /* EPA phase fail, bigger problem, need to save parameters, and debug */ + EPA_Failed, /* EPA phase fail, bigger problem, need to save parameters, and debug */ } status; btVector3 witnesses[2]; btVector3 normal; @@ -43,8 +43,8 @@ struct sResults int epa_iterations; int gjk_iterations; }; -static bool Collide(const btConvexShape* shape0,const btTransform& wtrs0, - const btConvexShape* shape1,const btTransform& wtrs1, +static bool Collide(btConvexShape* shape0,const btTransform& wtrs0, + btConvexShape* shape1,const btTransform& wtrs1, btScalar radialmargin, btStackAlloc* stackAlloc, sResults& results); diff --git a/extern/bullet2/src/BulletCollision/NarrowPhaseCollision/btGjkEpa2.cpp b/extern/bullet2/src/BulletCollision/NarrowPhaseCollision/btGjkEpa2.cpp deleted file mode 100644 index ccfc22ee673..00000000000 --- a/extern/bullet2/src/BulletCollision/NarrowPhaseCollision/btGjkEpa2.cpp +++ /dev/null @@ -1,943 +0,0 @@ -/* -Bullet Continuous Collision Detection and Physics Library -Copyright (c) 2003-2008 Erwin Coumans http://continuousphysics.com/Bullet/ - -This software is provided 'as-is', without any express or implied warranty. -In no event will the authors be held liable for any damages arising from the -use of this software. -Permission is granted to anyone to use this software for any purpose, -including commercial applications, and to alter it and redistribute it -freely, -subject to the following restrictions: - -1. The origin of this software must not be misrepresented; you must not -claim that you wrote the original software. If you use this software in a -product, an acknowledgment in the product documentation would be appreciated -but is not required. -2. Altered source versions must be plainly marked as such, and must not be -misrepresented as being the original software. -3. This notice may not be removed or altered from any source distribution. -*/ - -/* -GJK-EPA collision solver by Nathanael Presson, 2008 -*/ -#include "BulletCollision/CollisionShapes/btConvexInternalShape.h" -#include "BulletCollision/CollisionShapes/btSphereShape.h" -#include "btGjkEpa2.h" - -#if defined(DEBUG) || defined (_DEBUG) -#include //for debug printf -#ifdef __SPU__ -#include -#define printf spu_printf -#endif //__SPU__ -#endif - -namespace gjkepa2_impl -{ - -// Config - - /* GJK */ -#define GJK_MAX_ITERATIONS 128 -#define GJK_ACCURARY ((btScalar)0.0001) -#define GJK_MIN_DISTANCE ((btScalar)0.0001) -#define GJK_DUPLICATED_EPS ((btScalar)0.0001) -#define GJK_SIMPLEX2_EPS ((btScalar)0.0) -#define GJK_SIMPLEX3_EPS ((btScalar)0.0) -#define GJK_SIMPLEX4_EPS ((btScalar)0.0) - - /* EPA */ -#define EPA_MAX_VERTICES 64 -#define EPA_MAX_FACES (EPA_MAX_VERTICES*2) -#define EPA_MAX_ITERATIONS 255 -#define EPA_ACCURACY ((btScalar)0.0001) -#define EPA_FALLBACK (10*EPA_ACCURACY) -#define EPA_PLANE_EPS ((btScalar)0.00001) -#define EPA_INSIDE_EPS ((btScalar)0.01) - - -// Shorthands -typedef unsigned int U; -typedef unsigned char U1; - -// MinkowskiDiff -struct MinkowskiDiff - { - const btConvexShape* m_shapes[2]; - btMatrix3x3 m_toshape1; - btTransform m_toshape0; - btVector3 (btConvexShape::*Ls)(const btVector3&) const; - void EnableMargin(bool enable) - { - if(enable) - Ls=&btConvexShape::localGetSupportingVertex; - else - Ls=&btConvexShape::localGetSupportingVertexWithoutMargin; - } - inline btVector3 Support0(const btVector3& d) const - { - return(((m_shapes[0])->*(Ls))(d)); - } - inline btVector3 Support1(const btVector3& d) const - { - return(m_toshape0*((m_shapes[1])->*(Ls))(m_toshape1*d)); - } - inline btVector3 Support(const btVector3& d) const - { - return(Support0(d)-Support1(-d)); - } - btVector3 Support(const btVector3& d,U index) const - { - if(index) - return(Support1(d)); - else - return(Support0(d)); - } - }; - -typedef MinkowskiDiff tShape; - - -// GJK -struct GJK -{ -/* Types */ -struct sSV - { - btVector3 d,w; - }; -struct sSimplex - { - sSV* c[4]; - btScalar p[4]; - U rank; - }; -struct eStatus { enum _ { - Valid, - Inside, - Failed };}; -/* Fields */ -tShape m_shape; -btVector3 m_ray; -btScalar m_distance; -sSimplex m_simplices[2]; -sSV m_store[4]; -sSV* m_free[4]; -U m_nfree; -U m_current; -sSimplex* m_simplex; -eStatus::_ m_status; -/* Methods */ - GJK() - { - Initialize(); - } -void Initialize() - { - m_ray = btVector3(0,0,0); - m_nfree = 0; - m_status = eStatus::Failed; - m_current = 0; - m_distance = 0; - } -eStatus::_ Evaluate(const tShape& shapearg,const btVector3& guess) - { - U iterations=0; - btScalar sqdist=0; - btScalar alpha=0; - btVector3 lastw[4]; - U clastw=0; - /* Initialize solver */ - m_free[0] = &m_store[0]; - m_free[1] = &m_store[1]; - m_free[2] = &m_store[2]; - m_free[3] = &m_store[3]; - m_nfree = 4; - m_current = 0; - m_status = eStatus::Valid; - m_shape = shapearg; - m_distance = 0; - /* Initialize simplex */ - m_simplices[0].rank = 0; - m_ray = guess; - const btScalar sqrl= m_ray.length2(); - appendvertice(m_simplices[0],sqrl>0?-m_ray:btVector3(1,0,0)); - m_simplices[0].p[0] = 1; - m_ray = m_simplices[0].c[0]->w; - sqdist = sqrl; - lastw[0] = - lastw[1] = - lastw[2] = - lastw[3] = m_ray; - /* Loop */ - do { - const U next=1-m_current; - sSimplex& cs=m_simplices[m_current]; - sSimplex& ns=m_simplices[next]; - /* Check zero */ - const btScalar rl=m_ray.length(); - if(rlw; - bool found=false; - for(U i=0;i<4;++i) - { - if((w-lastw[i]).length2()w, - cs.c[1]->w, - weights,mask);break; - case 3: sqdist=projectorigin( cs.c[0]->w, - cs.c[1]->w, - cs.c[2]->w, - weights,mask);break; - case 4: sqdist=projectorigin( cs.c[0]->w, - cs.c[1]->w, - cs.c[2]->w, - cs.c[3]->w, - weights,mask);break; - } - if(sqdist>=0) - {/* Valid */ - ns.rank = 0; - m_ray = btVector3(0,0,0); - m_current = next; - for(U i=0,ni=cs.rank;iw*weights[i]; - } - else - { - m_free[m_nfree++] = cs.c[i]; - } - } - if(mask==15) m_status=eStatus::Inside; - } - else - {/* Return old simplex */ - removevertice(m_simplices[m_current]); - break; - } - m_status=((++iterations)rank) - { - case 1: - { - for(U i=0;i<3;++i) - { - btVector3 axis=btVector3(0,0,0); - axis[i]=1; - appendvertice(*m_simplex, axis); - if(EncloseOrigin()) return(true); - removevertice(*m_simplex); - appendvertice(*m_simplex,-axis); - if(EncloseOrigin()) return(true); - removevertice(*m_simplex); - } - } - break; - case 2: - { - const btVector3 d=m_simplex->c[1]->w-m_simplex->c[0]->w; - for(U i=0;i<3;++i) - { - btVector3 axis=btVector3(0,0,0); - axis[i]=1; - const btVector3 p=cross(d,axis); - if(p.length2()>0) - { - appendvertice(*m_simplex, p); - if(EncloseOrigin()) return(true); - removevertice(*m_simplex); - appendvertice(*m_simplex,-p); - if(EncloseOrigin()) return(true); - removevertice(*m_simplex); - } - } - } - break; - case 3: - { - const btVector3 n=cross(m_simplex->c[1]->w-m_simplex->c[0]->w, - m_simplex->c[2]->w-m_simplex->c[0]->w); - if(n.length2()>0) - { - appendvertice(*m_simplex,n); - if(EncloseOrigin()) return(true); - removevertice(*m_simplex); - appendvertice(*m_simplex,-n); - if(EncloseOrigin()) return(true); - removevertice(*m_simplex); - } - } - break; - case 4: - { - if(btFabs(det( m_simplex->c[0]->w-m_simplex->c[3]->w, - m_simplex->c[1]->w-m_simplex->c[3]->w, - m_simplex->c[2]->w-m_simplex->c[3]->w))>0) - return(true); - } - break; - } - return(false); - } -/* Internals */ -void getsupport(const btVector3& d,sSV& sv) const - { - sv.d = d/d.length(); - sv.w = m_shape.Support(sv.d); - } -void removevertice(sSimplex& simplex) - { - m_free[m_nfree++]=simplex.c[--simplex.rank]; - } -void appendvertice(sSimplex& simplex,const btVector3& v) - { - simplex.p[simplex.rank]=0; - simplex.c[simplex.rank]=m_free[--m_nfree]; - getsupport(v,*simplex.c[simplex.rank++]); - } -static btScalar det(const btVector3& a,const btVector3& b,const btVector3& c) - { - return( a.y()*b.z()*c.x()+a.z()*b.x()*c.y()- - a.x()*b.z()*c.y()-a.y()*b.x()*c.z()+ - a.x()*b.y()*c.z()-a.z()*b.y()*c.x()); - } -static btScalar projectorigin( const btVector3& a, - const btVector3& b, - btScalar* w,U& m) - { - const btVector3 d=b-a; - const btScalar l=d.length2(); - if(l>GJK_SIMPLEX2_EPS) - { - const btScalar t(l>0?-dot(a,d)/l:0); - if(t>=1) { w[0]=0;w[1]=1;m=2;return(b.length2()); } - else if(t<=0) { w[0]=1;w[1]=0;m=1;return(a.length2()); } - else { w[0]=1-(w[1]=t);m=3;return((a+d*t).length2()); } - } - return(-1); - } -static btScalar projectorigin( const btVector3& a, - const btVector3& b, - const btVector3& c, - btScalar* w,U& m) - { - static const U imd3[]={1,2,0}; - const btVector3* vt[]={&a,&b,&c}; - const btVector3 dl[]={a-b,b-c,c-a}; - const btVector3 n=cross(dl[0],dl[1]); - const btScalar l=n.length2(); - if(l>GJK_SIMPLEX3_EPS) - { - btScalar mindist=-1; - btScalar subw[2]; - U subm; - for(U i=0;i<3;++i) - { - if(dot(*vt[i],cross(dl[i],n))>0) - { - const U j=imd3[i]; - const btScalar subd(projectorigin(*vt[i],*vt[j],subw,subm)); - if((mindist<0)||(subd(((subm&1)?1<GJK_SIMPLEX4_EPS)) - { - btScalar mindist=-1; - btScalar subw[3]; - U subm; - for(U i=0;i<3;++i) - { - const U j=imd3[i]; - const btScalar s=vl*dot(d,cross(dl[i],dl[j])); - if(s>0) - { - const btScalar subd=projectorigin(*vt[i],*vt[j],d,subw,subm); - if((mindist<0)||(subd((subm&1?1<e[ea]=(U1)eb;fa->f[ea]=fb; - fb->e[eb]=(U1)ea;fb->f[eb]=fa; - } -static inline void append(sList& list,sFace* face) - { - face->l[0] = 0; - face->l[1] = list.root; - if(list.root) list.root->l[0]=face; - list.root = face; - ++list.count; - } -static inline void remove(sList& list,sFace* face) - { - if(face->l[1]) face->l[1]->l[0]=face->l[0]; - if(face->l[0]) face->l[0]->l[1]=face->l[1]; - if(face==list.root) list.root=face->l[1]; - --list.count; - } - - -void Initialize() - { - m_status = eStatus::Failed; - m_normal = btVector3(0,0,0); - m_depth = 0; - m_nextsv = 0; - for(U i=0;i1)&&gjk.EncloseOrigin()) - { - - /* Clean up */ - while(m_hull.root) - { - sFace* f = m_hull.root; - remove(m_hull,f); - append(m_stock,f); - } - m_status = eStatus::Valid; - m_nextsv = 0; - /* Orient simplex */ - if(gjk.det( simplex.c[0]->w-simplex.c[3]->w, - simplex.c[1]->w-simplex.c[3]->w, - simplex.c[2]->w-simplex.c[3]->w)<0) - { - btSwap(simplex.c[0],simplex.c[1]); - btSwap(simplex.p[0],simplex.p[1]); - } - /* Build initial hull */ - sFace* tetra[]={newface(simplex.c[0],simplex.c[1],simplex.c[2],true), - newface(simplex.c[1],simplex.c[0],simplex.c[3],true), - newface(simplex.c[2],simplex.c[1],simplex.c[3],true), - newface(simplex.c[0],simplex.c[2],simplex.c[3],true)}; - if(m_hull.count==4) - { - sFace* best=findbest(); - sFace outer=*best; - U pass=0; - U iterations=0; - bind(tetra[0],0,tetra[1],0); - bind(tetra[0],1,tetra[2],0); - bind(tetra[0],2,tetra[3],0); - bind(tetra[1],1,tetra[3],2); - bind(tetra[1],2,tetra[2],1); - bind(tetra[2],2,tetra[3],1); - m_status=eStatus::Valid; - for(;iterationspass = (U1)(++pass); - gjk.getsupport(best->n,*w); - const btScalar wdist=dot(best->n,w->w)-best->d; - if(wdist>EPA_ACCURACY) - { - for(U j=0;(j<3)&&valid;++j) - { - valid&=expand( pass,w, - best->f[j],best->e[j], - horizon); - } - if(valid&&(horizon.nf>=3)) - { - bind(horizon.cf,1,horizon.ff,2); - remove(m_hull,best); - append(m_stock,best); - best=findbest(); - if(best->p>=outer.p) outer=*best; - } else { m_status=eStatus::InvalidHull;break; } - } else { m_status=eStatus::AccuraryReached;break; } - } else { m_status=eStatus::OutOfVertices;break; } - } - const btVector3 projection=outer.n*outer.d; - m_normal = outer.n; - m_depth = outer.d; - m_result.rank = 3; - m_result.c[0] = outer.c[0]; - m_result.c[1] = outer.c[1]; - m_result.c[2] = outer.c[2]; - m_result.p[0] = cross( outer.c[1]->w-projection, - outer.c[2]->w-projection).length(); - m_result.p[1] = cross( outer.c[2]->w-projection, - outer.c[0]->w-projection).length(); - m_result.p[2] = cross( outer.c[0]->w-projection, - outer.c[1]->w-projection).length(); - const btScalar sum=m_result.p[0]+m_result.p[1]+m_result.p[2]; - m_result.p[0] /= sum; - m_result.p[1] /= sum; - m_result.p[2] /= sum; - return(m_status); - } - } - /* Fallback */ - m_status = eStatus::FallBack; - m_normal = -guess; - const btScalar nl=m_normal.length(); - if(nl>0) - m_normal = m_normal/nl; - else - m_normal = btVector3(1,0,0); - m_depth = 0; - m_result.rank=1; - m_result.c[0]=simplex.c[0]; - m_result.p[0]=1; - return(m_status); - } -sFace* newface(sSV* a,sSV* b,sSV* c,bool forced) - { - if(m_stock.root) - { - sFace* face=m_stock.root; - remove(m_stock,face); - append(m_hull,face); - face->pass = 0; - face->c[0] = a; - face->c[1] = b; - face->c[2] = c; - face->n = cross(b->w-a->w,c->w-a->w); - const btScalar l=face->n.length(); - const bool v=l>EPA_ACCURACY; - face->p = btMin(btMin( - dot(a->w,cross(face->n,a->w-b->w)), - dot(b->w,cross(face->n,b->w-c->w))), - dot(c->w,cross(face->n,c->w-a->w))) / - (v?l:1); - face->p = face->p>=-EPA_INSIDE_EPS?0:face->p; - if(v) - { - face->d = dot(a->w,face->n)/l; - face->n /= l; - if(forced||(face->d>=-EPA_PLANE_EPS)) - { - return(face); - } else m_status=eStatus::NonConvex; - } else m_status=eStatus::Degenerated; - remove(m_hull,face); - append(m_stock,face); - return(0); - } - m_status=m_stock.root?eStatus::OutOfVertices:eStatus::OutOfFaces; - return(0); - } -sFace* findbest() - { - sFace* minf=m_hull.root; - btScalar mind=minf->d*minf->d; - btScalar maxp=minf->p; - for(sFace* f=minf->l[1];f;f=f->l[1]) - { - const btScalar sqd=f->d*f->d; - if((f->p>=maxp)&&(sqdp; - } - } - return(minf); - } -bool expand(U pass,sSV* w,sFace* f,U e,sHorizon& horizon) - { - static const U i1m3[]={1,2,0}; - static const U i2m3[]={2,0,1}; - if(f->pass!=pass) - { - const U e1=i1m3[e]; - if((dot(f->n,w->w)-f->d)<-EPA_PLANE_EPS) - { - sFace* nf=newface(f->c[e1],f->c[e],w,false); - if(nf) - { - bind(nf,0,f,e); - if(horizon.cf) bind(horizon.cf,1,nf,2); else horizon.ff=nf; - horizon.cf=nf; - ++horizon.nf; - return(true); - } - } - else - { - const U e2=i2m3[e]; - f->pass = (U1)pass; - if( expand(pass,w,f->f[e1],f->e[e1],horizon)&& - expand(pass,w,f->f[e2],f->e[e2],horizon)) - { - remove(m_hull,f); - append(m_stock,f); - return(true); - } - } - } - return(false); - } - -}; - -// -static void Initialize( const btConvexShape* shape0,const btTransform& wtrs0, - const btConvexShape* shape1,const btTransform& wtrs1, - btGjkEpaSolver2::sResults& results, - tShape& shape, - bool withmargins) -{ -/* Results */ -results.witnesses[0] = -results.witnesses[1] = btVector3(0,0,0); -results.status = btGjkEpaSolver2::sResults::Separated; -/* Shape */ -shape.m_shapes[0] = shape0; -shape.m_shapes[1] = shape1; -shape.m_toshape1 = wtrs1.getBasis().transposeTimes(wtrs0.getBasis()); -shape.m_toshape0 = wtrs0.inverseTimes(wtrs1); -shape.EnableMargin(withmargins); -} - -} - -// -// Api -// - -using namespace gjkepa2_impl; - -// -int btGjkEpaSolver2::StackSizeRequirement() -{ -return(sizeof(GJK)+sizeof(EPA)); -} - -// -bool btGjkEpaSolver2::Distance( const btConvexShape* shape0, - const btTransform& wtrs0, - const btConvexShape* shape1, - const btTransform& wtrs1, - const btVector3& guess, - sResults& results) -{ -tShape shape; -Initialize(shape0,wtrs0,shape1,wtrs1,results,shape,false); -GJK gjk; -GJK::eStatus::_ gjk_status=gjk.Evaluate(shape,guess); -if(gjk_status==GJK::eStatus::Valid) - { - btVector3 w0=btVector3(0,0,0); - btVector3 w1=btVector3(0,0,0); - for(U i=0;irank;++i) - { - const btScalar p=gjk.m_simplex->p[i]; - w0+=shape.Support( gjk.m_simplex->c[i]->d,0)*p; - w1+=shape.Support(-gjk.m_simplex->c[i]->d,1)*p; - } - results.witnesses[0] = wtrs0*w0; - results.witnesses[1] = wtrs0*w1; - results.normal = w0-w1; - results.distance = results.normal.length(); - results.normal /= results.distance>GJK_MIN_DISTANCE?results.distance:1; - return(true); - } - else - { - results.status = gjk_status==GJK::eStatus::Inside? - sResults::Penetrating : - sResults::GJK_Failed ; - return(false); - } -} - -// -bool btGjkEpaSolver2::Penetration( const btConvexShape* shape0, - const btTransform& wtrs0, - const btConvexShape* shape1, - const btTransform& wtrs1, - const btVector3& guess, - sResults& results, - bool usemargins) -{ -tShape shape; -Initialize(shape0,wtrs0,shape1,wtrs1,results,shape,usemargins); -GJK gjk; -GJK::eStatus::_ gjk_status=gjk.Evaluate(shape,-guess); -switch(gjk_status) - { - case GJK::eStatus::Inside: - { - EPA epa; - EPA::eStatus::_ epa_status=epa.Evaluate(gjk,-guess); - if(epa_status!=EPA::eStatus::Failed) - { - btVector3 w0=btVector3(0,0,0); - for(U i=0;id,0)*epa.m_result.p[i]; - } - results.status = sResults::Penetrating; - results.witnesses[0] = wtrs0*w0; - results.witnesses[1] = wtrs0*(w0-epa.m_normal*epa.m_depth); - results.normal = -epa.m_normal; - results.distance = -epa.m_depth; - return(true); - } else results.status=sResults::EPA_Failed; - } - break; - case GJK::eStatus::Failed: - results.status=sResults::GJK_Failed; - break; - } -return(false); -} - -// -btScalar btGjkEpaSolver2::SignedDistance(const btVector3& position, - btScalar margin, - const btConvexShape* shape0, - const btTransform& wtrs0, - sResults& results) -{ -tShape shape; -btSphereShape shape1(margin); -btTransform wtrs1(btQuaternion(0,0,0,1),position); -Initialize(shape0,wtrs0,&shape1,wtrs1,results,shape,false); -GJK gjk; -GJK::eStatus::_ gjk_status=gjk.Evaluate(shape,btVector3(1,1,1)); -if(gjk_status==GJK::eStatus::Valid) - { - btVector3 w0=btVector3(0,0,0); - btVector3 w1=btVector3(0,0,0); - for(U i=0;irank;++i) - { - const btScalar p=gjk.m_simplex->p[i]; - w0+=shape.Support( gjk.m_simplex->c[i]->d,0)*p; - w1+=shape.Support(-gjk.m_simplex->c[i]->d,1)*p; - } - results.witnesses[0] = wtrs0*w0; - results.witnesses[1] = wtrs0*w1; - const btVector3 delta= results.witnesses[1]- - results.witnesses[0]; - const btScalar margin= shape0->getMargin()+ - shape1.getMargin(); - const btScalar length= delta.length(); - results.normal = delta/length; - results.witnesses[0] += results.normal*margin; - return(length-margin); - } - else - { - if(gjk_status==GJK::eStatus::Inside) - { - if(Penetration(shape0,wtrs0,&shape1,wtrs1,gjk.m_ray,results)) - { - const btVector3 delta= results.witnesses[0]- - results.witnesses[1]; - const btScalar length= delta.length(); - if (length >= SIMD_EPSILON) - results.normal = delta/length; - return(-length); - } - } - } -return(SIMD_INFINITY); -} - -// -bool btGjkEpaSolver2::SignedDistance(const btConvexShape* shape0, - const btTransform& wtrs0, - const btConvexShape* shape1, - const btTransform& wtrs1, - const btVector3& guess, - sResults& results) -{ -if(!Distance(shape0,wtrs0,shape1,wtrs1,guess,results)) - return(Penetration(shape0,wtrs0,shape1,wtrs1,guess,results,false)); - else - return(true); -} - -/* Symbols cleanup */ - -#undef GJK_MAX_ITERATIONS -#undef GJK_ACCURARY -#undef GJK_MIN_DISTANCE -#undef GJK_DUPLICATED_EPS -#undef GJK_SIMPLEX2_EPS -#undef GJK_SIMPLEX3_EPS -#undef GJK_SIMPLEX4_EPS - -#undef EPA_MAX_VERTICES -#undef EPA_MAX_FACES -#undef EPA_MAX_ITERATIONS -#undef EPA_ACCURACY -#undef EPA_FALLBACK -#undef EPA_PLANE_EPS -#undef EPA_INSIDE_EPS diff --git a/extern/bullet2/src/BulletCollision/NarrowPhaseCollision/btGjkEpa2.h b/extern/bullet2/src/BulletCollision/NarrowPhaseCollision/btGjkEpa2.h deleted file mode 100644 index a55214203d3..00000000000 --- a/extern/bullet2/src/BulletCollision/NarrowPhaseCollision/btGjkEpa2.h +++ /dev/null @@ -1,71 +0,0 @@ -/* -Bullet Continuous Collision Detection and Physics Library -Copyright (c) 2003-2008 Erwin Coumans http://continuousphysics.com/Bullet/ - -This software is provided 'as-is', without any express or implied warranty. -In no event will the authors be held liable for any damages arising from the -use of this software. -Permission is granted to anyone to use this software for any purpose, -including commercial applications, and to alter it and redistribute it -freely, -subject to the following restrictions: - -1. The origin of this software must not be misrepresented; you must not -claim that you wrote the original software. If you use this software in a -product, an acknowledgment in the product documentation would be appreciated -but is not required. -2. Altered source versions must be plainly marked as such, and must not be -misrepresented as being the original software. -3. This notice may not be removed or altered from any source distribution. -*/ - -/* -GJK-EPA collision solver by Nathanael Presson, 2008 -*/ -#ifndef _68DA1F85_90B7_4bb0_A705_83B4040A75C6_ -#define _68DA1F85_90B7_4bb0_A705_83B4040A75C6_ -#include "BulletCollision/CollisionShapes/btConvexShape.h" - -///btGjkEpaSolver contributed under zlib by Nathanael Presson -struct btGjkEpaSolver2 -{ -struct sResults - { - enum eStatus - { - Separated, /* Shapes doesnt penetrate */ - Penetrating, /* Shapes are penetrating */ - GJK_Failed, /* GJK phase fail, no big issue, shapes are probably just 'touching' */ - EPA_Failed /* EPA phase fail, bigger problem, need to save parameters, and debug */ - } status; - btVector3 witnesses[2]; - btVector3 normal; - btScalar distance; - }; - -static int StackSizeRequirement(); - -static bool Distance( const btConvexShape* shape0,const btTransform& wtrs0, - const btConvexShape* shape1,const btTransform& wtrs1, - const btVector3& guess, - sResults& results); - -static bool Penetration(const btConvexShape* shape0,const btTransform& wtrs0, - const btConvexShape* shape1,const btTransform& wtrs1, - const btVector3& guess, - sResults& results, - bool usemargins=true); - -static btScalar SignedDistance( const btVector3& position, - btScalar margin, - const btConvexShape* shape, - const btTransform& wtrs, - sResults& results); - -static bool SignedDistance( const btConvexShape* shape0,const btTransform& wtrs0, - const btConvexShape* shape1,const btTransform& wtrs1, - const btVector3& guess, - sResults& results); -}; - -#endif diff --git a/extern/bullet2/src/BulletCollision/NarrowPhaseCollision/btGjkEpaPenetrationDepthSolver.cpp b/extern/bullet2/src/BulletCollision/NarrowPhaseCollision/btGjkEpaPenetrationDepthSolver.cpp index c4f84ed4d75..87330493b60 100644 --- a/extern/bullet2/src/BulletCollision/NarrowPhaseCollision/btGjkEpaPenetrationDepthSolver.cpp +++ b/extern/bullet2/src/BulletCollision/NarrowPhaseCollision/btGjkEpaPenetrationDepthSolver.cpp @@ -18,10 +18,9 @@ subject to the following restrictions: #include "BulletCollision/CollisionShapes/btConvexShape.h" #include "btGjkEpaPenetrationDepthSolver.h" #include "BulletCollision/NarrowPhaseCollision/btGjkEpa.h" -#include "BulletCollision/NarrowPhaseCollision/btGjkEpa2.h" bool btGjkEpaPenetrationDepthSolver::calcPenDepth( btSimplexSolverInterface& simplexSolver, - const btConvexShape* pConvexA, const btConvexShape* pConvexB, + btConvexShape* pConvexA, btConvexShape* pConvexB, const btTransform& transformA, const btTransform& transformB, btVector3& v, btPoint3& wWitnessOnA, btPoint3& wWitnessOnB, class btIDebugDraw* debugDraw, btStackAlloc* stackAlloc ) @@ -33,20 +32,10 @@ bool btGjkEpaPenetrationDepthSolver::calcPenDepth( btSimplexSolverInterface& sim const btScalar radialmargin(btScalar(0.)); -//#define USE_ORIGINAL_GJK 1 -#ifdef USE_ORIGINAL_GJK btGjkEpaSolver::sResults results; if(btGjkEpaSolver::Collide( pConvexA,transformA, pConvexB,transformB, radialmargin,stackAlloc,results)) -#else - btVector3 guessVector(transformA.getOrigin()-transformB.getOrigin()); - btGjkEpaSolver2::sResults results; - if(btGjkEpaSolver2::Penetration(pConvexA,transformA, - pConvexB,transformB, - guessVector,results)) - -#endif { // debugDraw->drawLine(results.witnesses[1],results.witnesses[1]+results.normal,btVector3(255,0,0)); //resultOut->addContactPoint(results.normal,results.witnesses[1],-results.depth); diff --git a/extern/bullet2/src/BulletCollision/NarrowPhaseCollision/btGjkEpaPenetrationDepthSolver.h b/extern/bullet2/src/BulletCollision/NarrowPhaseCollision/btGjkEpaPenetrationDepthSolver.h index 2dc069ce5cf..3916ba0776c 100644 --- a/extern/bullet2/src/BulletCollision/NarrowPhaseCollision/btGjkEpaPenetrationDepthSolver.h +++ b/extern/bullet2/src/BulletCollision/NarrowPhaseCollision/btGjkEpaPenetrationDepthSolver.h @@ -26,7 +26,7 @@ class btGjkEpaPenetrationDepthSolver : public btConvexPenetrationDepthSolver public : bool calcPenDepth( btSimplexSolverInterface& simplexSolver, - const btConvexShape* pConvexA, const btConvexShape* pConvexB, + btConvexShape* pConvexA, btConvexShape* pConvexB, const btTransform& transformA, const btTransform& transformB, btVector3& v, btPoint3& wWitnessOnA, btPoint3& wWitnessOnB, class btIDebugDraw* debugDraw,btStackAlloc* stackAlloc ); diff --git a/extern/bullet2/src/BulletCollision/NarrowPhaseCollision/btGjkPairDetector.cpp b/extern/bullet2/src/BulletCollision/NarrowPhaseCollision/btGjkPairDetector.cpp index 01fb1a4b068..f1f3f7f7f6c 100644 --- a/extern/bullet2/src/BulletCollision/NarrowPhaseCollision/btGjkPairDetector.cpp +++ b/extern/bullet2/src/BulletCollision/NarrowPhaseCollision/btGjkPairDetector.cpp @@ -35,7 +35,7 @@ int gNumGjkChecks = 0; -btGjkPairDetector::btGjkPairDetector(const btConvexShape* objectA,const btConvexShape* objectB,btSimplexSolverInterface* simplexSolver,btConvexPenetrationDepthSolver* penetrationDepthSolver) +btGjkPairDetector::btGjkPairDetector(btConvexShape* objectA,btConvexShape* objectB,btSimplexSolverInterface* simplexSolver,btConvexPenetrationDepthSolver* penetrationDepthSolver) :m_cachedSeparatingAxis(btScalar(0.),btScalar(0.),btScalar(1.)), m_penetrationDepthSolver(penetrationDepthSolver), m_simplexSolver(simplexSolver), @@ -47,7 +47,7 @@ m_catchDegeneracies(1) { } -void btGjkPairDetector::getClosestPoints(const ClosestPointInput& input,Result& output,class btIDebugDraw* debugDraw,bool swapResults) +void btGjkPairDetector::getClosestPoints(const ClosestPointInput& input,Result& output,class btIDebugDraw* debugDraw) { btScalar distance=btScalar(0.); btVector3 normalInB(btScalar(0.),btScalar(0.),btScalar(0.)); @@ -144,13 +144,6 @@ void btGjkPairDetector::getClosestPoints(const ClosestPointInput& input,Result& break; } - if(m_cachedSeparatingAxis.length2() @@ -162,7 +169,7 @@ int btPersistentManifold::getCacheEntry(const btManifoldPoint& newPoint) const return nearestPoint; } -int btPersistentManifold::addManifoldPoint(const btManifoldPoint& newPoint) +void btPersistentManifold::AddManifoldPoint(const btManifoldPoint& newPoint) { assert(validContactDistance(newPoint)); @@ -175,7 +182,7 @@ int btPersistentManifold::addManifoldPoint(const btManifoldPoint& newPoint) #else insertIndex = 0; #endif - clearUserCache(m_pointCache[insertIndex]); + } else { @@ -183,9 +190,7 @@ int btPersistentManifold::addManifoldPoint(const btManifoldPoint& newPoint) } - btAssert(m_pointCache[insertIndex].m_userPersistentData==0); - m_pointCache[insertIndex] = newPoint; - return insertIndex; + replaceContactPoint(newPoint,insertIndex); } btScalar btPersistentManifold::getContactBreakingThreshold() const @@ -193,20 +198,10 @@ btScalar btPersistentManifold::getContactBreakingThreshold() const return gContactBreakingThreshold; } - - void btPersistentManifold::refreshContactPoints(const btTransform& trA,const btTransform& trB) { int i; -#ifdef DEBUG_PERSISTENCY - printf("refreshContactPoints posA = (%f,%f,%f) posB = (%f,%f,%f)\n", - trA.getOrigin().getX(), - trA.getOrigin().getY(), - trA.getOrigin().getZ(), - trB.getOrigin().getX(), - trB.getOrigin().getY(), - trB.getOrigin().getZ()); -#endif //DEBUG_PERSISTENCY + /// first refresh worldspace positions and distance for (i=getNumContacts()-1;i>=0;i--) { @@ -237,11 +232,6 @@ void btPersistentManifold::refreshContactPoints(const btTransform& trA,const btT if (distance2d > getContactBreakingThreshold()*getContactBreakingThreshold() ) { removeContactPoint(i); - } else - { - //contact point processed callback - if (gContactProcessedCallback) - (*gContactProcessedCallback)(manifoldPoint,m_body0,m_body1); } } } diff --git a/extern/bullet2/src/BulletCollision/NarrowPhaseCollision/btPersistentManifold.h b/extern/bullet2/src/BulletCollision/NarrowPhaseCollision/btPersistentManifold.h index c122eb865e8..a5918b84db3 100644 --- a/extern/bullet2/src/BulletCollision/NarrowPhaseCollision/btPersistentManifold.h +++ b/extern/bullet2/src/BulletCollision/NarrowPhaseCollision/btPersistentManifold.h @@ -17,10 +17,9 @@ subject to the following restrictions: #define PERSISTENT_MANIFOLD_H -#include "LinearMath/btVector3.h" -#include "LinearMath/btTransform.h" +#include "../../LinearMath/btVector3.h" +#include "../../LinearMath/btTransform.h" #include "btManifoldPoint.h" -#include "LinearMath/btAlignedAllocator.h" struct btCollisionResult; @@ -28,7 +27,6 @@ struct btCollisionResult; extern btScalar gContactBreakingThreshold; typedef bool (*ContactDestroyedCallback)(void* userPersistentData); -typedef bool (*ContactProcessedCallback)(btManifoldPoint& cp,void* body0,void* body1); extern ContactDestroyedCallback gContactDestroyedCallback; @@ -36,13 +34,8 @@ extern ContactDestroyedCallback gContactDestroyedCallback; #define MANIFOLD_CACHE_SIZE 4 -///btPersistentManifold is a contact point cache, it stays persistent as long as objects are overlapping in the broadphase. -///Those contact points are created by the collision narrow phase. -///The cache can be empty, or hold 1,2,3 or 4 points. Some collision algorithms (GJK) might only add one point at a time. -///updates/refreshes old contact points, and throw them away if necessary (distance becomes too large) -///reduces the cache to 4 points, when more then 4 points are added, using following rules: -///the contact point with deepest penetration is always kept, and it tries to maximuze the area covered by the points -///note that some pairs of objects might have more then one contact manifold. +///btPersistentManifold maintains contact points, and reduces them to 4. +///It does contact filtering/contact reduction. ATTRIBUTE_ALIGNED16( class) btPersistentManifold { @@ -62,23 +55,20 @@ ATTRIBUTE_ALIGNED16( class) btPersistentManifold public: - BT_DECLARE_ALIGNED_ALLOCATOR(); - - int m_index1a; + int m_index1; btPersistentManifold(); - btPersistentManifold(void* body0,void* body1,int bla) + btPersistentManifold(void* body0,void* body1) : m_body0(body0),m_body1(body1),m_cachedPoints(0) { - (void)bla; } - SIMD_FORCE_INLINE void* getBody0() { return m_body0;} - SIMD_FORCE_INLINE void* getBody1() { return m_body1;} + inline void* getBody0() { return m_body0;} + inline void* getBody1() { return m_body1;} - SIMD_FORCE_INLINE const void* getBody0() const { return m_body0;} - SIMD_FORCE_INLINE const void* getBody1() const { return m_body1;} + inline const void* getBody0() const { return m_body0;} + inline const void* getBody1() const { return m_body1;} void setBodies(void* body0,void* body1) { @@ -92,15 +82,15 @@ public: void DebugPersistency(); #endif // - SIMD_FORCE_INLINE int getNumContacts() const { return m_cachedPoints;} + inline int getNumContacts() const { return m_cachedPoints;} - SIMD_FORCE_INLINE const btManifoldPoint& getContactPoint(int index) const + inline const btManifoldPoint& getContactPoint(int index) const { btAssert(index < m_cachedPoints); return m_pointCache[index]; } - SIMD_FORCE_INLINE btManifoldPoint& getContactPoint(int index) + inline btManifoldPoint& getContactPoint(int index) { btAssert(index < m_cachedPoints); return m_pointCache[index]; @@ -111,7 +101,7 @@ public: int getCacheEntry(const btManifoldPoint& newPoint) const; - int addManifoldPoint( const btManifoldPoint& newPoint); + void AddManifoldPoint( const btManifoldPoint& newPoint); void removeContactPoint (int index) { @@ -124,11 +114,6 @@ public: m_pointCache[index] = m_pointCache[lastUsedIndex]; //get rid of duplicated userPersistentData pointer m_pointCache[lastUsedIndex].m_userPersistentData = 0; - m_pointCache[lastUsedIndex].m_appliedImpulse = 0.f; - m_pointCache[lastUsedIndex].m_lateralFrictionInitialized = false; - m_pointCache[lastUsedIndex].m_appliedImpulseLateral1 = 0.f; - m_pointCache[lastUsedIndex].m_appliedImpulseLateral2 = 0.f; - m_pointCache[lastUsedIndex].m_lifeTime = 0; } btAssert(m_pointCache[lastUsedIndex].m_userPersistentData==0); @@ -141,20 +126,12 @@ public: #define MAINTAIN_PERSISTENCY 1 #ifdef MAINTAIN_PERSISTENCY int lifeTime = m_pointCache[insertIndex].getLifeTime(); - btScalar appliedImpulse = m_pointCache[insertIndex].m_appliedImpulse; - btScalar appliedLateralImpulse1 = m_pointCache[insertIndex].m_appliedImpulseLateral1; - btScalar appliedLateralImpulse2 = m_pointCache[insertIndex].m_appliedImpulseLateral2; - btAssert(lifeTime>=0); void* cache = m_pointCache[insertIndex].m_userPersistentData; m_pointCache[insertIndex] = newPoint; m_pointCache[insertIndex].m_userPersistentData = cache; - m_pointCache[insertIndex].m_appliedImpulse = appliedImpulse; - m_pointCache[insertIndex].m_appliedImpulseLateral1 = appliedLateralImpulse1; - m_pointCache[insertIndex].m_appliedImpulseLateral2 = appliedLateralImpulse2; - m_pointCache[insertIndex].m_lifeTime = lifeTime; #else clearUserCache(m_pointCache[insertIndex]); @@ -170,16 +147,7 @@ public: /// calculated new worldspace coordinates and depth, and reject points that exceed the collision margin void refreshContactPoints( const btTransform& trA,const btTransform& trB); - - SIMD_FORCE_INLINE void clearManifold() - { - int i; - for (i=0;i -#include "BulletCollision/CollisionShapes/btConvexShape.h" -#include "BulletCollision/CollisionShapes/btTriangleShape.h" -#include "BulletCollision/NarrowPhaseCollision/btSubSimplexConvexCast.h" -#include "BulletCollision/NarrowPhaseCollision/btGjkConvexCast.h" -#include "BulletCollision/NarrowPhaseCollision/btContinuousConvexCollision.h" -#include "BulletCollision/NarrowPhaseCollision/btGjkEpaPenetrationDepthSolver.h" #include "btRaycastCallback.h" -btTriangleRaycastCallback::btTriangleRaycastCallback(const btVector3& from,const btVector3& to) +btTriangleRaycastCallback::btTriangleRaycastCallback(const btVector3& from,const btVector3& to,bool faceNormal) : m_from(from), m_to(to), + m_faceNormal(faceNormal), m_hitFraction(btScalar(1.)) { @@ -36,6 +30,8 @@ btTriangleRaycastCallback::btTriangleRaycastCallback(const btVector3& from,const void btTriangleRaycastCallback::processTriangle(btVector3* triangle,int partId, int triangleIndex) { + + const btVector3 &vert0=triangle[0]; const btVector3 &vert1=triangle[1]; const btVector3 &vert2=triangle[2]; @@ -89,8 +85,7 @@ void btTriangleRaycastCallback::processTriangle(btVector3* triangle,int partId, if ( (btScalar)(cp2.dot(triangleNormal)) >=edge_tolerance) { - - if ( dist_a > 0 ) + if (m_faceNormal || dist_a > 0) { m_hitFraction = reportHit(triangleNormal,distance,partId,triangleIndex); } @@ -104,60 +99,3 @@ void btTriangleRaycastCallback::processTriangle(btVector3* triangle,int partId, } } } - - -btTriangleConvexcastCallback::btTriangleConvexcastCallback (const btConvexShape* convexShape, const btTransform& convexShapeFrom, const btTransform& convexShapeTo, const btTransform& triangleToWorld, const btScalar triangleCollisionMargin) -{ - m_convexShape = convexShape; - m_convexShapeFrom = convexShapeFrom; - m_convexShapeTo = convexShapeTo; - m_triangleToWorld = triangleToWorld; - m_hitFraction = 1.0; - m_triangleCollisionMargin = triangleCollisionMargin; -} - -void -btTriangleConvexcastCallback::processTriangle (btVector3* triangle, int partId, int triangleIndex) -{ - btTriangleShape triangleShape (triangle[0], triangle[1], triangle[2]); - triangleShape.setMargin(m_triangleCollisionMargin); - - btVoronoiSimplexSolver simplexSolver; - btGjkEpaPenetrationDepthSolver gjkEpaPenetrationSolver; - -//#define USE_SUBSIMPLEX_CONVEX_CAST 1 -//if you reenable USE_SUBSIMPLEX_CONVEX_CAST see commented out code below -#ifdef USE_SUBSIMPLEX_CONVEX_CAST - btSubsimplexConvexCast convexCaster(m_convexShape, &triangleShape, &simplexSolver); -#else - //btGjkConvexCast convexCaster(m_convexShape,&triangleShape,&simplexSolver); - btContinuousConvexCollision convexCaster(m_convexShape,&triangleShape,&simplexSolver,&gjkEpaPenetrationSolver); -#endif //#USE_SUBSIMPLEX_CONVEX_CAST - - btConvexCast::CastResult castResult; - castResult.m_fraction = btScalar(1.); - if (convexCaster.calcTimeOfImpact(m_convexShapeFrom,m_convexShapeTo,m_triangleToWorld, m_triangleToWorld, castResult)) - { - //add hit - if (castResult.m_normal.length2() > btScalar(0.0001)) - { - if (castResult.m_fraction < m_hitFraction) - { -/* btContinuousConvexCast's normal is already in world space */ -/* -#ifdef USE_SUBSIMPLEX_CONVEX_CAST - //rotate normal into worldspace - castResult.m_normal = m_convexShapeFrom.getBasis() * castResult.m_normal; -#endif //USE_SUBSIMPLEX_CONVEX_CAST -*/ - castResult.m_normal.normalize(); - - reportHit (castResult.m_normal, - castResult.m_hitPoint, - castResult.m_fraction, - partId, - triangleIndex); - } - } - } -} diff --git a/extern/bullet2/src/BulletCollision/NarrowPhaseCollision/btRaycastCallback.h b/extern/bullet2/src/BulletCollision/NarrowPhaseCollision/btRaycastCallback.h index d2b4b80f8ba..71ed9fead49 100644 --- a/extern/bullet2/src/BulletCollision/NarrowPhaseCollision/btRaycastCallback.h +++ b/extern/bullet2/src/BulletCollision/NarrowPhaseCollision/btRaycastCallback.h @@ -16,22 +16,22 @@ subject to the following restrictions: #ifndef RAYCAST_TRI_CALLBACK_H #define RAYCAST_TRI_CALLBACK_H -#include "BulletCollision/CollisionShapes/btTriangleCallback.h" -#include "LinearMath/btTransform.h" +#include "../CollisionShapes/btTriangleCallback.h" struct btBroadphaseProxy; -class btConvexShape; + class btTriangleRaycastCallback: public btTriangleCallback { public: - //input + //input btVector3 m_from; btVector3 m_to; + bool m_faceNormal; btScalar m_hitFraction; - btTriangleRaycastCallback(const btVector3& from,const btVector3& to); + btTriangleRaycastCallback(const btVector3& from,const btVector3& to,bool faceNormal); virtual void processTriangle(btVector3* triangle, int partId, int triangleIndex); @@ -39,22 +39,5 @@ public: }; -class btTriangleConvexcastCallback : public btTriangleCallback -{ -public: - const btConvexShape* m_convexShape; - btTransform m_convexShapeFrom; - btTransform m_convexShapeTo; - btTransform m_triangleToWorld; - btScalar m_hitFraction; - btScalar m_triangleCollisionMargin; - - btTriangleConvexcastCallback (const btConvexShape* convexShape, const btTransform& convexShapeFrom, const btTransform& convexShapeTo, const btTransform& triangleToWorld, const btScalar triangleCollisionMargin); - - virtual void processTriangle (btVector3* triangle, int partId, int triangleIndex); - - virtual btScalar reportHit (const btVector3& hitNormalLocal, const btVector3& hitPointLocal, btScalar hitFraction, int partId, int triangleIndex) = 0; -}; - #endif //RAYCAST_TRI_CALLBACK_H diff --git a/extern/bullet2/src/BulletCollision/NarrowPhaseCollision/btSimplexSolverInterface.h b/extern/bullet2/src/BulletCollision/NarrowPhaseCollision/btSimplexSolverInterface.h index cf65f46505b..58393b2eab9 100644 --- a/extern/bullet2/src/BulletCollision/NarrowPhaseCollision/btSimplexSolverInterface.h +++ b/extern/bullet2/src/BulletCollision/NarrowPhaseCollision/btSimplexSolverInterface.h @@ -18,8 +18,8 @@ subject to the following restrictions: #ifndef SIMPLEX_SOLVER_INTERFACE_H #define SIMPLEX_SOLVER_INTERFACE_H -#include "LinearMath/btVector3.h" -#include "LinearMath/btPoint3.h" +#include "../../LinearMath/btVector3.h" +#include "../../LinearMath/btPoint3.h" #define NO_VIRTUAL_INTERFACE 1 #ifdef NO_VIRTUAL_INTERFACE diff --git a/extern/bullet2/src/BulletCollision/NarrowPhaseCollision/btSubSimplexConvexCast.cpp b/extern/bullet2/src/BulletCollision/NarrowPhaseCollision/btSubSimplexConvexCast.cpp index 4c709a8c3a9..687738b7fa9 100644 --- a/extern/bullet2/src/BulletCollision/NarrowPhaseCollision/btSubSimplexConvexCast.cpp +++ b/extern/bullet2/src/BulletCollision/NarrowPhaseCollision/btSubSimplexConvexCast.cpp @@ -16,11 +16,9 @@ subject to the following restrictions: #include "btSubSimplexConvexCast.h" #include "BulletCollision/CollisionShapes/btConvexShape.h" - #include "BulletCollision/CollisionShapes/btMinkowskiSumShape.h" #include "BulletCollision/NarrowPhaseCollision/btSimplexSolverInterface.h" -#include "btPointCollector.h" -#include "LinearMath/btTransformUtil.h" + btSubsimplexConvexCast::btSubsimplexConvexCast (const btConvexShape* convexA,const btConvexShape* convexB,btSimplexSolverInterface* simplexSolver) :m_simplexSolver(simplexSolver), @@ -43,24 +41,34 @@ bool btSubsimplexConvexCast::calcTimeOfImpact( CastResult& result) { + btMinkowskiSumShape combi(m_convexA,m_convexB); + btMinkowskiSumShape* convex = &combi; + + btTransform rayFromLocalA; + btTransform rayToLocalA; + + rayFromLocalA = fromA.inverse()* fromB; + rayToLocalA = toA.inverse()* toB; + + m_simplexSolver->reset(); - btVector3 linVelA,linVelB; - linVelA = toA.getOrigin()-fromA.getOrigin(); - linVelB = toB.getOrigin()-fromB.getOrigin(); + convex->setTransformB(btTransform(rayFromLocalA.getBasis())); + + //btScalar radius = btScalar(0.01); btScalar lambda = btScalar(0.); - - btTransform interpolatedTransA = fromA; - btTransform interpolatedTransB = fromB; - - ///take relative motion - btVector3 r = (linVelA-linVelB); - btVector3 v; + //todo: need to verify this: + //because of minkowski difference, we need the inverse direction - btVector3 supVertexA = fromA(m_convexA->localGetSupportingVertex(-r*fromA.getBasis())); - btVector3 supVertexB = fromB(m_convexB->localGetSupportingVertex(r*fromB.getBasis())); - v = supVertexA-supVertexB; + btVector3 s = -rayFromLocalA.getOrigin(); + btVector3 r = -(rayToLocalA.getOrigin()-rayFromLocalA.getOrigin()); + btVector3 x = s; + btVector3 v; + btVector3 arbitraryPoint = convex->localGetSupportingVertex(r); + + v = x - arbitraryPoint; + int maxIter = MAX_ITERATIONS; btVector3 n; @@ -82,17 +90,11 @@ bool btSubsimplexConvexCast::calcTimeOfImpact( while ( (dist2 > epsilon) && maxIter--) { - supVertexA = interpolatedTransA(m_convexA->localGetSupportingVertex(-v*interpolatedTransA.getBasis())); - supVertexB = interpolatedTransB(m_convexB->localGetSupportingVertex(v*interpolatedTransB.getBasis())); - w = supVertexA-supVertexB; + p = convex->localGetSupportingVertex( v); + w = x - p; btScalar VdotW = v.dot(w); - if (lambda > btScalar(1.0)) - { - return false; - } - if ( VdotW > btScalar(0.)) { VdotR = v.dot(r); @@ -102,25 +104,20 @@ bool btSubsimplexConvexCast::calcTimeOfImpact( else { lambda = lambda - VdotW / VdotR; - //interpolate to next lambda - // x = s + lambda * r; - interpolatedTransA.getOrigin().setInterpolate3(fromA.getOrigin(),toA.getOrigin(),lambda); - interpolatedTransB.getOrigin().setInterpolate3(fromB.getOrigin(),toB.getOrigin(),lambda); - //m_simplexSolver->reset(); + x = s + lambda * r; + m_simplexSolver->reset(); //check next line - w = supVertexA-supVertexB; + w = x-p; lastLambda = lambda; n = v; hasResult = true; } } - m_simplexSolver->addVertex( w, supVertexA , supVertexB); + m_simplexSolver->addVertex( w, x , p); if (m_simplexSolver->closest(v)) { dist2 = v.length2(); hasResult = true; - //todo: check this normal for validity - //n=v; //printf("V=%f , %f, %f\n",v[0],v[1],v[2]); //printf("DIST2=%f\n",dist2); //printf("numverts = %i\n",m_simplexSolver->numVertices()); @@ -132,26 +129,11 @@ bool btSubsimplexConvexCast::calcTimeOfImpact( //int numiter = MAX_ITERATIONS - maxIter; // printf("number of iterations: %d", numiter); - - //don't report a time of impact when moving 'away' from the hitnormal - - result.m_fraction = lambda; - if (n.length2() >= (SIMD_EPSILON*SIMD_EPSILON)) - result.m_normal = n.normalized(); - else - result.m_normal = btVector3(btScalar(0.0), btScalar(0.0), btScalar(0.0)); + result.m_normal = n; - //don't report time of impact for motion away from the contact normal (or causes minor penetration) - if (result.m_normal.dot(r)>=-result.m_allowedPenetration) - return false; - - btVector3 hitA,hitB; - m_simplexSolver->compute_points(hitA,hitB); - result.m_hitPoint=hitB; return true; } - diff --git a/extern/bullet2/src/BulletCollision/NarrowPhaseCollision/btVoronoiSimplexSolver.cpp b/extern/bullet2/src/BulletCollision/NarrowPhaseCollision/btVoronoiSimplexSolver.cpp index cf8a3ab5eb1..105b7eccefa 100644 --- a/extern/bullet2/src/BulletCollision/NarrowPhaseCollision/btVoronoiSimplexSolver.cpp +++ b/extern/bullet2/src/BulletCollision/NarrowPhaseCollision/btVoronoiSimplexSolver.cpp @@ -26,7 +26,7 @@ subject to the following restrictions: #include "btVoronoiSimplexSolver.h" #include -//#include +#include #define VERTA 0 #define VERTB 1 diff --git a/extern/bullet2/src/BulletDynamics/ConstraintSolver/btConeTwistConstraint.cpp b/extern/bullet2/src/BulletDynamics/ConstraintSolver/btConeTwistConstraint.cpp index e11b49d9420..2289621e8e3 100644 --- a/extern/bullet2/src/BulletDynamics/ConstraintSolver/btConeTwistConstraint.cpp +++ b/extern/bullet2/src/BulletDynamics/ConstraintSolver/btConeTwistConstraint.cpp @@ -19,20 +19,24 @@ Written by: Marcus Hennix #include "btConeTwistConstraint.h" #include "BulletDynamics/Dynamics/btRigidBody.h" #include "LinearMath/btTransformUtil.h" -#include "LinearMath/btMinMax.h" +#include "LinearMath/btSimdMinMax.h" #include btConeTwistConstraint::btConeTwistConstraint() -:btTypedConstraint(CONETWIST_CONSTRAINT_TYPE) { } btConeTwistConstraint::btConeTwistConstraint(btRigidBody& rbA,btRigidBody& rbB, const btTransform& rbAFrame,const btTransform& rbBFrame) - :btTypedConstraint(CONETWIST_CONSTRAINT_TYPE, rbA,rbB),m_rbAFrame(rbAFrame),m_rbBFrame(rbBFrame), + :btTypedConstraint(rbA,rbB),m_rbAFrame(rbAFrame),m_rbBFrame(rbBFrame), m_angularOnly(false) { + // flip axis for correct angles + m_rbBFrame.getBasis()[1][0] *= btScalar(-1.); + m_rbBFrame.getBasis()[1][1] *= btScalar(-1.); + m_rbBFrame.getBasis()[1][2] *= btScalar(-1.); + m_swingSpan1 = btScalar(1e30); m_swingSpan2 = btScalar(1e30); m_twistSpan = btScalar(1e30); @@ -45,11 +49,20 @@ btConeTwistConstraint::btConeTwistConstraint(btRigidBody& rbA,btRigidBody& rbB, } btConeTwistConstraint::btConeTwistConstraint(btRigidBody& rbA,const btTransform& rbAFrame) - :btTypedConstraint(CONETWIST_CONSTRAINT_TYPE,rbA),m_rbAFrame(rbAFrame), + :btTypedConstraint(rbA),m_rbAFrame(rbAFrame), m_angularOnly(false) { m_rbBFrame = m_rbAFrame; + // flip axis for correct angles + m_rbBFrame.getBasis()[1][0] *= btScalar(-1.); + m_rbBFrame.getBasis()[1][1] *= btScalar(-1.); + m_rbBFrame.getBasis()[1][2] *= btScalar(-1.); + + m_rbBFrame.getBasis()[2][0] *= btScalar(-1.); + m_rbBFrame.getBasis()[2][1] *= btScalar(-1.); + m_rbBFrame.getBasis()[2][2] *= btScalar(-1.); + m_swingSpan1 = btScalar(1e30); m_swingSpan2 = btScalar(1e30); m_twistSpan = btScalar(1e30); @@ -129,7 +142,7 @@ void btConeTwistConstraint::buildJacobian() btScalar RMaxAngle1Sq = 1.0f / (m_swingSpan1*m_swingSpan1); btScalar RMaxAngle2Sq = 1.0f / (m_swingSpan2*m_swingSpan2); - btScalar EllipseAngle = btFabs(swing1*swing1)* RMaxAngle1Sq + btFabs(swing2*swing2) * RMaxAngle2Sq; + btScalar EllipseAngle = btFabs(swing1)* RMaxAngle1Sq + btFabs(swing2) * RMaxAngle2Sq; if (EllipseAngle > 1.0f) { @@ -233,7 +246,7 @@ void btConeTwistConstraint::solveConstraint(btScalar timeStep) // Clamp the accumulated impulse btScalar temp = m_accSwingLimitImpulse; - m_accSwingLimitImpulse = btMax(m_accSwingLimitImpulse + impulseMag, btScalar(0.0) ); + m_accSwingLimitImpulse = btMax(m_accSwingLimitImpulse + impulseMag, 0.0f ); impulseMag = m_accSwingLimitImpulse - temp; btVector3 impulse = m_swingAxis * impulseMag; @@ -251,7 +264,7 @@ void btConeTwistConstraint::solveConstraint(btScalar timeStep) // Clamp the accumulated impulse btScalar temp = m_accTwistLimitImpulse; - m_accTwistLimitImpulse = btMax(m_accTwistLimitImpulse + impulseMag, btScalar(0.0) ); + m_accTwistLimitImpulse = btMax(m_accTwistLimitImpulse + impulseMag, 0.0f ); impulseMag = m_accTwistLimitImpulse - temp; btVector3 impulse = m_twistAxis * impulseMag; diff --git a/extern/bullet2/src/BulletDynamics/ConstraintSolver/btConeTwistConstraint.h b/extern/bullet2/src/BulletDynamics/ConstraintSolver/btConeTwistConstraint.h index f121919c8f9..874669c80b3 100644 --- a/extern/bullet2/src/BulletDynamics/ConstraintSolver/btConeTwistConstraint.h +++ b/extern/bullet2/src/BulletDynamics/ConstraintSolver/btConeTwistConstraint.h @@ -30,9 +30,6 @@ class btRigidBody; ///btConeTwistConstraint can be used to simulate ragdoll joints (upper arm, leg etc) class btConeTwistConstraint : public btTypedConstraint { -#ifdef IN_PARALLELL_SOLVER -public: -#endif btJacobianEntry m_jac[3]; //3 orthogonal linear constraints btTransform m_rbAFrame; diff --git a/extern/bullet2/src/BulletDynamics/ConstraintSolver/btConstraintSolver.h b/extern/bullet2/src/BulletDynamics/ConstraintSolver/btConstraintSolver.h index 7a8e9c1953d..7e8458c2c7b 100644 --- a/extern/bullet2/src/BulletDynamics/ConstraintSolver/btConstraintSolver.h +++ b/extern/bullet2/src/BulletDynamics/ConstraintSolver/btConstraintSolver.h @@ -16,7 +16,7 @@ subject to the following restrictions: #ifndef CONSTRAINT_SOLVER_H #define CONSTRAINT_SOLVER_H -#include "LinearMath/btScalar.h" +#include "../../LinearMath/btScalar.h" class btPersistentManifold; class btRigidBody; @@ -26,7 +26,7 @@ struct btContactSolverInfo; struct btBroadphaseProxy; class btIDebugDraw; class btStackAlloc; -class btDispatcher; + /// btConstraintSolver provides solver interface class btConstraintSolver { @@ -35,15 +35,8 @@ public: virtual ~btConstraintSolver() {} - virtual void prepareSolve (int /* numBodies */, int /* numManifolds */) {;} + virtual btScalar solveGroup(btCollisionObject** bodies,int numBodies,btPersistentManifold** manifold,int numManifolds,btTypedConstraint** constraints,int numConstraints, const btContactSolverInfo& info,class btIDebugDraw* debugDrawer, btStackAlloc* stackAlloc) = 0; - ///solve a group of constraints - virtual btScalar solveGroup(btCollisionObject** bodies,int numBodies,btPersistentManifold** manifold,int numManifolds,btTypedConstraint** constraints,int numConstraints, const btContactSolverInfo& info,class btIDebugDraw* debugDrawer, btStackAlloc* stackAlloc,btDispatcher* dispatcher) = 0; - - virtual void allSolved (const btContactSolverInfo& /* info */,class btIDebugDraw* /* debugDrawer */, btStackAlloc* /* stackAlloc */) {;} - - ///clear internal cached data and reset random seed - virtual void reset() = 0; }; diff --git a/extern/bullet2/src/BulletDynamics/ConstraintSolver/btContactConstraint.cpp b/extern/bullet2/src/BulletDynamics/ConstraintSolver/btContactConstraint.cpp index 4d7cd05feb7..bb3fe832592 100644 --- a/extern/bullet2/src/BulletDynamics/ConstraintSolver/btContactConstraint.cpp +++ b/extern/bullet2/src/BulletDynamics/ConstraintSolver/btContactConstraint.cpp @@ -192,8 +192,8 @@ btScalar resolveSingleFriction( j1 = -vrel * cpd->m_jacDiagABInvTangent0; btScalar oldTangentImpulse = cpd->m_accumulatedTangentImpulse0; cpd->m_accumulatedTangentImpulse0 = oldTangentImpulse + j1; - btSetMin(cpd->m_accumulatedTangentImpulse0, limit); - btSetMax(cpd->m_accumulatedTangentImpulse0, -limit); + GEN_set_min(cpd->m_accumulatedTangentImpulse0, limit); + GEN_set_max(cpd->m_accumulatedTangentImpulse0, -limit); j1 = cpd->m_accumulatedTangentImpulse0 - oldTangentImpulse; } @@ -206,8 +206,8 @@ btScalar resolveSingleFriction( j2 = -vrel * cpd->m_jacDiagABInvTangent1; btScalar oldTangentImpulse = cpd->m_accumulatedTangentImpulse1; cpd->m_accumulatedTangentImpulse1 = oldTangentImpulse + j2; - btSetMin(cpd->m_accumulatedTangentImpulse1, limit); - btSetMax(cpd->m_accumulatedTangentImpulse1, -limit); + GEN_set_min(cpd->m_accumulatedTangentImpulse1, limit); + GEN_set_max(cpd->m_accumulatedTangentImpulse1, -limit); j2 = cpd->m_accumulatedTangentImpulse1 - oldTangentImpulse; } @@ -233,12 +233,6 @@ btScalar resolveSingleFriction( } -btScalar resolveSingleFrictionOriginal( - btRigidBody& body1, - btRigidBody& body2, - btManifoldPoint& contactPoint, - const btContactSolverInfo& solverInfo); - btScalar resolveSingleFrictionOriginal( btRigidBody& body1, btRigidBody& body2, @@ -276,8 +270,8 @@ btScalar resolveSingleFrictionOriginal( // calculate j that moves us to zero relative velocity btScalar j = -vrel * cpd->m_jacDiagABInvTangent0; btScalar total = cpd->m_accumulatedTangentImpulse0 + j; - btSetMin(total, limit); - btSetMax(total, -limit); + GEN_set_min(total, limit); + GEN_set_max(total, -limit); j = total - cpd->m_accumulatedTangentImpulse0; cpd->m_accumulatedTangentImpulse0 = total; body1.applyImpulse(j * cpd->m_frictionWorldTangential0, rel_pos1); @@ -296,8 +290,8 @@ btScalar resolveSingleFrictionOriginal( // calculate j that moves us to zero relative velocity btScalar j = -vrel * cpd->m_jacDiagABInvTangent1; btScalar total = cpd->m_accumulatedTangentImpulse1 + j; - btSetMin(total, limit); - btSetMax(total, -limit); + GEN_set_min(total, limit); + GEN_set_max(total, -limit); j = total - cpd->m_accumulatedTangentImpulse1; cpd->m_accumulatedTangentImpulse1 = total; body1.applyImpulse(j * cpd->m_frictionWorldTangential1, rel_pos1); @@ -394,8 +388,8 @@ btScalar resolveSingleCollisionCombined( (body1.getInvMass() + body2.getInvMass() + lat_vel.dot(temp1.cross(rel_pos1) + temp2.cross(rel_pos2))); btScalar normal_impulse = cpd->m_appliedImpulse * combinedFriction; - btSetMin(friction_impulse, normal_impulse); - btSetMax(friction_impulse, -normal_impulse); + GEN_set_min(friction_impulse, normal_impulse); + GEN_set_max(friction_impulse, -normal_impulse); body1.applyImpulse(lat_vel * -friction_impulse, rel_pos1); body2.applyImpulse(lat_vel * friction_impulse, rel_pos2); } @@ -406,12 +400,6 @@ btScalar resolveSingleCollisionCombined( return normalImpulse; } -btScalar resolveSingleFrictionEmpty( - btRigidBody& body1, - btRigidBody& body2, - btManifoldPoint& contactPoint, - const btContactSolverInfo& solverInfo); - btScalar resolveSingleFrictionEmpty( btRigidBody& body1, btRigidBody& body2, diff --git a/extern/bullet2/src/BulletDynamics/ConstraintSolver/btContactConstraint.h b/extern/bullet2/src/BulletDynamics/ConstraintSolver/btContactConstraint.h index 826e79f78bd..0834deddeac 100644 --- a/extern/bullet2/src/BulletDynamics/ConstraintSolver/btContactConstraint.h +++ b/extern/bullet2/src/BulletDynamics/ConstraintSolver/btContactConstraint.h @@ -19,8 +19,8 @@ subject to the following restrictions: //todo: make into a proper class working with the iterative constraint solver class btRigidBody; -#include "LinearMath/btVector3.h" -#include "LinearMath/btScalar.h" +#include "../../LinearMath/btVector3.h" +#include "../../LinearMath/btScalar.h" struct btContactSolverInfo; class btManifoldPoint; diff --git a/extern/bullet2/src/BulletDynamics/ConstraintSolver/btContactSolverInfo.h b/extern/bullet2/src/BulletDynamics/ConstraintSolver/btContactSolverInfo.h index 916d4581f79..c3c73e300f4 100644 --- a/extern/bullet2/src/BulletDynamics/ConstraintSolver/btContactSolverInfo.h +++ b/extern/bullet2/src/BulletDynamics/ConstraintSolver/btContactSolverInfo.h @@ -16,42 +16,9 @@ subject to the following restrictions: #ifndef CONTACT_SOLVER_INFO #define CONTACT_SOLVER_INFO -enum btSolverMode + +struct btContactSolverInfo { - SOLVER_RANDMIZE_ORDER = 1, - SOLVER_FRICTION_SEPARATE = 2, - SOLVER_USE_WARMSTARTING = 4, - SOLVER_CACHE_FRIENDLY = 8 -}; - -struct btContactSolverInfoData -{ - - - btScalar m_tau; - btScalar m_damping; - btScalar m_friction; - btScalar m_timeStep; - btScalar m_restitution; - int m_numIterations; - btScalar m_maxErrorReduction; - btScalar m_sor; - btScalar m_erp;//used as Baumgarte factor - btScalar m_erp2;//used in Split Impulse - int m_splitImpulse; - btScalar m_splitImpulsePenetrationThreshold; - btScalar m_linearSlop; - btScalar m_warmstartingFactor; - - int m_solverMode; - - -}; - -struct btContactSolverInfo : public btContactSolverInfoData -{ - - inline btContactSolverInfo() { @@ -61,15 +28,20 @@ struct btContactSolverInfo : public btContactSolverInfoData m_restitution = btScalar(0.); m_maxErrorReduction = btScalar(20.); m_numIterations = 10; - m_erp = btScalar(0.2); - m_erp2 = btScalar(0.1); + m_erp = btScalar(0.4); m_sor = btScalar(1.3); - m_splitImpulse = false; - m_splitImpulsePenetrationThreshold = -0.02f; - m_linearSlop = btScalar(0.0); - m_warmstartingFactor=btScalar(0.85); - m_solverMode = SOLVER_RANDMIZE_ORDER | SOLVER_CACHE_FRIENDLY | SOLVER_USE_WARMSTARTING; } + + btScalar m_tau; + btScalar m_damping; + btScalar m_friction; + btScalar m_timeStep; + btScalar m_restitution; + int m_numIterations; + btScalar m_maxErrorReduction; + btScalar m_sor; + btScalar m_erp; + }; #endif //CONTACT_SOLVER_INFO diff --git a/extern/bullet2/src/BulletDynamics/ConstraintSolver/btGeneric6DofConstraint.cpp b/extern/bullet2/src/BulletDynamics/ConstraintSolver/btGeneric6DofConstraint.cpp index 077b326d13a..747d10d1f8b 100644 --- a/extern/bullet2/src/BulletDynamics/ConstraintSolver/btGeneric6DofConstraint.cpp +++ b/extern/bullet2/src/BulletDynamics/ConstraintSolver/btGeneric6DofConstraint.cpp @@ -4,20 +4,14 @@ Copyright (c) 2003-2006 Erwin Coumans http://continuousphysics.com/Bullet/ This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. -Permission is granted to anyone to use this software for any purpose, -including commercial applications, and to alter it and redistribute it freely, +Permission is granted to anyone to use this software for any purpose, +including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ -/* -2007-09-09 -Refactored by Francisco Le?n -email: projectileman@yahoo.com -http://gimpact.sf.net -*/ #include "btGeneric6DofConstraint.h" @@ -25,504 +19,371 @@ http://gimpact.sf.net #include "LinearMath/btTransformUtil.h" #include - static const btScalar kSign[] = { btScalar(1.0), btScalar(-1.0), btScalar(1.0) }; static const int kAxisA[] = { 1, 0, 0 }; static const int kAxisB[] = { 2, 2, 1 }; #define GENERIC_D6_DISABLE_WARMSTARTING 1 -btScalar btGetMatrixElem(const btMatrix3x3& mat, int index); -btScalar btGetMatrixElem(const btMatrix3x3& mat, int index) +btGeneric6DofConstraint::btGeneric6DofConstraint() { - int i = index%3; - int j = index/3; - return mat[i][j]; +} + +btGeneric6DofConstraint::btGeneric6DofConstraint(btRigidBody& rbA, btRigidBody& rbB, const btTransform& frameInA, const btTransform& frameInB) +: btTypedConstraint(rbA, rbB) +, m_frameInA(frameInA) +, m_frameInB(frameInB) +{ + //free means upper < lower, + //locked means upper == lower + //limited means upper > lower + //so start all locked + for (int i=0; i<6;++i) + { + m_lowerLimit[i] = btScalar(0.0); + m_upperLimit[i] = btScalar(0.0); + m_accumulatedImpulse[i] = btScalar(0.0); + } + +} + + +void btGeneric6DofConstraint::buildJacobian() +{ + btVector3 localNormalInA(0,0,0); + + const btVector3& pivotInA = m_frameInA.getOrigin(); + const btVector3& pivotInB = m_frameInB.getOrigin(); + + btVector3 pivotAInW = m_rbA.getCenterOfMassTransform() * m_frameInA.getOrigin(); + btVector3 pivotBInW = m_rbB.getCenterOfMassTransform() * m_frameInB.getOrigin(); + + btVector3 rel_pos1 = pivotAInW - m_rbA.getCenterOfMassPosition(); + btVector3 rel_pos2 = pivotBInW - m_rbB.getCenterOfMassPosition(); + + int i; + //linear part + for (i=0;i<3;i++) + { + if (isLimited(i)) + { + localNormalInA[i] = 1; + btVector3 normalWorld = m_rbA.getCenterOfMassTransform().getBasis() * localNormalInA; + + + // Create linear atom + new (&m_jacLinear[i]) btJacobianEntry( + m_rbA.getCenterOfMassTransform().getBasis().transpose(), + m_rbB.getCenterOfMassTransform().getBasis().transpose(), + m_rbA.getCenterOfMassTransform()*pivotInA - m_rbA.getCenterOfMassPosition(), + m_rbB.getCenterOfMassTransform()*pivotInB - m_rbB.getCenterOfMassPosition(), + normalWorld, + m_rbA.getInvInertiaDiagLocal(), + m_rbA.getInvMass(), + m_rbB.getInvInertiaDiagLocal(), + m_rbB.getInvMass()); + + //optionally disable warmstarting +#ifdef GENERIC_D6_DISABLE_WARMSTARTING + m_accumulatedImpulse[i] = btScalar(0.); +#endif //GENERIC_D6_DISABLE_WARMSTARTING + + // Apply accumulated impulse + btVector3 impulse_vector = m_accumulatedImpulse[i] * normalWorld; + + m_rbA.applyImpulse( impulse_vector, rel_pos1); + m_rbB.applyImpulse(-impulse_vector, rel_pos2); + + localNormalInA[i] = 0; + } + } + + // angular part + for (i=0;i<3;i++) + { + if (isLimited(i+3)) + { + btVector3 axisA = m_rbA.getCenterOfMassTransform().getBasis() * m_frameInA.getBasis().getColumn( kAxisA[i] ); + btVector3 axisB = m_rbB.getCenterOfMassTransform().getBasis() * m_frameInB.getBasis().getColumn( kAxisB[i] ); + + // Dirk: This is IMO mathematically the correct way, but we should consider axisA and axisB being near parallel maybe + btVector3 axis = kSign[i] * axisA.cross(axisB); + + // Create angular atom + new (&m_jacAng[i]) btJacobianEntry(axis, + m_rbA.getCenterOfMassTransform().getBasis().transpose(), + m_rbB.getCenterOfMassTransform().getBasis().transpose(), + m_rbA.getInvInertiaDiagLocal(), + m_rbB.getInvInertiaDiagLocal()); + +#ifdef GENERIC_D6_DISABLE_WARMSTARTING + m_accumulatedImpulse[i + 3] = btScalar(0.); +#endif //GENERIC_D6_DISABLE_WARMSTARTING + + // Apply accumulated impulse + btVector3 impulse_vector = m_accumulatedImpulse[i + 3] * axis; + + m_rbA.applyTorqueImpulse( impulse_vector); + m_rbB.applyTorqueImpulse(-impulse_vector); + } + } +} + +btScalar getMatrixElem(const btMatrix3x3& mat,int index) +{ + int row = index%3; + int col = index / 3; + return mat[row][col]; } ///MatrixToEulerXYZ from http://www.geometrictools.com/LibFoundation/Mathematics/Wm4Matrix3.inl.html -bool matrixToEulerXYZ(const btMatrix3x3& mat,btVector3& xyz); -bool matrixToEulerXYZ(const btMatrix3x3& mat,btVector3& xyz) +bool MatrixToEulerXYZ(const btMatrix3x3& mat,btVector3& xyz) { -// // rot = cy*cz -cy*sz sy -// // cz*sx*sy+cx*sz cx*cz-sx*sy*sz -cy*sx -// // -cx*cz*sy+sx*sz cz*sx+cx*sy*sz cx*cy -// - - if (btGetMatrixElem(mat,2) < btScalar(1.0)) - { - if (btGetMatrixElem(mat,2) > btScalar(-1.0)) - { - xyz[0] = btAtan2(-btGetMatrixElem(mat,5),btGetMatrixElem(mat,8)); - xyz[1] = btAsin(btGetMatrixElem(mat,2)); - xyz[2] = btAtan2(-btGetMatrixElem(mat,1),btGetMatrixElem(mat,0)); - return true; - } - else - { - // WARNING. Not unique. XA - ZA = -atan2(r10,r11) - xyz[0] = -btAtan2(btGetMatrixElem(mat,3),btGetMatrixElem(mat,4)); - xyz[1] = -SIMD_HALF_PI; - xyz[2] = btScalar(0.0); - return false; - } - } - else - { - // WARNING. Not unique. XAngle + ZAngle = atan2(r10,r11) - xyz[0] = btAtan2(btGetMatrixElem(mat,3),btGetMatrixElem(mat,4)); - xyz[1] = SIMD_HALF_PI; - xyz[2] = 0.0; - - } + // rot = cy*cz -cy*sz sy + // cz*sx*sy+cx*sz cx*cz-sx*sy*sz -cy*sx + // -cx*cz*sy+sx*sz cz*sx+cx*sy*sz cx*cy +/// 0..8 + if (getMatrixElem(mat,2) < btScalar(1.0)) + { + if (getMatrixElem(mat,2) > btScalar(-1.0)) + { + xyz[0] = btAtan2(-getMatrixElem(mat,5),getMatrixElem(mat,8)); + xyz[1] = btAsin(getMatrixElem(mat,2)); + xyz[2] = btAtan2(-getMatrixElem(mat,1),getMatrixElem(mat,0)); + return true; + } + else + { + // WARNING. Not unique. XA - ZA = -atan2(r10,r11) + xyz[0] = -btAtan2(getMatrixElem(mat,3),getMatrixElem(mat,4)); + xyz[1] = -SIMD_HALF_PI; + xyz[2] = btScalar(0.0); + return false; + } + } + else + { + // WARNING. Not unique. XAngle + ZAngle = atan2(r10,r11) + xyz[0] = btAtan2(getMatrixElem(mat,3),getMatrixElem(mat,4)); + xyz[1] = SIMD_HALF_PI; + xyz[2] = 0.0; + + } + return false; } - -//////////////////////////// btRotationalLimitMotor //////////////////////////////////// - - -int btRotationalLimitMotor::testLimitValue(btScalar test_value) +void btGeneric6DofConstraint::solveConstraint(btScalar timeStep) { - if(m_loLimit>m_hiLimit) - { - m_currentLimit = 0;//Free from violation - return 0; - } + btScalar tau = btScalar(0.1); + btScalar damping = btScalar(1.0); - if (test_value < m_loLimit) - { - m_currentLimit = 1;//low limit violation - m_currentLimitError = test_value - m_loLimit; - return 1; - } - else if (test_value> m_hiLimit) - { - m_currentLimit = 2;//High limit violation - m_currentLimitError = test_value - m_hiLimit; - return 2; - }; + btVector3 pivotAInW = m_rbA.getCenterOfMassTransform() * m_frameInA.getOrigin(); + btVector3 pivotBInW = m_rbB.getCenterOfMassTransform() * m_frameInB.getOrigin(); - m_currentLimit = 0;//Free from violation - return 0; + btVector3 rel_pos1 = pivotAInW - m_rbA.getCenterOfMassPosition(); + btVector3 rel_pos2 = pivotBInW - m_rbB.getCenterOfMassPosition(); -} - - -btScalar btRotationalLimitMotor::solveAngularLimits( - btScalar timeStep,btVector3& axis,btScalar jacDiagABInv, - btRigidBody * body0, btRigidBody * body1) -{ - if (needApplyTorques()==false) return 0.0f; - - btScalar target_velocity = m_targetVelocity; - btScalar maxMotorForce = m_maxMotorForce; - - //current error correction - if (m_currentLimit!=0) - { - target_velocity = -m_ERP*m_currentLimitError/(timeStep); - maxMotorForce = m_maxLimitForce; - } - - maxMotorForce *= timeStep; - - // current velocity difference - btVector3 vel_diff = body0->getAngularVelocity(); - if (body1) - { - vel_diff -= body1->getAngularVelocity(); - } - - - - btScalar rel_vel = axis.dot(vel_diff); - - // correction velocity - btScalar motor_relvel = m_limitSoftness*(target_velocity - m_damping*rel_vel); - - - if ( motor_relvel < SIMD_EPSILON && motor_relvel > -SIMD_EPSILON ) - { - return 0.0f;//no need for applying force - } - - - // correction impulse - btScalar unclippedMotorImpulse = (1+m_bounce)*motor_relvel*jacDiagABInv; - - // clip correction impulse - btScalar clippedMotorImpulse; - - //todo: should clip against accumulated impulse - if (unclippedMotorImpulse>0.0f) - { - clippedMotorImpulse = unclippedMotorImpulse > maxMotorForce? maxMotorForce: unclippedMotorImpulse; - } - else - { - clippedMotorImpulse = unclippedMotorImpulse < -maxMotorForce ? -maxMotorForce: unclippedMotorImpulse; - } - - - // sort with accumulated impulses - btScalar lo = btScalar(-1e30); - btScalar hi = btScalar(1e30); - - btScalar oldaccumImpulse = m_accumulatedImpulse; - btScalar sum = oldaccumImpulse + clippedMotorImpulse; - m_accumulatedImpulse = sum > hi ? btScalar(0.) : sum < lo ? btScalar(0.) : sum; - - clippedMotorImpulse = m_accumulatedImpulse - oldaccumImpulse; - - - - btVector3 motorImp = clippedMotorImpulse * axis; - - - body0->applyTorqueImpulse(motorImp); - if (body1) body1->applyTorqueImpulse(-motorImp); - - return clippedMotorImpulse; - - -} - -//////////////////////////// End btRotationalLimitMotor //////////////////////////////////// - -//////////////////////////// btTranslationalLimitMotor //////////////////////////////////// -btScalar btTranslationalLimitMotor::solveLinearAxis( - btScalar timeStep, - btScalar jacDiagABInv, - btRigidBody& body1,const btVector3 &pointInA, - btRigidBody& body2,const btVector3 &pointInB, - int limit_index, - const btVector3 & axis_normal_on_a, - const btVector3 & anchorPos) -{ - -///find relative velocity -// btVector3 rel_pos1 = pointInA - body1.getCenterOfMassPosition(); -// btVector3 rel_pos2 = pointInB - body2.getCenterOfMassPosition(); - btVector3 rel_pos1 = anchorPos - body1.getCenterOfMassPosition(); - btVector3 rel_pos2 = anchorPos - body2.getCenterOfMassPosition(); - - btVector3 vel1 = body1.getVelocityInLocalPoint(rel_pos1); - btVector3 vel2 = body2.getVelocityInLocalPoint(rel_pos2); - btVector3 vel = vel1 - vel2; - - btScalar rel_vel = axis_normal_on_a.dot(vel); - - - -/// apply displacement correction - -//positional error (zeroth order error) - btScalar depth = -(pointInA - pointInB).dot(axis_normal_on_a); - btScalar lo = btScalar(-1e30); - btScalar hi = btScalar(1e30); - - btScalar minLimit = m_lowerLimit[limit_index]; - btScalar maxLimit = m_upperLimit[limit_index]; - - //handle the limits - if (minLimit < maxLimit) - { - { - if (depth > maxLimit) - { - depth -= maxLimit; - lo = btScalar(0.); - - } - else - { - if (depth < minLimit) - { - depth -= minLimit; - hi = btScalar(0.); - } - else - { - return 0.0f; - } - } - } - } - - btScalar normalImpulse= m_limitSoftness*(m_restitution*depth/timeStep - m_damping*rel_vel) * jacDiagABInv; - - - - - btScalar oldNormalImpulse = m_accumulatedImpulse[limit_index]; - btScalar sum = oldNormalImpulse + normalImpulse; - m_accumulatedImpulse[limit_index] = sum > hi ? btScalar(0.) : sum < lo ? btScalar(0.) : sum; - normalImpulse = m_accumulatedImpulse[limit_index] - oldNormalImpulse; - - btVector3 impulse_vector = axis_normal_on_a * normalImpulse; - body1.applyImpulse( impulse_vector, rel_pos1); - body2.applyImpulse(-impulse_vector, rel_pos2); - return normalImpulse; -} - -//////////////////////////// btTranslationalLimitMotor //////////////////////////////////// - - -btGeneric6DofConstraint::btGeneric6DofConstraint() - :btTypedConstraint(D6_CONSTRAINT_TYPE), - m_useLinearReferenceFrameA(true) -{ -} - -btGeneric6DofConstraint::btGeneric6DofConstraint(btRigidBody& rbA, btRigidBody& rbB, const btTransform& frameInA, const btTransform& frameInB, bool useLinearReferenceFrameA) - : btTypedConstraint(D6_CONSTRAINT_TYPE, rbA, rbB) - , m_frameInA(frameInA) - , m_frameInB(frameInB), - m_useLinearReferenceFrameA(useLinearReferenceFrameA) -{ - -} - - - - - -void btGeneric6DofConstraint::calculateAngleInfo() -{ - btMatrix3x3 relative_frame = m_calculatedTransformA.getBasis().inverse()*m_calculatedTransformB.getBasis(); - - matrixToEulerXYZ(relative_frame,m_calculatedAxisAngleDiff); - - - - // in euler angle mode we do not actually constrain the angular velocity - // along the axes axis[0] and axis[2] (although we do use axis[1]) : - // - // to get constrain w2-w1 along ...not - // ------ --------------------- ------ - // d(angle[0])/dt = 0 ax[1] x ax[2] ax[0] - // d(angle[1])/dt = 0 ax[1] - // d(angle[2])/dt = 0 ax[0] x ax[1] ax[2] - // - // constraining w2-w1 along an axis 'a' means that a'*(w2-w1)=0. - // to prove the result for angle[0], write the expression for angle[0] from - // GetInfo1 then take the derivative. to prove this for angle[2] it is - // easier to take the euler rate expression for d(angle[2])/dt with respect - // to the components of w and set that to 0. - - btVector3 axis0 = m_calculatedTransformB.getBasis().getColumn(0); - btVector3 axis2 = m_calculatedTransformA.getBasis().getColumn(2); - - m_calculatedAxis[1] = axis2.cross(axis0); - m_calculatedAxis[0] = m_calculatedAxis[1].cross(axis2); - m_calculatedAxis[2] = axis0.cross(m_calculatedAxis[1]); - - -// if(m_debugDrawer) -// { -// -// char buff[300]; -// sprintf(buff,"\n X: %.2f ; Y: %.2f ; Z: %.2f ", -// m_calculatedAxisAngleDiff[0], -// m_calculatedAxisAngleDiff[1], -// m_calculatedAxisAngleDiff[2]); -// m_debugDrawer->reportErrorWarning(buff); -// } - -} - -void btGeneric6DofConstraint::calculateTransforms() -{ - m_calculatedTransformA = m_rbA.getCenterOfMassTransform() * m_frameInA; - m_calculatedTransformB = m_rbB.getCenterOfMassTransform() * m_frameInB; - - calculateAngleInfo(); -} - - -void btGeneric6DofConstraint::buildLinearJacobian( - btJacobianEntry & jacLinear,const btVector3 & normalWorld, - const btVector3 & pivotAInW,const btVector3 & pivotBInW) -{ - new (&jacLinear) btJacobianEntry( - m_rbA.getCenterOfMassTransform().getBasis().transpose(), - m_rbB.getCenterOfMassTransform().getBasis().transpose(), - pivotAInW - m_rbA.getCenterOfMassPosition(), - pivotBInW - m_rbB.getCenterOfMassPosition(), - normalWorld, - m_rbA.getInvInertiaDiagLocal(), - m_rbA.getInvMass(), - m_rbB.getInvInertiaDiagLocal(), - m_rbB.getInvMass()); - -} - -void btGeneric6DofConstraint::buildAngularJacobian( - btJacobianEntry & jacAngular,const btVector3 & jointAxisW) -{ - new (&jacAngular) btJacobianEntry(jointAxisW, - m_rbA.getCenterOfMassTransform().getBasis().transpose(), - m_rbB.getCenterOfMassTransform().getBasis().transpose(), - m_rbA.getInvInertiaDiagLocal(), - m_rbB.getInvInertiaDiagLocal()); - -} - -bool btGeneric6DofConstraint::testAngularLimitMotor(int axis_index) -{ - btScalar angle = m_calculatedAxisAngleDiff[axis_index]; - - //test limits - m_angularLimits[axis_index].testLimitValue(angle); - return m_angularLimits[axis_index].needApplyTorques(); -} - -void btGeneric6DofConstraint::buildJacobian() -{ - - // Clear accumulated impulses for the next simulation step - m_linearLimits.m_accumulatedImpulse.setValue(btScalar(0.), btScalar(0.), btScalar(0.)); - int i; - for(i = 0; i < 3; i++) - { - m_angularLimits[i].m_accumulatedImpulse = btScalar(0.); - } - //calculates transform - calculateTransforms(); - -// const btVector3& pivotAInW = m_calculatedTransformA.getOrigin(); -// const btVector3& pivotBInW = m_calculatedTransformB.getOrigin(); - calcAnchorPos(); - btVector3 pivotAInW = m_AnchorPos; - btVector3 pivotBInW = m_AnchorPos; - -// not used here -// btVector3 rel_pos1 = pivotAInW - m_rbA.getCenterOfMassPosition(); -// btVector3 rel_pos2 = pivotBInW - m_rbB.getCenterOfMassPosition(); - - btVector3 normalWorld; - //linear part - for (i=0;i<3;i++) - { - if (m_linearLimits.isLimited(i)) - { - if (m_useLinearReferenceFrameA) - normalWorld = m_calculatedTransformA.getBasis().getColumn(i); - else - normalWorld = m_calculatedTransformB.getBasis().getColumn(i); - - buildLinearJacobian( - m_jacLinear[i],normalWorld , - pivotAInW,pivotBInW); - - } - } - - // angular part - for (i=0;i<3;i++) - { - //calculates error angle - if (testAngularLimitMotor(i)) - { - normalWorld = this->getAxis(i); - // Create angular atom - buildAngularJacobian(m_jacAng[i],normalWorld); - } - } - - -} - - -void btGeneric6DofConstraint::solveConstraint(btScalar timeStep) -{ - m_timeStep = timeStep; - - //calculateTransforms(); - - int i; - - // linear - - btVector3 pointInA = m_calculatedTransformA.getOrigin(); - btVector3 pointInB = m_calculatedTransformB.getOrigin(); - - btScalar jacDiagABInv; - btVector3 linear_axis; - for (i=0;i<3;i++) - { - if (m_linearLimits.isLimited(i)) - { - jacDiagABInv = btScalar(1.) / m_jacLinear[i].getDiagonal(); - - if (m_useLinearReferenceFrameA) - linear_axis = m_calculatedTransformA.getBasis().getColumn(i); - else - linear_axis = m_calculatedTransformB.getBasis().getColumn(i); - - m_linearLimits.solveLinearAxis( - m_timeStep, - jacDiagABInv, - m_rbA,pointInA, - m_rbB,pointInB, - i,linear_axis, m_AnchorPos); - - } - } - - // angular - btVector3 angular_axis; - btScalar angularJacDiagABInv; - for (i=0;i<3;i++) - { - if (m_angularLimits[i].needApplyTorques()) - { - - // get axis - angular_axis = getAxis(i); - - angularJacDiagABInv = btScalar(1.) / m_jacAng[i].getDiagonal(); - - m_angularLimits[i].solveAngularLimits(m_timeStep,angular_axis,angularJacDiagABInv, &m_rbA,&m_rbB); - } - } + btVector3 localNormalInA(0,0,0); + int i; + + // linear + for (i=0;i<3;i++) + { + if (isLimited(i)) + { + btVector3 angvelA = m_rbA.getCenterOfMassTransform().getBasis().transpose() * m_rbA.getAngularVelocity(); + btVector3 angvelB = m_rbB.getCenterOfMassTransform().getBasis().transpose() * m_rbB.getAngularVelocity(); + + localNormalInA.setValue(0,0,0); + localNormalInA[i] = 1; + btVector3 normalWorld = m_rbA.getCenterOfMassTransform().getBasis() * localNormalInA; + + btScalar jacDiagABInv = btScalar(1.) / m_jacLinear[i].getDiagonal(); + + //velocity error (first order error) + btScalar rel_vel = m_jacLinear[i].getRelativeVelocity(m_rbA.getLinearVelocity(),angvelA, + m_rbB.getLinearVelocity(),angvelB); + + //positional error (zeroth order error) + btScalar depth = -(pivotAInW - pivotBInW).dot(normalWorld); + btScalar lo = btScalar(-1e30); + btScalar hi = btScalar(1e30); + + //handle the limits + if (m_lowerLimit[i] < m_upperLimit[i]) + { + { + if (depth > m_upperLimit[i]) + { + depth -= m_upperLimit[i]; + lo = btScalar(0.); + + } else + { + if (depth < m_lowerLimit[i]) + { + depth -= m_lowerLimit[i]; + hi = btScalar(0.); + } else + { + continue; + } + } + } + } + + btScalar normalImpulse= (tau*depth/timeStep - damping*rel_vel) * jacDiagABInv; + btScalar oldNormalImpulse = m_accumulatedImpulse[i]; + btScalar sum = oldNormalImpulse + normalImpulse; + m_accumulatedImpulse[i] = sum > hi ? btScalar(0.) : sum < lo ? btScalar(0.) : sum; + normalImpulse = m_accumulatedImpulse[i] - oldNormalImpulse; + + btVector3 impulse_vector = normalWorld * normalImpulse; + m_rbA.applyImpulse( impulse_vector, rel_pos1); + m_rbB.applyImpulse(-impulse_vector, rel_pos2); + + localNormalInA[i] = 0; + } + } + + btVector3 axis; + btScalar angle; + btTransform frameAWorld = m_rbA.getCenterOfMassTransform() * m_frameInA; + btTransform frameBWorld = m_rbB.getCenterOfMassTransform() * m_frameInB; + + btTransformUtil::calculateDiffAxisAngle(frameAWorld,frameBWorld,axis,angle); + btQuaternion diff(axis,angle); + btMatrix3x3 diffMat (diff); + btVector3 xyz; + ///this is not perfect, we can first check which axis are limited, and choose a more appropriate order + MatrixToEulerXYZ(diffMat,xyz); + + // angular + for (i=0;i<3;i++) + { + if (isLimited(i+3)) + { + btVector3 angvelA = m_rbA.getCenterOfMassTransform().getBasis().transpose() * m_rbA.getAngularVelocity(); + btVector3 angvelB = m_rbB.getCenterOfMassTransform().getBasis().transpose() * m_rbB.getAngularVelocity(); + + btScalar jacDiagABInv = btScalar(1.) / m_jacAng[i].getDiagonal(); + + //velocity error (first order error) + btScalar rel_vel = m_jacAng[i].getRelativeVelocity(m_rbA.getLinearVelocity(),angvelA, + m_rbB.getLinearVelocity(),angvelB); + + //positional error (zeroth order error) + btVector3 axisA = m_rbA.getCenterOfMassTransform().getBasis() * m_frameInA.getBasis().getColumn( kAxisA[i] ); + btVector3 axisB = m_rbB.getCenterOfMassTransform().getBasis() * m_frameInB.getBasis().getColumn( kAxisB[i] ); + + btScalar rel_pos = kSign[i] * axisA.dot(axisB); + + btScalar lo = btScalar(-1e30); + btScalar hi = btScalar(1e30); + + //handle the twist limit + if (m_lowerLimit[i+3] < m_upperLimit[i+3]) + { + //clamp the values + btScalar loLimit = m_lowerLimit[i+3] > -3.1415 ? m_lowerLimit[i+3] : btScalar(-1e30); + btScalar hiLimit = m_upperLimit[i+3] < 3.1415 ? m_upperLimit[i+3] : btScalar(1e30); + + btScalar projAngle = btScalar(-1.)*xyz[i]; + + if (projAngle < loLimit) + { + hi = btScalar(0.); + rel_pos = (loLimit - projAngle); + } else + { + if (projAngle > hiLimit) + { + lo = btScalar(0.); + rel_pos = (hiLimit - projAngle); + } else + { + continue; + } + } + } + + //impulse + + btScalar normalImpulse= -(tau*rel_pos/timeStep + damping*rel_vel) * jacDiagABInv; + btScalar oldNormalImpulse = m_accumulatedImpulse[i+3]; + btScalar sum = oldNormalImpulse + normalImpulse; + m_accumulatedImpulse[i+3] = sum > hi ? btScalar(0.) : sum < lo ? btScalar(0.) : sum; + normalImpulse = m_accumulatedImpulse[i+3] - oldNormalImpulse; + + // Dirk: Not needed - we could actually project onto Jacobian entry here (same as above) + btVector3 axis = kSign[i] * axisA.cross(axisB); + btVector3 impulse_vector = axis * normalImpulse; + + m_rbA.applyTorqueImpulse( impulse_vector); + m_rbB.applyTorqueImpulse(-impulse_vector); + } + } } void btGeneric6DofConstraint::updateRHS(btScalar timeStep) { - (void)timeStep; + (void)timeStep; } -btVector3 btGeneric6DofConstraint::getAxis(int axis_index) const -{ - return m_calculatedAxis[axis_index]; -} - -btScalar btGeneric6DofConstraint::getAngle(int axis_index) const -{ - return m_calculatedAxisAngleDiff[axis_index]; -} - -void btGeneric6DofConstraint::calcAnchorPos(void) -{ - btScalar imA = m_rbA.getInvMass(); - btScalar imB = m_rbB.getInvMass(); - btScalar weight; - if(imB == btScalar(0.0)) +btScalar btGeneric6DofConstraint::computeAngle(int axis) const { - weight = btScalar(1.0); - } - else - { - weight = imA / (imA + imB); - } - const btVector3& pA = m_calculatedTransformA.getOrigin(); - const btVector3& pB = m_calculatedTransformB.getOrigin(); - m_AnchorPos = pA * weight + pB * (btScalar(1.0) - weight); - return; -} // btGeneric6DofConstraint::calcAnchorPos() + btScalar angle = btScalar(0.f); + + switch (axis) + { + case 0: + { + btVector3 v1 = m_rbA.getCenterOfMassTransform().getBasis() * m_frameInA.getBasis().getColumn(1); + btVector3 v2 = m_rbB.getCenterOfMassTransform().getBasis() * m_frameInB.getBasis().getColumn(1); + btVector3 w2 = m_rbB.getCenterOfMassTransform().getBasis() * m_frameInB.getBasis().getColumn(2); + + btScalar s = v1.dot(w2); + btScalar c = v1.dot(v2); + + angle = btAtan2( s, c ); + } + break; + + case 1: + { + btVector3 w1 = m_rbA.getCenterOfMassTransform().getBasis() * m_frameInA.getBasis().getColumn(2); + btVector3 w2 = m_rbB.getCenterOfMassTransform().getBasis() * m_frameInB.getBasis().getColumn(2); + btVector3 u2 = m_rbB.getCenterOfMassTransform().getBasis() * m_frameInB.getBasis().getColumn(0); + + btScalar s = w1.dot(u2); + btScalar c = w1.dot(w2); + + angle = btAtan2( s, c ); + } + break; + + case 2: + { + btVector3 u1 = m_rbA.getCenterOfMassTransform().getBasis() * m_frameInA.getBasis().getColumn(0); + btVector3 u2 = m_rbB.getCenterOfMassTransform().getBasis() * m_frameInB.getBasis().getColumn(0); + btVector3 v2 = m_rbB.getCenterOfMassTransform().getBasis() * m_frameInB.getBasis().getColumn(1); + + btScalar s = u1.dot(v2); + btScalar c = u1.dot(u2); + + angle = btAtan2( s, c ); + } + break; + default: + btAssert ( 0 ) ; + + break ; + } + + return angle; + } diff --git a/extern/bullet2/src/BulletDynamics/ConstraintSolver/btGeneric6DofConstraint.h b/extern/bullet2/src/BulletDynamics/ConstraintSolver/btGeneric6DofConstraint.h index f0718d2d4a0..b114e54fa69 100644 --- a/extern/bullet2/src/BulletDynamics/ConstraintSolver/btGeneric6DofConstraint.h +++ b/extern/bullet2/src/BulletDynamics/ConstraintSolver/btGeneric6DofConstraint.h @@ -4,433 +4,116 @@ Copyright (c) 2003-2006 Erwin Coumans http://continuousphysics.com/Bullet/ This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. -Permission is granted to anyone to use this software for any purpose, -including commercial applications, and to alter it and redistribute it freely, +Permission is granted to anyone to use this software for any purpose, +including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ -/* -2007-09-09 -btGeneric6DofConstraint Refactored by Francisco Le?n -email: projectileman@yahoo.com -http://gimpact.sf.net -*/ - #ifndef GENERIC_6DOF_CONSTRAINT_H #define GENERIC_6DOF_CONSTRAINT_H -#include "LinearMath/btVector3.h" +#include "../../LinearMath/btVector3.h" #include "btJacobianEntry.h" #include "btTypedConstraint.h" class btRigidBody; -//! Rotation Limit structure for generic joints -class btRotationalLimitMotor -{ -public: - //! limit_parameters - //!@{ - btScalar m_loLimit;//!< joint limit - btScalar m_hiLimit;//!< joint limit - btScalar m_targetVelocity;//!< target motor velocity - btScalar m_maxMotorForce;//!< max force on motor - btScalar m_maxLimitForce;//!< max force on limit - btScalar m_damping;//!< Damping. - btScalar m_limitSoftness;//! Relaxation factor - btScalar m_ERP;//!< Error tolerance factor when joint is at limit - btScalar m_bounce;//!< restitution factor - bool m_enableMotor; - - //!@} - - //! temp_variables - //!@{ - btScalar m_currentLimitError;//! How much is violated this limit - int m_currentLimit;//!< 0=free, 1=at lo limit, 2=at hi limit - btScalar m_accumulatedImpulse; - //!@} - - btRotationalLimitMotor() - { - m_accumulatedImpulse = 0.f; - m_targetVelocity = 0; - m_maxMotorForce = 0.1f; - m_maxLimitForce = 300.0f; - m_loLimit = -SIMD_INFINITY; - m_hiLimit = SIMD_INFINITY; - m_ERP = 0.5f; - m_bounce = 0.0f; - m_damping = 1.0f; - m_limitSoftness = 0.5f; - m_currentLimit = 0; - m_currentLimitError = 0; - m_enableMotor = false; - } - - btRotationalLimitMotor(const btRotationalLimitMotor & limot) - { - m_targetVelocity = limot.m_targetVelocity; - m_maxMotorForce = limot.m_maxMotorForce; - m_limitSoftness = limot.m_limitSoftness; - m_loLimit = limot.m_loLimit; - m_hiLimit = limot.m_hiLimit; - m_ERP = limot.m_ERP; - m_bounce = limot.m_bounce; - m_currentLimit = limot.m_currentLimit; - m_currentLimitError = limot.m_currentLimitError; - m_enableMotor = limot.m_enableMotor; - } - - - - //! Is limited - bool isLimited() - { - if(m_loLimit>=m_hiLimit) return false; - return true; - } - - //! Need apply correction - bool needApplyTorques() - { - if(m_currentLimit == 0 && m_enableMotor == false) return false; - return true; - } - - //! calculates error - /*! - calculates m_currentLimit and m_currentLimitError. - */ - int testLimitValue(btScalar test_value); - - //! apply the correction impulses for two bodies - btScalar solveAngularLimits(btScalar timeStep,btVector3& axis, btScalar jacDiagABInv,btRigidBody * body0, btRigidBody * body1); - - -}; - - - -class btTranslationalLimitMotor -{ -public: - btVector3 m_lowerLimit;//!< the constraint lower limits - btVector3 m_upperLimit;//!< the constraint upper limits - btVector3 m_accumulatedImpulse; - //! Linear_Limit_parameters - //!@{ - btScalar m_limitSoftness;//!< Softness for linear limit - btScalar m_damping;//!< Damping for linear limit - btScalar m_restitution;//! Bounce parameter for linear limit - //!@} - - btTranslationalLimitMotor() - { - m_lowerLimit.setValue(0.f,0.f,0.f); - m_upperLimit.setValue(0.f,0.f,0.f); - m_accumulatedImpulse.setValue(0.f,0.f,0.f); - - m_limitSoftness = 0.7f; - m_damping = btScalar(1.0f); - m_restitution = btScalar(0.5f); - } - - btTranslationalLimitMotor(const btTranslationalLimitMotor & other ) - { - m_lowerLimit = other.m_lowerLimit; - m_upperLimit = other.m_upperLimit; - m_accumulatedImpulse = other.m_accumulatedImpulse; - - m_limitSoftness = other.m_limitSoftness ; - m_damping = other.m_damping; - m_restitution = other.m_restitution; - } - - //! Test limit - /*! - - free means upper < lower, - - locked means upper == lower - - limited means upper > lower - - limitIndex: first 3 are linear, next 3 are angular - */ - inline bool isLimited(int limitIndex) - { - return (m_upperLimit[limitIndex] >= m_lowerLimit[limitIndex]); - } - - - btScalar solveLinearAxis( - btScalar timeStep, - btScalar jacDiagABInv, - btRigidBody& body1,const btVector3 &pointInA, - btRigidBody& body2,const btVector3 &pointInB, - int limit_index, - const btVector3 & axis_normal_on_a, - const btVector3 & anchorPos); - - -}; /// btGeneric6DofConstraint between two rigidbodies each with a pivotpoint that descibes the axis location in local space -/*! -btGeneric6DofConstraint can leave any of the 6 degree of freedom 'free' or 'locked'. -currently this limit supports rotational motors
-
    -
  • For Linear limits, use btGeneric6DofConstraint.setLinearUpperLimit, btGeneric6DofConstraint.setLinearLowerLimit. You can set the parameters with the btTranslationalLimitMotor structure accsesible through the btGeneric6DofConstraint.getTranslationalLimitMotor method. -At this moment translational motors are not supported. May be in the future.
  • - -
  • For Angular limits, use the btRotationalLimitMotor structure for configuring the limit. -This is accessible through btGeneric6DofConstraint.getLimitMotor method, -This brings support for limit parameters and motors.
  • - -
  • Angulars limits have these possible ranges: - -AXIS - - - - - - - - - - - - -
    MIN ANGLEMAX ANGLEX-PIPIY-PI/2PI/2Z-PI/2PI/2
    -
  • -
- -*/ +/// btGeneric6DofConstraint can leave any of the 6 degree of freedom 'free' or 'locked' +/// Work in progress (is still a Hinge actually) class btGeneric6DofConstraint : public btTypedConstraint { -protected: + btJacobianEntry m_jacLinear[3]; // 3 orthogonal linear constraints + btJacobianEntry m_jacAng[3]; // 3 orthogonal angular constraints - //! relative_frames - //!@{ - btTransform m_frameInA;//!< the constraint space w.r.t body A - btTransform m_frameInB;//!< the constraint space w.r.t body B - //!@} - - //! Jacobians - //!@{ - btJacobianEntry m_jacLinear[3];//!< 3 orthogonal linear constraints - btJacobianEntry m_jacAng[3];//!< 3 orthogonal angular constraints - //!@} - - //! Linear_Limit_parameters - //!@{ - btTranslationalLimitMotor m_linearLimits; - //!@} - - - //! hinge_parameters - //!@{ - btRotationalLimitMotor m_angularLimits[3]; - //!@} - - -protected: - //! temporal variables - //!@{ - btScalar m_timeStep; - btTransform m_calculatedTransformA; - btTransform m_calculatedTransformB; - btVector3 m_calculatedAxisAngleDiff; - btVector3 m_calculatedAxis[3]; - - btVector3 m_AnchorPos; // point betwen pivots of bodies A and B to solve linear axes - - bool m_useLinearReferenceFrameA; - - //!@} - - btGeneric6DofConstraint& operator=(btGeneric6DofConstraint& other) - { - btAssert(0); - (void) other; - return *this; - } - - - - void buildLinearJacobian( - btJacobianEntry & jacLinear,const btVector3 & normalWorld, - const btVector3 & pivotAInW,const btVector3 & pivotBInW); - - void buildAngularJacobian(btJacobianEntry & jacAngular,const btVector3 & jointAxisW); - - - //! calcs the euler angles between the two bodies. - void calculateAngleInfo(); + btTransform m_frameInA; // the constraint space w.r.t body A + btTransform m_frameInB; // the constraint space w.r.t body B + btScalar m_lowerLimit[6]; // the constraint lower limits + btScalar m_upperLimit[6]; // the constraint upper limits + btScalar m_accumulatedImpulse[6]; + btGeneric6DofConstraint& operator=(btGeneric6DofConstraint& other) + { + btAssert(0); + (void) other; + return *this; + } + public: - btGeneric6DofConstraint(btRigidBody& rbA, btRigidBody& rbB, const btTransform& frameInA, const btTransform& frameInB ,bool useLinearReferenceFrameA); + btGeneric6DofConstraint(btRigidBody& rbA, btRigidBody& rbB, const btTransform& frameInA, const btTransform& frameInB ); - btGeneric6DofConstraint(); + btGeneric6DofConstraint(); - //! Calcs global transform of the offsets - /*! - Calcs the global transform for the joint offset for body A an B, and also calcs the agle differences between the bodies. - \sa btGeneric6DofConstraint.getCalculatedTransformA , btGeneric6DofConstraint.getCalculatedTransformB, btGeneric6DofConstraint.calculateAngleInfo - */ - void calculateTransforms(); + + virtual void buildJacobian(); - //! Gets the global transform of the offset for body A - /*! - \sa btGeneric6DofConstraint.getFrameOffsetA, btGeneric6DofConstraint.getFrameOffsetB, btGeneric6DofConstraint.calculateAngleInfo. - */ - const btTransform & getCalculatedTransformA() const - { - return m_calculatedTransformA; - } + virtual void solveConstraint(btScalar timeStep); - //! Gets the global transform of the offset for body B - /*! - \sa btGeneric6DofConstraint.getFrameOffsetA, btGeneric6DofConstraint.getFrameOffsetB, btGeneric6DofConstraint.calculateAngleInfo. - */ - const btTransform & getCalculatedTransformB() const - { - return m_calculatedTransformB; - } + void updateRHS(btScalar timeStep); - const btTransform & getFrameOffsetA() const - { - return m_frameInA; - } + btScalar computeAngle(int axis) const; - const btTransform & getFrameOffsetB() const - { - return m_frameInB; - } + void setLinearLowerLimit(const btVector3& linearLower) + { + m_lowerLimit[0] = linearLower.getX(); + m_lowerLimit[1] = linearLower.getY(); + m_lowerLimit[2] = linearLower.getZ(); + } + void setLinearUpperLimit(const btVector3& linearUpper) + { + m_upperLimit[0] = linearUpper.getX(); + m_upperLimit[1] = linearUpper.getY(); + m_upperLimit[2] = linearUpper.getZ(); + } - btTransform & getFrameOffsetA() - { - return m_frameInA; - } + void setAngularLowerLimit(const btVector3& angularLower) + { + m_lowerLimit[3] = angularLower.getX(); + m_lowerLimit[4] = angularLower.getY(); + m_lowerLimit[5] = angularLower.getZ(); + } - btTransform & getFrameOffsetB() - { - return m_frameInB; - } + void setAngularUpperLimit(const btVector3& angularUpper) + { + m_upperLimit[3] = angularUpper.getX(); + m_upperLimit[4] = angularUpper.getY(); + m_upperLimit[5] = angularUpper.getZ(); + } + //first 3 are linear, next 3 are angular + void SetLimit(int axis, btScalar lo, btScalar hi) + { + m_lowerLimit[axis] = lo; + m_upperLimit[axis] = hi; + } - //! performs Jacobian calculation, and also calculates angle differences and axis - virtual void buildJacobian(); + //free means upper < lower, + //locked means upper == lower + //limited means upper > lower + //limitIndex: first 3 are linear, next 3 are angular + bool isLimited(int limitIndex) + { + return (m_upperLimit[limitIndex] >= m_lowerLimit[limitIndex]); + } - virtual void solveConstraint(btScalar timeStep); - - void updateRHS(btScalar timeStep); - - //! Get the rotation axis in global coordinates - /*! - \pre btGeneric6DofConstraint.buildJacobian must be called previously. - */ - btVector3 getAxis(int axis_index) const; - - //! Get the relative Euler angle - /*! - \pre btGeneric6DofConstraint.buildJacobian must be called previously. - */ - btScalar getAngle(int axis_index) const; - - //! Test angular limit. - /*! - Calculates angular correction and returns true if limit needs to be corrected. - \pre btGeneric6DofConstraint.buildJacobian must be called previously. - */ - bool testAngularLimitMotor(int axis_index); - - void setLinearLowerLimit(const btVector3& linearLower) - { - m_linearLimits.m_lowerLimit = linearLower; - } - - void setLinearUpperLimit(const btVector3& linearUpper) - { - m_linearLimits.m_upperLimit = linearUpper; - } - - void setAngularLowerLimit(const btVector3& angularLower) - { - m_angularLimits[0].m_loLimit = angularLower.getX(); - m_angularLimits[1].m_loLimit = angularLower.getY(); - m_angularLimits[2].m_loLimit = angularLower.getZ(); - } - - void setAngularUpperLimit(const btVector3& angularUpper) - { - m_angularLimits[0].m_hiLimit = angularUpper.getX(); - m_angularLimits[1].m_hiLimit = angularUpper.getY(); - m_angularLimits[2].m_hiLimit = angularUpper.getZ(); - } - - //! Retrieves the angular limit informacion - btRotationalLimitMotor * getRotationalLimitMotor(int index) - { - return &m_angularLimits[index]; - } - - //! Retrieves the limit informacion - btTranslationalLimitMotor * getTranslationalLimitMotor() - { - return &m_linearLimits; - } - - //first 3 are linear, next 3 are angular - void setLimit(int axis, btScalar lo, btScalar hi) - { - if(axis<3) - { - m_linearLimits.m_lowerLimit[axis] = lo; - m_linearLimits.m_upperLimit[axis] = hi; - } - else - { - m_angularLimits[axis-3].m_loLimit = lo; - m_angularLimits[axis-3].m_hiLimit = hi; - } - } - - //! Test limit - /*! - - free means upper < lower, - - locked means upper == lower - - limited means upper > lower - - limitIndex: first 3 are linear, next 3 are angular - */ - bool isLimited(int limitIndex) - { - if(limitIndex<3) - { - return m_linearLimits.isLimited(limitIndex); - - } - return m_angularLimits[limitIndex-3].isLimited(); - } - - const btRigidBody& getRigidBodyA() const - { - return m_rbA; - } - const btRigidBody& getRigidBodyB() const - { - return m_rbB; - } - - virtual void calcAnchorPos(void); // overridable + const btRigidBody& getRigidBodyA() const + { + return m_rbA; + } + const btRigidBody& getRigidBodyB() const + { + return m_rbB; + } + }; diff --git a/extern/bullet2/src/BulletDynamics/ConstraintSolver/btHingeConstraint.cpp b/extern/bullet2/src/BulletDynamics/ConstraintSolver/btHingeConstraint.cpp index 114abce24c7..27e30987549 100644 --- a/extern/bullet2/src/BulletDynamics/ConstraintSolver/btHingeConstraint.cpp +++ b/extern/bullet2/src/BulletDynamics/ConstraintSolver/btHingeConstraint.cpp @@ -17,185 +17,58 @@ subject to the following restrictions: #include "btHingeConstraint.h" #include "BulletDynamics/Dynamics/btRigidBody.h" #include "LinearMath/btTransformUtil.h" -#include "LinearMath/btMinMax.h" #include - -btHingeConstraint::btHingeConstraint() -: btTypedConstraint (HINGE_CONSTRAINT_TYPE), +btHingeConstraint::btHingeConstraint(): m_enableAngularMotor(false) { } btHingeConstraint::btHingeConstraint(btRigidBody& rbA,btRigidBody& rbB, const btVector3& pivotInA,const btVector3& pivotInB, - btVector3& axisInA,btVector3& axisInB) - :btTypedConstraint(HINGE_CONSTRAINT_TYPE, rbA,rbB), - m_angularOnly(false), - m_enableAngularMotor(false) + btVector3& axisInA,btVector3& axisInB) +:btTypedConstraint(rbA,rbB),m_pivotInA(pivotInA),m_pivotInB(pivotInB), +m_axisInA(axisInA), +m_axisInB(-axisInB), +m_angularOnly(false), +m_enableAngularMotor(false) { - m_rbAFrame.getOrigin() = pivotInA; - - // since no frame is given, assume this to be zero angle and just pick rb transform axis - btVector3 rbAxisA1 = rbA.getCenterOfMassTransform().getBasis().getColumn(0); - - btVector3 rbAxisA2; - btScalar projection = axisInA.dot(rbAxisA1); - if (projection >= 1.0f - SIMD_EPSILON) { - rbAxisA1 = -rbA.getCenterOfMassTransform().getBasis().getColumn(2); - rbAxisA2 = rbA.getCenterOfMassTransform().getBasis().getColumn(1); - } else if (projection <= -1.0f + SIMD_EPSILON) { - rbAxisA1 = rbA.getCenterOfMassTransform().getBasis().getColumn(2); - rbAxisA2 = rbA.getCenterOfMassTransform().getBasis().getColumn(1); - } else { - rbAxisA2 = axisInA.cross(rbAxisA1); - rbAxisA1 = rbAxisA2.cross(axisInA); - } - - m_rbAFrame.getBasis().setValue( rbAxisA1.getX(),rbAxisA2.getX(),axisInA.getX(), - rbAxisA1.getY(),rbAxisA2.getY(),axisInA.getY(), - rbAxisA1.getZ(),rbAxisA2.getZ(),axisInA.getZ() ); - - btQuaternion rotationArc = shortestArcQuat(axisInA,axisInB); - btVector3 rbAxisB1 = quatRotate(rotationArc,rbAxisA1); - btVector3 rbAxisB2 = axisInB.cross(rbAxisB1); - - m_rbBFrame.getOrigin() = pivotInB; - m_rbBFrame.getBasis().setValue( rbAxisB1.getX(),rbAxisB2.getX(),-axisInB.getX(), - rbAxisB1.getY(),rbAxisB2.getY(),-axisInB.getY(), - rbAxisB1.getZ(),rbAxisB2.getZ(),-axisInB.getZ() ); - - //start with free - m_lowerLimit = btScalar(1e30); - m_upperLimit = btScalar(-1e30); - m_biasFactor = 0.3f; - m_relaxationFactor = 1.0f; - m_limitSoftness = 0.9f; - m_solveLimit = false; } btHingeConstraint::btHingeConstraint(btRigidBody& rbA,const btVector3& pivotInA,btVector3& axisInA) -:btTypedConstraint(HINGE_CONSTRAINT_TYPE, rbA), m_angularOnly(false), m_enableAngularMotor(false) +:btTypedConstraint(rbA),m_pivotInA(pivotInA),m_pivotInB(rbA.getCenterOfMassTransform()(pivotInA)), +m_axisInA(axisInA), +//fixed axis in worldspace +m_axisInB(rbA.getCenterOfMassTransform().getBasis() * -axisInA), +m_angularOnly(false), +m_enableAngularMotor(false) { - - // since no frame is given, assume this to be zero angle and just pick rb transform axis - // fixed axis in worldspace - btVector3 rbAxisA1 = rbA.getCenterOfMassTransform().getBasis().getColumn(0); - btScalar projection = rbAxisA1.dot(axisInA); - if (projection > SIMD_EPSILON) - rbAxisA1 = rbAxisA1*projection - axisInA; - else - rbAxisA1 = rbA.getCenterOfMassTransform().getBasis().getColumn(1); - - btVector3 rbAxisA2 = axisInA.cross(rbAxisA1); - - m_rbAFrame.getOrigin() = pivotInA; - m_rbAFrame.getBasis().setValue( rbAxisA1.getX(),rbAxisA2.getX(),axisInA.getX(), - rbAxisA1.getY(),rbAxisA2.getY(),axisInA.getY(), - rbAxisA1.getZ(),rbAxisA2.getZ(),axisInA.getZ() ); - - - btVector3 axisInB = rbA.getCenterOfMassTransform().getBasis() * -axisInA; - - btQuaternion rotationArc = shortestArcQuat(axisInA,axisInB); - btVector3 rbAxisB1 = quatRotate(rotationArc,rbAxisA1); - btVector3 rbAxisB2 = axisInB.cross(rbAxisB1); - - - m_rbBFrame.getOrigin() = rbA.getCenterOfMassTransform()(pivotInA); - m_rbBFrame.getBasis().setValue( rbAxisB1.getX(),rbAxisB2.getX(),axisInB.getX(), - rbAxisB1.getY(),rbAxisB2.getY(),axisInB.getY(), - rbAxisB1.getZ(),rbAxisB2.getZ(),axisInB.getZ() ); - //start with free - m_lowerLimit = btScalar(1e30); - m_upperLimit = btScalar(-1e30); - m_biasFactor = 0.3f; - m_relaxationFactor = 1.0f; - m_limitSoftness = 0.9f; - m_solveLimit = false; -} - -btHingeConstraint::btHingeConstraint(btRigidBody& rbA,btRigidBody& rbB, - const btTransform& rbAFrame, const btTransform& rbBFrame) -:btTypedConstraint(HINGE_CONSTRAINT_TYPE, rbA,rbB),m_rbAFrame(rbAFrame),m_rbBFrame(rbBFrame), -m_angularOnly(false), -m_enableAngularMotor(false) -{ - // flip axis - m_rbBFrame.getBasis()[0][2] *= btScalar(-1.); - m_rbBFrame.getBasis()[1][2] *= btScalar(-1.); - m_rbBFrame.getBasis()[2][2] *= btScalar(-1.); - - //start with free - m_lowerLimit = btScalar(1e30); - m_upperLimit = btScalar(-1e30); - m_biasFactor = 0.3f; - m_relaxationFactor = 1.0f; - m_limitSoftness = 0.9f; - m_solveLimit = false; -} - - - -btHingeConstraint::btHingeConstraint(btRigidBody& rbA, const btTransform& rbAFrame) -:btTypedConstraint(HINGE_CONSTRAINT_TYPE, rbA),m_rbAFrame(rbAFrame),m_rbBFrame(rbAFrame), -m_angularOnly(false), -m_enableAngularMotor(false) -{ - ///not providing rigidbody B means implicitly using worldspace for body B - - // flip axis - m_rbBFrame.getBasis()[0][2] *= btScalar(-1.); - m_rbBFrame.getBasis()[1][2] *= btScalar(-1.); - m_rbBFrame.getBasis()[2][2] *= btScalar(-1.); - - m_rbBFrame.getOrigin() = m_rbA.getCenterOfMassTransform()(m_rbAFrame.getOrigin()); - - //start with free - m_lowerLimit = btScalar(1e30); - m_upperLimit = btScalar(-1e30); - m_biasFactor = 0.3f; - m_relaxationFactor = 1.0f; - m_limitSoftness = 0.9f; - m_solveLimit = false; } void btHingeConstraint::buildJacobian() { m_appliedImpulse = btScalar(0.); + btVector3 normal(0,0,0); + if (!m_angularOnly) { - btVector3 pivotAInW = m_rbA.getCenterOfMassTransform()*m_rbAFrame.getOrigin(); - btVector3 pivotBInW = m_rbB.getCenterOfMassTransform()*m_rbBFrame.getOrigin(); - btVector3 relPos = pivotBInW - pivotAInW; - - btVector3 normal[3]; - if (relPos.length2() > SIMD_EPSILON) - { - normal[0] = relPos.normalized(); - } - else - { - normal[0].setValue(btScalar(1.0),0,0); - } - - btPlaneSpace1(normal[0], normal[1], normal[2]); - for (int i=0;i<3;i++) { + normal[i] = 1; new (&m_jac[i]) btJacobianEntry( m_rbA.getCenterOfMassTransform().getBasis().transpose(), m_rbB.getCenterOfMassTransform().getBasis().transpose(), - pivotAInW - m_rbA.getCenterOfMassPosition(), - pivotBInW - m_rbB.getCenterOfMassPosition(), - normal[i], + m_rbA.getCenterOfMassTransform()*m_pivotInA - m_rbA.getCenterOfMassPosition(), + m_rbB.getCenterOfMassTransform()*m_pivotInB - m_rbB.getCenterOfMassPosition(), + normal, m_rbA.getInvInertiaDiagLocal(), m_rbA.getInvMass(), m_rbB.getInvInertiaDiagLocal(), m_rbB.getInvMass()); + normal[i] = 0; } } @@ -206,12 +79,12 @@ void btHingeConstraint::buildJacobian() btVector3 jointAxis0local; btVector3 jointAxis1local; - btPlaneSpace1(m_rbAFrame.getBasis().getColumn(2),jointAxis0local,jointAxis1local); + btPlaneSpace1(m_axisInA,jointAxis0local,jointAxis1local); - getRigidBodyA().getCenterOfMassTransform().getBasis() * m_rbAFrame.getBasis().getColumn(2); + getRigidBodyA().getCenterOfMassTransform().getBasis() * m_axisInA; btVector3 jointAxis0 = getRigidBodyA().getCenterOfMassTransform().getBasis() * jointAxis0local; btVector3 jointAxis1 = getRigidBodyA().getCenterOfMassTransform().getBasis() * jointAxis1local; - btVector3 hingeAxisWorld = getRigidBodyA().getCenterOfMassTransform().getBasis() * m_rbAFrame.getBasis().getColumn(2); + btVector3 hingeAxisWorld = getRigidBodyA().getCenterOfMassTransform().getBasis() * m_axisInA; new (&m_jacAng[0]) btJacobianEntry(jointAxis0, m_rbA.getCenterOfMassTransform().getBasis().transpose(), @@ -232,70 +105,44 @@ void btHingeConstraint::buildJacobian() m_rbB.getInvInertiaDiagLocal()); - // Compute limit information - btScalar hingeAngle = getHingeAngle(); - - //set bias, sign, clear accumulator - m_correction = btScalar(0.); - m_limitSign = btScalar(0.); - m_solveLimit = false; - m_accLimitImpulse = btScalar(0.); - - if (m_lowerLimit < m_upperLimit) - { - if (hingeAngle <= m_lowerLimit*m_limitSoftness) - { - m_correction = (m_lowerLimit - hingeAngle); - m_limitSign = 1.0f; - m_solveLimit = true; - } - else if (hingeAngle >= m_upperLimit*m_limitSoftness) - { - m_correction = m_upperLimit - hingeAngle; - m_limitSign = -1.0f; - m_solveLimit = true; - } - } - - //Compute K = J*W*J' for hinge axis - btVector3 axisA = getRigidBodyA().getCenterOfMassTransform().getBasis() * m_rbAFrame.getBasis().getColumn(2); - m_kHinge = 1.0f / (getRigidBodyA().computeAngularImpulseDenominator(axisA) + - getRigidBodyB().computeAngularImpulseDenominator(axisA)); } void btHingeConstraint::solveConstraint(btScalar timeStep) { - btVector3 pivotAInW = m_rbA.getCenterOfMassTransform()*m_rbAFrame.getOrigin(); - btVector3 pivotBInW = m_rbB.getCenterOfMassTransform()*m_rbBFrame.getOrigin(); + btVector3 pivotAInW = m_rbA.getCenterOfMassTransform()*m_pivotInA; + btVector3 pivotBInW = m_rbB.getCenterOfMassTransform()*m_pivotInB; + btVector3 normal(0,0,0); btScalar tau = btScalar(0.3); + btScalar damping = btScalar(1.); - //linear part +//linear part if (!m_angularOnly) { - btVector3 rel_pos1 = pivotAInW - m_rbA.getCenterOfMassPosition(); - btVector3 rel_pos2 = pivotBInW - m_rbB.getCenterOfMassPosition(); - - btVector3 vel1 = m_rbA.getVelocityInLocalPoint(rel_pos1); - btVector3 vel2 = m_rbB.getVelocityInLocalPoint(rel_pos2); - btVector3 vel = vel1 - vel2; - for (int i=0;i<3;i++) { - const btVector3& normal = m_jac[i].m_linearJointAxis; + normal[i] = 1; btScalar jacDiagABInv = btScalar(1.) / m_jac[i].getDiagonal(); + btVector3 rel_pos1 = pivotAInW - m_rbA.getCenterOfMassPosition(); + btVector3 rel_pos2 = pivotBInW - m_rbB.getCenterOfMassPosition(); + + btVector3 vel1 = m_rbA.getVelocityInLocalPoint(rel_pos1); + btVector3 vel2 = m_rbB.getVelocityInLocalPoint(rel_pos2); + btVector3 vel = vel1 - vel2; btScalar rel_vel; rel_vel = normal.dot(vel); //positional error (zeroth order error) btScalar depth = -(pivotAInW - pivotBInW).dot(normal); //this is the error projected on the normal - btScalar impulse = depth*tau/timeStep * jacDiagABInv - rel_vel * jacDiagABInv; + btScalar impulse = depth*tau/timeStep * jacDiagABInv - damping * rel_vel * jacDiagABInv * damping; m_appliedImpulse += impulse; btVector3 impulse_vector = normal * impulse; m_rbA.applyImpulse(impulse_vector, pivotAInW - m_rbA.getCenterOfMassPosition()); m_rbB.applyImpulse(-impulse_vector, pivotBInW - m_rbB.getCenterOfMassPosition()); + + normal[i] = 0; } } @@ -304,8 +151,8 @@ void btHingeConstraint::solveConstraint(btScalar timeStep) ///solve angular part // get axes in world space - btVector3 axisA = getRigidBodyA().getCenterOfMassTransform().getBasis() * m_rbAFrame.getBasis().getColumn(2); - btVector3 axisB = getRigidBodyB().getCenterOfMassTransform().getBasis() * m_rbBFrame.getBasis().getColumn(2); + btVector3 axisA = getRigidBodyA().getCenterOfMassTransform().getBasis() * m_axisInA; + btVector3 axisB = getRigidBodyB().getCenterOfMassTransform().getBasis() * m_axisInB; const btVector3& angVelA = getRigidBodyA().getAngularVelocity(); const btVector3& angVelB = getRigidBodyB().getAngularVelocity(); @@ -327,7 +174,7 @@ void btHingeConstraint::solveConstraint(btScalar timeStep) getRigidBodyB().computeAngularImpulseDenominator(normal); // scale for mass and relaxation //todo: expose this 0.9 factor to developer - velrelOrthog *= (btScalar(1.)/denom) * m_relaxationFactor; + velrelOrthog *= (btScalar(1.)/denom) * btScalar(0.9); } //solve angular positional correction @@ -343,28 +190,10 @@ void btHingeConstraint::solveConstraint(btScalar timeStep) m_rbA.applyTorqueImpulse(-velrelOrthog+angularError); m_rbB.applyTorqueImpulse(velrelOrthog-angularError); - - // solve limit - if (m_solveLimit) - { - btScalar amplitude = ( (angVelB - angVelA).dot( axisA )*m_relaxationFactor + m_correction* (btScalar(1.)/timeStep)*m_biasFactor ) * m_limitSign; - - btScalar impulseMag = amplitude * m_kHinge; - - // Clamp the accumulated impulse - btScalar temp = m_accLimitImpulse; - m_accLimitImpulse = btMax(m_accLimitImpulse + impulseMag, btScalar(0) ); - impulseMag = m_accLimitImpulse - temp; - - - btVector3 impulse = axisA * impulseMag * m_limitSign; - m_rbA.applyTorqueImpulse(impulse); - m_rbB.applyTorqueImpulse(-impulse); - } } //apply motor - if (m_enableAngularMotor) + if (m_enableAngularMotor) { //todo: add limits too btVector3 angularLimit(0,0,0); @@ -375,7 +204,10 @@ void btHingeConstraint::solveConstraint(btScalar timeStep) btScalar desiredMotorVel = m_motorTargetVelocity; btScalar motor_relvel = desiredMotorVel - projRelVel; - btScalar unclippedMotorImpulse = m_kHinge * motor_relvel;; + btScalar denom3 = getRigidBodyA().computeAngularImpulseDenominator(axisA) + + getRigidBodyB().computeAngularImpulseDenominator(axisA); + + btScalar unclippedMotorImpulse = (btScalar(1.)/denom3) * motor_relvel;; //todo: should clip against accumulated impulse btScalar clippedMotorImpulse = unclippedMotorImpulse > m_maxMotorImpulse ? m_maxMotorImpulse : unclippedMotorImpulse; clippedMotorImpulse = clippedMotorImpulse < -m_maxMotorImpulse ? -m_maxMotorImpulse : clippedMotorImpulse; @@ -395,12 +227,3 @@ void btHingeConstraint::updateRHS(btScalar timeStep) } -btScalar btHingeConstraint::getHingeAngle() -{ - const btVector3 refAxis0 = getRigidBodyA().getCenterOfMassTransform().getBasis() * m_rbAFrame.getBasis().getColumn(0); - const btVector3 refAxis1 = getRigidBodyA().getCenterOfMassTransform().getBasis() * m_rbAFrame.getBasis().getColumn(1); - const btVector3 swingAxis = getRigidBodyB().getCenterOfMassTransform().getBasis() * m_rbBFrame.getBasis().getColumn(1); - - return btAtan2Fast( swingAxis.dot(refAxis0), swingAxis.dot(refAxis1) ); -} - diff --git a/extern/bullet2/src/BulletDynamics/ConstraintSolver/btHingeConstraint.h b/extern/bullet2/src/BulletDynamics/ConstraintSolver/btHingeConstraint.h index 4fa9972f6d8..5c1ceafbc5b 100644 --- a/extern/bullet2/src/BulletDynamics/ConstraintSolver/btHingeConstraint.h +++ b/extern/bullet2/src/BulletDynamics/ConstraintSolver/btHingeConstraint.h @@ -13,61 +13,39 @@ subject to the following restrictions: 3. This notice may not be removed or altered from any source distribution. */ -/* Hinge Constraint by Dirk Gregorius. Limits added by Marcus Hennix at Starbreeze Studios */ - #ifndef HINGECONSTRAINT_H #define HINGECONSTRAINT_H -#include "LinearMath/btVector3.h" +#include "../../LinearMath/btVector3.h" #include "btJacobianEntry.h" #include "btTypedConstraint.h" class btRigidBody; + /// hinge constraint between two rigidbodies each with a pivotpoint that descibes the axis location in local space /// axis defines the orientation of the hinge axis class btHingeConstraint : public btTypedConstraint { -#ifdef IN_PARALLELL_SOLVER -public: -#endif btJacobianEntry m_jac[3]; //3 orthogonal linear constraints btJacobianEntry m_jacAng[3]; //2 orthogonal angular constraints+ 1 for limit/motor - btTransform m_rbAFrame; // constraint axii. Assumes z is hinge axis. - btTransform m_rbBFrame; - - btScalar m_motorTargetVelocity; - btScalar m_maxMotorImpulse; - - btScalar m_limitSoftness; - btScalar m_biasFactor; - btScalar m_relaxationFactor; - - btScalar m_lowerLimit; - btScalar m_upperLimit; - - btScalar m_kHinge; - - btScalar m_limitSign; - btScalar m_correction; - - btScalar m_accLimitImpulse; + btVector3 m_pivotInA; + btVector3 m_pivotInB; + btVector3 m_axisInA; + btVector3 m_axisInB; bool m_angularOnly; - bool m_enableAngularMotor; - bool m_solveLimit; + btScalar m_motorTargetVelocity; + btScalar m_maxMotorImpulse; + bool m_enableAngularMotor; public: - btHingeConstraint(btRigidBody& rbA,btRigidBody& rbB, const btVector3& pivotInA,const btVector3& pivotInB, btVector3& axisInA,btVector3& axisInB); + btHingeConstraint(btRigidBody& rbA,btRigidBody& rbB, const btVector3& pivotInA,const btVector3& pivotInB,btVector3& axisInA,btVector3& axisInB); btHingeConstraint(btRigidBody& rbA,const btVector3& pivotInA,btVector3& axisInA); - - btHingeConstraint(btRigidBody& rbA,btRigidBody& rbB, const btTransform& rbAFrame, const btTransform& rbBFrame); - - btHingeConstraint(btRigidBody& rbA,const btTransform& rbAFrame); btHingeConstraint(); @@ -98,61 +76,6 @@ public: m_maxMotorImpulse = maxMotorImpulse; } - void setLimit(btScalar low,btScalar high,btScalar _softness = 0.9f, btScalar _biasFactor = 0.3f, btScalar _relaxationFactor = 1.0f) - { - m_lowerLimit = low; - m_upperLimit = high; - - m_limitSoftness = _softness; - m_biasFactor = _biasFactor; - m_relaxationFactor = _relaxationFactor; - - } - - btScalar getLowerLimit() const - { - return m_lowerLimit; - } - - btScalar getUpperLimit() const - { - return m_upperLimit; - } - - - btScalar getHingeAngle(); - - - const btTransform& getAFrame() { return m_rbAFrame; }; - const btTransform& getBFrame() { return m_rbBFrame; }; - - inline int getSolveLimit() - { - return m_solveLimit; - } - - inline btScalar getLimitSign() - { - return m_limitSign; - } - - inline bool getAngularOnly() - { - return m_angularOnly; - } - inline bool getEnableAngularMotor() - { - return m_enableAngularMotor; - } - inline btScalar getMotorTargetVelosity() - { - return m_motorTargetVelocity; - } - inline btScalar getMaxMotorImpulse() - { - return m_maxMotorImpulse; - } - }; #endif //HINGECONSTRAINT_H diff --git a/extern/bullet2/src/BulletDynamics/ConstraintSolver/btJacobianEntry.h b/extern/bullet2/src/BulletDynamics/ConstraintSolver/btJacobianEntry.h index bfeb24c2dfb..aae3ed0373f 100644 --- a/extern/bullet2/src/BulletDynamics/ConstraintSolver/btJacobianEntry.h +++ b/extern/bullet2/src/BulletDynamics/ConstraintSolver/btJacobianEntry.h @@ -16,8 +16,8 @@ subject to the following restrictions: #ifndef JACOBIAN_ENTRY_H #define JACOBIAN_ENTRY_H -#include "LinearMath/btVector3.h" -#include "BulletDynamics/Dynamics/btRigidBody.h" +#include "../../LinearMath/btVector3.h" +#include "../Dynamics/btRigidBody.h" //notes: diff --git a/extern/bullet2/src/BulletDynamics/ConstraintSolver/btPoint2PointConstraint.cpp b/extern/bullet2/src/BulletDynamics/ConstraintSolver/btPoint2PointConstraint.cpp index 2b69ad90438..aacb0a3ea66 100644 --- a/extern/bullet2/src/BulletDynamics/ConstraintSolver/btPoint2PointConstraint.cpp +++ b/extern/bullet2/src/BulletDynamics/ConstraintSolver/btPoint2PointConstraint.cpp @@ -21,19 +21,18 @@ subject to the following restrictions: btPoint2PointConstraint::btPoint2PointConstraint() -:btTypedConstraint(POINT2POINT_CONSTRAINT_TYPE) { } btPoint2PointConstraint::btPoint2PointConstraint(btRigidBody& rbA,btRigidBody& rbB, const btVector3& pivotInA,const btVector3& pivotInB) -:btTypedConstraint(POINT2POINT_CONSTRAINT_TYPE,rbA,rbB),m_pivotInA(pivotInA),m_pivotInB(pivotInB) +:btTypedConstraint(rbA,rbB),m_pivotInA(pivotInA),m_pivotInB(pivotInB) { } btPoint2PointConstraint::btPoint2PointConstraint(btRigidBody& rbA,const btVector3& pivotInA) -:btTypedConstraint(POINT2POINT_CONSTRAINT_TYPE,rbA),m_pivotInA(pivotInA),m_pivotInB(rbA.getCenterOfMassTransform()(pivotInA)) +:btTypedConstraint(rbA),m_pivotInA(pivotInA),m_pivotInB(rbA.getCenterOfMassTransform()(pivotInA)) { } @@ -100,16 +99,6 @@ void btPoint2PointConstraint::solveConstraint(btScalar timeStep) btScalar depth = -(pivotAInW - pivotBInW).dot(normal); //this is the error projected on the normal btScalar impulse = depth*m_setting.m_tau/timeStep * jacDiagABInv - m_setting.m_damping * rel_vel * jacDiagABInv; - - btScalar impulseClamp = m_setting.m_impulseClamp; - if (impulseClamp > 0) - { - if (impulse < -impulseClamp) - impulse = -impulseClamp; - if (impulse > impulseClamp) - impulse = impulseClamp; - } - m_appliedImpulse+=impulse; btVector3 impulse_vector = normal * impulse; m_rbA.applyImpulse(impulse_vector, pivotAInW - m_rbA.getCenterOfMassPosition()); diff --git a/extern/bullet2/src/BulletDynamics/ConstraintSolver/btPoint2PointConstraint.h b/extern/bullet2/src/BulletDynamics/ConstraintSolver/btPoint2PointConstraint.h index c9d5968530c..71da8ac0347 100644 --- a/extern/bullet2/src/BulletDynamics/ConstraintSolver/btPoint2PointConstraint.h +++ b/extern/bullet2/src/BulletDynamics/ConstraintSolver/btPoint2PointConstraint.h @@ -16,7 +16,7 @@ subject to the following restrictions: #ifndef POINT2POINTCONSTRAINT_H #define POINT2POINTCONSTRAINT_H -#include "LinearMath/btVector3.h" +#include "../../LinearMath/btVector3.h" #include "btJacobianEntry.h" #include "btTypedConstraint.h" @@ -26,21 +26,16 @@ struct btConstraintSetting { btConstraintSetting() : m_tau(btScalar(0.3)), - m_damping(btScalar(1.)), - m_impulseClamp(btScalar(0.)) + m_damping(btScalar(1.)) { } btScalar m_tau; btScalar m_damping; - btScalar m_impulseClamp; }; /// point to point constraint between two rigidbodies each with a pivotpoint that descibes the 'ballsocket' location in local space class btPoint2PointConstraint : public btTypedConstraint { -#ifdef IN_PARALLELL_SOLVER -public: -#endif btJacobianEntry m_jac[3]; //3 orthogonal linear constraints btVector3 m_pivotInA; @@ -75,15 +70,6 @@ public: m_pivotInB = pivotB; } - const btVector3& getPivotInA() const - { - return m_pivotInA; - } - - const btVector3& getPivotInB() const - { - return m_pivotInB; - } }; diff --git a/extern/bullet2/src/BulletDynamics/ConstraintSolver/btSequentialImpulseConstraintSolver.cpp b/extern/bullet2/src/BulletDynamics/ConstraintSolver/btSequentialImpulseConstraintSolver.cpp index b8afbd6aac5..14b36ad44fd 100644 --- a/extern/bullet2/src/BulletDynamics/ConstraintSolver/btSequentialImpulseConstraintSolver.cpp +++ b/extern/bullet2/src/BulletDynamics/ConstraintSolver/btSequentialImpulseConstraintSolver.cpp @@ -13,9 +13,6 @@ subject to the following restrictions: 3. This notice may not be removed or altered from any source distribution. */ -//#define COMPUTE_IMPULSE_DENOM 1 -//It is not necessary (redundant) to refresh contact manifolds, this refresh has been moved to the collision algorithms. -//#define FORCE_REFESH_CONTACT_MANIFOLDS 1 #include "btSequentialImpulseConstraintSolver.h" #include "BulletCollision/NarrowPhaseCollision/btPersistentManifold.h" @@ -33,9 +30,11 @@ subject to the following restrictions: #include "btSolverBody.h" #include "btSolverConstraint.h" - #include "LinearMath/btAlignedObjectArray.h" +#ifdef USE_PROFILE +#include "LinearMath/btQuickprof.h" +#endif //USE_PROFILE int totalCpd = 0; @@ -65,7 +64,7 @@ unsigned long btSequentialImpulseConstraintSolver::btRand2() int btSequentialImpulseConstraintSolver::btRandInt2 (int n) { // seems good; xor-fold and modulus - const unsigned long un = static_cast(n); + const unsigned long un = n; unsigned long r = btRand2(); // note: probably more aggressive than it needs to be -- might be @@ -92,12 +91,12 @@ int btSequentialImpulseConstraintSolver::btRandInt2 (int n) -bool MyContactDestroyedCallback(void* userPersistentData); + bool MyContactDestroyedCallback(void* userPersistentData) { assert (userPersistentData); btConstraintPersistentData* cpd = (btConstraintPersistentData*)userPersistentData; - btAlignedFree(cpd); + delete cpd; totalCpd--; //printf("totalCpd = %i. DELETED Ptr %x\n",totalCpd,userPersistentData); return true; @@ -106,7 +105,8 @@ bool MyContactDestroyedCallback(void* userPersistentData) btSequentialImpulseConstraintSolver::btSequentialImpulseConstraintSolver() -:m_btSeed2(0) +:m_solverMode(SOLVER_RANDMIZE_ORDER | SOLVER_CACHE_FRIENDLY), //not using SOLVER_USE_WARMSTARTING, +m_btSeed2(0) { gContactDestroyedCallback = &MyContactDestroyedCallback; @@ -121,42 +121,27 @@ btSequentialImpulseConstraintSolver::btSequentialImpulseConstraintSolver() } } -btSequentialImpulseConstraintSolver::~btSequentialImpulseConstraintSolver() -{ +void initSolverBody(btSolverBody* solverBody, btRigidBody* rigidbody) +{ +/* int size = sizeof(btSolverBody); + int sizeofrb = sizeof(btRigidBody); + int sizemanifold = sizeof(btPersistentManifold); + int sizeofmp = sizeof(btManifoldPoint); + int sizeofPersistData = sizeof (btConstraintPersistentData); +*/ + + solverBody->m_angularVelocity = rigidbody->getAngularVelocity(); + solverBody->m_centerOfMassPosition = rigidbody->getCenterOfMassPosition(); + solverBody->m_friction = rigidbody->getFriction(); +// solverBody->m_invInertiaWorld = rigidbody->getInvInertiaTensorWorld(); + solverBody->m_invMass = rigidbody->getInvMass(); + solverBody->m_linearVelocity = rigidbody->getLinearVelocity(); + solverBody->m_originalBody = rigidbody; + solverBody->m_angularFactor = rigidbody->getAngularFactor(); } -void initSolverBody(btSolverBody* solverBody, btCollisionObject* collisionObject); -void initSolverBody(btSolverBody* solverBody, btCollisionObject* collisionObject) -{ - btRigidBody* rb = btRigidBody::upcast(collisionObject); - if (rb) - { - solverBody->m_angularVelocity = rb->getAngularVelocity() ; - solverBody->m_centerOfMassPosition = collisionObject->getWorldTransform().getOrigin(); - solverBody->m_friction = collisionObject->getFriction(); - solverBody->m_invMass = rb->getInvMass(); - solverBody->m_linearVelocity = rb->getLinearVelocity(); - solverBody->m_originalBody = rb; - solverBody->m_angularFactor = rb->getAngularFactor(); - } else - { - solverBody->m_angularVelocity.setValue(0,0,0); - solverBody->m_centerOfMassPosition = collisionObject->getWorldTransform().getOrigin(); - solverBody->m_friction = collisionObject->getFriction(); - solverBody->m_invMass = 0.f; - solverBody->m_linearVelocity.setValue(0,0,0); - solverBody->m_originalBody = 0; - solverBody->m_angularFactor = 1.f; - } - solverBody->m_pushVelocity.setValue(0.f,0.f,0.f); - solverBody->m_turnVelocity.setValue(0.f,0.f,0.f); -} - - -int gNumSplitImpulseRecoveries = 0; - -btScalar restitutionCurve(btScalar rel_vel, btScalar restitution); +btScalar penetrationResolveFactor = btScalar(0.9); btScalar restitutionCurve(btScalar rel_vel, btScalar restitution) { btScalar rest = restitution * -rel_vel; @@ -164,95 +149,30 @@ btScalar restitutionCurve(btScalar rel_vel, btScalar restitution) } -void resolveSplitPenetrationImpulseCacheFriendly( - btSolverBody& body1, - btSolverBody& body2, - const btSolverConstraint& contactConstraint, - const btContactSolverInfo& solverInfo); - -//SIMD_FORCE_INLINE -void resolveSplitPenetrationImpulseCacheFriendly( - btSolverBody& body1, - btSolverBody& body2, - const btSolverConstraint& contactConstraint, - const btContactSolverInfo& solverInfo) -{ - (void)solverInfo; - - if (contactConstraint.m_penetration < solverInfo.m_splitImpulsePenetrationThreshold) - { - - gNumSplitImpulseRecoveries++; - btScalar normalImpulse; - - // Optimized version of projected relative velocity, use precomputed cross products with normal - // body1.getVelocityInLocalPoint(contactConstraint.m_rel_posA,vel1); - // body2.getVelocityInLocalPoint(contactConstraint.m_rel_posB,vel2); - // btVector3 vel = vel1 - vel2; - // btScalar rel_vel = contactConstraint.m_contactNormal.dot(vel); - - btScalar rel_vel; - btScalar vel1Dotn = contactConstraint.m_contactNormal.dot(body1.m_pushVelocity) - + contactConstraint.m_relpos1CrossNormal.dot(body1.m_turnVelocity); - btScalar vel2Dotn = contactConstraint.m_contactNormal.dot(body2.m_pushVelocity) - + contactConstraint.m_relpos2CrossNormal.dot(body2.m_turnVelocity); - - rel_vel = vel1Dotn-vel2Dotn; - btScalar positionalError = -contactConstraint.m_penetration * solverInfo.m_erp2/solverInfo.m_timeStep; - // btScalar positionalError = contactConstraint.m_penetration; - - btScalar velocityError = contactConstraint.m_restitution - rel_vel;// * damping; - - btScalar penetrationImpulse = positionalError * contactConstraint.m_jacDiagABInv; - btScalar velocityImpulse = velocityError * contactConstraint.m_jacDiagABInv; - normalImpulse = penetrationImpulse+velocityImpulse; - - // See Erin Catto's GDC 2006 paper: Clamp the accumulated impulse - btScalar oldNormalImpulse = contactConstraint.m_appliedPushImpulse; - btScalar sum = oldNormalImpulse + normalImpulse; - contactConstraint.m_appliedPushImpulse = btScalar(0.) > sum ? btScalar(0.): sum; - - normalImpulse = contactConstraint.m_appliedPushImpulse - oldNormalImpulse; - - body1.internalApplyPushImpulse(contactConstraint.m_contactNormal*body1.m_invMass, contactConstraint.m_angularComponentA,normalImpulse); - - body2.internalApplyPushImpulse(contactConstraint.m_contactNormal*body2.m_invMass, contactConstraint.m_angularComponentB,-normalImpulse); - - } - -} //velocity + friction //response between two dynamic objects with friction - -btScalar resolveSingleCollisionCombinedCacheFriendly( +SIMD_FORCE_INLINE btScalar resolveSingleCollisionCombinedCacheFriendly( btSolverBody& body1, btSolverBody& body2, - const btSolverConstraint& contactConstraint, - const btContactSolverInfo& solverInfo); - -//SIMD_FORCE_INLINE -btScalar resolveSingleCollisionCombinedCacheFriendly( - btSolverBody& body1, - btSolverBody& body2, - const btSolverConstraint& contactConstraint, + btSolverConstraint& contactConstraint, const btContactSolverInfo& solverInfo) { (void)solverInfo; - btScalar normalImpulse; - + btScalar normalImpulse(0.f); { + if (contactConstraint.m_penetration < 0.f) + return 0.f; - - // Optimized version of projected relative velocity, use precomputed cross products with normal - // body1.getVelocityInLocalPoint(contactConstraint.m_rel_posA,vel1); - // body2.getVelocityInLocalPoint(contactConstraint.m_rel_posB,vel2); - // btVector3 vel = vel1 - vel2; - // btScalar rel_vel = contactConstraint.m_contactNormal.dot(vel); + // Optimized version of projected relative velocity, use precomputed cross products with normal + // body1.getVelocityInLocalPoint(contactConstraint.m_rel_posA,vel1); + // body2.getVelocityInLocalPoint(contactConstraint.m_rel_posB,vel2); + // btVector3 vel = vel1 - vel2; + // btScalar rel_vel = contactConstraint.m_contactNormal.dot(vel); btScalar rel_vel; btScalar vel1Dotn = contactConstraint.m_contactNormal.dot(body1.m_linearVelocity) @@ -262,51 +182,50 @@ btScalar resolveSingleCollisionCombinedCacheFriendly( rel_vel = vel1Dotn-vel2Dotn; - btScalar positionalError = 0.f; - if (!solverInfo.m_splitImpulse || (contactConstraint.m_penetration > solverInfo.m_splitImpulsePenetrationThreshold)) - { - positionalError = -contactConstraint.m_penetration * solverInfo.m_erp/solverInfo.m_timeStep; - } + btScalar positionalError = contactConstraint.m_penetration; btScalar velocityError = contactConstraint.m_restitution - rel_vel;// * damping; btScalar penetrationImpulse = positionalError * contactConstraint.m_jacDiagABInv; btScalar velocityImpulse = velocityError * contactConstraint.m_jacDiagABInv; - normalImpulse = penetrationImpulse+velocityImpulse; - + btScalar normalImpulse = penetrationImpulse+velocityImpulse; // See Erin Catto's GDC 2006 paper: Clamp the accumulated impulse btScalar oldNormalImpulse = contactConstraint.m_appliedImpulse; btScalar sum = oldNormalImpulse + normalImpulse; contactConstraint.m_appliedImpulse = btScalar(0.) > sum ? btScalar(0.): sum; + btScalar oldVelocityImpulse = contactConstraint.m_appliedVelocityImpulse; + btScalar velocitySum = oldVelocityImpulse + velocityImpulse; + contactConstraint.m_appliedVelocityImpulse = btScalar(0.) > velocitySum ? btScalar(0.): velocitySum; + normalImpulse = contactConstraint.m_appliedImpulse - oldNormalImpulse; - body1.internalApplyImpulse(contactConstraint.m_contactNormal*body1.m_invMass, + if (body1.m_invMass) + { + body1.internalApplyImpulse(contactConstraint.m_contactNormal*body1.m_invMass, contactConstraint.m_angularComponentA,normalImpulse); - - body2.internalApplyImpulse(contactConstraint.m_contactNormal*body2.m_invMass, + } + if (body2.m_invMass) + { + body2.internalApplyImpulse(contactConstraint.m_contactNormal*body2.m_invMass, contactConstraint.m_angularComponentB,-normalImpulse); + } + } + + return normalImpulse; } #ifndef NO_FRICTION_TANGENTIALS -btScalar resolveSingleFrictionCacheFriendly( +SIMD_FORCE_INLINE btScalar resolveSingleFrictionCacheFriendly( btSolverBody& body1, btSolverBody& body2, - const btSolverConstraint& contactConstraint, - const btContactSolverInfo& solverInfo, - btScalar appliedNormalImpulse); - -//SIMD_FORCE_INLINE -btScalar resolveSingleFrictionCacheFriendly( - btSolverBody& body1, - btSolverBody& body2, - const btSolverConstraint& contactConstraint, + btSolverConstraint& contactConstraint, const btContactSolverInfo& solverInfo, btScalar appliedNormalImpulse) { @@ -333,42 +252,22 @@ btScalar resolveSingleFrictionCacheFriendly( // calculate j that moves us to zero relative velocity j1 = -rel_vel * contactConstraint.m_jacDiagABInv; -#define CLAMP_ACCUMULATED_FRICTION_IMPULSE 1 -#ifdef CLAMP_ACCUMULATED_FRICTION_IMPULSE btScalar oldTangentImpulse = contactConstraint.m_appliedImpulse; contactConstraint.m_appliedImpulse = oldTangentImpulse + j1; - - if (limit < contactConstraint.m_appliedImpulse) - { - contactConstraint.m_appliedImpulse = limit; - } else - { - if (contactConstraint.m_appliedImpulse < -limit) - contactConstraint.m_appliedImpulse = -limit; - } + GEN_set_min(contactConstraint.m_appliedImpulse, limit); + GEN_set_max(contactConstraint.m_appliedImpulse, -limit); j1 = contactConstraint.m_appliedImpulse - oldTangentImpulse; -#else - if (limit < j1) - { - j1 = limit; - } else - { - if (j1 < -limit) - j1 = -limit; - } - -#endif //CLAMP_ACCUMULATED_FRICTION_IMPULSE - - //GEN_set_min(contactConstraint.m_appliedImpulse, limit); - //GEN_set_max(contactConstraint.m_appliedImpulse, -limit); - - } - body1.internalApplyImpulse(contactConstraint.m_contactNormal*body1.m_invMass,contactConstraint.m_angularComponentA,j1); - - body2.internalApplyImpulse(contactConstraint.m_contactNormal*body2.m_invMass,contactConstraint.m_angularComponentB,-j1); + if (body1.m_invMass) + { + body1.internalApplyImpulse(contactConstraint.m_contactNormal*body1.m_invMass,contactConstraint.m_angularComponentA,j1); + } + if (body2.m_invMass) + { + body2.internalApplyImpulse(contactConstraint.m_contactNormal*body2.m_invMass,contactConstraint.m_angularComponentB,-j1); + } } return 0.f; @@ -410,6 +309,7 @@ btScalar resolveSingleFrictionCacheFriendly( const btVector3& rel_pos2 = contactConstraint.m_rel_posB; + //if (contactConstraint.m_appliedVelocityImpulse > 0.f) if (lat_rel_vel > SIMD_EPSILON*SIMD_EPSILON) { lat_rel_vel = btSqrt(lat_rel_vel); @@ -419,7 +319,7 @@ btScalar resolveSingleFrictionCacheFriendly( btVector3 temp2 = body2.m_invInertiaWorld * rel_pos2.cross(lat_vel); btScalar friction_impulse = lat_rel_vel / (body1.m_invMass + body2.m_invMass + lat_vel.dot(temp1.cross(rel_pos1) + temp2.cross(rel_pos2))); - btScalar normal_impulse = contactConstraint.m_appliedImpulse * combinedFriction; + btScalar normal_impulse = contactConstraint.m_appliedVelocityImpulse * combinedFriction; GEN_set_min(friction_impulse, normal_impulse); GEN_set_max(friction_impulse, -normal_impulse); @@ -433,111 +333,39 @@ btScalar resolveSingleFrictionCacheFriendly( #endif //NO_FRICTION_TANGENTIALS +btAlignedObjectArray tmpSolverBodyPool; +btAlignedObjectArray tmpSolverConstraintPool; +btAlignedObjectArray tmpSolverFrictionConstraintPool; - - -void btSequentialImpulseConstraintSolver::addFrictionConstraint(const btVector3& normalAxis,int solverBodyIdA,int solverBodyIdB,int frictionIndex,btManifoldPoint& cp,const btVector3& rel_pos1,const btVector3& rel_pos2,btCollisionObject* colObj0,btCollisionObject* colObj1, btScalar relaxation) +btScalar btSequentialImpulseConstraintSolver::solveGroupCacheFriendly(btCollisionObject** bodies,int numBodies,btPersistentManifold** manifoldPtr, int numManifolds,btTypedConstraint** constraints,int numConstraints,const btContactSolverInfo& infoGlobal,btIDebugDraw* debugDrawer,btStackAlloc* stackAlloc) { - - btRigidBody* body0=btRigidBody::upcast(colObj0); - btRigidBody* body1=btRigidBody::upcast(colObj1); - - btSolverConstraint& solverConstraint = m_tmpSolverFrictionConstraintPool.expand(); - solverConstraint.m_contactNormal = normalAxis; - - solverConstraint.m_solverBodyIdA = solverBodyIdA; - solverConstraint.m_solverBodyIdB = solverBodyIdB; - solverConstraint.m_constraintType = btSolverConstraint::BT_SOLVER_FRICTION_1D; - solverConstraint.m_frictionIndex = frictionIndex; - - solverConstraint.m_friction = cp.m_combinedFriction; - solverConstraint.m_originalContactPoint = 0; - - solverConstraint.m_appliedImpulse = btScalar(0.); - solverConstraint.m_appliedPushImpulse = 0.f; - solverConstraint.m_penetration = 0.f; - { - btVector3 ftorqueAxis1 = rel_pos1.cross(solverConstraint.m_contactNormal); - solverConstraint.m_relpos1CrossNormal = ftorqueAxis1; - solverConstraint.m_angularComponentA = body0 ? body0->getInvInertiaTensorWorld()*ftorqueAxis1 : btVector3(0,0,0); - } - { - btVector3 ftorqueAxis1 = rel_pos2.cross(solverConstraint.m_contactNormal); - solverConstraint.m_relpos2CrossNormal = ftorqueAxis1; - solverConstraint.m_angularComponentB = body1 ? body1->getInvInertiaTensorWorld()*ftorqueAxis1 : btVector3(0,0,0); - } - -#ifdef COMPUTE_IMPULSE_DENOM - btScalar denom0 = rb0->computeImpulseDenominator(pos1,solverConstraint.m_contactNormal); - btScalar denom1 = rb1->computeImpulseDenominator(pos2,solverConstraint.m_contactNormal); -#else - btVector3 vec; - btScalar denom0 = 0.f; - btScalar denom1 = 0.f; - if (body0) - { - vec = ( solverConstraint.m_angularComponentA).cross(rel_pos1); - denom0 = body0->getInvMass() + normalAxis.dot(vec); - } - if (body1) - { - vec = ( solverConstraint.m_angularComponentB).cross(rel_pos2); - denom1 = body1->getInvMass() + normalAxis.dot(vec); - } - - -#endif //COMPUTE_IMPULSE_DENOM - btScalar denom = relaxation/(denom0+denom1); - solverConstraint.m_jacDiagABInv = denom; - - -} - - - -btScalar btSequentialImpulseConstraintSolver::solveGroupCacheFriendlySetup(btCollisionObject** /*bodies */,int /*numBodies */,btPersistentManifold** manifoldPtr, int numManifolds,btTypedConstraint** constraints,int numConstraints,const btContactSolverInfo& infoGlobal,btIDebugDraw* debugDrawer,btStackAlloc* stackAlloc) -{ - BT_PROFILE("solveGroupCacheFriendlySetup"); (void)stackAlloc; (void)debugDrawer; - if (!(numConstraints + numManifolds)) { // printf("empty\n"); return 0.f; } - btPersistentManifold* manifold = 0; - btCollisionObject* colObj0=0,*colObj1=0; - - //btRigidBody* rb0=0,*rb1=0; - - -#ifdef FORCE_REFESH_CONTACT_MANIFOLDS BEGIN_PROFILE("refreshManifolds"); int i; - - - for (i=0;igetBody1(); - rb0 = (btRigidBody*)manifold->getBody0(); - + btPersistentManifold* manifold = manifoldPtr[i]; + btRigidBody* rb0 = (btRigidBody*)manifold->getBody0(); + btRigidBody* rb1 = (btRigidBody*)manifold->getBody1(); + manifold->refreshContactPoints(rb0->getCenterOfMassTransform(),rb1->getCenterOfMassTransform()); } - - END_PROFILE("refreshManifolds"); -#endif //FORCE_REFESH_CONTACT_MANIFOLDS - + END_PROFILE("refreshManifolds"); + BEGIN_PROFILE("gatherSolverData"); //int sizeofSB = sizeof(btSolverBody); //int sizeofSC = sizeof(btSolverConstraint); @@ -554,12 +382,10 @@ btScalar btSequentialImpulseConstraintSolver::solveGroupCacheFriendlySetup(btCol //todo: use stack allocator for this temp memory -// int minReservation = numManifolds*2; + int minReservation = numManifolds*2; - //m_tmpSolverBodyPool.reserve(minReservation); + tmpSolverBodyPool.reserve(minReservation); - //don't convert all bodies, only the one we need so solver the constraints -/* { for (int i=0;igetIslandTag() >= 0)) { btAssert(rb->getCompanionId() < 0); - int solverBodyId = m_tmpSolverBodyPool.size(); - btSolverBody& solverBody = m_tmpSolverBodyPool.expand(); + int solverBodyId = tmpSolverBodyPool.size(); + btSolverBody& solverBody = tmpSolverBodyPool.expand(); initSolverBody(&solverBody,rb); rb->setCompanionId(solverBodyId); } } } -*/ - - //m_tmpSolverConstraintPool.reserve(minReservation); - //m_tmpSolverFrictionConstraintPool.reserve(minReservation); + + tmpSolverConstraintPool.reserve(minReservation); + tmpSolverFrictionConstraintPool.reserve(minReservation); { int i; for (i=0;igetBody0(); - colObj1 = (btCollisionObject*)manifold->getBody1(); + btPersistentManifold* manifold = manifoldPtr[i]; + btRigidBody* rb0 = (btRigidBody*)manifold->getBody0(); + btRigidBody* rb1 = (btRigidBody*)manifold->getBody1(); + int solverBodyIdA=-1; int solverBodyIdB=-1; @@ -596,108 +422,61 @@ btScalar btSequentialImpulseConstraintSolver::solveGroupCacheFriendlySetup(btCol - if (colObj0->getIslandTag() >= 0) + if (rb0->getIslandTag() >= 0) { - if (colObj0->getCompanionId() >= 0) - { - //body has already been converted - solverBodyIdA = colObj0->getCompanionId(); - } else - { - solverBodyIdA = m_tmpSolverBodyPool.size(); - btSolverBody& solverBody = m_tmpSolverBodyPool.expand(); - initSolverBody(&solverBody,colObj0); - colObj0->setCompanionId(solverBodyIdA); - } + solverBodyIdA = rb0->getCompanionId(); } else { //create a static body - solverBodyIdA = m_tmpSolverBodyPool.size(); - btSolverBody& solverBody = m_tmpSolverBodyPool.expand(); - initSolverBody(&solverBody,colObj0); + solverBodyIdA = tmpSolverBodyPool.size(); + btSolverBody& solverBody = tmpSolverBodyPool.expand(); + initSolverBody(&solverBody,rb0); } - if (colObj1->getIslandTag() >= 0) + if (rb1->getIslandTag() >= 0) { - if (colObj1->getCompanionId() >= 0) - { - solverBodyIdB = colObj1->getCompanionId(); - } else - { - solverBodyIdB = m_tmpSolverBodyPool.size(); - btSolverBody& solverBody = m_tmpSolverBodyPool.expand(); - initSolverBody(&solverBody,colObj1); - colObj1->setCompanionId(solverBodyIdB); - } + solverBodyIdB = rb1->getCompanionId(); } else { //create a static body - solverBodyIdB = m_tmpSolverBodyPool.size(); - btSolverBody& solverBody = m_tmpSolverBodyPool.expand(); - initSolverBody(&solverBody,colObj1); + solverBodyIdB = tmpSolverBodyPool.size(); + btSolverBody& solverBody = tmpSolverBodyPool.expand(); + initSolverBody(&solverBody,rb1); } } - btVector3 rel_pos1; - btVector3 rel_pos2; - btScalar relaxation; - for (int j=0;jgetNumContacts();j++) { btManifoldPoint& cp = manifold->getContactPoint(j); - + + int frictionIndex = tmpSolverConstraintPool.size(); + if (cp.getDistance() <= btScalar(0.)) { const btVector3& pos1 = cp.getPositionWorldOnA(); const btVector3& pos2 = cp.getPositionWorldOnB(); - rel_pos1 = pos1 - colObj0->getWorldTransform().getOrigin(); - rel_pos2 = pos2 - colObj1->getWorldTransform().getOrigin(); + btVector3 rel_pos1 = pos1 - rb0->getCenterOfMassPosition(); + btVector3 rel_pos2 = pos2 - rb1->getCenterOfMassPosition(); - relaxation = 1.f; - btScalar rel_vel; - btVector3 vel; - - int frictionIndex = m_tmpSolverConstraintPool.size(); + btScalar relaxation = 1.f; { - btSolverConstraint& solverConstraint = m_tmpSolverConstraintPool.expand(); - btRigidBody* rb0 = btRigidBody::upcast(colObj0); - btRigidBody* rb1 = btRigidBody::upcast(colObj1); + btSolverConstraint& solverConstraint = tmpSolverConstraintPool.expand(); solverConstraint.m_solverBodyIdA = solverBodyIdA; solverConstraint.m_solverBodyIdB = solverBodyIdB; solverConstraint.m_constraintType = btSolverConstraint::BT_SOLVER_CONTACT_1D; - solverConstraint.m_originalContactPoint = &cp; + - btVector3 torqueAxis0 = rel_pos1.cross(cp.m_normalWorldOnB); - solverConstraint.m_angularComponentA = rb0 ? rb0->getInvInertiaTensorWorld()*torqueAxis0 : btVector3(0,0,0); - btVector3 torqueAxis1 = rel_pos2.cross(cp.m_normalWorldOnB); - solverConstraint.m_angularComponentB = rb1 ? rb1->getInvInertiaTensorWorld()*torqueAxis1 : btVector3(0,0,0); { -#ifdef COMPUTE_IMPULSE_DENOM + //can be optimized, the cross products are already calculated btScalar denom0 = rb0->computeImpulseDenominator(pos1,cp.m_normalWorldOnB); btScalar denom1 = rb1->computeImpulseDenominator(pos2,cp.m_normalWorldOnB); -#else - btVector3 vec; - btScalar denom0 = 0.f; - btScalar denom1 = 0.f; - if (rb0) - { - vec = ( solverConstraint.m_angularComponentA).cross(rel_pos1); - denom0 = rb0->getInvMass() + cp.m_normalWorldOnB.dot(vec); - } - if (rb1) - { - vec = ( solverConstraint.m_angularComponentB).cross(rel_pos2); - denom1 = rb1->getInvMass() + cp.m_normalWorldOnB.dot(vec); - } -#endif //COMPUTE_IMPULSE_DENOM - btScalar denom = relaxation/(denom0+denom1); solverConstraint.m_jacDiagABInv = denom; } @@ -707,115 +486,121 @@ btScalar btSequentialImpulseConstraintSolver::solveGroupCacheFriendlySetup(btCol solverConstraint.m_relpos2CrossNormal = rel_pos2.cross(cp.m_normalWorldOnB); - btVector3 vel1 = rb0 ? rb0->getVelocityInLocalPoint(rel_pos1) : btVector3(0,0,0); - btVector3 vel2 = rb1 ? rb1->getVelocityInLocalPoint(rel_pos2) : btVector3(0,0,0); + btVector3 vel1 = rb0->getVelocityInLocalPoint(rel_pos1); + btVector3 vel2 = rb1->getVelocityInLocalPoint(rel_pos2); - vel = vel1 - vel2; - + btVector3 vel = vel1 - vel2; + btScalar rel_vel; rel_vel = cp.m_normalWorldOnB.dot(vel); - solverConstraint.m_penetration = btMin(cp.getDistance()+infoGlobal.m_linearSlop,btScalar(0.)); - //solverConstraint.m_penetration = cp.getDistance(); + solverConstraint.m_penetration = cp.getDistance();///btScalar(infoGlobal.m_numIterations); solverConstraint.m_friction = cp.m_combinedFriction; - solverConstraint.m_restitution = restitutionCurve(rel_vel, cp.m_combinedRestitution); - if (solverConstraint.m_restitution <= btScalar(0.)) + btScalar rest = restitutionCurve(rel_vel, cp.m_combinedRestitution); + if (rest <= btScalar(0.)) { - solverConstraint.m_restitution = 0.f; + rest = 0.f; }; - btScalar penVel = -solverConstraint.m_penetration/infoGlobal.m_timeStep; + if (rest > penVel) + { + rest = btScalar(0.); + } + solverConstraint.m_restitution = rest; - + solverConstraint.m_penetration *= -(infoGlobal.m_erp/infoGlobal.m_timeStep); - if (solverConstraint.m_restitution > penVel) - { - solverConstraint.m_penetration = btScalar(0.); - } - + solverConstraint.m_appliedImpulse = 0.f; + solverConstraint.m_appliedVelocityImpulse = 0.f; - - ///warm starting (or zero if disabled) - if (infoGlobal.m_solverMode & SOLVER_USE_WARMSTARTING) - { - solverConstraint.m_appliedImpulse = cp.m_appliedImpulse * infoGlobal.m_warmstartingFactor; - if (rb0) - m_tmpSolverBodyPool[solverConstraint.m_solverBodyIdA].internalApplyImpulse(solverConstraint.m_contactNormal*rb0->getInvMass(),solverConstraint.m_angularComponentA,solverConstraint.m_appliedImpulse); - if (rb1) - m_tmpSolverBodyPool[solverConstraint.m_solverBodyIdB].internalApplyImpulse(solverConstraint.m_contactNormal*rb1->getInvMass(),solverConstraint.m_angularComponentB,-solverConstraint.m_appliedImpulse); - } else - { - solverConstraint.m_appliedImpulse = 0.f; - } - - solverConstraint.m_appliedPushImpulse = 0.f; - - solverConstraint.m_frictionIndex = m_tmpSolverFrictionConstraintPool.size(); - if (!cp.m_lateralFrictionInitialized) - { - cp.m_lateralFrictionDir1 = vel - cp.m_normalWorldOnB * rel_vel; - btScalar lat_rel_vel = cp.m_lateralFrictionDir1.length2(); - if (lat_rel_vel > SIMD_EPSILON)//0.0f) - { - cp.m_lateralFrictionDir1 /= btSqrt(lat_rel_vel); - addFrictionConstraint(cp.m_lateralFrictionDir1,solverBodyIdA,solverBodyIdB,frictionIndex,cp,rel_pos1,rel_pos2,colObj0,colObj1, relaxation); - cp.m_lateralFrictionDir2 = cp.m_lateralFrictionDir1.cross(cp.m_normalWorldOnB); - cp.m_lateralFrictionDir2.normalize();//?? - addFrictionConstraint(cp.m_lateralFrictionDir2,solverBodyIdA,solverBodyIdB,frictionIndex,cp,rel_pos1,rel_pos2,colObj0,colObj1, relaxation); - } else - { - //re-calculate friction direction every frame, todo: check if this is really needed - - btPlaneSpace1(cp.m_normalWorldOnB,cp.m_lateralFrictionDir1,cp.m_lateralFrictionDir2); - addFrictionConstraint(cp.m_lateralFrictionDir1,solverBodyIdA,solverBodyIdB,frictionIndex,cp,rel_pos1,rel_pos2,colObj0,colObj1, relaxation); - addFrictionConstraint(cp.m_lateralFrictionDir2,solverBodyIdA,solverBodyIdB,frictionIndex,cp,rel_pos1,rel_pos2,colObj0,colObj1, relaxation); - } - cp.m_lateralFrictionInitialized = true; - - } else - { - addFrictionConstraint(cp.m_lateralFrictionDir1,solverBodyIdA,solverBodyIdB,frictionIndex,cp,rel_pos1,rel_pos2,colObj0,colObj1, relaxation); - addFrictionConstraint(cp.m_lateralFrictionDir2,solverBodyIdA,solverBodyIdB,frictionIndex,cp,rel_pos1,rel_pos2,colObj0,colObj1, relaxation); - } - - { - btSolverConstraint& frictionConstraint1 = m_tmpSolverFrictionConstraintPool[solverConstraint.m_frictionIndex]; - if (infoGlobal.m_solverMode & SOLVER_USE_WARMSTARTING) - { - frictionConstraint1.m_appliedImpulse = cp.m_appliedImpulseLateral1 * infoGlobal.m_warmstartingFactor; - if (rb0) - m_tmpSolverBodyPool[solverConstraint.m_solverBodyIdA].internalApplyImpulse(frictionConstraint1.m_contactNormal*rb0->getInvMass(),frictionConstraint1.m_angularComponentA,frictionConstraint1.m_appliedImpulse); - if (rb1) - m_tmpSolverBodyPool[solverConstraint.m_solverBodyIdB].internalApplyImpulse(frictionConstraint1.m_contactNormal*rb1->getInvMass(),frictionConstraint1.m_angularComponentB,-frictionConstraint1.m_appliedImpulse); - } else - { - frictionConstraint1.m_appliedImpulse = 0.f; - } - } - { - btSolverConstraint& frictionConstraint2 = m_tmpSolverFrictionConstraintPool[solverConstraint.m_frictionIndex+1]; - if (infoGlobal.m_solverMode & SOLVER_USE_WARMSTARTING) - { - frictionConstraint2.m_appliedImpulse = cp.m_appliedImpulseLateral2 * infoGlobal.m_warmstartingFactor; - if (rb0) - m_tmpSolverBodyPool[solverConstraint.m_solverBodyIdA].internalApplyImpulse(frictionConstraint2.m_contactNormal*rb0->getInvMass(),frictionConstraint2.m_angularComponentA,frictionConstraint2.m_appliedImpulse); - if (rb1) - m_tmpSolverBodyPool[solverConstraint.m_solverBodyIdB].internalApplyImpulse(frictionConstraint2.m_contactNormal*rb1->getInvMass(),frictionConstraint2.m_angularComponentB,-frictionConstraint2.m_appliedImpulse); - } else - { - frictionConstraint2.m_appliedImpulse = 0.f; - } - } + + btVector3 torqueAxis0 = rel_pos1.cross(cp.m_normalWorldOnB); + solverConstraint.m_angularComponentA = rb0->getInvInertiaTensorWorld()*torqueAxis0; + btVector3 torqueAxis1 = rel_pos2.cross(cp.m_normalWorldOnB); + solverConstraint.m_angularComponentB = rb1->getInvInertiaTensorWorld()*torqueAxis1; } + //create 2 '1d axis' constraints for 2 tangential friction directions + + //re-calculate friction direction every frame, todo: check if this is really needed + btVector3 frictionTangential0a, frictionTangential1b; + + btPlaneSpace1(cp.m_normalWorldOnB,frictionTangential0a,frictionTangential1b); + + { + btSolverConstraint& solverConstraint = tmpSolverFrictionConstraintPool.expand(); + solverConstraint.m_contactNormal = frictionTangential0a; + + solverConstraint.m_solverBodyIdA = solverBodyIdA; + solverConstraint.m_solverBodyIdB = solverBodyIdB; + solverConstraint.m_constraintType = btSolverConstraint::BT_SOLVER_FRICTION_1D; + solverConstraint.m_frictionIndex = frictionIndex; + + solverConstraint.m_friction = cp.m_combinedFriction; + + solverConstraint.m_appliedImpulse = btScalar(0.); + solverConstraint.m_appliedVelocityImpulse = 0.f; + + btScalar denom0 = rb0->computeImpulseDenominator(pos1,solverConstraint.m_contactNormal); + btScalar denom1 = rb1->computeImpulseDenominator(pos2,solverConstraint.m_contactNormal); + btScalar denom = relaxation/(denom0+denom1); + solverConstraint.m_jacDiagABInv = denom; + + { + btVector3 ftorqueAxis0 = rel_pos1.cross(solverConstraint.m_contactNormal); + solverConstraint.m_relpos1CrossNormal = ftorqueAxis0; + solverConstraint.m_angularComponentA = rb0->getInvInertiaTensorWorld()*ftorqueAxis0; + } + { + btVector3 ftorqueAxis0 = rel_pos2.cross(solverConstraint.m_contactNormal); + solverConstraint.m_relpos2CrossNormal = ftorqueAxis0; + solverConstraint.m_angularComponentB = rb1->getInvInertiaTensorWorld()*ftorqueAxis0; + } + + } + + + { + + btSolverConstraint& solverConstraint = tmpSolverFrictionConstraintPool.expand(); + solverConstraint.m_contactNormal = frictionTangential1b; + + solverConstraint.m_solverBodyIdA = solverBodyIdA; + solverConstraint.m_solverBodyIdB = solverBodyIdB; + solverConstraint.m_constraintType = btSolverConstraint::BT_SOLVER_FRICTION_1D; + solverConstraint.m_frictionIndex = frictionIndex; + + solverConstraint.m_friction = cp.m_combinedFriction; + + solverConstraint.m_appliedImpulse = btScalar(0.); + solverConstraint.m_appliedVelocityImpulse = 0.f; + + btScalar denom0 = rb0->computeImpulseDenominator(pos1,solverConstraint.m_contactNormal); + btScalar denom1 = rb1->computeImpulseDenominator(pos2,solverConstraint.m_contactNormal); + btScalar denom = relaxation/(denom0+denom1); + solverConstraint.m_jacDiagABInv = denom; + { + btVector3 ftorqueAxis1 = rel_pos1.cross(solverConstraint.m_contactNormal); + solverConstraint.m_relpos1CrossNormal = ftorqueAxis1; + solverConstraint.m_angularComponentA = rb0->getInvInertiaTensorWorld()*ftorqueAxis1; + } + { + btVector3 ftorqueAxis1 = rel_pos2.cross(solverConstraint.m_contactNormal); + solverConstraint.m_relpos2CrossNormal = ftorqueAxis1; + solverConstraint.m_angularComponentB = rb1->getInvInertiaTensorWorld()*ftorqueAxis1; + } + } } } } } } - + END_PROFILE("gatherSolverData"); + + BEGIN_PROFILE("prepareConstraints"); + btContactSolverInfo info = infoGlobal; { @@ -827,60 +612,57 @@ btScalar btSequentialImpulseConstraintSolver::solveGroupCacheFriendlySetup(btCol } } - + btAlignedObjectArray gOrderTmpConstraintPool; + btAlignedObjectArray gOrderFrictionConstraintPool; - int numConstraintPool = m_tmpSolverConstraintPool.size(); - int numFrictionPool = m_tmpSolverFrictionConstraintPool.size(); + int numConstraintPool = tmpSolverConstraintPool.size(); + int numFrictionPool = tmpSolverFrictionConstraintPool.size(); ///todo: use stack allocator for such temporarily memory, same for solver bodies/constraints - m_orderTmpConstraintPool.resize(numConstraintPool); - m_orderFrictionConstraintPool.resize(numFrictionPool); + gOrderTmpConstraintPool.resize(numConstraintPool); + gOrderFrictionConstraintPool.resize(numFrictionPool); { int i; for (i=0;igetRigidBodyA().getIslandTag() >= 0) && (constraint->getRigidBodyA().getCompanionId() >= 0)) { - m_tmpSolverBodyPool[constraint->getRigidBodyA().getCompanionId()].writebackVelocity(); + tmpSolverBodyPool[constraint->getRigidBodyA().getCompanionId()].writebackVelocity(); } if ((constraint->getRigidBodyB().getIslandTag() >= 0) && (constraint->getRigidBodyB().getCompanionId() >= 0)) { - m_tmpSolverBodyPool[constraint->getRigidBodyB().getCompanionId()].writebackVelocity(); + tmpSolverBodyPool[constraint->getRigidBodyB().getCompanionId()].writebackVelocity(); } - constraint->solveConstraint(infoGlobal.m_timeStep); + constraint->solveConstraint(info.m_timeStep); if ((constraint->getRigidBodyA().getIslandTag() >= 0) && (constraint->getRigidBodyA().getCompanionId() >= 0)) { - m_tmpSolverBodyPool[constraint->getRigidBodyA().getCompanionId()].readVelocity(); + tmpSolverBodyPool[constraint->getRigidBodyA().getCompanionId()].readVelocity(); } if ((constraint->getRigidBodyB().getIslandTag() >= 0) && (constraint->getRigidBodyB().getCompanionId() >= 0)) { - m_tmpSolverBodyPool[constraint->getRigidBodyB().getCompanionId()].readVelocity(); + tmpSolverBodyPool[constraint->getRigidBodyB().getCompanionId()].readVelocity(); } } { - int numPoolConstraints = m_tmpSolverConstraintPool.size(); + int numPoolConstraints = tmpSolverConstraintPool.size(); for (j=0;jm_appliedImpulse = solveManifold.m_appliedImpulse; - pt->m_appliedImpulseLateral1 = m_tmpSolverFrictionConstraintPool[solveManifold.m_frictionIndex].m_appliedImpulse; - pt->m_appliedImpulseLateral1 = m_tmpSolverFrictionConstraintPool[solveManifold.m_frictionIndex+1].m_appliedImpulse; - - //do a callback here? - - } - - if (infoGlobal.m_splitImpulse) - { - for ( i=0;igetBody0(), (btRigidBody*)manifold->getBody1(),manifold->getContactPoint(gOrder[j].m_pointIndex),info,iteration,debugDrawer); } - } } + END_PROFILE("solveConstraints"); + + +#ifdef USE_PROFILE + btProfiler::endBlock("solve"); +#endif //USE_PROFILE + @@ -1140,14 +878,13 @@ void btSequentialImpulseConstraintSolver::prepareConstraints(btPersistentManifol //only necessary to refresh the manifold once (first iteration). The integration is done outside the loop { -#ifdef FORCE_REFESH_CONTACT_MANIFOLDS manifoldPtr->refreshContactPoints(body0->getCenterOfMassTransform(),body1->getCenterOfMassTransform()); -#endif //FORCE_REFESH_CONTACT_MANIFOLDS + int numpoints = manifoldPtr->getNumContacts(); gTotalContactPoints += numpoints; - + btVector3 color(0,1,0); for (int i=0;igetContactPoint(i); @@ -1188,9 +925,7 @@ void btSequentialImpulseConstraintSolver::prepareConstraints(btPersistentManifol } else { - //todo: should this be in a pool? - void* mem = btAlignedAlloc(sizeof(btConstraintPersistentData),16); - cpd = new (mem)btConstraintPersistentData; + cpd = new btConstraintPersistentData; assert(cpd); totalCpd ++; @@ -1237,9 +972,10 @@ void btSequentialImpulseConstraintSolver::prepareConstraints(btPersistentManifol cpd->m_penetration = btScalar(0.); } + btScalar relaxation = info.m_damping; - if (info.m_solverMode & SOLVER_USE_WARMSTARTING) + if (m_solverMode & SOLVER_USE_WARMSTARTING) { cpd->m_appliedImpulse *= relaxation; } else @@ -1324,12 +1060,16 @@ btScalar btSequentialImpulseConstraintSolver::solveCombinedContactFriction(btRig { - + btVector3 color(0,1,0); { if (cp.getDistance() <= btScalar(0.)) { - + if (iter == 0) + { + if (debugDrawer) + debugDrawer->drawContactPoint(cp.m_positionWorldOnB,cp.m_normalWorldOnB,cp.getDistance(),cp.getLifeTime(),color); + } { @@ -1358,12 +1098,16 @@ btScalar btSequentialImpulseConstraintSolver::solve(btRigidBody* body0,btRigidBo { - + btVector3 color(0,1,0); { if (cp.getDistance() <= btScalar(0.)) { - + if (iter == 0) + { + if (debugDrawer) + debugDrawer->drawContactPoint(cp.m_positionWorldOnB,cp.m_normalWorldOnB,cp.getDistance(),cp.getLifeTime(),color); + } { @@ -1392,7 +1136,7 @@ btScalar btSequentialImpulseConstraintSolver::solveFriction(btRigidBody* body0,b { - + btVector3 color(0,1,0); { if (cp.getDistance() <= btScalar(0.)) @@ -1412,11 +1156,3 @@ btScalar btSequentialImpulseConstraintSolver::solveFriction(btRigidBody* body0,b } return btScalar(0.); } - - -void btSequentialImpulseConstraintSolver::reset() -{ - m_btSeed2 = 0; -} - - diff --git a/extern/bullet2/src/BulletDynamics/ConstraintSolver/btSequentialImpulseConstraintSolver.h b/extern/bullet2/src/BulletDynamics/ConstraintSolver/btSequentialImpulseConstraintSolver.h index 7143bc41991..13e70c41be4 100644 --- a/extern/bullet2/src/BulletDynamics/ConstraintSolver/btSequentialImpulseConstraintSolver.h +++ b/extern/bullet2/src/BulletDynamics/ConstraintSolver/btSequentialImpulseConstraintSolver.h @@ -19,8 +19,7 @@ subject to the following restrictions: #include "btConstraintSolver.h" class btIDebugDraw; #include "btContactConstraint.h" -#include "btSolverBody.h" -#include "btSolverConstraint.h" + /// btSequentialImpulseConstraintSolver uses a Propagation Method and Sequentially applies impulses @@ -30,29 +29,29 @@ class btIDebugDraw; class btSequentialImpulseConstraintSolver : public btConstraintSolver { - btAlignedObjectArray m_tmpSolverBodyPool; - btAlignedObjectArray m_tmpSolverConstraintPool; - btAlignedObjectArray m_tmpSolverFrictionConstraintPool; - btAlignedObjectArray m_orderTmpConstraintPool; - btAlignedObjectArray m_orderFrictionConstraintPool; - - protected: btScalar solve(btRigidBody* body0,btRigidBody* body1, btManifoldPoint& cp, const btContactSolverInfo& info,int iter,btIDebugDraw* debugDrawer); btScalar solveFriction(btRigidBody* body0,btRigidBody* body1, btManifoldPoint& cp, const btContactSolverInfo& info,int iter,btIDebugDraw* debugDrawer); void prepareConstraints(btPersistentManifold* manifoldPtr, const btContactSolverInfo& info,btIDebugDraw* debugDrawer); - void addFrictionConstraint(const btVector3& normalAxis,int solverBodyIdA,int solverBodyIdB,int frictionIndex,btManifoldPoint& cp,const btVector3& rel_pos1,const btVector3& rel_pos2,btCollisionObject* colObj0,btCollisionObject* colObj1, btScalar relaxation); ContactSolverFunc m_contactDispatch[MAX_CONTACT_SOLVER_TYPES][MAX_CONTACT_SOLVER_TYPES]; ContactSolverFunc m_frictionDispatch[MAX_CONTACT_SOLVER_TYPES][MAX_CONTACT_SOLVER_TYPES]; - + //choose between several modes, different friction model etc. + int m_solverMode; ///m_btSeed2 is used for re-arranging the constraint rows. improves convergence/quality of friction unsigned long m_btSeed2; public: - + enum eSolverMode + { + SOLVER_RANDMIZE_ORDER = 1, + SOLVER_FRICTION_SEPARATE = 2, + SOLVER_USE_WARMSTARTING = 4, + SOLVER_CACHE_FRIENDLY = 8 + }; + btSequentialImpulseConstraintSolver(); ///Advanced: Override the default contact solving function for contacts, for certain types of rigidbody @@ -69,22 +68,25 @@ public: m_frictionDispatch[type0][type1] = func; } - virtual ~btSequentialImpulseConstraintSolver(); + virtual ~btSequentialImpulseConstraintSolver() {} - virtual btScalar solveGroup(btCollisionObject** bodies,int numBodies,btPersistentManifold** manifold,int numManifolds,btTypedConstraint** constraints,int numConstraints,const btContactSolverInfo& info, btIDebugDraw* debugDrawer, btStackAlloc* stackAlloc,btDispatcher* dispatcher); + virtual btScalar solveGroup(btCollisionObject** bodies,int numBodies,btPersistentManifold** manifold,int numManifolds,btTypedConstraint** constraints,int numConstraints,const btContactSolverInfo& info, btIDebugDraw* debugDrawer, btStackAlloc* stackAlloc); virtual btScalar solveGroupCacheFriendly(btCollisionObject** bodies,int numBodies,btPersistentManifold** manifoldPtr, int numManifolds,btTypedConstraint** constraints,int numConstraints,const btContactSolverInfo& infoGlobal,btIDebugDraw* debugDrawer,btStackAlloc* stackAlloc); - btScalar solveGroupCacheFriendlyIterations(btCollisionObject** bodies,int numBodies,btPersistentManifold** manifoldPtr, int numManifolds,btTypedConstraint** constraints,int numConstraints,const btContactSolverInfo& infoGlobal,btIDebugDraw* debugDrawer,btStackAlloc* stackAlloc); - btScalar solveGroupCacheFriendlySetup(btCollisionObject** bodies,int numBodies,btPersistentManifold** manifoldPtr, int numManifolds,btTypedConstraint** constraints,int numConstraints,const btContactSolverInfo& infoGlobal,btIDebugDraw* debugDrawer,btStackAlloc* stackAlloc); - - - ///clear internal cached data and reset random seed - virtual void reset(); btScalar solveCombinedContactFriction(btRigidBody* body0,btRigidBody* body1, btManifoldPoint& cp, const btContactSolverInfo& info,int iter,btIDebugDraw* debugDrawer); - + void setSolverMode(int mode) + { + m_solverMode = mode; + } + + int getSolverMode() const + { + return m_solverMode; + } + unsigned long btRand2(); int btRandInt2 (int n); @@ -100,9 +102,7 @@ public: }; -#ifndef BT_PREFER_SIMD -typedef btSequentialImpulseConstraintSolver btSequentialImpulseConstraintSolverPrefered; -#endif + #endif //SEQUENTIAL_IMPULSE_CONSTRAINT_SOLVER_H diff --git a/extern/bullet2/src/BulletDynamics/ConstraintSolver/btSliderConstraint.cpp b/extern/bullet2/src/BulletDynamics/ConstraintSolver/btSliderConstraint.cpp deleted file mode 100644 index e7f07a428eb..00000000000 --- a/extern/bullet2/src/BulletDynamics/ConstraintSolver/btSliderConstraint.cpp +++ /dev/null @@ -1,414 +0,0 @@ -/* -Bullet Continuous Collision Detection and Physics Library -Copyright (c) 2003-2006 Erwin Coumans http://continuousphysics.com/Bullet/ - -This software is provided 'as-is', without any express or implied warranty. -In no event will the authors be held liable for any damages arising from the use of this software. -Permission is granted to anyone to use this software for any purpose, -including commercial applications, and to alter it and redistribute it freely, -subject to the following restrictions: - -1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. -2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. -3. This notice may not be removed or altered from any source distribution. -*/ - -/* -Added by Roman Ponomarev (rponom@gmail.com) -April 04, 2008 -*/ - -//----------------------------------------------------------------------------- - -#include "btSliderConstraint.h" -#include "BulletDynamics/Dynamics/btRigidBody.h" -#include "LinearMath/btTransformUtil.h" -#include - -//----------------------------------------------------------------------------- - -void btSliderConstraint::initParams() -{ - m_lowerLinLimit = btScalar(1.0); - m_upperLinLimit = btScalar(-1.0); - m_lowerAngLimit = btScalar(0.); - m_upperAngLimit = btScalar(0.); - m_softnessDirLin = SLIDER_CONSTRAINT_DEF_SOFTNESS; - m_restitutionDirLin = SLIDER_CONSTRAINT_DEF_RESTITUTION; - m_dampingDirLin = btScalar(0.); - m_softnessDirAng = SLIDER_CONSTRAINT_DEF_SOFTNESS; - m_restitutionDirAng = SLIDER_CONSTRAINT_DEF_RESTITUTION; - m_dampingDirAng = btScalar(0.); - m_softnessOrthoLin = SLIDER_CONSTRAINT_DEF_SOFTNESS; - m_restitutionOrthoLin = SLIDER_CONSTRAINT_DEF_RESTITUTION; - m_dampingOrthoLin = SLIDER_CONSTRAINT_DEF_DAMPING; - m_softnessOrthoAng = SLIDER_CONSTRAINT_DEF_SOFTNESS; - m_restitutionOrthoAng = SLIDER_CONSTRAINT_DEF_RESTITUTION; - m_dampingOrthoAng = SLIDER_CONSTRAINT_DEF_DAMPING; - m_softnessLimLin = SLIDER_CONSTRAINT_DEF_SOFTNESS; - m_restitutionLimLin = SLIDER_CONSTRAINT_DEF_RESTITUTION; - m_dampingLimLin = SLIDER_CONSTRAINT_DEF_DAMPING; - m_softnessLimAng = SLIDER_CONSTRAINT_DEF_SOFTNESS; - m_restitutionLimAng = SLIDER_CONSTRAINT_DEF_RESTITUTION; - m_dampingLimAng = SLIDER_CONSTRAINT_DEF_DAMPING; - - m_poweredLinMotor = false; - m_targetLinMotorVelocity = btScalar(0.); - m_maxLinMotorForce = btScalar(0.); - m_accumulatedLinMotorImpulse = btScalar(0.0); - - m_poweredAngMotor = false; - m_targetAngMotorVelocity = btScalar(0.); - m_maxAngMotorForce = btScalar(0.); - m_accumulatedAngMotorImpulse = btScalar(0.0); - -} // btSliderConstraint::initParams() - -//----------------------------------------------------------------------------- - -btSliderConstraint::btSliderConstraint() - :btTypedConstraint(SLIDER_CONSTRAINT_TYPE), - m_useLinearReferenceFrameA(true) -{ - initParams(); -} // btSliderConstraint::btSliderConstraint() - -//----------------------------------------------------------------------------- - -btSliderConstraint::btSliderConstraint(btRigidBody& rbA, btRigidBody& rbB, const btTransform& frameInA, const btTransform& frameInB, bool useLinearReferenceFrameA) - : btTypedConstraint(SLIDER_CONSTRAINT_TYPE, rbA, rbB) - , m_frameInA(frameInA) - , m_frameInB(frameInB), - m_useLinearReferenceFrameA(useLinearReferenceFrameA) -{ - initParams(); -} // btSliderConstraint::btSliderConstraint() - -//----------------------------------------------------------------------------- - -void btSliderConstraint::buildJacobian() -{ - if(m_useLinearReferenceFrameA) - { - buildJacobianInt(m_rbA, m_rbB, m_frameInA, m_frameInB); - } - else - { - buildJacobianInt(m_rbB, m_rbA, m_frameInB, m_frameInA); - } -} // btSliderConstraint::buildJacobian() - -//----------------------------------------------------------------------------- - -void btSliderConstraint::buildJacobianInt(btRigidBody& rbA, btRigidBody& rbB, const btTransform& frameInA, const btTransform& frameInB) -{ - //calculate transforms - m_calculatedTransformA = rbA.getCenterOfMassTransform() * frameInA; - m_calculatedTransformB = rbB.getCenterOfMassTransform() * frameInB; - m_realPivotAInW = m_calculatedTransformA.getOrigin(); - m_realPivotBInW = m_calculatedTransformB.getOrigin(); - m_sliderAxis = m_calculatedTransformA.getBasis().getColumn(0); // along X - m_delta = m_realPivotBInW - m_realPivotAInW; - m_projPivotInW = m_realPivotAInW + m_sliderAxis.dot(m_delta) * m_sliderAxis; - m_relPosA = m_projPivotInW - rbA.getCenterOfMassPosition(); - m_relPosB = m_realPivotBInW - rbB.getCenterOfMassPosition(); - btVector3 normalWorld; - int i; - //linear part - for(i = 0; i < 3; i++) - { - normalWorld = m_calculatedTransformA.getBasis().getColumn(i); - new (&m_jacLin[i]) btJacobianEntry( - rbA.getCenterOfMassTransform().getBasis().transpose(), - rbB.getCenterOfMassTransform().getBasis().transpose(), - m_relPosA, - m_relPosB, - normalWorld, - rbA.getInvInertiaDiagLocal(), - rbA.getInvMass(), - rbB.getInvInertiaDiagLocal(), - rbB.getInvMass() - ); - m_jacLinDiagABInv[i] = btScalar(1.) / m_jacLin[i].getDiagonal(); - m_depth[i] = m_delta.dot(normalWorld); - } - testLinLimits(); - // angular part - for(i = 0; i < 3; i++) - { - normalWorld = m_calculatedTransformA.getBasis().getColumn(i); - new (&m_jacAng[i]) btJacobianEntry( - normalWorld, - rbA.getCenterOfMassTransform().getBasis().transpose(), - rbB.getCenterOfMassTransform().getBasis().transpose(), - rbA.getInvInertiaDiagLocal(), - rbB.getInvInertiaDiagLocal() - ); - } - testAngLimits(); - btVector3 axisA = m_calculatedTransformA.getBasis().getColumn(0); - m_kAngle = btScalar(1.0 )/ (rbA.computeAngularImpulseDenominator(axisA) + rbB.computeAngularImpulseDenominator(axisA)); - // clear accumulator for motors - m_accumulatedLinMotorImpulse = btScalar(0.0); - m_accumulatedAngMotorImpulse = btScalar(0.0); -} // btSliderConstraint::buildJacobianInt() - -//----------------------------------------------------------------------------- - -void btSliderConstraint::solveConstraint(btScalar timeStep) -{ - m_timeStep = timeStep; - if(m_useLinearReferenceFrameA) - { - solveConstraintInt(m_rbA, m_rbB); - } - else - { - solveConstraintInt(m_rbB, m_rbA); - } -} // btSliderConstraint::solveConstraint() - -//----------------------------------------------------------------------------- - -void btSliderConstraint::solveConstraintInt(btRigidBody& rbA, btRigidBody& rbB) -{ - int i; - // linear - btVector3 velA = rbA.getVelocityInLocalPoint(m_relPosA); - btVector3 velB = rbB.getVelocityInLocalPoint(m_relPosB); - btVector3 vel = velA - velB; - for(i = 0; i < 3; i++) - { - const btVector3& normal = m_jacLin[i].m_linearJointAxis; - btScalar rel_vel = normal.dot(vel); - // calculate positional error - btScalar depth = m_depth[i]; - // get parameters - btScalar softness = (i) ? m_softnessOrthoLin : (m_solveLinLim ? m_softnessLimLin : m_softnessDirLin); - btScalar restitution = (i) ? m_restitutionOrthoLin : (m_solveLinLim ? m_restitutionLimLin : m_restitutionDirLin); - btScalar damping = (i) ? m_dampingOrthoLin : (m_solveLinLim ? m_dampingLimLin : m_dampingDirLin); - // calcutate and apply impulse - btScalar normalImpulse = softness * (restitution * depth / m_timeStep - damping * rel_vel) * m_jacLinDiagABInv[i]; - btVector3 impulse_vector = normal * normalImpulse; - rbA.applyImpulse( impulse_vector, m_relPosA); - rbB.applyImpulse(-impulse_vector, m_relPosB); - if(m_poweredLinMotor && (!i)) - { // apply linear motor - if(m_accumulatedLinMotorImpulse < m_maxLinMotorForce) - { - btScalar desiredMotorVel = m_targetLinMotorVelocity; - btScalar motor_relvel = desiredMotorVel + rel_vel; - normalImpulse = -motor_relvel * m_jacLinDiagABInv[i]; - // clamp accumulated impulse - btScalar new_acc = m_accumulatedLinMotorImpulse + btFabs(normalImpulse); - if(new_acc > m_maxLinMotorForce) - { - new_acc = m_maxLinMotorForce; - } - btScalar del = new_acc - m_accumulatedLinMotorImpulse; - if(normalImpulse < btScalar(0.0)) - { - normalImpulse = -del; - } - else - { - normalImpulse = del; - } - m_accumulatedLinMotorImpulse = new_acc; - // apply clamped impulse - impulse_vector = normal * normalImpulse; - rbA.applyImpulse( impulse_vector, m_relPosA); - rbB.applyImpulse(-impulse_vector, m_relPosB); - } - } - } - // angular - // get axes in world space - btVector3 axisA = m_calculatedTransformA.getBasis().getColumn(0); - btVector3 axisB = m_calculatedTransformB.getBasis().getColumn(0); - - const btVector3& angVelA = rbA.getAngularVelocity(); - const btVector3& angVelB = rbB.getAngularVelocity(); - - btVector3 angVelAroundAxisA = axisA * axisA.dot(angVelA); - btVector3 angVelAroundAxisB = axisB * axisB.dot(angVelB); - - btVector3 angAorthog = angVelA - angVelAroundAxisA; - btVector3 angBorthog = angVelB - angVelAroundAxisB; - btVector3 velrelOrthog = angAorthog-angBorthog; - //solve orthogonal angular velocity correction - btScalar len = velrelOrthog.length(); - if (len > btScalar(0.00001)) - { - btVector3 normal = velrelOrthog.normalized(); - btScalar denom = rbA.computeAngularImpulseDenominator(normal) + rbB.computeAngularImpulseDenominator(normal); - velrelOrthog *= (btScalar(1.)/denom) * m_dampingOrthoAng * m_softnessOrthoAng; - } - //solve angular positional correction - btVector3 angularError = axisA.cross(axisB) *(btScalar(1.)/m_timeStep); - btScalar len2 = angularError.length(); - if (len2>btScalar(0.00001)) - { - btVector3 normal2 = angularError.normalized(); - btScalar denom2 = rbA.computeAngularImpulseDenominator(normal2) + rbB.computeAngularImpulseDenominator(normal2); - angularError *= (btScalar(1.)/denom2) * m_restitutionOrthoAng * m_softnessOrthoAng; - } - // apply impulse - rbA.applyTorqueImpulse(-velrelOrthog+angularError); - rbB.applyTorqueImpulse(velrelOrthog-angularError); - btScalar impulseMag; - //solve angular limits - if(m_solveAngLim) - { - impulseMag = (angVelB - angVelA).dot(axisA) * m_dampingLimAng + m_angDepth * m_restitutionLimAng / m_timeStep; - impulseMag *= m_kAngle * m_softnessLimAng; - } - else - { - impulseMag = (angVelB - angVelA).dot(axisA) * m_dampingDirAng + m_angDepth * m_restitutionDirAng / m_timeStep; - impulseMag *= m_kAngle * m_softnessDirAng; - } - btVector3 impulse = axisA * impulseMag; - rbA.applyTorqueImpulse(impulse); - rbB.applyTorqueImpulse(-impulse); - //apply angular motor - if(m_poweredAngMotor) - { - if(m_accumulatedAngMotorImpulse < m_maxAngMotorForce) - { - btVector3 velrel = angVelAroundAxisA - angVelAroundAxisB; - btScalar projRelVel = velrel.dot(axisA); - - btScalar desiredMotorVel = m_targetAngMotorVelocity; - btScalar motor_relvel = desiredMotorVel - projRelVel; - - btScalar angImpulse = m_kAngle * motor_relvel; - // clamp accumulated impulse - btScalar new_acc = m_accumulatedAngMotorImpulse + btFabs(angImpulse); - if(new_acc > m_maxAngMotorForce) - { - new_acc = m_maxAngMotorForce; - } - btScalar del = new_acc - m_accumulatedAngMotorImpulse; - if(angImpulse < btScalar(0.0)) - { - angImpulse = -del; - } - else - { - angImpulse = del; - } - m_accumulatedAngMotorImpulse = new_acc; - // apply clamped impulse - btVector3 motorImp = angImpulse * axisA; - m_rbA.applyTorqueImpulse(motorImp); - m_rbB.applyTorqueImpulse(-motorImp); - } - } -} // btSliderConstraint::solveConstraint() - -//----------------------------------------------------------------------------- - -//----------------------------------------------------------------------------- - -void btSliderConstraint::calculateTransforms(void){ - if(m_useLinearReferenceFrameA) - { - m_calculatedTransformA = m_rbA.getCenterOfMassTransform() * m_frameInA; - m_calculatedTransformB = m_rbB.getCenterOfMassTransform() * m_frameInB; - } - else - { - m_calculatedTransformA = m_rbB.getCenterOfMassTransform() * m_frameInB; - m_calculatedTransformB = m_rbA.getCenterOfMassTransform() * m_frameInA; - } - m_realPivotAInW = m_calculatedTransformA.getOrigin(); - m_realPivotBInW = m_calculatedTransformB.getOrigin(); - m_sliderAxis = m_calculatedTransformA.getBasis().getColumn(0); // along X - m_delta = m_realPivotBInW - m_realPivotAInW; - m_projPivotInW = m_realPivotAInW + m_sliderAxis.dot(m_delta) * m_sliderAxis; - btVector3 normalWorld; - int i; - //linear part - for(i = 0; i < 3; i++) - { - normalWorld = m_calculatedTransformA.getBasis().getColumn(i); - m_depth[i] = m_delta.dot(normalWorld); - } -} // btSliderConstraint::calculateTransforms() - -//----------------------------------------------------------------------------- - -void btSliderConstraint::testLinLimits(void) -{ - m_solveLinLim = false; - if(m_lowerLinLimit <= m_upperLinLimit) - { - if(m_depth[0] > m_upperLinLimit) - { - m_depth[0] -= m_upperLinLimit; - m_solveLinLim = true; - } - else if(m_depth[0] < m_lowerLinLimit) - { - m_depth[0] -= m_lowerLinLimit; - m_solveLinLim = true; - } - else - { - m_depth[0] = btScalar(0.); - } - } - else - { - m_depth[0] = btScalar(0.); - } -} // btSliderConstraint::testLinLimits() - -//----------------------------------------------------------------------------- - - -void btSliderConstraint::testAngLimits(void) -{ - m_angDepth = btScalar(0.); - m_solveAngLim = false; - if(m_lowerAngLimit <= m_upperAngLimit) - { - const btVector3 axisA0 = m_calculatedTransformA.getBasis().getColumn(1); - const btVector3 axisA1 = m_calculatedTransformA.getBasis().getColumn(2); - const btVector3 axisB0 = m_calculatedTransformB.getBasis().getColumn(1); - btScalar rot = btAtan2Fast(axisB0.dot(axisA1), axisB0.dot(axisA0)); - if(rot < m_lowerAngLimit) - { - m_angDepth = rot - m_lowerAngLimit; - m_solveAngLim = true; - } - else if(rot > m_upperAngLimit) - { - m_angDepth = rot - m_upperAngLimit; - m_solveAngLim = true; - } - } -} // btSliderConstraint::testAngLimits() - - -//----------------------------------------------------------------------------- - - - -btVector3 btSliderConstraint::getAncorInA(void) -{ - btVector3 ancorInA; - ancorInA = m_realPivotAInW + (m_lowerLinLimit + m_upperLinLimit) * btScalar(0.5) * m_sliderAxis; - ancorInA = m_rbA.getCenterOfMassTransform().inverse() * ancorInA; - return ancorInA; -} // btSliderConstraint::getAncorInA() - -//----------------------------------------------------------------------------- - -btVector3 btSliderConstraint::getAncorInB(void) -{ - btVector3 ancorInB; - ancorInB = m_frameInB.getOrigin(); - return ancorInB; -} // btSliderConstraint::getAncorInB(); diff --git a/extern/bullet2/src/BulletDynamics/ConstraintSolver/btSliderConstraint.h b/extern/bullet2/src/BulletDynamics/ConstraintSolver/btSliderConstraint.h deleted file mode 100644 index f69dfcf3aa7..00000000000 --- a/extern/bullet2/src/BulletDynamics/ConstraintSolver/btSliderConstraint.h +++ /dev/null @@ -1,215 +0,0 @@ -/* -Bullet Continuous Collision Detection and Physics Library -Copyright (c) 2003-2006 Erwin Coumans http://continuousphysics.com/Bullet/ - -This software is provided 'as-is', without any express or implied warranty. -In no event will the authors be held liable for any damages arising from the use of this software. -Permission is granted to anyone to use this software for any purpose, -including commercial applications, and to alter it and redistribute it freely, -subject to the following restrictions: - -1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. -2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. -3. This notice may not be removed or altered from any source distribution. -*/ - -/* -Added by Roman Ponomarev (rponom@gmail.com) -April 04, 2008 - -TODO: - - add clamping od accumulated impulse to improve stability - - add conversion for ODE constraint solver -*/ - -#ifndef SLIDER_CONSTRAINT_H -#define SLIDER_CONSTRAINT_H - -//----------------------------------------------------------------------------- - -#include "LinearMath/btVector3.h" -#include "btJacobianEntry.h" -#include "btTypedConstraint.h" - -//----------------------------------------------------------------------------- - -class btRigidBody; - -//----------------------------------------------------------------------------- - -#define SLIDER_CONSTRAINT_DEF_SOFTNESS (btScalar(1.0)) -#define SLIDER_CONSTRAINT_DEF_DAMPING (btScalar(1.0)) -#define SLIDER_CONSTRAINT_DEF_RESTITUTION (btScalar(0.7)) - -//----------------------------------------------------------------------------- - -class btSliderConstraint : public btTypedConstraint -{ -protected: - btTransform m_frameInA; - btTransform m_frameInB; - // use frameA fo define limits, if true - bool m_useLinearReferenceFrameA; - // linear limits - btScalar m_lowerLinLimit; - btScalar m_upperLinLimit; - // angular limits - btScalar m_lowerAngLimit; - btScalar m_upperAngLimit; - // softness, restitution and damping for different cases - // DirLin - moving inside linear limits - // LimLin - hitting linear limit - // DirAng - moving inside angular limits - // LimAng - hitting angular limit - // OrthoLin, OrthoAng - against constraint axis - btScalar m_softnessDirLin; - btScalar m_restitutionDirLin; - btScalar m_dampingDirLin; - btScalar m_softnessDirAng; - btScalar m_restitutionDirAng; - btScalar m_dampingDirAng; - btScalar m_softnessLimLin; - btScalar m_restitutionLimLin; - btScalar m_dampingLimLin; - btScalar m_softnessLimAng; - btScalar m_restitutionLimAng; - btScalar m_dampingLimAng; - btScalar m_softnessOrthoLin; - btScalar m_restitutionOrthoLin; - btScalar m_dampingOrthoLin; - btScalar m_softnessOrthoAng; - btScalar m_restitutionOrthoAng; - btScalar m_dampingOrthoAng; - - // for interlal use - bool m_solveLinLim; - bool m_solveAngLim; - - btJacobianEntry m_jacLin[3]; - btScalar m_jacLinDiagABInv[3]; - - btJacobianEntry m_jacAng[3]; - - btScalar m_timeStep; - btTransform m_calculatedTransformA; - btTransform m_calculatedTransformB; - - btVector3 m_sliderAxis; - btVector3 m_realPivotAInW; - btVector3 m_realPivotBInW; - btVector3 m_projPivotInW; - btVector3 m_delta; - btVector3 m_depth; - btVector3 m_relPosA; - btVector3 m_relPosB; - - btScalar m_angDepth; - btScalar m_kAngle; - - bool m_poweredLinMotor; - btScalar m_targetLinMotorVelocity; - btScalar m_maxLinMotorForce; - btScalar m_accumulatedLinMotorImpulse; - - bool m_poweredAngMotor; - btScalar m_targetAngMotorVelocity; - btScalar m_maxAngMotorForce; - btScalar m_accumulatedAngMotorImpulse; - - //------------------------ - void initParams(); -public: - // constructors - btSliderConstraint(btRigidBody& rbA, btRigidBody& rbB, const btTransform& frameInA, const btTransform& frameInB ,bool useLinearReferenceFrameA); - btSliderConstraint(); - // overrides - virtual void buildJacobian(); - virtual void solveConstraint(btScalar timeStep); - // access - const btRigidBody& getRigidBodyA() const { return m_rbA; } - const btRigidBody& getRigidBodyB() const { return m_rbB; } - const btTransform & getCalculatedTransformA() const { return m_calculatedTransformA; } - const btTransform & getCalculatedTransformB() const { return m_calculatedTransformB; } - const btTransform & getFrameOffsetA() const { return m_frameInA; } - const btTransform & getFrameOffsetB() const { return m_frameInB; } - btTransform & getFrameOffsetA() { return m_frameInA; } - btTransform & getFrameOffsetB() { return m_frameInB; } - btScalar getLowerLinLimit() { return m_lowerLinLimit; } - void setLowerLinLimit(btScalar lowerLimit) { m_lowerLinLimit = lowerLimit; } - btScalar getUpperLinLimit() { return m_upperLinLimit; } - void setUpperLinLimit(btScalar upperLimit) { m_upperLinLimit = upperLimit; } - btScalar getLowerAngLimit() { return m_lowerAngLimit; } - void setLowerAngLimit(btScalar lowerLimit) { m_lowerAngLimit = lowerLimit; } - btScalar getUpperAngLimit() { return m_upperAngLimit; } - void setUpperAngLimit(btScalar upperLimit) { m_upperAngLimit = upperLimit; } - bool getUseLinearReferenceFrameA() { return m_useLinearReferenceFrameA; } - btScalar getSoftnessDirLin() { return m_softnessDirLin; } - btScalar getRestitutionDirLin() { return m_restitutionDirLin; } - btScalar getDampingDirLin() { return m_dampingDirLin ; } - btScalar getSoftnessDirAng() { return m_softnessDirAng; } - btScalar getRestitutionDirAng() { return m_restitutionDirAng; } - btScalar getDampingDirAng() { return m_dampingDirAng; } - btScalar getSoftnessLimLin() { return m_softnessLimLin; } - btScalar getRestitutionLimLin() { return m_restitutionLimLin; } - btScalar getDampingLimLin() { return m_dampingLimLin; } - btScalar getSoftnessLimAng() { return m_softnessLimAng; } - btScalar getRestitutionLimAng() { return m_restitutionLimAng; } - btScalar getDampingLimAng() { return m_dampingLimAng; } - btScalar getSoftnessOrthoLin() { return m_softnessOrthoLin; } - btScalar getRestitutionOrthoLin() { return m_restitutionOrthoLin; } - btScalar getDampingOrthoLin() { return m_dampingOrthoLin; } - btScalar getSoftnessOrthoAng() { return m_softnessOrthoAng; } - btScalar getRestitutionOrthoAng() { return m_restitutionOrthoAng; } - btScalar getDampingOrthoAng() { return m_dampingOrthoAng; } - void setSoftnessDirLin(btScalar softnessDirLin) { m_softnessDirLin = softnessDirLin; } - void setRestitutionDirLin(btScalar restitutionDirLin) { m_restitutionDirLin = restitutionDirLin; } - void setDampingDirLin(btScalar dampingDirLin) { m_dampingDirLin = dampingDirLin; } - void setSoftnessDirAng(btScalar softnessDirAng) { m_softnessDirAng = softnessDirAng; } - void setRestitutionDirAng(btScalar restitutionDirAng) { m_restitutionDirAng = restitutionDirAng; } - void setDampingDirAng(btScalar dampingDirAng) { m_dampingDirAng = dampingDirAng; } - void setSoftnessLimLin(btScalar softnessLimLin) { m_softnessLimLin = softnessLimLin; } - void setRestitutionLimLin(btScalar restitutionLimLin) { m_restitutionLimLin = restitutionLimLin; } - void setDampingLimLin(btScalar dampingLimLin) { m_dampingLimLin = dampingLimLin; } - void setSoftnessLimAng(btScalar softnessLimAng) { m_softnessLimAng = softnessLimAng; } - void setRestitutionLimAng(btScalar restitutionLimAng) { m_restitutionLimAng = restitutionLimAng; } - void setDampingLimAng(btScalar dampingLimAng) { m_dampingLimAng = dampingLimAng; } - void setSoftnessOrthoLin(btScalar softnessOrthoLin) { m_softnessOrthoLin = softnessOrthoLin; } - void setRestitutionOrthoLin(btScalar restitutionOrthoLin) { m_restitutionOrthoLin = restitutionOrthoLin; } - void setDampingOrthoLin(btScalar dampingOrthoLin) { m_dampingOrthoLin = dampingOrthoLin; } - void setSoftnessOrthoAng(btScalar softnessOrthoAng) { m_softnessOrthoAng = softnessOrthoAng; } - void setRestitutionOrthoAng(btScalar restitutionOrthoAng) { m_restitutionOrthoAng = restitutionOrthoAng; } - void setDampingOrthoAng(btScalar dampingOrthoAng) { m_dampingOrthoAng = dampingOrthoAng; } - void setPoweredLinMotor(bool onOff) { m_poweredLinMotor = onOff; } - bool getPoweredLinMotor() { return m_poweredLinMotor; } - void setTargetLinMotorVelocity(btScalar targetLinMotorVelocity) { m_targetLinMotorVelocity = targetLinMotorVelocity; } - btScalar getTargetLinMotorVelocity() { return m_targetLinMotorVelocity; } - void setMaxLinMotorForce(btScalar maxLinMotorForce) { m_maxLinMotorForce = maxLinMotorForce; } - btScalar getMaxLinMotorForce() { return m_maxLinMotorForce; } - void setPoweredAngMotor(bool onOff) { m_poweredAngMotor = onOff; } - bool getPoweredAngMotor() { return m_poweredAngMotor; } - void setTargetAngMotorVelocity(btScalar targetAngMotorVelocity) { m_targetAngMotorVelocity = targetAngMotorVelocity; } - btScalar getTargetAngMotorVelocity() { return m_targetAngMotorVelocity; } - void setMaxAngMotorForce(btScalar maxAngMotorForce) { m_maxAngMotorForce = maxAngMotorForce; } - btScalar getMaxAngMotorForce() { return m_maxAngMotorForce; } - - // access for ODE solver - bool getSolveLinLimit() { return m_solveLinLim; } - btScalar getLinDepth() { return m_depth[0]; } - bool getSolveAngLimit() { return m_solveAngLim; } - btScalar getAngDepth() { return m_angDepth; } - // internal - void buildJacobianInt(btRigidBody& rbA, btRigidBody& rbB, const btTransform& frameInA, const btTransform& frameInB); - void solveConstraintInt(btRigidBody& rbA, btRigidBody& rbB); - // shared code used by ODE solver - void calculateTransforms(void); - void testLinLimits(void); - void testAngLimits(void); - // access for PE Solver - btVector3 getAncorInA(void); - btVector3 getAncorInB(void); -}; - -//----------------------------------------------------------------------------- - -#endif //SLIDER_CONSTRAINT_H - diff --git a/extern/bullet2/src/BulletDynamics/ConstraintSolver/btSolve2LinearConstraint.h b/extern/bullet2/src/BulletDynamics/ConstraintSolver/btSolve2LinearConstraint.h index 057d3fac827..e7d26645c6a 100644 --- a/extern/bullet2/src/BulletDynamics/ConstraintSolver/btSolve2LinearConstraint.h +++ b/extern/bullet2/src/BulletDynamics/ConstraintSolver/btSolve2LinearConstraint.h @@ -16,8 +16,8 @@ subject to the following restrictions: #ifndef SOLVE_2LINEAR_CONSTRAINT_H #define SOLVE_2LINEAR_CONSTRAINT_H -#include "LinearMath/btMatrix3x3.h" -#include "LinearMath/btVector3.h" +#include "../../LinearMath/btMatrix3x3.h" +#include "../../LinearMath/btVector3.h" class btRigidBody; diff --git a/extern/bullet2/src/BulletDynamics/ConstraintSolver/btSolverBody.h b/extern/bullet2/src/BulletDynamics/ConstraintSolver/btSolverBody.h index b3f0c9d7444..0ab536f42b3 100644 --- a/extern/bullet2/src/BulletDynamics/ConstraintSolver/btSolverBody.h +++ b/extern/bullet2/src/BulletDynamics/ConstraintSolver/btSolverBody.h @@ -19,78 +19,38 @@ subject to the following restrictions: class btRigidBody; #include "LinearMath/btVector3.h" #include "LinearMath/btMatrix3x3.h" -#include "BulletDynamics/Dynamics/btRigidBody.h" -#include "LinearMath/btAlignedAllocator.h" -#include "LinearMath/btTransformUtil.h" -///btSolverBody is an internal datastructure for the constraint solver. Only necessary data is packed to increase cache coherence/performance. + + ATTRIBUTE_ALIGNED16 (struct) btSolverBody { - BT_DECLARE_ALIGNED_ALLOCATOR(); - + btVector3 m_centerOfMassPosition; + btVector3 m_linearVelocity; btVector3 m_angularVelocity; - float m_angularFactor; + btRigidBody* m_originalBody; float m_invMass; float m_friction; - btRigidBody* m_originalBody; - btVector3 m_linearVelocity; - btVector3 m_centerOfMassPosition; - - btVector3 m_pushVelocity; - btVector3 m_turnVelocity; - - - SIMD_FORCE_INLINE void getVelocityInLocalPoint(const btVector3& rel_pos, btVector3& velocity ) const + float m_angularFactor; + + inline void getVelocityInLocalPoint(const btVector3& rel_pos, btVector3& velocity ) const { velocity = m_linearVelocity + m_angularVelocity.cross(rel_pos); } //Optimization for the iterative solver: avoid calculating constant terms involving inertia, normal, relative position - SIMD_FORCE_INLINE void internalApplyImpulse(const btVector3& linearComponent, const btVector3& angularComponent,btScalar impulseMagnitude) + inline void internalApplyImpulse(const btVector3& linearComponent, const btVector3& angularComponent,btScalar impulseMagnitude) { - if (m_invMass) - { - m_linearVelocity += linearComponent*impulseMagnitude; - m_angularVelocity += angularComponent*(impulseMagnitude*m_angularFactor); - } - } - - SIMD_FORCE_INLINE void internalApplyPushImpulse(const btVector3& linearComponent, const btVector3& angularComponent,btScalar impulseMagnitude) - { - if (m_invMass) - { - m_pushVelocity += linearComponent*impulseMagnitude; - m_turnVelocity += angularComponent*(impulseMagnitude*m_angularFactor); - } + m_linearVelocity += linearComponent*impulseMagnitude; + m_angularVelocity += angularComponent*impulseMagnitude*m_angularFactor; } - void writebackVelocity() { if (m_invMass) { m_originalBody->setLinearVelocity(m_linearVelocity); m_originalBody->setAngularVelocity(m_angularVelocity); - - //m_originalBody->setCompanionId(-1); - } - } - - - void writebackVelocity(btScalar timeStep) - { - if (m_invMass) - { - m_originalBody->setLinearVelocity(m_linearVelocity); - m_originalBody->setAngularVelocity(m_angularVelocity); - - //correct the position/orientation based on push/turn recovery - btTransform newTransform; - btTransformUtil::integrateTransform(m_originalBody->getWorldTransform(),m_pushVelocity,m_turnVelocity,timeStep,newTransform); - m_originalBody->setWorldTransform(newTransform); - - //m_originalBody->setCompanionId(-1); } } @@ -109,5 +69,3 @@ ATTRIBUTE_ALIGNED16 (struct) btSolverBody }; #endif //BT_SOLVER_BODY_H - - diff --git a/extern/bullet2/src/BulletDynamics/ConstraintSolver/btSolverConstraint.h b/extern/bullet2/src/BulletDynamics/ConstraintSolver/btSolverConstraint.h index 2c71360c5b9..f1f40ffdf19 100644 --- a/extern/bullet2/src/BulletDynamics/ConstraintSolver/btSolverConstraint.h +++ b/extern/bullet2/src/BulletDynamics/ConstraintSolver/btSolverConstraint.h @@ -1,3 +1,5 @@ + + /* Bullet Continuous Collision Detection and Physics Library Copyright (c) 2003-2006 Erwin Coumans http://continuousphysics.com/Bullet/ @@ -25,34 +27,24 @@ class btRigidBody; ///1D constraint along a normal axis between bodyA and bodyB. It can be combined to solve contact and friction constraints. ATTRIBUTE_ALIGNED16 (struct) btSolverConstraint { - BT_DECLARE_ALIGNED_ALLOCATOR(); - btVector3 m_relpos1CrossNormal; - btVector3 m_contactNormal; - btVector3 m_relpos2CrossNormal; + btVector3 m_contactNormal; btVector3 m_angularComponentA; - btVector3 m_angularComponentB; - mutable btScalar m_appliedPushImpulse; - - mutable btScalar m_appliedImpulse; + btScalar m_appliedVelocityImpulse; int m_solverBodyIdA; int m_solverBodyIdB; - btScalar m_friction; btScalar m_restitution; btScalar m_jacDiagABInv; btScalar m_penetration; - + btScalar m_appliedImpulse; - int m_constraintType; int m_frictionIndex; - void* m_originalContactPoint; - int m_unusedPadding[1]; - + int m_unusedPadding[2]; enum btSolverConstraintType { @@ -69,4 +61,3 @@ ATTRIBUTE_ALIGNED16 (struct) btSolverConstraint #endif //BT_SOLVER_CONSTRAINT_H - diff --git a/extern/bullet2/src/BulletDynamics/ConstraintSolver/btTypedConstraint.cpp b/extern/bullet2/src/BulletDynamics/ConstraintSolver/btTypedConstraint.cpp index 6e8b552dbbc..a15b3e026cd 100644 --- a/extern/bullet2/src/BulletDynamics/ConstraintSolver/btTypedConstraint.cpp +++ b/extern/bullet2/src/BulletDynamics/ConstraintSolver/btTypedConstraint.cpp @@ -19,20 +19,18 @@ subject to the following restrictions: static btRigidBody s_fixed(0, 0,0); -btTypedConstraint::btTypedConstraint(btTypedConstraintType type) -:m_userConstraintType(-1), +btTypedConstraint::btTypedConstraint() +: m_userConstraintType(-1), m_userConstraintId(-1), -m_constraintType (type), m_rbA(s_fixed), m_rbB(s_fixed), m_appliedImpulse(btScalar(0.)) { s_fixed.setMassProps(btScalar(0.),btVector3(btScalar(0.),btScalar(0.),btScalar(0.))); } -btTypedConstraint::btTypedConstraint(btTypedConstraintType type, btRigidBody& rbA) -:m_userConstraintType(-1), +btTypedConstraint::btTypedConstraint(btRigidBody& rbA) +: m_userConstraintType(-1), m_userConstraintId(-1), -m_constraintType (type), m_rbA(rbA), m_rbB(s_fixed), m_appliedImpulse(btScalar(0.)) @@ -42,10 +40,9 @@ m_appliedImpulse(btScalar(0.)) } -btTypedConstraint::btTypedConstraint(btTypedConstraintType type, btRigidBody& rbA,btRigidBody& rbB) -:m_userConstraintType(-1), +btTypedConstraint::btTypedConstraint(btRigidBody& rbA,btRigidBody& rbB) +: m_userConstraintType(-1), m_userConstraintId(-1), -m_constraintType (type), m_rbA(rbA), m_rbB(rbB), m_appliedImpulse(btScalar(0.)) diff --git a/extern/bullet2/src/BulletDynamics/ConstraintSolver/btTypedConstraint.h b/extern/bullet2/src/BulletDynamics/ConstraintSolver/btTypedConstraint.h index c50ec6ec579..dfee6e80d0e 100644 --- a/extern/bullet2/src/BulletDynamics/ConstraintSolver/btTypedConstraint.h +++ b/extern/bullet2/src/BulletDynamics/ConstraintSolver/btTypedConstraint.h @@ -17,17 +17,7 @@ subject to the following restrictions: #define TYPED_CONSTRAINT_H class btRigidBody; -#include "LinearMath/btScalar.h" - -enum btTypedConstraintType -{ - POINT2POINT_CONSTRAINT_TYPE, - HINGE_CONSTRAINT_TYPE, - CONETWIST_CONSTRAINT_TYPE, - D6_CONSTRAINT_TYPE, - VEHICLE_CONSTRAINT_TYPE, - SLIDER_CONSTRAINT_TYPE -}; +#include "../../LinearMath/btScalar.h" ///TypedConstraint is the baseclass for Bullet constraints and vehicles class btTypedConstraint @@ -35,8 +25,6 @@ class btTypedConstraint int m_userConstraintType; int m_userConstraintId; - btTypedConstraintType m_constraintType; - btTypedConstraint& operator=(btTypedConstraint& other) { btAssert(0); @@ -52,11 +40,11 @@ protected: public: - btTypedConstraint(btTypedConstraintType type); + btTypedConstraint(); virtual ~btTypedConstraint() {}; - btTypedConstraint(btTypedConstraintType type, btRigidBody& rbA); + btTypedConstraint(btRigidBody& rbA); - btTypedConstraint(btTypedConstraintType type, btRigidBody& rbA,btRigidBody& rbB); + btTypedConstraint(btRigidBody& rbA,btRigidBody& rbB); virtual void buildJacobian() = 0; @@ -71,7 +59,7 @@ public: return m_rbB; } - btRigidBody& getRigidBodyA() + btRigidBody& getRigidBodyA() { return m_rbA; } @@ -95,26 +83,14 @@ public: m_userConstraintId = uid; } - int getUserConstraintId() const + int getUserConstraintId() { return m_userConstraintId; } - - int getUid() const - { - return m_userConstraintId; - } - - btScalar getAppliedImpulse() const + btScalar getAppliedImpulse() { return m_appliedImpulse; } - - btTypedConstraintType getConstraintType () const - { - return m_constraintType; - } - }; #endif //TYPED_CONSTRAINT_H diff --git a/extern/bullet2/src/BulletDynamics/Dynamics/Bullet-C-API.cpp b/extern/bullet2/src/BulletDynamics/Dynamics/Bullet-C-API.cpp index b28a46e299e..248c582dcd8 100644 --- a/extern/bullet2/src/BulletDynamics/Dynamics/Bullet-C-API.cpp +++ b/extern/bullet2/src/BulletDynamics/Dynamics/Bullet-C-API.cpp @@ -24,287 +24,97 @@ subject to the following restrictions: #include "btBulletDynamicsCommon.h" #include "LinearMath/btAlignedAllocator.h" -/* - Create and Delete a Physics SDK -*/ -struct btPhysicsSdk +#include "LinearMath/btVector3.h" +#include "LinearMath/btScalar.h" +#include "LinearMath/btMatrix3x3.h" +#include "LinearMath/btTransform.h" +#include "BulletCollision/NarrowPhaseCollision/btVoronoiSimplexSolver.h" +#include "BulletCollision/CollisionShapes/btTriangleShape.h" + +#include "BulletCollision/NarrowPhaseCollision/btGjkPairDetector.h" +#include "BulletCollision/NarrowPhaseCollision/btPointCollector.h" +#include "BulletCollision/NarrowPhaseCollision/btVoronoiSimplexSolver.h" +#include "BulletCollision/NarrowPhaseCollision/btSubSimplexConvexCast.h" +#include "BulletCollision/NarrowPhaseCollision/btGjkEpaPenetrationDepthSolver.h" +#include "BulletCollision/NarrowPhaseCollision/btGjkEpa.h" +#include "BulletCollision/CollisionShapes/btMinkowskiSumShape.h" +#include "BulletCollision/NarrowPhaseCollision/btSubSimplexConvexCast.h" +#include "BulletCollision/NarrowPhaseCollision/btVoronoiSimplexSolver.h" +#include "BulletCollision/NarrowPhaseCollision/btGjkPairDetector.h" + +#include "BulletCollision/NarrowPhaseCollision/btDiscreteCollisionDetectorInterface.h" +#include "BulletCollision/NarrowPhaseCollision/btSimplexSolverInterface.h" +#include "BulletCollision/NarrowPhaseCollision/btMinkowskiPenetrationDepthSolver.h" +#include "BulletCollision/NarrowPhaseCollision/btGjkPairDetector.h" +#include "BulletCollision/NarrowPhaseCollision/btGjkEpaPenetrationDepthSolver.h" +#include "LinearMath/btStackAlloc.h" + +extern "C" +double plNearestPoints(float p1[3], float p2[3], float p3[3], float q1[3], float q2[3], float q3[3], float *pa, float *pb, float normal[3]) { - -// btDispatcher* m_dispatcher; -// btOverlappingPairCache* m_pairCache; -// btConstraintSolver* m_constraintSolver - - btVector3 m_worldAabbMin; - btVector3 m_worldAabbMax; - - - //todo: version, hardware/optimization settings etc? - btPhysicsSdk() - :m_worldAabbMin(-1000,-1000,-1000), - m_worldAabbMax(1000,1000,1000) + btVector3 vp(p1[0], p1[1], p1[2]); + btTriangleShape trishapeA(vp, + btVector3(p2[0], p2[1], p2[2]), + btVector3(p3[0], p3[1], p3[2])); + trishapeA.setMargin(0.000001f); + btVector3 vq(q1[0], q1[1], q1[2]); + btTriangleShape trishapeB(vq, + btVector3(q2[0], q2[1], q2[2]), + btVector3(q3[0], q3[1], q3[2])); + trishapeB.setMargin(0.000001f); + + // btVoronoiSimplexSolver sGjkSimplexSolver; + // btGjkEpaPenetrationDepthSolver penSolverPtr; + + static btSimplexSolverInterface sGjkSimplexSolver; + sGjkSimplexSolver.reset(); + + static btGjkEpaPenetrationDepthSolver Solver0; + static btMinkowskiPenetrationDepthSolver Solver1; + + btConvexPenetrationDepthSolver* Solver = NULL; + + Solver = &Solver1; + + btGjkPairDetector convexConvex(&trishapeA ,&trishapeB,&sGjkSimplexSolver,Solver); + + convexConvex.m_catchDegeneracies = 1; + + // btGjkPairDetector convexConvex(&trishapeA ,&trishapeB,&sGjkSimplexSolver,0); + + btPointCollector gjkOutput; + btGjkPairDetector::ClosestPointInput input; + + btStackAlloc gStackAlloc(1024*1024*2); + + input.m_stackAlloc = &gStackAlloc; + + btTransform tr; + tr.setIdentity(); + + input.m_transformA = tr; + input.m_transformB = tr; + + convexConvex.getClosestPoints(input, gjkOutput, 0); + + + if (gjkOutput.m_hasResult) { + + pb[0] = pa[0] = gjkOutput.m_pointInWorld[0]; + pb[1] = pa[1] = gjkOutput.m_pointInWorld[1]; + pb[2] = pa[2] = gjkOutput.m_pointInWorld[2]; + pb[0]+= gjkOutput.m_normalOnBInWorld[0] * gjkOutput.m_distance; + pb[1]+= gjkOutput.m_normalOnBInWorld[1] * gjkOutput.m_distance; + pb[2]+= gjkOutput.m_normalOnBInWorld[2] * gjkOutput.m_distance; + + normal[0] = gjkOutput.m_normalOnBInWorld[0]; + normal[1] = gjkOutput.m_normalOnBInWorld[1]; + normal[2] = gjkOutput.m_normalOnBInWorld[2]; + + return gjkOutput.m_distance; } - - -}; - -plPhysicsSdkHandle plNewBulletSdk() -{ - void* mem = btAlignedAlloc(sizeof(btPhysicsSdk),16); - return (plPhysicsSdkHandle)new (mem)btPhysicsSdk; + return -1.0f; } - -void plDeletePhysicsSdk(plPhysicsSdkHandle physicsSdk) -{ - btPhysicsSdk* phys = reinterpret_cast(physicsSdk); - btAlignedFree(phys); -} - - -/* Dynamics World */ -plDynamicsWorldHandle plCreateDynamicsWorld(plPhysicsSdkHandle physicsSdkHandle) -{ - btPhysicsSdk* physicsSdk = reinterpret_cast(physicsSdkHandle); - void* mem = btAlignedAlloc(sizeof(btDefaultCollisionConfiguration),16); - btDefaultCollisionConfiguration* collisionConfiguration = new (mem)btDefaultCollisionConfiguration(); - mem = btAlignedAlloc(sizeof(btCollisionDispatcher),16); - btDispatcher* dispatcher = new (mem)btCollisionDispatcher(collisionConfiguration); - mem = btAlignedAlloc(sizeof(btAxisSweep3),16); - btBroadphaseInterface* pairCache = new (mem)btAxisSweep3(physicsSdk->m_worldAabbMin,physicsSdk->m_worldAabbMax); - mem = btAlignedAlloc(sizeof(btSequentialImpulseConstraintSolver),16); - btConstraintSolver* constraintSolver = new(mem) btSequentialImpulseConstraintSolver(); - - mem = btAlignedAlloc(sizeof(btDiscreteDynamicsWorld),16); - return (plDynamicsWorldHandle) new (mem)btDiscreteDynamicsWorld(dispatcher,pairCache,constraintSolver,collisionConfiguration); -} -void plDeleteDynamicsWorld(plDynamicsWorldHandle world) -{ - //todo: also clean up the other allocations, axisSweep, pairCache,dispatcher,constraintSolver,collisionConfiguration - btDynamicsWorld* dynamicsWorld = reinterpret_cast< btDynamicsWorld* >(world); - btAlignedFree(dynamicsWorld); -} - -void plStepSimulation(plDynamicsWorldHandle world, plReal timeStep) -{ - btDynamicsWorld* dynamicsWorld = reinterpret_cast< btDynamicsWorld* >(world); - assert(dynamicsWorld); - dynamicsWorld->stepSimulation(timeStep); -} - -void plAddRigidBody(plDynamicsWorldHandle world, plRigidBodyHandle object) -{ - btDynamicsWorld* dynamicsWorld = reinterpret_cast< btDynamicsWorld* >(world); - assert(dynamicsWorld); - btRigidBody* body = reinterpret_cast< btRigidBody* >(object); - assert(body); - - dynamicsWorld->addRigidBody(body); -} - -void plRemoveRigidBody(plDynamicsWorldHandle world, plRigidBodyHandle object) -{ - btDynamicsWorld* dynamicsWorld = reinterpret_cast< btDynamicsWorld* >(world); - assert(dynamicsWorld); - btRigidBody* body = reinterpret_cast< btRigidBody* >(object); - assert(body); - - dynamicsWorld->removeRigidBody(body); -} - -/* Rigid Body */ - -plRigidBodyHandle plCreateRigidBody( void* user_data, float mass, plCollisionShapeHandle cshape ) -{ - btTransform trans; - trans.setIdentity(); - btVector3 localInertia(0,0,0); - btCollisionShape* shape = reinterpret_cast( cshape); - assert(shape); - if (mass) - { - shape->calculateLocalInertia(mass,localInertia); - } - void* mem = btAlignedAlloc(sizeof(btRigidBody),16); - btRigidBody::btRigidBodyConstructionInfo rbci(mass, 0,shape,localInertia); - btRigidBody* body = new (mem)btRigidBody(rbci); - body->setWorldTransform(trans); - body->setUserPointer(user_data); - return (plRigidBodyHandle) body; -} - -void plDeleteRigidBody(plRigidBodyHandle cbody) -{ - btRigidBody* body = reinterpret_cast< btRigidBody* >(cbody); - assert(body); - btAlignedFree( body); -} - - -/* Collision Shape definition */ - -plCollisionShapeHandle plNewSphereShape(plReal radius) -{ - void* mem = btAlignedAlloc(sizeof(btSphereShape),16); - return (plCollisionShapeHandle) new (mem)btSphereShape(radius); - -} - -plCollisionShapeHandle plNewBoxShape(plReal x, plReal y, plReal z) -{ - void* mem = btAlignedAlloc(sizeof(btBoxShape),16); - return (plCollisionShapeHandle) new (mem)btBoxShape(btVector3(x,y,z)); -} - -plCollisionShapeHandle plNewCapsuleShape(plReal radius, plReal height) -{ - //capsule is convex hull of 2 spheres, so use btMultiSphereShape - btVector3 inertiaHalfExtents(radius,height,radius); - const int numSpheres = 2; - btVector3 positions[numSpheres] = {btVector3(0,height,0),btVector3(0,-height,0)}; - btScalar radi[numSpheres] = {radius,radius}; - void* mem = btAlignedAlloc(sizeof(btMultiSphereShape),16); - return (plCollisionShapeHandle) new (mem)btMultiSphereShape(inertiaHalfExtents,positions,radi,numSpheres); -} -plCollisionShapeHandle plNewConeShape(plReal radius, plReal height) -{ - void* mem = btAlignedAlloc(sizeof(btConeShape),16); - return (plCollisionShapeHandle) new (mem)btConeShape(radius,height); -} - -plCollisionShapeHandle plNewCylinderShape(plReal radius, plReal height) -{ - void* mem = btAlignedAlloc(sizeof(btCylinderShape),16); - return (plCollisionShapeHandle) new (mem)btCylinderShape(btVector3(radius,height,radius)); -} - -/* Convex Meshes */ -plCollisionShapeHandle plNewConvexHullShape() -{ - void* mem = btAlignedAlloc(sizeof(btConvexHullShape),16); - return (plCollisionShapeHandle) new (mem)btConvexHullShape(); -} - - -/* Concave static triangle meshes */ -plMeshInterfaceHandle plNewMeshInterface() -{ - return 0; -} - -plCollisionShapeHandle plNewCompoundShape() -{ - void* mem = btAlignedAlloc(sizeof(btCompoundShape),16); - return (plCollisionShapeHandle) new (mem)btCompoundShape(); -} - -void plAddChildShape(plCollisionShapeHandle compoundShapeHandle,plCollisionShapeHandle childShapeHandle, plVector3 childPos,plQuaternion childOrn) -{ - btCollisionShape* colShape = reinterpret_cast(compoundShapeHandle); - btAssert(colShape->getShapeType() == COMPOUND_SHAPE_PROXYTYPE); - btCompoundShape* compoundShape = reinterpret_cast(colShape); - btCollisionShape* childShape = reinterpret_cast(childShapeHandle); - btTransform localTrans; - localTrans.setIdentity(); - localTrans.setOrigin(btVector3(childPos[0],childPos[1],childPos[2])); - localTrans.setRotation(btQuaternion(childOrn[0],childOrn[1],childOrn[2],childOrn[3])); - compoundShape->addChildShape(localTrans,childShape); -} - -void plSetEuler(plReal yaw,plReal pitch,plReal roll, plQuaternion orient) -{ - btQuaternion orn; - orn.setEuler(yaw,pitch,roll); - orient[0] = orn.getX(); - orient[1] = orn.getY(); - orient[2] = orn.getZ(); - orient[3] = orn.getW(); - -} - - -// extern void plAddTriangle(plMeshInterfaceHandle meshHandle, plVector3 v0,plVector3 v1,plVector3 v2); -// extern plCollisionShapeHandle plNewStaticTriangleMeshShape(plMeshInterfaceHandle); - - -void plAddVertex(plCollisionShapeHandle cshape, plReal x,plReal y,plReal z) -{ - btCollisionShape* colShape = reinterpret_cast( cshape); - (void)colShape; - btAssert(colShape->getShapeType()==CONVEX_HULL_SHAPE_PROXYTYPE); - btConvexHullShape* convexHullShape = reinterpret_cast( cshape); - convexHullShape->addPoint(btPoint3(x,y,z)); - -} - -void plDeleteShape(plCollisionShapeHandle cshape) -{ - btCollisionShape* shape = reinterpret_cast( cshape); - assert(shape); - btAlignedFree(shape); -} -void plSetScaling(plCollisionShapeHandle cshape, plVector3 cscaling) -{ - btCollisionShape* shape = reinterpret_cast( cshape); - assert(shape); - btVector3 scaling(cscaling[0],cscaling[1],cscaling[2]); - shape->setLocalScaling(scaling); -} - - - -void plSetPosition(plRigidBodyHandle object, const plVector3 position) -{ - btRigidBody* body = reinterpret_cast< btRigidBody* >(object); - btAssert(body); - btVector3 pos(position[0],position[1],position[2]); - btTransform worldTrans = body->getWorldTransform(); - worldTrans.setOrigin(pos); - body->setWorldTransform(worldTrans); -} - -void plSetOrientation(plRigidBodyHandle object, const plQuaternion orientation) -{ - btRigidBody* body = reinterpret_cast< btRigidBody* >(object); - btAssert(body); - btQuaternion orn(orientation[0],orientation[1],orientation[2],orientation[3]); - btTransform worldTrans = body->getWorldTransform(); - worldTrans.setRotation(orn); - body->setWorldTransform(worldTrans); -} - -void plGetOpenGLMatrix(plRigidBodyHandle object, plReal* matrix) -{ - btRigidBody* body = reinterpret_cast< btRigidBody* >(object); - btAssert(body); - body->getWorldTransform().getOpenGLMatrix(matrix); - -} - -void plGetPosition(plRigidBodyHandle object,plVector3 position) -{ - btRigidBody* body = reinterpret_cast< btRigidBody* >(object); - btAssert(body); - const btVector3& pos = body->getWorldTransform().getOrigin(); - position[0] = pos.getX(); - position[1] = pos.getY(); - position[2] = pos.getZ(); -} - -void plGetOrientation(plRigidBodyHandle object,plQuaternion orientation) -{ - btRigidBody* body = reinterpret_cast< btRigidBody* >(object); - btAssert(body); - const btQuaternion& orn = body->getWorldTransform().getRotation(); - orientation[0] = orn.getX(); - orientation[1] = orn.getY(); - orientation[2] = orn.getZ(); - orientation[3] = orn.getW(); -} - - - -//plRigidBodyHandle plRayCast(plDynamicsWorldHandle world, const plVector3 rayStart, const plVector3 rayEnd, plVector3 hitpoint, plVector3 normal); - -// extern plRigidBodyHandle plObjectCast(plDynamicsWorldHandle world, const plVector3 rayStart, const plVector3 rayEnd, plVector3 hitpoint, plVector3 normal); diff --git a/extern/bullet2/src/BulletDynamics/Dynamics/btContinuousDynamicsWorld.cpp b/extern/bullet2/src/BulletDynamics/Dynamics/btContinuousDynamicsWorld.cpp deleted file mode 100644 index 19443adc723..00000000000 --- a/extern/bullet2/src/BulletDynamics/Dynamics/btContinuousDynamicsWorld.cpp +++ /dev/null @@ -1,193 +0,0 @@ -/* -Bullet Continuous Collision Detection and Physics Library -Copyright (c) 2003-2007 Erwin Coumans http://continuousphysics.com/Bullet/ - -This software is provided 'as-is', without any express or implied warranty. -In no event will the authors be held liable for any damages arising from the use of this software. -Permission is granted to anyone to use this software for any purpose, -including commercial applications, and to alter it and redistribute it freely, -subject to the following restrictions: - -1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. -2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. -3. This notice may not be removed or altered from any source distribution. -*/ - - -#include "btContinuousDynamicsWorld.h" -#include "LinearMath/btQuickprof.h" - -//collision detection -#include "BulletCollision/CollisionDispatch/btCollisionDispatcher.h" -#include "BulletCollision/BroadphaseCollision/btSimpleBroadphase.h" -#include "BulletCollision/CollisionShapes/btCollisionShape.h" -#include "BulletCollision/CollisionDispatch/btSimulationIslandManager.h" - -//rigidbody & constraints -#include "BulletDynamics/Dynamics/btRigidBody.h" -#include "BulletDynamics/ConstraintSolver/btSequentialImpulseConstraintSolver.h" -#include "BulletDynamics/ConstraintSolver/btContactSolverInfo.h" -#include "BulletDynamics/ConstraintSolver/btTypedConstraint.h" - - - -#include - -btContinuousDynamicsWorld::btContinuousDynamicsWorld(btDispatcher* dispatcher,btBroadphaseInterface* pairCache,btConstraintSolver* constraintSolver,btCollisionConfiguration* collisionConfiguration) -:btDiscreteDynamicsWorld(dispatcher,pairCache,constraintSolver,collisionConfiguration) -{ -} - -btContinuousDynamicsWorld::~btContinuousDynamicsWorld() -{ -} - - -void btContinuousDynamicsWorld::internalSingleStepSimulation( btScalar timeStep) -{ - - startProfiling(timeStep); - - - ///update aabbs information - updateAabbs(); - //static int frame=0; -// printf("frame %d\n",frame++); - - ///apply gravity, predict motion - predictUnconstraintMotion(timeStep); - - btDispatcherInfo& dispatchInfo = getDispatchInfo(); - - dispatchInfo.m_timeStep = timeStep; - dispatchInfo.m_stepCount = 0; - dispatchInfo.m_debugDraw = getDebugDrawer(); - - ///perform collision detection - performDiscreteCollisionDetection(); - - calculateSimulationIslands(); - - - getSolverInfo().m_timeStep = timeStep; - - - - ///solve contact and other joint constraints - solveConstraints(getSolverInfo()); - - ///CallbackTriggers(); - calculateTimeOfImpacts(timeStep); - - btScalar toi = dispatchInfo.m_timeOfImpact; -// if (toi < 1.f) -// printf("toi = %f\n",toi); - if (toi < 0.f) - printf("toi = %f\n",toi); - - - ///integrate transforms - integrateTransforms(timeStep * toi); - - ///update vehicle simulation - updateVehicles(timeStep); - - - updateActivationState( timeStep ); - - if(0 != m_internalTickCallback) { - (*m_internalTickCallback)(this, timeStep); - } -} - -void btContinuousDynamicsWorld::calculateTimeOfImpacts(btScalar timeStep) -{ - ///these should be 'temporal' aabbs! - updateTemporalAabbs(timeStep); - - ///'toi' is the global smallest time of impact. However, we just calculate the time of impact for each object individually. - ///so we handle the case moving versus static properly, and we cheat for moving versus moving - btScalar toi = 1.f; - - - btDispatcherInfo& dispatchInfo = getDispatchInfo(); - dispatchInfo.m_timeStep = timeStep; - dispatchInfo.m_timeOfImpact = 1.f; - dispatchInfo.m_stepCount = 0; - dispatchInfo.m_dispatchFunc = btDispatcherInfo::DISPATCH_CONTINUOUS; - - ///calculate time of impact for overlapping pairs - - - btDispatcher* dispatcher = getDispatcher(); - if (dispatcher) - dispatcher->dispatchAllCollisionPairs(m_broadphasePairCache->getOverlappingPairCache(),dispatchInfo,m_dispatcher1); - - toi = dispatchInfo.m_timeOfImpact; - - dispatchInfo.m_dispatchFunc = btDispatcherInfo::DISPATCH_DISCRETE; - -} - -void btContinuousDynamicsWorld::updateTemporalAabbs(btScalar timeStep) -{ - - btVector3 temporalAabbMin,temporalAabbMax; - - for ( int i=0;igetCollisionShape()->getAabb(m_collisionObjects[i]->getWorldTransform(),temporalAabbMin,temporalAabbMax); - const btVector3& linvel = body->getLinearVelocity(); - - //make the AABB temporal - btScalar temporalAabbMaxx = temporalAabbMax.getX(); - btScalar temporalAabbMaxy = temporalAabbMax.getY(); - btScalar temporalAabbMaxz = temporalAabbMax.getZ(); - btScalar temporalAabbMinx = temporalAabbMin.getX(); - btScalar temporalAabbMiny = temporalAabbMin.getY(); - btScalar temporalAabbMinz = temporalAabbMin.getZ(); - - // add linear motion - btVector3 linMotion = linvel*timeStep; - - if (linMotion.x() > 0.f) - temporalAabbMaxx += linMotion.x(); - else - temporalAabbMinx += linMotion.x(); - if (linMotion.y() > 0.f) - temporalAabbMaxy += linMotion.y(); - else - temporalAabbMiny += linMotion.y(); - if (linMotion.z() > 0.f) - temporalAabbMaxz += linMotion.z(); - else - temporalAabbMinz += linMotion.z(); - - //add conservative angular motion - btScalar angularMotion(0);// = angvel.length() * GetAngularMotionDisc() * timeStep; - btVector3 angularMotion3d(angularMotion,angularMotion,angularMotion); - temporalAabbMin = btVector3(temporalAabbMinx,temporalAabbMiny,temporalAabbMinz); - temporalAabbMax = btVector3(temporalAabbMaxx,temporalAabbMaxy,temporalAabbMaxz); - - temporalAabbMin -= angularMotion3d; - temporalAabbMax += angularMotion3d; - - m_broadphasePairCache->setAabb(body->getBroadphaseHandle(),temporalAabbMin,temporalAabbMax,m_dispatcher1); - } - } - - //update aabb (of all moved objects) - - m_broadphasePairCache->calculateOverlappingPairs(m_dispatcher1); - - - -} - - - diff --git a/extern/bullet2/src/BulletDynamics/Dynamics/btContinuousDynamicsWorld.h b/extern/bullet2/src/BulletDynamics/Dynamics/btContinuousDynamicsWorld.h deleted file mode 100644 index 61c8dea03eb..00000000000 --- a/extern/bullet2/src/BulletDynamics/Dynamics/btContinuousDynamicsWorld.h +++ /dev/null @@ -1,46 +0,0 @@ -/* -Bullet Continuous Collision Detection and Physics Library -Copyright (c) 2003-2007 Erwin Coumans http://continuousphysics.com/Bullet/ - -This software is provided 'as-is', without any express or implied warranty. -In no event will the authors be held liable for any damages arising from the use of this software. -Permission is granted to anyone to use this software for any purpose, -including commercial applications, and to alter it and redistribute it freely, -subject to the following restrictions: - -1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. -2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. -3. This notice may not be removed or altered from any source distribution. -*/ - -#ifndef BT_CONTINUOUS_DYNAMICS_WORLD_H -#define BT_CONTINUOUS_DYNAMICS_WORLD_H - -#include "btDiscreteDynamicsWorld.h" - -///btContinuousDynamicsWorld adds optional (per object) continuous collision detection for fast moving objects to the btDiscreteDynamicsWorld. -///This copes with fast moving objects that otherwise would tunnel/miss collisions. -///Under construction, don't use yet! Please use btDiscreteDynamicsWorld instead. -class btContinuousDynamicsWorld : public btDiscreteDynamicsWorld -{ - - void updateTemporalAabbs(btScalar timeStep); - - public: - - btContinuousDynamicsWorld(btDispatcher* dispatcher,btBroadphaseInterface* pairCache,btConstraintSolver* constraintSolver,btCollisionConfiguration* collisionConfiguration); - virtual ~btContinuousDynamicsWorld(); - - ///time stepping with calculation of time of impact for selected fast moving objects - virtual void internalSingleStepSimulation( btScalar timeStep); - - virtual void calculateTimeOfImpacts(btScalar timeStep); - - virtual btDynamicsWorldType getWorldType() const - { - return BT_CONTINUOUS_DYNAMICS_WORLD; - } - -}; - -#endif //BT_CONTINUOUS_DYNAMICS_WORLD_H diff --git a/extern/bullet2/src/BulletDynamics/Dynamics/btDiscreteDynamicsWorld.cpp b/extern/bullet2/src/BulletDynamics/Dynamics/btDiscreteDynamicsWorld.cpp index c7b1af245e9..1017c8af6ea 100644 --- a/extern/bullet2/src/BulletDynamics/Dynamics/btDiscreteDynamicsWorld.cpp +++ b/extern/bullet2/src/BulletDynamics/Dynamics/btDiscreteDynamicsWorld.cpp @@ -21,8 +21,7 @@ subject to the following restrictions: #include "BulletCollision/BroadphaseCollision/btSimpleBroadphase.h" #include "BulletCollision/CollisionShapes/btCollisionShape.h" #include "BulletCollision/CollisionDispatch/btSimulationIslandManager.h" -#include "LinearMath/btTransformUtil.h" -#include "LinearMath/btQuickprof.h" +#include //rigidbody & constraints #include "BulletDynamics/Dynamics/btRigidBody.h" @@ -42,7 +41,6 @@ subject to the following restrictions: #include "BulletCollision/CollisionShapes/btSphereShape.h" #include "BulletCollision/CollisionShapes/btTriangleCallback.h" #include "BulletCollision/CollisionShapes/btTriangleMeshShape.h" -#include "BulletCollision/CollisionShapes/btStaticPlaneShape.h" #include "LinearMath/btIDebugDraw.h" @@ -59,29 +57,17 @@ subject to the following restrictions: -btDiscreteDynamicsWorld::btDiscreteDynamicsWorld(btDispatcher* dispatcher,btBroadphaseInterface* pairCache,btConstraintSolver* constraintSolver, btCollisionConfiguration* collisionConfiguration) -:btDynamicsWorld(dispatcher,pairCache,collisionConfiguration), -m_constraintSolver(constraintSolver), +btDiscreteDynamicsWorld::btDiscreteDynamicsWorld(btDispatcher* dispatcher,btOverlappingPairCache* pairCache,btConstraintSolver* constraintSolver) +:btDynamicsWorld(dispatcher,pairCache), +m_constraintSolver(constraintSolver? constraintSolver: new btSequentialImpulseConstraintSolver), +m_debugDrawer(0), m_gravity(0,-10,0), m_localTime(btScalar(1.)/btScalar(60.)), m_profileTimings(0) { - if (!m_constraintSolver) - { - void* mem = btAlignedAlloc(sizeof(btSequentialImpulseConstraintSolver),16); - m_constraintSolver = new (mem) btSequentialImpulseConstraintSolver; - m_ownsConstraintSolver = true; - } else - { - m_ownsConstraintSolver = false; - } - - { - void* mem = btAlignedAlloc(sizeof(btSimulationIslandManager),16); - m_islandManager = new (mem) btSimulationIslandManager(); - } - + m_islandManager = new btSimulationIslandManager(); m_ownsIslandManager = true; + m_ownsConstraintSolver = (constraintSolver==0); } @@ -89,16 +75,9 @@ btDiscreteDynamicsWorld::~btDiscreteDynamicsWorld() { //only delete it when we created it if (m_ownsIslandManager) - { - m_islandManager->~btSimulationIslandManager(); - btAlignedFree( m_islandManager); - } + delete m_islandManager; if (m_ownsConstraintSolver) - { - - m_constraintSolver->~btConstraintSolver(); - btAlignedFree(m_constraintSolver); - } + delete m_constraintSolver; } void btDiscreteDynamicsWorld::saveKinematicState(btScalar timeStep) @@ -123,35 +102,14 @@ void btDiscreteDynamicsWorld::saveKinematicState(btScalar timeStep) } } -void btDiscreteDynamicsWorld::debugDrawWorld() +void btDiscreteDynamicsWorld::synchronizeMotionStates() { - - if (getDebugDrawer() && getDebugDrawer()->getDebugMode() & btIDebugDraw::DBG_DrawContactPoints) + //debug vehicle wheels + + { - int numManifolds = getDispatcher()->getNumManifolds(); - btVector3 color(0,0,0); - for (int i=0;igetManifoldByIndexInternal(i); - //btCollisionObject* obA = static_cast(contactManifold->getBody0()); - //btCollisionObject* obB = static_cast(contactManifold->getBody1()); - - int numContacts = contactManifold->getNumContacts(); - for (int j=0;jgetContactPoint(j); - getDebugDrawer()->drawContactPoint(cp.m_positionWorldOnB,cp.m_normalWorldOnB,cp.getDistance(),cp.getLifeTime(),color); - } - } - } - - - if (getDebugDrawer() && getDebugDrawer()->getDebugMode() & (btIDebugDraw::DBG_DrawWireframe | btIDebugDraw::DBG_DrawAabb)) - { - int i; - //todo: iterate over awake simulation islands! - for ( i=0;igetDebugMode() & btIDebugDraw::DBG_DrawWireframe) @@ -177,88 +135,6 @@ void btDiscreteDynamicsWorld::debugDrawWorld() debugDrawObject(colObj->getWorldTransform(),colObj->getCollisionShape(),color); } - if (m_debugDrawer && (m_debugDrawer->getDebugMode() & btIDebugDraw::DBG_DrawAabb)) - { - btPoint3 minAabb,maxAabb; - btVector3 colorvec(1,0,0); - colObj->getCollisionShape()->getAabb(colObj->getWorldTransform(), minAabb,maxAabb); - m_debugDrawer->drawAabb(minAabb,maxAabb,colorvec); - } - - } - - for ( i=0;im_vehicles.size();i++) - { - for (int v=0;vgetNumWheels();v++) - { - btVector3 wheelColor(0,255,255); - if (m_vehicles[i]->getWheelInfo(v).m_raycastInfo.m_isInContact) - { - wheelColor.setValue(0,0,255); - } else - { - wheelColor.setValue(255,0,255); - } - - btVector3 wheelPosWS = m_vehicles[i]->getWheelInfo(v).m_worldTransform.getOrigin(); - - btVector3 axle = btVector3( - m_vehicles[i]->getWheelInfo(v).m_worldTransform.getBasis()[0][m_vehicles[i]->getRightAxis()], - m_vehicles[i]->getWheelInfo(v).m_worldTransform.getBasis()[1][m_vehicles[i]->getRightAxis()], - m_vehicles[i]->getWheelInfo(v).m_worldTransform.getBasis()[2][m_vehicles[i]->getRightAxis()]); - - - //m_vehicles[i]->getWheelInfo(v).m_raycastInfo.m_wheelAxleWS - //debug wheels (cylinders) - m_debugDrawer->drawLine(wheelPosWS,wheelPosWS+axle,wheelColor); - m_debugDrawer->drawLine(wheelPosWS,m_vehicles[i]->getWheelInfo(v).m_raycastInfo.m_contactPointWS,wheelColor); - - } - } - } -} - -void btDiscreteDynamicsWorld::clearForces() -{ - //todo: iterate over awake simulation islands! - for ( int i=0;iclearForces(); - } - } -} - -///apply gravity, call this once per timestep -void btDiscreteDynamicsWorld::applyGravity() -{ - //todo: iterate over awake simulation islands! - for ( int i=0;iisActive()) - { - body->applyGravity(); - } - } -} - - - -void btDiscreteDynamicsWorld::synchronizeMotionStates() -{ - { - //todo: iterate over awake simulation islands! - for ( int i=0;igetMotionState() && !body->isStaticOrKinematicObject()) { @@ -282,8 +158,31 @@ void btDiscreteDynamicsWorld::synchronizeMotionStates() { for (int v=0;vgetNumWheels();v++) { + btVector3 wheelColor(0,255,255); + if (m_vehicles[i]->getWheelInfo(v).m_raycastInfo.m_isInContact) + { + wheelColor.setValue(0,0,255); + } else + { + wheelColor.setValue(255,0,255); + } + //synchronize the wheels with the (interpolated) chassis worldtransform m_vehicles[i]->updateWheelTransform(v,true); + + btVector3 wheelPosWS = m_vehicles[i]->getWheelInfo(v).m_worldTransform.getOrigin(); + + btVector3 axle = btVector3( + m_vehicles[i]->getWheelInfo(v).m_worldTransform.getBasis()[0][m_vehicles[i]->getRightAxis()], + m_vehicles[i]->getWheelInfo(v).m_worldTransform.getBasis()[1][m_vehicles[i]->getRightAxis()], + m_vehicles[i]->getWheelInfo(v).m_worldTransform.getBasis()[2][m_vehicles[i]->getRightAxis()]); + + + //m_vehicles[i]->getWheelInfo(v).m_raycastInfo.m_wheelAxleWS + //debug wheels (cylinders) + m_debugDrawer->drawLine(wheelPosWS,wheelPosWS+axle,wheelColor); + m_debugDrawer->drawLine(wheelPosWS,m_vehicles[i]->getWheelInfo(v).m_raycastInfo.m_contactPointWS,wheelColor); + } } } @@ -293,10 +192,6 @@ void btDiscreteDynamicsWorld::synchronizeMotionStates() int btDiscreteDynamicsWorld::stepSimulation( btScalar timeStep,int maxSubSteps, btScalar fixedTimeStep) { - startProfiling(timeStep); - - BT_PROFILE("stepSimulation"); - int numSimulationSubSteps = 0; if (maxSubSteps) @@ -334,8 +229,6 @@ int btDiscreteDynamicsWorld::stepSimulation( btScalar timeStep,int maxSubSteps, saveKinematicState(fixedTimeStep); - applyGravity(); - //clamp the number of substeps, to prevent simulation grinding spiralling down to a halt int clampedSimulationSteps = (numSimulationSubSteps > maxSubSteps)? maxSubSteps : numSimulationSubSteps; @@ -349,19 +242,16 @@ int btDiscreteDynamicsWorld::stepSimulation( btScalar timeStep,int maxSubSteps, synchronizeMotionStates(); - clearForces(); - -#ifndef BT_NO_PROFILE - CProfileManager::Increment_Frame_Counter(); -#endif //BT_NO_PROFILE - return numSimulationSubSteps; } void btDiscreteDynamicsWorld::internalSingleStepSimulation(btScalar timeStep) { - BT_PROFILE("internalSingleStepSimulation"); + startProfiling(timeStep); + + ///update aabbs information + updateAabbs(); ///apply gravity, predict motion predictUnconstraintMotion(timeStep); @@ -396,9 +286,8 @@ void btDiscreteDynamicsWorld::internalSingleStepSimulation(btScalar timeStep) updateActivationState( timeStep ); - if(0 != m_internalTickCallback) { - (*m_internalTickCallback)(this, timeStep); - } + + } void btDiscreteDynamicsWorld::setGravity(const btVector3& gravity) @@ -415,11 +304,6 @@ void btDiscreteDynamicsWorld::setGravity(const btVector3& gravity) } } -btVector3 btDiscreteDynamicsWorld::getGravity () const -{ - return m_gravity; -} - void btDiscreteDynamicsWorld::removeRigidBody(btRigidBody* body) { @@ -459,18 +343,19 @@ void btDiscreteDynamicsWorld::addRigidBody(btRigidBody* body, short group, short void btDiscreteDynamicsWorld::updateVehicles(btScalar timeStep) { - BT_PROFILE("updateVehicles"); - + BEGIN_PROFILE("updateVehicles"); + for ( int i=0;iupdateVehicle( timeStep); } + END_PROFILE("updateVehicles"); } void btDiscreteDynamicsWorld::updateActivationState(btScalar timeStep) { - BT_PROFILE("updateActivationState"); + BEGIN_PROFILE("updateActivationState"); for ( int i=0;igetActivationState() == ACTIVE_TAG) body->setActivationState( WANTS_DEACTIVATION ); - if (body->getActivationState() == ISLAND_SLEEPING) - { - body->setAngularVelocity(btVector3(0,0,0)); - body->setLinearVelocity(btVector3(0,0,0)); - } - } } else { @@ -503,6 +382,7 @@ void btDiscreteDynamicsWorld::updateActivationState(btScalar timeStep) } } } + END_PROFILE("updateActivationState"); } void btDiscreteDynamicsWorld::addConstraint(btTypedConstraint* constraint,bool disableCollisionsBetweenLinkedBodies) @@ -532,7 +412,7 @@ void btDiscreteDynamicsWorld::removeVehicle(btRaycastVehicle* vehicle) m_vehicles.remove(vehicle); } -SIMD_FORCE_INLINE int btGetConstraintIslandId(const btTypedConstraint* lhs) +inline int btGetConstraintIslandId(const btTypedConstraint* lhs) { int islandId; @@ -562,7 +442,6 @@ class btSortConstraintOnIslandPredicate void btDiscreteDynamicsWorld::solveConstraints(btContactSolverInfo& solverInfo) { - BT_PROFILE("solveConstraints"); struct InplaceSolverIslandCallback : public btSimulationIslandManager::IslandCallback { @@ -573,7 +452,7 @@ void btDiscreteDynamicsWorld::solveConstraints(btContactSolverInfo& solverInfo) int m_numConstraints; btIDebugDraw* m_debugDrawer; btStackAlloc* m_stackAlloc; - btDispatcher* m_dispatcher; + InplaceSolverIslandCallback( btContactSolverInfo& solverInfo, @@ -581,15 +460,13 @@ void btDiscreteDynamicsWorld::solveConstraints(btContactSolverInfo& solverInfo) btTypedConstraint** sortedConstraints, int numConstraints, btIDebugDraw* debugDrawer, - btStackAlloc* stackAlloc, - btDispatcher* dispatcher) + btStackAlloc* stackAlloc) :m_solverInfo(solverInfo), m_solver(solver), m_sortedConstraints(sortedConstraints), m_numConstraints(numConstraints), m_debugDrawer(debugDrawer), - m_stackAlloc(stackAlloc), - m_dispatcher(dispatcher) + m_stackAlloc(stackAlloc) { } @@ -602,42 +479,30 @@ void btDiscreteDynamicsWorld::solveConstraints(btContactSolverInfo& solverInfo) } virtual void ProcessIsland(btCollisionObject** bodies,int numBodies,btPersistentManifold** manifolds,int numManifolds, int islandId) { - if (islandId<0) + //also add all non-contact constraints/joints for this island + btTypedConstraint** startConstraint = 0; + int numCurConstraints = 0; + int i; + + //find the first constraint for this island + for (i=0;isolveGroup( bodies,numBodies,manifolds, numManifolds,&m_sortedConstraints[0],m_numConstraints,m_solverInfo,m_debugDrawer,m_stackAlloc,m_dispatcher); - } else - { - //also add all non-contact constraints/joints for this island - btTypedConstraint** startConstraint = 0; - int numCurConstraints = 0; - int i; - - //find the first constraint for this island - for (i=0;isolveGroup( bodies,numBodies,manifolds, numManifolds,startConstraint,numCurConstraints,m_solverInfo,m_debugDrawer,m_stackAlloc,m_dispatcher); - } - } + //count the number of constraints in this island + for (;isolveGroup( bodies,numBodies,manifolds, numManifolds,startConstraint,numCurConstraints,m_solverInfo,m_debugDrawer,m_stackAlloc); } }; @@ -655,18 +520,18 @@ void btDiscreteDynamicsWorld::solveConstraints(btContactSolverInfo& solverInfo) - sortedConstraints.quickSort(btSortConstraintOnIslandPredicate()); + sortedConstraints.heapSort(btSortConstraintOnIslandPredicate()); btTypedConstraint** constraintsPtr = getNumConstraints() ? &sortedConstraints[0] : 0; - InplaceSolverIslandCallback solverCallback( solverInfo, m_constraintSolver, constraintsPtr,sortedConstraints.size(), m_debugDrawer,m_stackAlloc,m_dispatcher1); + InplaceSolverIslandCallback solverCallback( solverInfo, m_constraintSolver, constraintsPtr,sortedConstraints.size(), m_debugDrawer,m_stackAlloc); + - m_constraintSolver->prepareSolve(getCollisionWorld()->getNumCollisionObjects(), getCollisionWorld()->getDispatcher()->getNumManifolds()); /// solve all the constraints for this island m_islandManager->buildAndProcessIslands(getCollisionWorld()->getDispatcher(),getCollisionWorld()->getCollisionObjectArray(),&solverCallback); - m_constraintSolver->allSolved(solverInfo, m_debugDrawer, m_stackAlloc); + } @@ -674,7 +539,7 @@ void btDiscreteDynamicsWorld::solveConstraints(btContactSolverInfo& solverInfo) void btDiscreteDynamicsWorld::calculateSimulationIslands() { - BT_PROFILE("calculateSimulationIslands"); + BEGIN_PROFILE("calculateSimulationIslands"); getSimulationIslandManager()->updateActivationState(getCollisionWorld(),getCollisionWorld()->getDispatcher()); @@ -704,14 +569,66 @@ void btDiscreteDynamicsWorld::calculateSimulationIslands() //Store the island id in each body getSimulationIslandManager()->storeIslandActivationState(getCollisionWorld()); - + END_PROFILE("calculateSimulationIslands"); + } +void btDiscreteDynamicsWorld::updateAabbs() +{ + BEGIN_PROFILE("updateAabbs"); + + btVector3 colorvec(1,0,0); + btTransform predictedTrans; + for ( int i=0;iIsActive() && (!body->IsStatic())) + { + btPoint3 minAabb,maxAabb; + colObj->getCollisionShape()->getAabb(colObj->getWorldTransform(), minAabb,maxAabb); + btBroadphaseInterface* bp = (btBroadphaseInterface*)m_broadphasePairCache; + + //moving objects should be moderately sized, probably something wrong if not + if ( colObj->isStaticObject() || ((maxAabb-minAabb).length2() < btScalar(1e12))) + { + bp->setAabb(body->getBroadphaseHandle(),minAabb,maxAabb); + } else + { + //something went wrong, investigate + //this assert is unwanted in 3D modelers (danger of loosing work) + body->setActivationState(DISABLE_SIMULATION); + + static bool reportMe = true; + if (reportMe && m_debugDrawer) + { + reportMe = false; + m_debugDrawer->reportErrorWarning("Overflow in AABB, object removed from simulation"); + m_debugDrawer->reportErrorWarning("If you can reproduce this, please email bugs@continuousphysics.com\n"); + m_debugDrawer->reportErrorWarning("Please include above information, your Platform, version of OS.\n"); + m_debugDrawer->reportErrorWarning("Thanks.\n"); + } + + + } + if (m_debugDrawer && (m_debugDrawer->getDebugMode() & btIDebugDraw::DBG_DrawAabb)) + { + m_debugDrawer->drawAabb(minAabb,maxAabb,colorvec); + } + } + } + } + + END_PROFILE("updateAabbs"); +} void btDiscreteDynamicsWorld::integrateTransforms(btScalar timeStep) { - BT_PROFILE("integrateTransforms"); + BEGIN_PROFILE("integrateTransforms"); btTransform predictedTrans; for ( int i=0;iisActive()) { + body->applyForces( timeStep); body->integrateVelocities( timeStep); - //damping - body->applyDamping(timeStep); - body->predictIntegratedTransform(timeStep,body->getInterpolationWorldTransform()); } } } } + END_PROFILE("predictUnconstraintMotion"); } void btDiscreteDynamicsWorld::startProfiling(btScalar timeStep) { (void)timeStep; + #ifdef USE_QUICKPROF -#ifndef BT_NO_PROFILE - CProfileManager::Reset(); -#endif //BT_NO_PROFILE + //toggle btProfiler + if ( m_debugDrawer && m_debugDrawer->getDebugMode() & btIDebugDraw::DBG_ProfileTimings) + { + if (!m_profileTimings) + { + m_profileTimings = 1; + // To disable profiling, simply comment out the following line. + static int counter = 0; + + char filename[128]; + sprintf(filename,"quickprof_bullet_timings%i.csv",counter++); + btProfiler::init(filename, btProfiler::BLOCK_CYCLE_SECONDS);//BLOCK_TOTAL_MICROSECONDS + } else + { + btProfiler::endProfilingCycle(); + } + + } else + { + if (m_profileTimings) + { + btProfiler::endProfilingCycle(); + + m_profileTimings = 0; + btProfiler::destroy(); + } + } +#endif //USE_QUICKPROF } @@ -884,52 +827,27 @@ void btDiscreteDynamicsWorld::debugDrawObject(const btTransform& worldTransform, btScalar radius = capsuleShape->getRadius(); btScalar halfHeight = capsuleShape->getHalfHeight(); - - int upAxis = capsuleShape->getUpAxis(); - - - btVector3 capStart(0.f,0.f,0.f); - capStart[upAxis] = -halfHeight; - - btVector3 capEnd(0.f,0.f,0.f); - capEnd[upAxis] = halfHeight; // Draw the ends { - btTransform childTransform = worldTransform; - childTransform.getOrigin() = worldTransform * capStart; + childTransform.getOrigin() = worldTransform * btVector3(0,halfHeight,0); debugDrawSphere(radius, childTransform, color); } { btTransform childTransform = worldTransform; - childTransform.getOrigin() = worldTransform * capEnd; + childTransform.getOrigin() = worldTransform * btVector3(0,-halfHeight,0); debugDrawSphere(radius, childTransform, color); } // Draw some additional lines btVector3 start = worldTransform.getOrigin(); + getDebugDrawer()->drawLine(start+worldTransform.getBasis() * btVector3(-radius,halfHeight,0),start+worldTransform.getBasis() * btVector3(-radius,-halfHeight,0), color); + getDebugDrawer()->drawLine(start+worldTransform.getBasis() * btVector3(radius,halfHeight,0),start+worldTransform.getBasis() * btVector3(radius,-halfHeight,0), color); + getDebugDrawer()->drawLine(start+worldTransform.getBasis() * btVector3(0,halfHeight,-radius),start+worldTransform.getBasis() * btVector3(0,-halfHeight,-radius), color); + getDebugDrawer()->drawLine(start+worldTransform.getBasis() * btVector3(0,halfHeight,radius),start+worldTransform.getBasis() * btVector3(0,-halfHeight,radius), color); - - capStart[(upAxis+1)%3] = radius; - capEnd[(upAxis+1)%3] = radius; - getDebugDrawer()->drawLine(start+worldTransform.getBasis() * capStart,start+worldTransform.getBasis() * capEnd, color); - capStart[(upAxis+1)%3] = -radius; - capEnd[(upAxis+1)%3] = -radius; - getDebugDrawer()->drawLine(start+worldTransform.getBasis() * capStart,start+worldTransform.getBasis() * capEnd, color); - - capStart[(upAxis+1)%3] = 0.f; - capEnd[(upAxis+1)%3] = 0.f; - - capStart[(upAxis+2)%3] = radius; - capEnd[(upAxis+2)%3] = radius; - getDebugDrawer()->drawLine(start+worldTransform.getBasis() * capStart,start+worldTransform.getBasis() * capEnd, color); - capStart[(upAxis+2)%3] = -radius; - capEnd[(upAxis+2)%3] = -radius; - getDebugDrawer()->drawLine(start+worldTransform.getBasis() * capStart,start+worldTransform.getBasis() * capEnd, color); - - break; } case CONE_SHAPE_PROXYTYPE: @@ -938,10 +856,9 @@ void btDiscreteDynamicsWorld::debugDrawObject(const btTransform& worldTransform, btScalar radius = coneShape->getRadius();//+coneShape->getMargin(); btScalar height = coneShape->getHeight();//+coneShape->getMargin(); btVector3 start = worldTransform.getOrigin(); - + // insert here Bullet 2.69 that fixes representation of cone int upAxis= coneShape->getConeUpIndex(); - btVector3 offsetHeight(0,0,0); offsetHeight[upAxis] = height * btScalar(0.5); btVector3 offsetRadius(0,0,0); @@ -954,8 +871,11 @@ void btDiscreteDynamicsWorld::debugDrawObject(const btTransform& worldTransform, getDebugDrawer()->drawLine(start+worldTransform.getBasis() * (offsetHeight),start+worldTransform.getBasis() * (-offsetHeight+offset2Radius),color); getDebugDrawer()->drawLine(start+worldTransform.getBasis() * (offsetHeight),start+worldTransform.getBasis() * (-offsetHeight-offset2Radius),color); - - + // buggy code that does not take into account the direction of the cone + //getDebugDrawer()->drawLine(start+worldTransform.getBasis() * btVector3(btScalar(0.),btScalar(0.),btScalar(0.5)*height),start+worldTransform.getBasis() * btVector3(radius,btScalar(0.),btScalar(-0.5)*height),color); + //getDebugDrawer()->drawLine(start+worldTransform.getBasis() * btVector3(btScalar(0.),btScalar(0.),btScalar(0.5)*height),start+worldTransform.getBasis() * btVector3(-radius,btScalar(0.),btScalar(-0.5)*height),color); + //getDebugDrawer()->drawLine(start+worldTransform.getBasis() * btVector3(btScalar(0.),btScalar(0.),btScalar(0.5)*height),start+worldTransform.getBasis() * btVector3(btScalar(0.),radius,btScalar(-0.5)*height),color); + //getDebugDrawer()->drawLine(start+worldTransform.getBasis() * btVector3(btScalar(0.),btScalar(0.),btScalar(0.5)*height),start+worldTransform.getBasis() * btVector3(btScalar(0.),-radius,btScalar(-0.5)*height),color); break; } @@ -964,7 +884,7 @@ void btDiscreteDynamicsWorld::debugDrawObject(const btTransform& worldTransform, const btCylinderShape* cylinder = static_cast(shape); int upAxis = cylinder->getUpAxis(); btScalar radius = cylinder->getRadius(); - btScalar halfHeight = cylinder->getHalfExtentsWithMargin()[upAxis]; + btScalar halfHeight = cylinder->getHalfExtents()[upAxis]; btVector3 start = worldTransform.getOrigin(); btVector3 offsetHeight(0,0,0); offsetHeight[upAxis] = halfHeight; @@ -974,25 +894,6 @@ void btDiscreteDynamicsWorld::debugDrawObject(const btTransform& worldTransform, getDebugDrawer()->drawLine(start+worldTransform.getBasis() * (offsetHeight-offsetRadius),start+worldTransform.getBasis() * (-offsetHeight-offsetRadius),color); break; } - - case STATIC_PLANE_PROXYTYPE: - { - const btStaticPlaneShape* staticPlaneShape = static_cast(shape); - btScalar planeConst = staticPlaneShape->getPlaneConstant(); - const btVector3& planeNormal = staticPlaneShape->getPlaneNormal(); - btVector3 planeOrigin = planeNormal * planeConst; - btVector3 vec0,vec1; - btPlaneSpace1(planeNormal,vec0,vec1); - btScalar vecLen = 100.f; - btVector3 pt0 = planeOrigin + vec0*vecLen; - btVector3 pt1 = planeOrigin - vec0*vecLen; - btVector3 pt2 = planeOrigin + vec1*vecLen; - btVector3 pt3 = planeOrigin - vec1*vecLen; - getDebugDrawer()->drawLine(worldTransform*pt0,worldTransform*pt1,color); - getDebugDrawer()->drawLine(worldTransform*pt2,worldTransform*pt3,color); - break; - - } default: { @@ -1017,7 +918,7 @@ void btDiscreteDynamicsWorld::debugDrawObject(const btTransform& worldTransform, btVector3 aabbMin(btScalar(-1e30),btScalar(-1e30),btScalar(-1e30)); //DebugDrawcallback drawCallback; DebugDrawcallback drawCallback(getDebugDrawer(),worldTransform,color); - convexMesh->getMeshInterface()->InternalProcessAllTriangles(&drawCallback,aabbMin,aabbMax); + convexMesh->getStridingMesh()->InternalProcessAllTriangles(&drawCallback,aabbMin,aabbMax); } @@ -1049,18 +950,12 @@ void btDiscreteDynamicsWorld::setConstraintSolver(btConstraintSolver* solver) { if (m_ownsConstraintSolver) { - btAlignedFree( m_constraintSolver); + delete m_constraintSolver; } m_ownsConstraintSolver = false; m_constraintSolver = solver; } -btConstraintSolver* btDiscreteDynamicsWorld::getConstraintSolver() -{ - return m_constraintSolver; -} - - int btDiscreteDynamicsWorld::getNumConstraints() const { return int(m_constraints.size()); diff --git a/extern/bullet2/src/BulletDynamics/Dynamics/btDiscreteDynamicsWorld.h b/extern/bullet2/src/BulletDynamics/Dynamics/btDiscreteDynamicsWorld.h index d206a604960..83b90bfeebc 100644 --- a/extern/bullet2/src/BulletDynamics/Dynamics/btDiscreteDynamicsWorld.h +++ b/extern/bullet2/src/BulletDynamics/Dynamics/btDiscreteDynamicsWorld.h @@ -23,11 +23,11 @@ class btOverlappingPairCache; class btConstraintSolver; class btSimulationIslandManager; class btTypedConstraint; - +#include "../ConstraintSolver/btContactSolverInfo.h" class btRaycastVehicle; class btIDebugDraw; -#include "LinearMath/btAlignedObjectArray.h" +#include "../../LinearMath/btAlignedObjectArray.h" ///btDiscreteDynamicsWorld provides discrete rigid body simulation @@ -42,6 +42,7 @@ protected: btAlignedObjectArray m_constraints; + btIDebugDraw* m_debugDrawer; btVector3 m_gravity; @@ -52,12 +53,14 @@ protected: bool m_ownsIslandManager; bool m_ownsConstraintSolver; - + btContactSolverInfo m_solverInfo; + + btAlignedObjectArray m_vehicles; int m_profileTimings; - virtual void predictUnconstraintMotion(btScalar timeStep); + void predictUnconstraintMotion(btScalar timeStep); void integrateTransforms(btScalar timeStep); @@ -83,13 +86,14 @@ public: ///this btDiscreteDynamicsWorld constructor gets created objects from the user, and will not delete those - btDiscreteDynamicsWorld(btDispatcher* dispatcher,btBroadphaseInterface* pairCache,btConstraintSolver* constraintSolver,btCollisionConfiguration* collisionConfiguration); + btDiscreteDynamicsWorld(btDispatcher* dispatcher,btOverlappingPairCache* pairCache,btConstraintSolver* constraintSolver); virtual ~btDiscreteDynamicsWorld(); ///if maxSubSteps > 0, it will interpolate motion between fixedTimeStep's virtual int stepSimulation( btScalar timeStep,int maxSubSteps=1, btScalar fixedTimeStep=btScalar(1.)/btScalar(60.)); + virtual void updateAabbs(); void addConstraint(btTypedConstraint* constraint, bool disableCollisionsBetweenLinkedBodies=false); @@ -114,9 +118,17 @@ public: return this; } + virtual void setDebugDrawer(btIDebugDraw* debugDrawer) + { + m_debugDrawer = debugDrawer; + } + + virtual btIDebugDraw* getDebugDrawer() + { + return m_debugDrawer; + } virtual void setGravity(const btVector3& gravity); - virtual btVector3 getGravity () const; virtual void addRigidBody(btRigidBody* body); @@ -126,11 +138,7 @@ public: void debugDrawObject(const btTransform& worldTransform, const btCollisionShape* shape, const btVector3& color); - virtual void debugDrawWorld(); - virtual void setConstraintSolver(btConstraintSolver* solver); - - virtual btConstraintSolver* getConstraintSolver(); virtual int getNumConstraints() const; @@ -138,21 +146,11 @@ public: virtual const btTypedConstraint* getConstraint(int index) const; - - virtual btDynamicsWorldType getWorldType() const + btContactSolverInfo& getSolverInfo() { - return BT_DISCRETE_DYNAMICS_WORLD; + return m_solverInfo; } - - ///the forces on each rigidbody is accumulating together with gravity. clear this after each timestep. - virtual void clearForces(); - ///apply gravity, call this once per timestep - virtual void applyGravity(); - - virtual void setNumTasks(int numTasks) - { - } }; diff --git a/extern/bullet2/src/BulletDynamics/Dynamics/btDynamicsWorld.h b/extern/bullet2/src/BulletDynamics/Dynamics/btDynamicsWorld.h index dd9dfa71b7f..65b63fad4b5 100644 --- a/extern/bullet2/src/BulletDynamics/Dynamics/btDynamicsWorld.h +++ b/extern/bullet2/src/BulletDynamics/Dynamics/btDynamicsWorld.h @@ -16,39 +16,20 @@ subject to the following restrictions: #ifndef BT_DYNAMICS_WORLD_H #define BT_DYNAMICS_WORLD_H -#include "BulletCollision/CollisionDispatch/btCollisionWorld.h" -#include "BulletDynamics/ConstraintSolver/btContactSolverInfo.h" - +#include "../../BulletCollision/CollisionDispatch/btCollisionWorld.h" class btTypedConstraint; class btRaycastVehicle; class btConstraintSolver; -class btDynamicsWorld; -/// Type for the callback for each tick -typedef void (*btInternalTickCallback)(btDynamicsWorld *world, btScalar timeStep); -enum btDynamicsWorldType -{ - BT_SIMPLE_DYNAMICS_WORLD=1, - BT_DISCRETE_DYNAMICS_WORLD=2, - BT_CONTINUOUS_DYNAMICS_WORLD=3 -}; - -///The btDynamicsWorld is the interface class for several dynamics implementation, basic, discrete, parallel, and continuous etc. +///btDynamicsWorld is the baseclass for several dynamics implementation, basic, discrete, parallel, and continuous class btDynamicsWorld : public btCollisionWorld { - -protected: - btInternalTickCallback m_internalTickCallback; - void* m_worldUserInfo; - - btContactSolverInfo m_solverInfo; - -public: + public: - btDynamicsWorld(btDispatcher* dispatcher,btBroadphaseInterface* broadphase,btCollisionConfiguration* collisionConfiguration) - :btCollisionWorld(dispatcher,broadphase,collisionConfiguration), m_internalTickCallback(0), m_worldUserInfo(0) + btDynamicsWorld(btDispatcher* dispatcher,btOverlappingPairCache* pairCache) + :btCollisionWorld(dispatcher,pairCache) { } @@ -56,37 +37,34 @@ public: { } - ///stepSimulation proceeds the simulation over 'timeStep', units in preferably in seconds. - ///By default, Bullet will subdivide the timestep in constant substeps of each 'fixedTimeStep'. - ///in order to keep the simulation real-time, the maximum number of substeps can be clamped to 'maxSubSteps'. - ///You can disable subdividing the timestep/substepping by passing maxSubSteps=0 as second argument to stepSimulation, but in that case you have to keep the timeStep constant. - virtual int stepSimulation( btScalar timeStep,int maxSubSteps=10, btScalar fixedTimeStep=btScalar(1.)/btScalar(60.))=0; + ///stepSimulation proceeds the simulation over timeStep units + ///if maxSubSteps > 0, it will interpolate time steps + virtual int stepSimulation( btScalar timeStep,int maxSubSteps=1, btScalar fixedTimeStep=btScalar(1.)/btScalar(60.))=0; - virtual void debugDrawWorld() = 0; + virtual void updateAabbs() = 0; - virtual void addConstraint(btTypedConstraint* constraint, bool disableCollisionsBetweenLinkedBodies=false) - { - (void)constraint; (void)disableCollisionsBetweenLinkedBodies; - } + virtual void addConstraint(btTypedConstraint* constraint, bool disableCollisionsBetweenLinkedBodies=false) { (void)constraint;}; - virtual void removeConstraint(btTypedConstraint* constraint) {(void)constraint;} + virtual void removeConstraint(btTypedConstraint* constraint) {(void)constraint;}; - virtual void addVehicle(btRaycastVehicle* vehicle) {(void)vehicle;} + virtual void addVehicle(btRaycastVehicle* vehicle) {(void)vehicle;}; - virtual void removeVehicle(btRaycastVehicle* vehicle) {(void)vehicle;} + virtual void removeVehicle(btRaycastVehicle* vehicle) {(void)vehicle;}; + + + virtual void setDebugDrawer(btIDebugDraw* debugDrawer) = 0; + + virtual btIDebugDraw* getDebugDrawer() = 0; //once a rigidbody is added to the dynamics world, it will get this gravity assigned //existing rigidbodies in the world get gravity assigned too, during this method virtual void setGravity(const btVector3& gravity) = 0; - virtual btVector3 getGravity () const = 0; virtual void addRigidBody(btRigidBody* body) = 0; virtual void removeRigidBody(btRigidBody* body) = 0; virtual void setConstraintSolver(btConstraintSolver* solver) = 0; - - virtual btConstraintSolver* getConstraintSolver() = 0; virtual int getNumConstraints() const { return 0; } @@ -94,35 +72,7 @@ public: virtual const btTypedConstraint* getConstraint(int index) const { (void)index; return 0; } - virtual btDynamicsWorldType getWorldType() const=0; - - virtual void clearForces() = 0; - - /// Set the callback for when an internal tick (simulation substep) happens, optional user info - void setInternalTickCallback(btInternalTickCallback cb, void* worldUserInfo=0) - { - m_internalTickCallback = cb; - m_worldUserInfo = worldUserInfo; - } - - void setWorldUserInfo(void* worldUserInfo) - { - m_worldUserInfo = worldUserInfo; - } - - void* getWorldUserInfo() const - { - return m_worldUserInfo; - } - - btContactSolverInfo& getSolverInfo() - { - return m_solverInfo; - } - - }; #endif //BT_DYNAMICS_WORLD_H - diff --git a/extern/bullet2/src/BulletDynamics/Dynamics/btRigidBody.cpp b/extern/bullet2/src/BulletDynamics/Dynamics/btRigidBody.cpp index e2afb687ac6..9ed3579d89c 100644 --- a/extern/bullet2/src/BulletDynamics/Dynamics/btRigidBody.cpp +++ b/extern/bullet2/src/BulletDynamics/Dynamics/btRigidBody.cpp @@ -20,53 +20,36 @@ subject to the following restrictions: #include "LinearMath/btMotionState.h" #include "BulletDynamics/ConstraintSolver/btTypedConstraint.h" +btScalar gLinearAirDamping = btScalar(1.); //'temporarily' global variables btScalar gDeactivationTime = btScalar(2.); bool gDisableDeactivation = false; + +btScalar gLinearSleepingThreshold = btScalar(0.8); +btScalar gAngularSleepingThreshold = btScalar(1.0); static int uniqueId = 0; - -btRigidBody::btRigidBody(const btRigidBody::btRigidBodyConstructionInfo& constructionInfo) -{ - setupRigidBody(constructionInfo); -} - -btRigidBody::btRigidBody(btScalar mass, btMotionState *motionState, btCollisionShape *collisionShape, const btVector3 &localInertia) -{ - btRigidBodyConstructionInfo cinfo(mass,motionState,collisionShape,localInertia); - setupRigidBody(cinfo); -} - -void btRigidBody::setupRigidBody(const btRigidBody::btRigidBodyConstructionInfo& constructionInfo) +btRigidBody::btRigidBody(btScalar mass, btMotionState* motionState, btCollisionShape* collisionShape, const btVector3& localInertia,btScalar linearDamping,btScalar angularDamping,btScalar friction,btScalar restitution) +: + m_linearVelocity(btScalar(0.0), btScalar(0.0), btScalar(0.0)), + m_angularVelocity(btScalar(0.),btScalar(0.),btScalar(0.)), + m_angularFactor(btScalar(1.)), + m_gravity(btScalar(0.0), btScalar(0.0), btScalar(0.0)), + m_totalForce(btScalar(0.0), btScalar(0.0), btScalar(0.0)), + m_totalTorque(btScalar(0.0), btScalar(0.0), btScalar(0.0)), + m_linearDamping(btScalar(0.)), + m_angularDamping(btScalar(0.5)), + m_optionalMotionState(motionState), + m_contactSolverType(0), + m_frictionSolverType(0) { - m_internalType=CO_RIGID_BODY; - - m_linearVelocity.setValue(btScalar(0.0), btScalar(0.0), btScalar(0.0)); - m_angularVelocity.setValue(btScalar(0.),btScalar(0.),btScalar(0.)); - m_angularFactor = btScalar(1.); - m_gravity.setValue(btScalar(0.0), btScalar(0.0), btScalar(0.0)); - m_totalForce.setValue(btScalar(0.0), btScalar(0.0), btScalar(0.0)); - m_totalTorque.setValue(btScalar(0.0), btScalar(0.0), btScalar(0.0)), - m_linearDamping = btScalar(0.); - m_angularDamping = btScalar(0.5); - m_linearSleepingThreshold = constructionInfo.m_linearSleepingThreshold; - m_angularSleepingThreshold = constructionInfo.m_angularSleepingThreshold; - m_optionalMotionState = constructionInfo.m_motionState; - m_contactSolverType = 0; - m_frictionSolverType = 0; - m_additionalDamping = constructionInfo.m_additionalDamping; - m_additionalDampingFactor = constructionInfo.m_additionalDampingFactor; - m_additionalLinearDampingThresholdSqr = constructionInfo.m_additionalLinearDampingThresholdSqr; - m_additionalAngularDampingThresholdSqr = constructionInfo.m_additionalAngularDampingThresholdSqr; - m_additionalAngularDampingFactor = constructionInfo.m_additionalAngularDampingFactor; - - if (m_optionalMotionState) + if (motionState) { - m_optionalMotionState->getWorldTransform(m_worldTransform); + motionState->getWorldTransform(m_worldTransform); } else { - m_worldTransform = constructionInfo.m_startWorldTransform; + m_worldTransform = btTransform::getIdentity(); } m_interpolationWorldTransform = m_worldTransform; @@ -74,21 +57,90 @@ void btRigidBody::setupRigidBody(const btRigidBody::btRigidBodyConstructionInfo& m_interpolationAngularVelocity.setValue(0,0,0); //moved to btCollisionObject - m_friction = constructionInfo.m_friction; - m_restitution = constructionInfo.m_restitution; + m_friction = friction; + m_restitution = restitution; - setCollisionShape( constructionInfo.m_collisionShape ); + m_collisionShape = collisionShape; m_debugBodyId = uniqueId++; - setMassProps(constructionInfo.m_mass, constructionInfo.m_localInertia); - setDamping(constructionInfo.m_linearDamping, constructionInfo.m_angularDamping); + //m_internalOwner is to allow upcasting from collision object to rigid body + m_internalOwner = this; + + setMassProps(mass, localInertia); + setDamping(linearDamping, angularDamping); updateInertiaTensor(); } +#ifdef OBSOLETE_MOTIONSTATE_LESS +btRigidBody::btRigidBody( btScalar mass,const btTransform& worldTransform,btCollisionShape* collisionShape,const btVector3& localInertia,btScalar linearDamping,btScalar angularDamping,btScalar friction,btScalar restitution) +: + m_gravity(btScalar(0.0), btScalar(0.0), btScalar(0.0)), + m_totalForce(btScalar(0.0), btScalar(0.0), btScalar(0.0)), + m_totalTorque(btScalar(0.0), btScalar(0.0), btScalar(0.0)), + m_linearVelocity(btScalar(0.0), btScalar(0.0), btScalar(0.0)), + m_angularVelocity(btScalar(0.),btScalar(0.),btScalar(0.)), + m_linearDamping(btScalar(0.)), + m_angularDamping(btScalar(0.5)), + m_optionalMotionState(0), + m_contactSolverType(0), + m_frictionSolverType(0) +{ + + m_worldTransform = worldTransform; + m_interpolationWorldTransform = m_worldTransform; + m_interpolationLinearVelocity.setValue(0,0,0); + m_interpolationAngularVelocity.setValue(0,0,0); + + //moved to btCollisionObject + m_friction = friction; + m_restitution = restitution; + + m_collisionShape = collisionShape; + m_debugBodyId = uniqueId++; + + //m_internalOwner is to allow upcasting from collision object to rigid body + m_internalOwner = this; + + setMassProps(mass, localInertia); + setDamping(linearDamping, angularDamping); + updateInertiaTensor(); + +} + +#endif //OBSOLETE_MOTIONSTATE_LESS + + + + +//#define EXPERIMENTAL_JITTER_REMOVAL 1 +#ifdef EXPERIMENTAL_JITTER_REMOVAL +//Bullet 2.20b has experimental damping code to reduce jitter just before objects fall asleep/deactivate +//doesn't work very well yet (value 0 disabled this damping) +//note there this influences deactivation thresholds! +btScalar gClippedAngvelThresholdSqr = btScalar(0.01); +btScalar gClippedLinearThresholdSqr = btScalar(0.01); +#endif //EXPERIMENTAL_JITTER_REMOVAL + +btScalar gJitterVelocityDampingFactor = btScalar(0.7); void btRigidBody::predictIntegratedTransform(btScalar timeStep,btTransform& predictedTransform) { + +#ifdef EXPERIMENTAL_JITTER_REMOVAL + //if (wantsSleeping()) + { + //clip to avoid jitter + if ((m_angularVelocity.length2() < gClippedAngvelThresholdSqr) && + (m_linearVelocity.length2() < gClippedLinearThresholdSqr)) + { + m_angularVelocity *= gJitterVelocityDampingFactor; + m_linearVelocity *= gJitterVelocityDampingFactor; + } + } + +#endif //EXPERIMENTAL_JITTER_REMOVAL + btTransformUtil::integrateTransform(m_worldTransform,m_linearVelocity,m_angularVelocity,timeStep,predictedTransform); } @@ -139,63 +191,50 @@ void btRigidBody::setDamping(btScalar lin_damping, btScalar ang_damping) - -///applyDamping damps the velocity, using the given m_linearDamping and m_angularDamping -void btRigidBody::applyDamping(btScalar timeStep) -{ - m_linearVelocity *= GEN_clamped((btScalar(1.) - timeStep * m_linearDamping), (btScalar)btScalar(0.0), (btScalar)btScalar(1.0)); - m_angularVelocity *= GEN_clamped((btScalar(1.) - timeStep * m_angularDamping), (btScalar)btScalar(0.0), (btScalar)btScalar(1.0)); - - if (m_additionalDamping) - { - //Additional damping can help avoiding lowpass jitter motion, help stability for ragdolls etc. - //Such damping is undesirable, so once the overall simulation quality of the rigid body dynamics system has improved, this should become obsolete - if ((m_angularVelocity.length2() < m_additionalAngularDampingThresholdSqr) && - (m_linearVelocity.length2() < m_additionalLinearDampingThresholdSqr)) - { - m_angularVelocity *= m_additionalDampingFactor; - m_linearVelocity *= m_additionalDampingFactor; - } - - - btScalar speed = m_linearVelocity.length(); - if (speed < m_linearDamping) - { - btScalar dampVel = btScalar(0.005); - if (speed > dampVel) - { - btVector3 dir = m_linearVelocity.normalized(); - m_linearVelocity -= dir * dampVel; - } else - { - m_linearVelocity.setValue(btScalar(0.),btScalar(0.),btScalar(0.)); - } - } - - btScalar angSpeed = m_angularVelocity.length(); - if (angSpeed < m_angularDamping) - { - btScalar angDampVel = btScalar(0.005); - if (angSpeed > angDampVel) - { - btVector3 dir = m_angularVelocity.normalized(); - m_angularVelocity -= dir * angDampVel; - } else - { - m_angularVelocity.setValue(btScalar(0.),btScalar(0.),btScalar(0.)); - } - } - } -} +#include -void btRigidBody::applyGravity() +void btRigidBody::applyForces(btScalar step) { if (isStaticOrKinematicObject()) return; applyCentralForce(m_gravity); + + m_linearVelocity *= GEN_clamped((btScalar(1.) - step * gLinearAirDamping * m_linearDamping), (btScalar)btScalar(0.0), (btScalar)btScalar(1.0)); + m_angularVelocity *= GEN_clamped((btScalar(1.) - step * m_angularDamping), (btScalar)btScalar(0.0), (btScalar)btScalar(1.0)); +#define FORCE_VELOCITY_DAMPING 1 +#ifdef FORCE_VELOCITY_DAMPING + btScalar speed = m_linearVelocity.length(); + if (speed < m_linearDamping) + { + btScalar dampVel = btScalar(0.005); + if (speed > dampVel) + { + btVector3 dir = m_linearVelocity.normalized(); + m_linearVelocity -= dir * dampVel; + } else + { + m_linearVelocity.setValue(btScalar(0.),btScalar(0.),btScalar(0.)); + } + } + + btScalar angSpeed = m_angularVelocity.length(); + if (angSpeed < m_angularDamping) + { + btScalar angDampVel = btScalar(0.005); + if (angSpeed > angDampVel) + { + btVector3 dir = m_angularVelocity.normalized(); + m_angularVelocity -= dir * angDampVel; + } else + { + m_angularVelocity.setValue(btScalar(0.),btScalar(0.),btScalar(0.)); + } + } +#endif //FORCE_VELOCITY_DAMPING + } void btRigidBody::proceedToTransform(const btTransform& newTrans) @@ -246,6 +285,7 @@ void btRigidBody::integrateVelocities(btScalar step) m_angularVelocity *= (MAX_ANGVEL/step) /angvel; } + clearForces(); } btQuaternion btRigidBody::getOrientation() const diff --git a/extern/bullet2/src/BulletDynamics/Dynamics/btRigidBody.h b/extern/bullet2/src/BulletDynamics/Dynamics/btRigidBody.h index 4596f90a00f..0707595d48e 100644 --- a/extern/bullet2/src/BulletDynamics/Dynamics/btRigidBody.h +++ b/extern/bullet2/src/BulletDynamics/Dynamics/btRigidBody.h @@ -16,29 +16,27 @@ subject to the following restrictions: #ifndef RIGIDBODY_H #define RIGIDBODY_H -#include "LinearMath/btAlignedObjectArray.h" -#include "LinearMath/btPoint3.h" -#include "LinearMath/btTransform.h" -#include "BulletCollision/BroadphaseCollision/btBroadphaseProxy.h" -#include "BulletCollision/CollisionDispatch/btCollisionObject.h" +#include "../../LinearMath/btAlignedObjectArray.h" +#include "../../LinearMath/btPoint3.h" +#include "../../LinearMath/btTransform.h" +#include "../../BulletCollision/BroadphaseCollision/btBroadphaseProxy.h" +#include "../../BulletCollision/CollisionDispatch/btCollisionObject.h" class btCollisionShape; class btMotionState; class btTypedConstraint; +extern btScalar gLinearAirDamping; + extern btScalar gDeactivationTime; extern bool gDisableDeactivation; +extern btScalar gLinearSleepingThreshold; +extern btScalar gAngularSleepingThreshold; -///btRigidBody is the main class for rigid body objects. It is derived from btCollisionObject, so it keeps a pointer to a btCollisionShape. -///It is recommended for performance and memory use to share btCollisionShape objects whenever possible. -///There are 3 types of rigid bodies: -///- A) Dynamic rigid bodies, with positive mass. Motion is controlled by rigid body dynamics. -///- B) Fixed objects with zero mass. They are not moving (basically collision objects) -///- C) Kinematic objects, which are objects without mass, but the user can move them. There is on-way interaction, and Bullet calculates a velocity based on the timestep and previous and current world transform. -///Bullet automatically deactivates dynamic rigid bodies, when the velocity is below a threshold for a given time. -///Deactivated (sleeping) rigid bodies don't take any processing time, except a minor broadphase collision detection impact (to allow active objects to activate/wake up sleeping objects) +/// btRigidBody class for btRigidBody Dynamics +/// class btRigidBody : public btCollisionObject { @@ -55,16 +53,7 @@ class btRigidBody : public btCollisionObject btScalar m_linearDamping; btScalar m_angularDamping; - - bool m_additionalDamping; - btScalar m_additionalDampingFactor; - btScalar m_additionalLinearDampingThresholdSqr; - btScalar m_additionalAngularDampingThresholdSqr; - btScalar m_additionalAngularDampingFactor; - - - btScalar m_linearSleepingThreshold; - btScalar m_angularSleepingThreshold; + //m_optionalMotionState allows to automatic synchronize the world transform for active objects btMotionState* m_optionalMotionState; @@ -74,85 +63,12 @@ class btRigidBody : public btCollisionObject public: +#ifdef OBSOLETE_MOTIONSTATE_LESS + //not supported, please use btMotionState + btRigidBody(btScalar mass, const btTransform& worldTransform, btCollisionShape* collisionShape, const btVector3& localInertia=btVector3(0,0,0),btScalar linearDamping=btScalar(0.),btScalar angularDamping=btScalar(0.),btScalar friction=btScalar(0.5),btScalar restitution=btScalar(0.)); +#endif //OBSOLETE_MOTIONSTATE_LESS - ///btRigidBodyConstructionInfo provides information to create a rigid body. Setting mass to zero creates a fixed (non-dynamic) rigid body. - ///For dynamic objects, you can use the collision shape to approximate the local inertia tensor, otherwise use the zero vector (default argument) - ///You can use the motion state to synchronize the world transform between physics and graphics objects. - ///And if the motion state is provided, the rigid body will initialize its initial world transform from the motion state, - ///m_startWorldTransform is only used when you don't provide a motion state. - struct btRigidBodyConstructionInfo - { - btScalar m_mass; - - ///When a motionState is provided, the rigid body will initialize its world transform from the motion state - ///In this case, m_startWorldTransform is ignored. - btMotionState* m_motionState; - btTransform m_startWorldTransform; - - btCollisionShape* m_collisionShape; - btVector3 m_localInertia; - btScalar m_linearDamping; - btScalar m_angularDamping; - - ///best simulation results when friction is non-zero - btScalar m_friction; - ///best simulation results using zero restitution. - btScalar m_restitution; - - btScalar m_linearSleepingThreshold; - btScalar m_angularSleepingThreshold; - - //Additional damping can help avoiding lowpass jitter motion, help stability for ragdolls etc. - //Such damping is undesirable, so once the overall simulation quality of the rigid body dynamics system has improved, this should become obsolete - bool m_additionalDamping; - btScalar m_additionalDampingFactor; - btScalar m_additionalLinearDampingThresholdSqr; - btScalar m_additionalAngularDampingThresholdSqr; - btScalar m_additionalAngularDampingFactor; - - - btRigidBodyConstructionInfo( btScalar mass, btMotionState* motionState, btCollisionShape* collisionShape, const btVector3& localInertia=btVector3(0,0,0)): - m_mass(mass), - m_motionState(motionState), - m_collisionShape(collisionShape), - m_localInertia(localInertia), - m_linearDamping(btScalar(0.)), - m_angularDamping(btScalar(0.)), - m_friction(btScalar(0.5)), - m_restitution(btScalar(0.)), - m_linearSleepingThreshold(btScalar(0.8)), - m_angularSleepingThreshold(btScalar(1.f)), - m_additionalDamping(false), - m_additionalDampingFactor(btScalar(0.005)), - m_additionalLinearDampingThresholdSqr(btScalar(0.01)), - m_additionalAngularDampingThresholdSqr(btScalar(0.01)), - m_additionalAngularDampingFactor(btScalar(0.01)) - { - m_startWorldTransform.setIdentity(); - } - }; - - ///btRigidBody constructor using construction info - btRigidBody( const btRigidBodyConstructionInfo& constructionInfo); - - ///btRigidBody constructor for backwards compatibility. - ///To specify friction (etc) during rigid body construction, please use the other constructor (using btRigidBodyConstructionInfo) - btRigidBody( btScalar mass, btMotionState* motionState, btCollisionShape* collisionShape, const btVector3& localInertia=btVector3(0,0,0)); - - - virtual ~btRigidBody() - { - //No constraints should point to this rigidbody - //Remove constraints from the dynamics world before you delete the related rigidbodies. - btAssert(m_constraintRefs.size()==0); - } - -protected: - - ///setupRigidBody is only used internally by the constructor - void setupRigidBody(const btRigidBodyConstructionInfo& constructionInfo); - -public: + btRigidBody(btScalar mass, btMotionState* motionState, btCollisionShape* collisionShape, const btVector3& localInertia=btVector3(0,0,0),btScalar linearDamping=btScalar(0.),btScalar angularDamping=btScalar(0.),btScalar friction=btScalar(0.5),btScalar restitution=btScalar(0.)); void proceedToTransform(const btTransform& newTrans); @@ -160,15 +76,11 @@ public: ///but a rigidbody is derived from btCollisionObject, so we can safely perform an upcast static const btRigidBody* upcast(const btCollisionObject* colObj) { - if (colObj->getInternalType()==btCollisionObject::CO_RIGID_BODY) - return (const btRigidBody*)colObj; - return 0; + return (const btRigidBody*)colObj->getInternalOwner(); } static btRigidBody* upcast(btCollisionObject* colObj) { - if (colObj->getInternalType()==btCollisionObject::CO_RIGID_BODY) - return (btRigidBody*)colObj; - return 0; + return (btRigidBody*)colObj->getInternalOwner(); } /// continuous collision detection needs prediction @@ -176,7 +88,8 @@ public: void saveKinematicState(btScalar step); - void applyGravity(); + + void applyForces(btScalar step); void setGravity(const btVector3& acceleration); @@ -186,34 +99,12 @@ public: } void setDamping(btScalar lin_damping, btScalar ang_damping); - - btScalar getLinearDamping() const - { - return m_linearDamping; - } - - btScalar getAngularDamping() const - { - return m_angularDamping; - } - - btScalar getLinearSleepingThreshold() const - { - return m_linearSleepingThreshold; - } - - btScalar getAngularSleepingThreshold() const - { - return m_angularSleepingThreshold; - } - - void applyDamping(btScalar timeStep); - - SIMD_FORCE_INLINE const btCollisionShape* getCollisionShape() const { + + inline const btCollisionShape* getCollisionShape() const { return m_collisionShape; } - SIMD_FORCE_INLINE btCollisionShape* getCollisionShape() { + inline btCollisionShape* getCollisionShape() { return m_collisionShape; } @@ -243,12 +134,6 @@ public: m_invInertiaLocal = diagInvInertia; } - void setSleepingThresholds(btScalar linear,btScalar angular) - { - m_linearSleepingThreshold = linear; - m_angularSleepingThreshold = angular; - } - void applyTorque(const btVector3& torque) { m_totalTorque += torque; @@ -257,7 +142,7 @@ public: void applyForce(const btVector3& force, const btVector3& rel_pos) { applyCentralForce(force); - applyTorque(rel_pos.cross(force)*m_angularFactor); + applyTorque(rel_pos.cross(force)); } void applyCentralImpulse(const btVector3& impulse) @@ -283,7 +168,7 @@ public: } //Optimization for the iterative solver: avoid calculating constant terms involving inertia, normal, relative position - SIMD_FORCE_INLINE void internalApplyImpulse(const btVector3& linearComponent, const btVector3& angularComponent,btScalar impulseMagnitude) + inline void internalApplyImpulse(const btVector3& linearComponent, const btVector3& angularComponent,btScalar impulseMagnitude) { if (m_inverseMass != btScalar(0.)) { @@ -353,7 +238,7 @@ public: - SIMD_FORCE_INLINE btScalar computeImpulseDenominator(const btPoint3& pos, const btVector3& normal) const + inline btScalar computeImpulseDenominator(const btPoint3& pos, const btVector3& normal) const { btVector3 r0 = pos - getCenterOfMassPosition(); @@ -365,19 +250,19 @@ public: } - SIMD_FORCE_INLINE btScalar computeAngularImpulseDenominator(const btVector3& axis) const + inline btScalar computeAngularImpulseDenominator(const btVector3& axis) const { btVector3 vec = axis * getInvInertiaTensorWorld(); return axis.dot(vec); } - SIMD_FORCE_INLINE void updateDeactivation(btScalar timeStep) + inline void updateDeactivation(btScalar timeStep) { if ( (getActivationState() == ISLAND_SLEEPING) || (getActivationState() == DISABLE_DEACTIVATION)) return; - if ((getLinearVelocity().length2() < m_linearSleepingThreshold*m_linearSleepingThreshold) && - (getAngularVelocity().length2() < m_angularSleepingThreshold*m_angularSleepingThreshold)) + if ((getLinearVelocity().length2() < gLinearSleepingThreshold*gLinearSleepingThreshold) && + (getAngularVelocity().length2() < gAngularSleepingThreshold*gAngularSleepingThreshold)) { m_deactivationTime += timeStep; } else @@ -388,7 +273,7 @@ public: } - SIMD_FORCE_INLINE bool wantsSleeping() + inline bool wantsSleeping() { if (getActivationState() == DISABLE_DEACTIVATION) @@ -463,16 +348,6 @@ public: void addConstraintRef(btTypedConstraint* c); void removeConstraintRef(btTypedConstraint* c); - btTypedConstraint* getConstraintRef(int index) - { - return m_constraintRefs[index]; - } - - int getNumConstraintRefs() - { - return m_constraintRefs.size(); - } - int m_debugBodyId; }; diff --git a/extern/bullet2/src/BulletDynamics/Dynamics/btSimpleDynamicsWorld.cpp b/extern/bullet2/src/BulletDynamics/Dynamics/btSimpleDynamicsWorld.cpp index 3be04d1a4ad..4ebcb8e7517 100644 --- a/extern/bullet2/src/BulletDynamics/Dynamics/btSimpleDynamicsWorld.cpp +++ b/extern/bullet2/src/BulletDynamics/Dynamics/btSimpleDynamicsWorld.cpp @@ -27,19 +27,16 @@ subject to the following restrictions: can be used by probes that are checking whether the library is actually installed. */ -extern "C" -{ - void btBulletDynamicsProbe (); - void btBulletDynamicsProbe () {} -} +extern "C" void btBulletDynamicsProbe () {} -btSimpleDynamicsWorld::btSimpleDynamicsWorld(btDispatcher* dispatcher,btBroadphaseInterface* pairCache,btConstraintSolver* constraintSolver,btCollisionConfiguration* collisionConfiguration) -:btDynamicsWorld(dispatcher,pairCache,collisionConfiguration), +btSimpleDynamicsWorld::btSimpleDynamicsWorld(btDispatcher* dispatcher,btOverlappingPairCache* pairCache,btConstraintSolver* constraintSolver) +:btDynamicsWorld(dispatcher,pairCache), m_constraintSolver(constraintSolver), m_ownsConstraintSolver(false), +m_debugDrawer(0), m_gravity(0,0,-10) { @@ -49,7 +46,7 @@ m_gravity(0,0,-10) btSimpleDynamicsWorld::~btSimpleDynamicsWorld() { if (m_ownsConstraintSolver) - btAlignedFree( m_constraintSolver); + delete m_constraintSolver; } int btSimpleDynamicsWorld::stepSimulation( btScalar timeStep,int maxSubSteps, btScalar fixedTimeStep) @@ -77,9 +74,8 @@ int btSimpleDynamicsWorld::stepSimulation( btScalar timeStep,int maxSubSteps, b btContactSolverInfo infoGlobal; infoGlobal.m_timeStep = timeStep; - m_constraintSolver->prepareSolve(0,numManifolds); - m_constraintSolver->solveGroup(0,0,manifoldPtr, numManifolds,0,0,infoGlobal,m_debugDrawer, m_stackAlloc,m_dispatcher1); - m_constraintSolver->allSolved(infoGlobal,m_debugDrawer, m_stackAlloc); + + m_constraintSolver->solveGroup(0,0,manifoldPtr, numManifolds,0,0,infoGlobal,m_debugDrawer, m_stackAlloc); } ///integrate transforms @@ -89,27 +85,10 @@ int btSimpleDynamicsWorld::stepSimulation( btScalar timeStep,int maxSubSteps, b synchronizeMotionStates(); - clearForces(); - return 1; } -void btSimpleDynamicsWorld::clearForces() -{ - //todo: iterate over awake simulation islands! - for ( int i=0;iclearForces(); - } - } -} - void btSimpleDynamicsWorld::setGravity(const btVector3& gravity) { @@ -125,11 +104,6 @@ void btSimpleDynamicsWorld::setGravity(const btVector3& gravity) } } -btVector3 btSimpleDynamicsWorld::getGravity () const -{ - return m_gravity; -} - void btSimpleDynamicsWorld::removeRigidBody(btRigidBody* body) { removeCollisionObject(body); @@ -159,7 +133,7 @@ void btSimpleDynamicsWorld::updateAabbs() btPoint3 minAabb,maxAabb; colObj->getCollisionShape()->getAabb(colObj->getWorldTransform(), minAabb,maxAabb); btBroadphaseInterface* bp = getBroadphase(); - bp->setAabb(body->getBroadphaseHandle(),minAabb,maxAabb, m_dispatcher1); + bp->setAabb(body->getBroadphaseHandle(),minAabb,maxAabb); } } } @@ -197,9 +171,8 @@ void btSimpleDynamicsWorld::predictUnconstraintMotion(btScalar timeStep) { if (body->isActive()) { - body->applyGravity(); + body->applyForces( timeStep); body->integrateVelocities( timeStep); - body->applyDamping(timeStep); body->predictIntegratedTransform(timeStep,body->getInterpolationWorldTransform()); } } @@ -231,13 +204,8 @@ void btSimpleDynamicsWorld::setConstraintSolver(btConstraintSolver* solver) { if (m_ownsConstraintSolver) { - btAlignedFree(m_constraintSolver); + delete m_constraintSolver; } m_ownsConstraintSolver = false; m_constraintSolver = solver; } - -btConstraintSolver* btSimpleDynamicsWorld::getConstraintSolver() -{ - return m_constraintSolver; -} diff --git a/extern/bullet2/src/BulletDynamics/Dynamics/btSimpleDynamicsWorld.h b/extern/bullet2/src/BulletDynamics/Dynamics/btSimpleDynamicsWorld.h index 5c56fdf1327..25f4ccd8e68 100644 --- a/extern/bullet2/src/BulletDynamics/Dynamics/btSimpleDynamicsWorld.h +++ b/extern/bullet2/src/BulletDynamics/Dynamics/btSimpleDynamicsWorld.h @@ -22,8 +22,11 @@ class btDispatcher; class btOverlappingPairCache; class btConstraintSolver; -///btSimpleDynamicsWorld serves as unit-test and to verify more complicated and optimized dynamics worlds. -///Please use btDiscreteDynamicsWorld instead (or btContinuousDynamicsWorld once it is finished). +///btSimpleDynamicsWorld demonstrates very basic usage of Bullet rigid body dynamics +///It can be used for basic simulations, and as a starting point for porting Bullet +///btSimpleDynamicsWorld lacks object deactivation, island management and other concepts. +///For more complicated simulations, btDiscreteDynamicsWorld and btContinuousDynamicsWorld are recommended +///those classes replace the obsolete CcdPhysicsEnvironment/CcdPhysicsController class btSimpleDynamicsWorld : public btDynamicsWorld { protected: @@ -32,6 +35,8 @@ protected: bool m_ownsConstraintSolver; + btIDebugDraw* m_debugDrawer; + void predictUnconstraintMotion(btScalar timeStep); void integrateTransforms(btScalar timeStep); @@ -43,16 +48,24 @@ public: ///this btSimpleDynamicsWorld constructor creates dispatcher, broadphase pairCache and constraintSolver - btSimpleDynamicsWorld(btDispatcher* dispatcher,btBroadphaseInterface* pairCache,btConstraintSolver* constraintSolver,btCollisionConfiguration* collisionConfiguration); + btSimpleDynamicsWorld(btDispatcher* dispatcher,btOverlappingPairCache* pairCache,btConstraintSolver* constraintSolver); virtual ~btSimpleDynamicsWorld(); ///maxSubSteps/fixedTimeStep for interpolation is currently ignored for btSimpleDynamicsWorld, use btDiscreteDynamicsWorld instead virtual int stepSimulation( btScalar timeStep,int maxSubSteps=1, btScalar fixedTimeStep=btScalar(1.)/btScalar(60.)); - virtual void setGravity(const btVector3& gravity); + virtual void setDebugDrawer(btIDebugDraw* debugDrawer) + { + m_debugDrawer = debugDrawer; + }; - virtual btVector3 getGravity () const; + virtual btIDebugDraw* getDebugDrawer() + { + return m_debugDrawer; + } + + virtual void setGravity(const btVector3& gravity); virtual void addRigidBody(btRigidBody* body); @@ -64,15 +77,6 @@ public: virtual void setConstraintSolver(btConstraintSolver* solver); - virtual btConstraintSolver* getConstraintSolver(); - - virtual btDynamicsWorldType getWorldType() const - { - return BT_SIMPLE_DYNAMICS_WORLD; - } - - virtual void clearForces(); - }; #endif //BT_SIMPLE_DYNAMICS_WORLD_H diff --git a/extern/bullet2/src/BulletDynamics/Vehicle/btRaycastVehicle.cpp b/extern/bullet2/src/BulletDynamics/Vehicle/btRaycastVehicle.cpp index fe65245c2a1..d53de7f3687 100644 --- a/extern/bullet2/src/BulletDynamics/Vehicle/btRaycastVehicle.cpp +++ b/extern/bullet2/src/BulletDynamics/Vehicle/btRaycastVehicle.cpp @@ -23,11 +23,12 @@ #include "BulletDynamics/ConstraintSolver/btContactConstraint.h" + + static btRigidBody s_fixedObject( 0,0,0); btRaycastVehicle::btRaycastVehicle(const btVehicleTuning& tuning,btRigidBody* chassis, btVehicleRaycaster* raycaster ) -: btTypedConstraint(VEHICLE_CONSTRAINT_TYPE), -m_vehicleRaycaster(raycaster), +:m_vehicleRaycaster(raycaster), m_pitchControl(btScalar(0.)) { m_chassisBody = chassis; @@ -486,7 +487,6 @@ struct btWheelContactPoint }; -btScalar calcRollingFriction(btWheelContactPoint& contactPoint); btScalar calcRollingFriction(btWheelContactPoint& contactPoint) { @@ -507,8 +507,8 @@ btScalar calcRollingFriction(btWheelContactPoint& contactPoint) // calculate j that moves us to zero relative velocity j1 = -vrel * contactPoint.m_jacDiagABInv; - btSetMin(j1, maxImpulse); - btSetMax(j1, -maxImpulse); + GEN_set_min(j1, maxImpulse); + GEN_set_max(j1, -maxImpulse); return j1; } @@ -525,10 +525,11 @@ void btRaycastVehicle::updateFriction(btScalar timeStep) if (!numWheel) return; - m_forwardWS.resize(numWheel); - m_axle.resize(numWheel); - m_forwardImpulse.resize(numWheel); - m_sideImpulse.resize(numWheel); + + btVector3* forwardWS = new btVector3[numWheel]; + btVector3* axle = new btVector3[numWheel]; + btScalar* forwardImpulse = new btScalar[numWheel]; + btScalar* sideImpulse = new btScalar[numWheel]; int numWheelsOnGround = 0; @@ -540,8 +541,8 @@ void btRaycastVehicle::updateFriction(btScalar timeStep) class btRigidBody* groundObject = (class btRigidBody*) wheelInfo.m_raycastInfo.m_groundObject; if (groundObject) numWheelsOnGround++; - m_sideImpulse[i] = btScalar(0.); - m_forwardImpulse[i] = btScalar(0.); + sideImpulse[i] = btScalar(0.); + forwardImpulse[i] = btScalar(0.); } @@ -560,25 +561,25 @@ void btRaycastVehicle::updateFriction(btScalar timeStep) const btTransform& wheelTrans = getWheelTransformWS( i ); btMatrix3x3 wheelBasis0 = wheelTrans.getBasis(); - m_axle[i] = btVector3( + axle[i] = btVector3( wheelBasis0[0][m_indexRightAxis], wheelBasis0[1][m_indexRightAxis], wheelBasis0[2][m_indexRightAxis]); const btVector3& surfNormalWS = wheelInfo.m_raycastInfo.m_contactNormalWS; - btScalar proj = m_axle[i].dot(surfNormalWS); - m_axle[i] -= surfNormalWS * proj; - m_axle[i] = m_axle[i].normalize(); + btScalar proj = axle[i].dot(surfNormalWS); + axle[i] -= surfNormalWS * proj; + axle[i] = axle[i].normalize(); - m_forwardWS[i] = surfNormalWS.cross(m_axle[i]); - m_forwardWS[i].normalize(); + forwardWS[i] = surfNormalWS.cross(axle[i]); + forwardWS[i].normalize(); resolveSingleBilateral(*m_chassisBody, wheelInfo.m_raycastInfo.m_contactPointWS, *groundObject, wheelInfo.m_raycastInfo.m_contactPointWS, - btScalar(0.), m_axle[i],m_sideImpulse[i],timeStep); + btScalar(0.), axle[i],sideImpulse[i],timeStep); - m_sideImpulse[i] *= sideFrictionStiffness2; + sideImpulse[i] *= sideFrictionStiffness2; } @@ -607,7 +608,7 @@ void btRaycastVehicle::updateFriction(btScalar timeStep) { btScalar defaultRollingFrictionImpulse = 0.f; btScalar maxImpulse = wheelInfo.m_brake ? wheelInfo.m_brake : defaultRollingFrictionImpulse; - btWheelContactPoint contactPt(m_chassisBody,groundObject,wheelInfo.m_raycastInfo.m_contactPointWS,m_forwardWS[wheel],maxImpulse); + btWheelContactPoint contactPt(m_chassisBody,groundObject,wheelInfo.m_raycastInfo.m_contactPointWS,forwardWS[wheel],maxImpulse); rollingFriction = calcRollingFriction(contactPt); } } @@ -617,7 +618,7 @@ void btRaycastVehicle::updateFriction(btScalar timeStep) - m_forwardImpulse[wheel] = btScalar(0.); + forwardImpulse[wheel] = btScalar(0.); m_wheelInfo[wheel].m_skidInfo= btScalar(1.); if (groundObject) @@ -630,10 +631,10 @@ void btRaycastVehicle::updateFriction(btScalar timeStep) btScalar maximpSquared = maximp * maximpSide; - m_forwardImpulse[wheel] = rollingFriction;//wheelInfo.m_engineForce* timeStep; + forwardImpulse[wheel] = rollingFriction;//wheelInfo.m_engineForce* timeStep; - btScalar x = (m_forwardImpulse[wheel] ) * fwdFactor; - btScalar y = (m_sideImpulse[wheel] ) * sideFactor; + btScalar x = (forwardImpulse[wheel] ) * fwdFactor; + btScalar y = (sideImpulse[wheel] ) * sideFactor; btScalar impulseSquared = (x*x + y*y); @@ -657,12 +658,12 @@ void btRaycastVehicle::updateFriction(btScalar timeStep) { for (int wheel = 0;wheel < getNumWheels(); wheel++) { - if (m_sideImpulse[wheel] != btScalar(0.)) + if (sideImpulse[wheel] != btScalar(0.)) { if (m_wheelInfo[wheel].m_skidInfo< btScalar(1.)) { - m_forwardImpulse[wheel] *= m_wheelInfo[wheel].m_skidInfo; - m_sideImpulse[wheel] *= m_wheelInfo[wheel].m_skidInfo; + forwardImpulse[wheel] *= m_wheelInfo[wheel].m_skidInfo; + sideImpulse[wheel] *= m_wheelInfo[wheel].m_skidInfo; } } } @@ -677,11 +678,11 @@ void btRaycastVehicle::updateFriction(btScalar timeStep) btVector3 rel_pos = wheelInfo.m_raycastInfo.m_contactPointWS - m_chassisBody->getCenterOfMassPosition(); - if (m_forwardImpulse[wheel] != btScalar(0.)) + if (forwardImpulse[wheel] != btScalar(0.)) { - m_chassisBody->applyImpulse(m_forwardWS[wheel]*(m_forwardImpulse[wheel]),rel_pos); + m_chassisBody->applyImpulse(forwardWS[wheel]*(forwardImpulse[wheel]),rel_pos); } - if (m_sideImpulse[wheel] != btScalar(0.)) + if (sideImpulse[wheel] != btScalar(0.)) { class btRigidBody* groundObject = (class btRigidBody*) m_wheelInfo[wheel].m_raycastInfo.m_groundObject; @@ -689,7 +690,7 @@ void btRaycastVehicle::updateFriction(btScalar timeStep) groundObject->getCenterOfMassPosition(); - btVector3 sideImp = m_axle[wheel] * m_sideImpulse[wheel]; + btVector3 sideImp = axle[wheel] * sideImpulse[wheel]; rel_pos[2] *= wheelInfo.m_rollInfluence; m_chassisBody->applyImpulse(sideImp,rel_pos); @@ -700,7 +701,10 @@ void btRaycastVehicle::updateFriction(btScalar timeStep) } } - + delete []forwardWS; + delete [] axle; + delete[]forwardImpulse; + delete[] sideImpulse; } @@ -712,11 +716,11 @@ void* btDefaultVehicleRaycaster::castRay(const btVector3& from,const btVector3& m_dynamicsWorld->rayTest(from, to, rayCallback); - if (rayCallback.hasHit()) + if (rayCallback.HasHit()) { btRigidBody* body = btRigidBody::upcast(rayCallback.m_collisionObject); - if (body && body->hasContactResponse()) + if (body) { result.m_hitPointInWorld = rayCallback.m_hitPointWorld; result.m_hitNormalInWorld = rayCallback.m_hitNormalWorld; diff --git a/extern/bullet2/src/BulletDynamics/Vehicle/btRaycastVehicle.h b/extern/bullet2/src/BulletDynamics/Vehicle/btRaycastVehicle.h index 8361dcabe4b..f4249599615 100644 --- a/extern/bullet2/src/BulletDynamics/Vehicle/btRaycastVehicle.h +++ b/extern/bullet2/src/BulletDynamics/Vehicle/btRaycastVehicle.h @@ -11,11 +11,11 @@ #ifndef RAYCASTVEHICLE_H #define RAYCASTVEHICLE_H -#include "BulletDynamics/Dynamics/btRigidBody.h" -#include "BulletDynamics/ConstraintSolver/btTypedConstraint.h" +#include "../Dynamics/btRigidBody.h" +#include "../ConstraintSolver/btTypedConstraint.h" #include "btVehicleRaycaster.h" class btDynamicsWorld; -#include "LinearMath/btAlignedObjectArray.h" +#include "../../LinearMath/btAlignedObjectArray.h" #include "btWheelInfo.h" class btVehicleTuning; @@ -23,12 +23,6 @@ class btVehicleTuning; ///rayCast vehicle, very special constraint that turn a rigidbody into a vehicle. class btRaycastVehicle : public btTypedConstraint { - - btAlignedObjectArray m_forwardWS; - btAlignedObjectArray m_axle; - btAlignedObjectArray m_forwardImpulse; - btAlignedObjectArray m_sideImpulse; - public: class btVehicleTuning { @@ -120,7 +114,7 @@ public: void updateSuspension(btScalar deltaTime); - virtual void updateFriction(btScalar timeStep); + void updateFriction(btScalar timeStep); diff --git a/extern/bullet2/src/BulletDynamics/Vehicle/btVehicleRaycaster.h b/extern/bullet2/src/BulletDynamics/Vehicle/btVehicleRaycaster.h index 5112ce6d420..64a47fcaada 100644 --- a/extern/bullet2/src/BulletDynamics/Vehicle/btVehicleRaycaster.h +++ b/extern/bullet2/src/BulletDynamics/Vehicle/btVehicleRaycaster.h @@ -11,7 +11,7 @@ #ifndef VEHICLE_RAYCASTER_H #define VEHICLE_RAYCASTER_H -#include "LinearMath/btVector3.h" +#include "../../LinearMath/btVector3.h" /// btVehicleRaycaster is provides interface for between vehicle simulation and raycasting struct btVehicleRaycaster diff --git a/extern/bullet2/src/BulletDynamics/Vehicle/btWheelInfo.h b/extern/bullet2/src/BulletDynamics/Vehicle/btWheelInfo.h index ac2729f4fd7..2e349b3fde4 100644 --- a/extern/bullet2/src/BulletDynamics/Vehicle/btWheelInfo.h +++ b/extern/bullet2/src/BulletDynamics/Vehicle/btWheelInfo.h @@ -11,8 +11,8 @@ #ifndef WHEEL_INFO_H #define WHEEL_INFO_H -#include "LinearMath/btVector3.h" -#include "LinearMath/btTransform.h" +#include "../../LinearMath/btVector3.h" +#include "../../LinearMath/btTransform.h" class btRigidBody; diff --git a/extern/bullet2/src/BulletSoftBody/CMakeLists.txt b/extern/bullet2/src/BulletSoftBody/CMakeLists.txt deleted file mode 100644 index a725e10ff77..00000000000 --- a/extern/bullet2/src/BulletSoftBody/CMakeLists.txt +++ /dev/null @@ -1,21 +0,0 @@ - -INCLUDE_DIRECTORIES( -${BULLET_PHYSICS_SOURCE_DIR}/src } -) - -ADD_LIBRARY(LibBulletSoftBody - btSoftBody.cpp - btSoftBody.h - btSoftBodyHelpers.cpp - btSparseSDF.h - btSoftBodyHelpers.h - btSoftBodyRigidBodyCollisionConfiguration.cpp - btSoftRigidCollisionAlgorithm.cpp - btSoftRigidCollisionAlgorithm.h - btSoftSoftCollisionAlgorithm.cpp - btSoftSoftCollisionAlgorithm.h - btSoftBodyConcaveCollisionAlgorithm.cpp - btSoftBodyConcaveCollisionAlgorithm.h - btSoftRigidDynamicsWorld.h - btSoftRigidDynamicsWorld.cpp -) diff --git a/extern/bullet2/src/BulletSoftBody/btSoftBody.cpp b/extern/bullet2/src/BulletSoftBody/btSoftBody.cpp deleted file mode 100644 index dfb48e2ff2d..00000000000 --- a/extern/bullet2/src/BulletSoftBody/btSoftBody.cpp +++ /dev/null @@ -1,2590 +0,0 @@ -/* -Bullet Continuous Collision Detection and Physics Library -Copyright (c) 2003-2006 Erwin Coumans http://continuousphysics.com/Bullet/ - -This software is provided 'as-is', without any express or implied warranty. -In no event will the authors be held liable for any damages arising from the use of this software. -Permission is granted to anyone to use this software for any purpose, -including commercial applications, and to alter it and redistribute it freely, -subject to the following restrictions: - -1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. -2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. -3. This notice may not be removed or altered from any source distribution. -*/ -///btSoftBody implementation by Nathanael Presson - -#include "btSoftBodyInternals.h" - -// -btSoftBody::btSoftBody(btSoftBodyWorldInfo* worldInfo,int node_count, const btVector3* x, const btScalar* m) -:m_worldInfo(worldInfo) -{ - /* Init */ - m_internalType = CO_SOFT_BODY; - m_cfg.aeromodel = eAeroModel::V_Point; - m_cfg.kVCF = 1; - m_cfg.kDG = 0; - m_cfg.kLF = 0; - m_cfg.kDP = 0; - m_cfg.kPR = 0; - m_cfg.kVC = 0; - m_cfg.kDF = (btScalar)0.2; - m_cfg.kMT = 0; - m_cfg.kCHR = (btScalar)1.0; - m_cfg.kKHR = (btScalar)0.1; - m_cfg.kSHR = (btScalar)1.0; - m_cfg.kAHR = (btScalar)0.7; - m_cfg.kSRHR_CL = (btScalar)0.1; - m_cfg.kSKHR_CL = (btScalar)1; - m_cfg.kSSHR_CL = (btScalar)0.5; - m_cfg.kSR_SPLT_CL = (btScalar)0.5; - m_cfg.kSK_SPLT_CL = (btScalar)0.5; - m_cfg.kSS_SPLT_CL = (btScalar)0.5; - m_cfg.maxvolume = (btScalar)1; - m_cfg.timescale = 1; - m_cfg.viterations = 0; - m_cfg.piterations = 1; - m_cfg.diterations = 0; - m_cfg.citerations = 4; - m_cfg.collisions = fCollision::Default; - m_pose.m_bvolume = false; - m_pose.m_bframe = false; - m_pose.m_volume = 0; - m_pose.m_com = btVector3(0,0,0); - m_pose.m_rot.setIdentity(); - m_pose.m_scl.setIdentity(); - m_tag = 0; - m_timeacc = 0; - m_bUpdateRtCst = true; - m_bounds[0] = btVector3(0,0,0); - m_bounds[1] = btVector3(0,0,0); - m_worldTransform.setIdentity(); - setSolver(eSolverPresets::Positions); - /* Default material */ - Material* pm=appendMaterial(); - pm->m_kLST = 1; - pm->m_kAST = 1; - pm->m_kVST = 1; - pm->m_flags = fMaterial::Default; - /* Collision shape */ - ///for now, create a collision shape internally - setCollisionShape(new btSoftBodyCollisionShape(this)); - m_collisionShape->setMargin(0.25); - /* Nodes */ - const btScalar margin=getCollisionShape()->getMargin(); - m_nodes.resize(node_count); - for(int i=0,ni=node_count;i0?1/n.m_im:0; - n.m_leaf = m_ndbvt.insert(btDbvtVolume::FromCR(n.m_x,margin),&n); - n.m_material= pm; - } - updateBounds(); - - -} - -// -btSoftBody::~btSoftBody() -{ - //for now, delete the internal shape - delete m_collisionShape; - int i; - - for(i=0;i0) - *pm=*m_materials[0]; - else - ZeroInitialize(*pm); -m_materials.push_back(pm); -return(pm); -} - -// -void btSoftBody::appendNote( const char* text, - const btVector3& o, - const btVector4& c, - Node* n0, - Node* n1, - Node* n2, - Node* n3) -{ -Note n; -ZeroInitialize(n); -n.m_rank = 0; -n.m_text = text; -n.m_offset = o; -n.m_coords[0] = c.x(); -n.m_coords[1] = c.y(); -n.m_coords[2] = c.z(); -n.m_coords[3] = c.w(); -n.m_nodes[0] = n0;n.m_rank+=n0?1:0; -n.m_nodes[1] = n1;n.m_rank+=n1?1:0; -n.m_nodes[2] = n2;n.m_rank+=n2?1:0; -n.m_nodes[3] = n3;n.m_rank+=n3?1:0; -m_notes.push_back(n); -} - -// -void btSoftBody::appendNote( const char* text, - const btVector3& o, - Node* feature) -{ -appendNote(text,o,btVector4(1,0,0,0),feature); -} - -// -void btSoftBody::appendNote( const char* text, - const btVector3& o, - Link* feature) -{ -static const btScalar w=1/(btScalar)2; -appendNote(text,o,btVector4(w,w,0,0), feature->m_n[0], - feature->m_n[1]); -} - -// -void btSoftBody::appendNote( const char* text, - const btVector3& o, - Face* feature) -{ -static const btScalar w=1/(btScalar)3; -appendNote(text,o,btVector4(w,w,w,0), feature->m_n[0], - feature->m_n[1], - feature->m_n[2]); -} - -// -void btSoftBody::appendNode( const btVector3& x,btScalar m) -{ -if(m_nodes.capacity()==m_nodes.size()) - { - pointersToIndices(); - m_nodes.reserve(m_nodes.size()*2+1); - indicesToPointers(); - } -const btScalar margin=getCollisionShape()->getMargin(); -m_nodes.push_back(Node()); -Node& n=m_nodes[m_nodes.size()-1]; -ZeroInitialize(n); -n.m_x = x; -n.m_q = n.m_x; -n.m_im = m>0?1/m:0; -n.m_material = m_materials[0]; -n.m_leaf = m_ndbvt.insert(btDbvtVolume::FromCR(n.m_x,margin),&n); -} - -// -void btSoftBody::appendLink(int model,Material* mat) -{ -Link l; -if(model>=0) - l=m_links[model]; - else - { ZeroInitialize(l);l.m_material=mat?mat:m_materials[0]; } -m_links.push_back(l); -} - -// -void btSoftBody::appendLink( int node0, - int node1, - Material* mat, - bool bcheckexist) -{ - appendLink(&m_nodes[node0],&m_nodes[node1],mat,bcheckexist); -} - -// -void btSoftBody::appendLink( Node* node0, - Node* node1, - Material* mat, - bool bcheckexist) -{ - if((!bcheckexist)||(!checkLink(node0,node1))) - { - appendLink(-1,mat); - Link& l=m_links[m_links.size()-1]; - l.m_n[0] = node0; - l.m_n[1] = node1; - l.m_rl = (l.m_n[0]->m_x-l.m_n[1]->m_x).length(); - m_bUpdateRtCst=true; - } -} - -// -void btSoftBody::appendFace(int model,Material* mat) -{ -Face f; -if(model>=0) - { f=m_faces[model]; } - else - { ZeroInitialize(f);f.m_material=mat?mat:m_materials[0]; } -m_faces.push_back(f); -} - -// -void btSoftBody::appendFace(int node0,int node1,int node2,Material* mat) -{ - appendFace(-1,mat); - Face& f=m_faces[m_faces.size()-1]; - btAssert(node0!=node1); - btAssert(node1!=node2); - btAssert(node2!=node0); - f.m_n[0] = &m_nodes[node0]; - f.m_n[1] = &m_nodes[node1]; - f.m_n[2] = &m_nodes[node2]; - f.m_ra = AreaOf( f.m_n[0]->m_x, - f.m_n[1]->m_x, - f.m_n[2]->m_x); - m_bUpdateRtCst=true; -} - -// -void btSoftBody::appendAnchor(int node,btRigidBody* body) -{ - Anchor a; - a.m_node = &m_nodes[node]; - a.m_body = body; - a.m_local = body->getInterpolationWorldTransform().inverse()*a.m_node->m_x; - a.m_node->m_battach = 1; - m_anchors.push_back(a); -} - -// -void btSoftBody::appendLinearJoint(const LJoint::Specs& specs,Cluster* body0,Body body1) -{ -LJoint* pj = new(btAlignedAlloc(sizeof(LJoint),16)) LJoint(); -pj->m_bodies[0] = body0; -pj->m_bodies[1] = body1; -pj->m_refs[0] = pj->m_bodies[0].xform().inverse()*specs.position; -pj->m_refs[1] = pj->m_bodies[1].xform().inverse()*specs.position; -pj->m_cfm = specs.cfm; -pj->m_erp = specs.erp; -pj->m_split = specs.split; -m_joints.push_back(pj); -} - -// -void btSoftBody::appendLinearJoint(const LJoint::Specs& specs,Body body) -{ -appendLinearJoint(specs,m_clusters[0],body); -} - -// -void btSoftBody::appendLinearJoint(const LJoint::Specs& specs,btSoftBody* body) -{ -appendLinearJoint(specs,m_clusters[0],body->m_clusters[0]); -} - -// -void btSoftBody::appendAngularJoint(const AJoint::Specs& specs,Cluster* body0,Body body1) -{ -AJoint* pj = new(btAlignedAlloc(sizeof(AJoint),16)) AJoint(); -pj->m_bodies[0] = body0; -pj->m_bodies[1] = body1; -pj->m_refs[0] = pj->m_bodies[0].xform().inverse().getBasis()*specs.axis; -pj->m_refs[1] = pj->m_bodies[1].xform().inverse().getBasis()*specs.axis; -pj->m_cfm = specs.cfm; -pj->m_erp = specs.erp; -pj->m_split = specs.split; -pj->m_icontrol = specs.icontrol; -m_joints.push_back(pj); -} - -// -void btSoftBody::appendAngularJoint(const AJoint::Specs& specs,Body body) -{ -appendAngularJoint(specs,m_clusters[0],body); -} - -// -void btSoftBody::appendAngularJoint(const AJoint::Specs& specs,btSoftBody* body) -{ -appendAngularJoint(specs,m_clusters[0],body->m_clusters[0]); -} - -// -void btSoftBody::addForce(const btVector3& force) -{ - for(int i=0,ni=m_nodes.size();i0) - { - n.m_f += force; - } -} - -// -void btSoftBody::addVelocity(const btVector3& velocity) -{ - for(int i=0,ni=m_nodes.size();i0) - { - n.m_v += velocity; - } -} - -// -void btSoftBody::setMass(int node,btScalar mass) -{ - m_nodes[node].m_im=mass>0?1/mass:0; - m_bUpdateRtCst=true; -} - -// -btScalar btSoftBody::getMass(int node) const -{ - return(m_nodes[node].m_im>0?1/m_nodes[node].m_im:0); -} - -// -btScalar btSoftBody::getTotalMass() const -{ - btScalar mass=0; - for(int i=0;im_x, - f.m_n[1]->m_x, - f.m_n[2]->m_x); - for(int j=0;j<3;++j) - { - f.m_n[j]->m_im+=twicearea; - } - } - for( i=0;igetMargin(); - for(int i=0,ni=m_nodes.size();igetMargin(); - for(int i=0,ni=m_nodes.size();i0 ? - 1/(m_nodes[i].m_im*tmass) : - kmass/tmass; - } - /* Pos */ - const btVector3 com=evaluateCom(); - m_pose.m_pos.resize(m_nodes.size()); - for( i=0,ni=m_nodes.size();i0) - { - int i,ni; - - const btVector3 org=m_nodes[0].m_x; - for(i=0,ni=m_faces.size();im_x-org,cross(f.m_n[1]->m_x-org,f.m_n[2]->m_x-org)); - } - vol/=(btScalar)6; - } - return(vol); -} - -// -int btSoftBody::clusterCount() const -{ -return(m_clusters.size()); -} - -// -btVector3 btSoftBody::clusterCom(const Cluster* cluster) -{ -btVector3 com(0,0,0); -for(int i=0,ni=cluster->m_nodes.size();im_nodes[i]->m_x*cluster->m_masses[i]; - } -return(com*cluster->m_imass); -} - -// -btVector3 btSoftBody::clusterCom(int cluster) const -{ -return(clusterCom(m_clusters[cluster])); -} - -// -btVector3 btSoftBody::clusterVelocity(const Cluster* cluster,const btVector3& rpos) -{ -return(cluster->m_lv+cross(cluster->m_av,rpos)); -} - -// -void btSoftBody::clusterVImpulse(Cluster* cluster,const btVector3& rpos,const btVector3& impulse) -{ -const btVector3 li=cluster->m_imass*impulse; -const btVector3 ai=cluster->m_invwi*cross(rpos,impulse); -cluster->m_vimpulses[0]+=li;cluster->m_lv+=li; -cluster->m_vimpulses[1]+=ai;cluster->m_av+=ai; -cluster->m_nvimpulses++; -} - -// -void btSoftBody::clusterDImpulse(Cluster* cluster,const btVector3& rpos,const btVector3& impulse) -{ -const btVector3 li=cluster->m_imass*impulse; -const btVector3 ai=cluster->m_invwi*cross(rpos,impulse); -cluster->m_dimpulses[0]+=li; -cluster->m_dimpulses[1]+=ai; -cluster->m_ndimpulses++; -} - -// -void btSoftBody::clusterImpulse(Cluster* cluster,const btVector3& rpos,const Impulse& impulse) -{ -if(impulse.m_asVelocity) clusterVImpulse(cluster,rpos,impulse.m_velocity); -if(impulse.m_asDrift) clusterDImpulse(cluster,rpos,impulse.m_drift); -} - -// -void btSoftBody::clusterVAImpulse(Cluster* cluster,const btVector3& impulse) -{ -const btVector3 ai=cluster->m_invwi*impulse; -cluster->m_vimpulses[1]+=ai;cluster->m_av+=ai; -cluster->m_nvimpulses++; -} - -// -void btSoftBody::clusterDAImpulse(Cluster* cluster,const btVector3& impulse) -{ -const btVector3 ai=cluster->m_invwi*impulse; -cluster->m_dimpulses[1]+=ai; -cluster->m_ndimpulses++; -} - -// -void btSoftBody::clusterAImpulse(Cluster* cluster,const Impulse& impulse) -{ -if(impulse.m_asVelocity) clusterVAImpulse(cluster,impulse.m_velocity); -if(impulse.m_asDrift) clusterDAImpulse(cluster,impulse.m_drift); -} - -// -void btSoftBody::clusterDCImpulse(Cluster* cluster,const btVector3& impulse) -{ -cluster->m_dimpulses[0]+=impulse*cluster->m_imass; -cluster->m_ndimpulses++; -} - -// -int btSoftBody::generateBendingConstraints(int distance,Material* mat) -{ - int i,j; - - if(distance>1) - { - /* Build graph */ - const int n=m_nodes.size(); - const unsigned inf=(~(unsigned)0)>>1; - unsigned* adj=new unsigned[n*n]; -#define IDX(_x_,_y_) ((_y_)*n+(_x_)) - for(j=0;jsum) - { - adj[IDX(i,j)]=adj[IDX(j,i)]=sum; - } - } - } - } - /* Build links */ - int nlinks=0; - for(j=0;jm_leaf) m_cdbvt.remove(m_clusters[i]->m_leaf); - btAlignedFree(m_clusters[i]); - } -m_clusters.resize(btMin(k,m_nodes.size())); - - - -for(i=0;im_collide= true; - } -k=m_clusters.size(); -if(k>0) - { - /* Initialize */ - btAlignedObjectArray centers; - btVector3 cog(0,0,0); - int i; - for(i=0;im_nodes.push_back(&m_nodes[i]); - } - cog/=(btScalar)m_nodes.size(); - centers.resize(k,cog); - /* Iterate */ - const btScalar slope=16; - bool changed; - int iterations=0; - do { - const btScalar w=2-btMin(1,iterations/slope); - changed=false; - iterations++; - int i; - - for(i=0;im_nodes.size();++j) - { - c+=m_clusters[i]->m_nodes[j]->m_x; - } - if(m_clusters[i]->m_nodes.size()) - { - c /= (btScalar)m_clusters[i]->m_nodes.size(); - c = centers[i]+(c-centers[i])*w; - changed |= ((c-centers[i]).length2()>SIMD_EPSILON); - centers[i] = c; - m_clusters[i]->m_nodes.resize(0); - } - } - for(i=0;im_nodes.push_back(&m_nodes[i]); - } - } while(changed&&(iterations cids; - cids.resize(m_nodes.size(),-1); - for(i=0;im_nodes.size();++j) - { - cids[int(m_clusters[i]->m_nodes[j]-&m_nodes[0])]=i; - } - } - for(i=0;im_nodes.findLinearSearch(&m_nodes[kid])==m_clusters[cid]->m_nodes.size()) - { - m_clusters[cid]->m_nodes.push_back(&m_nodes[kid]); - } - } - } - } - } - /* Master */ - if(m_clusters.size()>1) - { - Cluster* pmaster=new(btAlignedAlloc(sizeof(Cluster),16)) Cluster(); - pmaster->m_collide = false; - pmaster->m_nodes.reserve(m_nodes.size()); - for(int i=0;im_nodes.push_back(&m_nodes[i]); - m_clusters.push_back(pmaster); - btSwap(m_clusters[0],m_clusters[m_clusters.size()-1]); - } - /* Terminate */ - for(i=0;im_nodes.size()==0) - { - btAlignedFree(m_clusters[i]); - btSwap(m_clusters[i],m_clusters[m_clusters.size()-1]); - m_clusters.pop_back(); - --i; - } - } - - initializeClusters(); - updateClusters(); - return(m_clusters.size()); - } -return(0); -} - -// -void btSoftBody::refine(ImplicitFn* ifn,btScalar accurary,bool cut) -{ -const Node* nbase = &m_nodes[0]; -int ncount = m_nodes.size(); -btSymMatrix edges(ncount,-2); -int newnodes=0; -int i,j,k,ni; - -/* Filter out */ -for(i=0;iEval(l.m_n[0]->m_x),ifn->Eval(l.m_n[1]->m_x))) - { - btSwap(m_links[i],m_links[m_links.size()-1]); - m_links.pop_back();--i; - } - } - } -/* Fill edges */ -for(i=0;i0) - { - const btVector3 x=Lerp(a.m_x,b.m_x,t); - const btVector3 v=Lerp(a.m_v,b.m_v,t); - btScalar m=0; - if(a.m_im>0) - { - if(b.m_im>0) - { - const btScalar ma=1/a.m_im; - const btScalar mb=1/b.m_im; - const btScalar mc=Lerp(ma,mb,t); - const btScalar f=(ma+mb)/(ma+mb+mc); - a.m_im=1/(ma*f); - b.m_im=1/(mb*f); - m=mc*f; - } - else - { a.m_im/=0.5;m=1/a.m_im; } - } - else - { - if(b.m_im>0) - { b.m_im/=0.5;m=1/b.m_im; } - else - m=0; - } - appendNode(x,m); - edges(i,j)=m_nodes.size()-1; - m_nodes[edges(i,j)].m_v=v; - ++newnodes; - } - } - } - } -nbase=&m_nodes[0]; -/* Refine links */ -for(i=0,ni=m_links.size();i0) - { - appendLink(i); - Link* pft[]={ &m_links[i], - &m_links[m_links.size()-1]}; - pft[0]->m_n[0]=&m_nodes[idx[0]]; - pft[0]->m_n[1]=&m_nodes[ni]; - pft[1]->m_n[0]=&m_nodes[ni]; - pft[1]->m_n[1]=&m_nodes[idx[1]]; - } - } - } -/* Refine faces */ -for(i=0;i0) - { - appendFace(i); - const int l=(k+1)%3; - Face* pft[]={ &m_faces[i], - &m_faces[m_faces.size()-1]}; - pft[0]->m_n[0]=&m_nodes[idx[l]]; - pft[0]->m_n[1]=&m_nodes[idx[j]]; - pft[0]->m_n[2]=&m_nodes[ni]; - pft[1]->m_n[0]=&m_nodes[ni]; - pft[1]->m_n[1]=&m_nodes[idx[k]]; - pft[1]->m_n[2]=&m_nodes[idx[l]]; - appendLink(ni,idx[l],pft[0]->m_material); - --i;break; - } - } - } - } -/* Cut */ -if(cut) - { - btAlignedObjectArray cnodes; - const int pcount=ncount; - int i; - ncount=m_nodes.size(); - cnodes.resize(ncount,0); - /* Nodes */ - for(i=0;i=pcount)||(btFabs(ifn->Eval(x))0) { m*=0.5;m_nodes[i].m_im/=0.5; } - appendNode(x,m); - cnodes[i]=m_nodes.size()-1; - m_nodes[cnodes[i]].m_v=v; - } - } - nbase=&m_nodes[0]; - /* Links */ - for(i=0,ni=m_links.size();iEval(m_nodes[id[0]].m_x)Eval(m_nodes[id[1]].m_x)Eval(n[0]->m_x)Eval(n[1]->m_x)Eval(n[2]->m_x) ranks; - btAlignedObjectArray todelete; - ranks.resize(nnodes,0); - for(i=0,ni=m_links.size();i=0;--i) - { - if(!ranks[i]) todelete.push_back(i); - } - if(todelete.size()) - { - btAlignedObjectArray& map=ranks; - for(int i=0;im_v=v; -pn[1]->m_v=v; -for(i=0,ni=m_links.size();im_n[1]=pn[mtch]; - pft[1]->m_n[0]=pn[1-mtch]; - done=true; - } - } -for(i=0,ni=m_faces.size();im_n[l]=pn[mtch]; - pft[1]->m_n[k]=pn[1-mtch]; - appendLink(pn[0],pft[0]->m_n[(l+1)%3],pft[0]->m_material,true); - appendLink(pn[1],pft[0]->m_n[(l+1)%3],pft[0]->m_material,true); - } - } - } -if(!done) - { - m_ndbvt.remove(pn[0]->m_leaf); - m_ndbvt.remove(pn[1]->m_leaf); - m_nodes.pop_back(); - m_nodes.pop_back(); - } -return(done); -} - -// -bool btSoftBody::rayCast(const btVector3& org, - const btVector3& dir, - sRayCast& results, - btScalar maxtime) -{ -if(m_faces.size()&&m_fdbvt.empty()) initializeFaceTree(); -results.body = this; -results.time = maxtime; -results.feature = eFeature::None; -results.index = -1; -return(rayCast(org,dir,results.time,results.feature,results.index,false)!=0); -} - -// -void btSoftBody::setSolver(eSolverPresets::_ preset) -{ -m_cfg.m_vsequence.clear(); -m_cfg.m_psequence.clear(); -m_cfg.m_dsequence.clear(); -switch(preset) - { - case eSolverPresets::Positions: - m_cfg.m_psequence.push_back(ePSolver::Anchors); - m_cfg.m_psequence.push_back(ePSolver::RContacts); - m_cfg.m_psequence.push_back(ePSolver::SContacts); - m_cfg.m_psequence.push_back(ePSolver::Linear); - break; - case eSolverPresets::Velocities: - m_cfg.m_vsequence.push_back(eVSolver::Linear); - - m_cfg.m_psequence.push_back(ePSolver::Anchors); - m_cfg.m_psequence.push_back(ePSolver::RContacts); - m_cfg.m_psequence.push_back(ePSolver::SContacts); - - m_cfg.m_dsequence.push_back(ePSolver::Linear); - break; - } -} - -// -void btSoftBody::predictMotion(btScalar dt) -{ - int i,ni; - - /* Update */ - if(m_bUpdateRtCst) - { - m_bUpdateRtCst=false; - updateConstants(); - m_fdbvt.clear(); - if(m_cfg.collisions&fCollision::VF_SS) - { - initializeFaceTree(); - } - } - - /* Prepare */ - m_sst.sdt = dt*m_cfg.timescale; - m_sst.isdt = 1/m_sst.sdt; - m_sst.velmrg = m_sst.sdt*3; - m_sst.radmrg = getCollisionShape()->getMargin(); - m_sst.updmrg = m_sst.radmrg*(btScalar)0.25; - /* Forces */ - addVelocity(m_worldInfo->m_gravity*m_sst.sdt); - applyForces(); - /* Integrate */ - for(i=0,ni=m_nodes.size();im_v+ - f.m_n[1]->m_v+ - f.m_n[2]->m_v)/3; - m_fdbvt.update( f.m_leaf, - VolumeOf(f,m_sst.radmrg), - v*m_sst.velmrg, - m_sst.updmrg); - } - } - /* Pose */ - updatePose(); - /* Match */ - if(m_pose.m_bframe&&(m_cfg.kMT>0)) - { - const btMatrix3x3 posetrs=m_pose.m_rot; - for(int i=0,ni=m_nodes.size();i0) - { - const btVector3 x=posetrs*m_pose.m_pos[i]+m_pose.m_com; - n.m_x=Lerp(n.m_x,x,m_cfg.kMT); - } - } - } - /* Clear contacts */ - m_rcontacts.resize(0); - m_scontacts.resize(0); - /* Optimize dbvt's */ - m_ndbvt.optimizeIncremental(1); - m_fdbvt.optimizeIncremental(1); - m_cdbvt.optimizeIncremental(1); -} - -// -void btSoftBody::solveConstraints() -{ -/* Apply clusters */ -applyClusters(false); -/* Prepare links */ - -int i,ni; - -for(i=0,ni=m_links.size();im_q-l.m_n[0]->m_q; - l.m_c2 = 1/(l.m_c3.length2()*l.m_c0); - } -/* Prepare anchors */ -for(i=0,ni=m_anchors.size();igetWorldTransform().getBasis()*a.m_local; - a.m_c0 = ImpulseMatrix( m_sst.sdt, - a.m_node->m_im, - a.m_body->getInvMass(), - a.m_body->getInvInertiaTensorWorld(), - ra); - a.m_c1 = ra; - a.m_c2 = m_sst.sdt*a.m_node->m_im; - a.m_body->activate(); - } -/* Solve velocities */ -if(m_cfg.viterations>0) - { - /* Solve */ - for(int isolve=0;isolve0) - { - for(int isolve=0;isolve0) - { - const btScalar vcf=m_cfg.kVCF*m_sst.isdt; - for(i=0,ni=m_nodes.size();i& bodies) -{ -const int nb=bodies.size(); -int iterations=0; -int i; - -for(i=0;im_cfg.citerations); - } -for(i=0;iprepareClusters(iterations); - } -for(i=0;isolveClusters(sor); - } - } -for(i=0;icleanupClusters(); - } -} - -// -void btSoftBody::integrateMotion() -{ - /* Update */ - updateNormals(); -} - -// - btSoftBody::RayCaster::RayCaster(const btVector3& org,const btVector3& dir,btScalar mxt) -{ -o = org; -d = dir; -mint = mxt; -face = 0; -tests = 0; -} - -// -void btSoftBody::RayCaster::Process(const btDbvtNode* leaf) -{ -btSoftBody::Face& f=*(btSoftBody::Face*)leaf->data; -const btScalar t=rayTriangle( o,d, - f.m_n[0]->m_x, - f.m_n[1]->m_x, - f.m_n[2]->m_x, - mint); -if((t>0)&&(tteps)&&(tceps) && - (dot(n,cross(b-hit,c-hit))>ceps) && - (dot(n,cross(c-hit,a-hit))>ceps)) - { - return(t); - } - } - } - return(-1); -} - -// -void btSoftBody::pointersToIndices() -{ -#define PTR2IDX(_p_,_b_) reinterpret_cast((_p_)-(_b_)) - btSoftBody::Node* base=&m_nodes[0]; - int i,ni; - - for(i=0,ni=m_nodes.size();idata=*(void**)&i; - } - } - for(i=0,ni=m_links.size();idata=*(void**)&i; - } - } - for(i=0,ni=m_anchors.size();idata=&m_nodes[i]; - } - } - for(i=0,ni=m_links.size();idata=&m_faces[i]; - } - } - for(i=0,ni=m_anchors.size();im_x, - f.m_n[1]->m_x, - f.m_n[2]->m_x, - mint); - if(t>0) - { - ++cnt; - if(!bcountonly) - { - feature=btSoftBody::eFeature::Face; - index=i; - mint=t; - } - } - } - } - else - {/* Use dbvt */ - RayCaster collider(org,dir,mint); - btDbvt::collideRAY(m_fdbvt.m_root,org,dir,collider); - if(collider.face) - { - mint=collider.mint; - feature=btSoftBody::eFeature::Face; - index=(int)(collider.face-&m_faces[0]); - cnt=1; - } - } - return(cnt); -} - -// -void btSoftBody::initializeFaceTree() -{ -m_fdbvt.clear(); -for(int i=0;igetCollisionShape(); - const btTransform& wtr=prb->getInterpolationWorldTransform(); - btScalar dst=m_worldInfo->m_sparsesdf.Evaluate( wtr.invXform(x), - shp, - nrm, - margin); - if(dst<0) - { - cti.m_body = prb; - cti.m_normal = wtr.getBasis()*nrm; - cti.m_offset = -dot( cti.m_normal, - x-cti.m_normal*dst); - return(true); - } - return(false); -} - -// -void btSoftBody::updateNormals() -{ - const btVector3 zv(0,0,0); - int i,ni; - - for(i=0,ni=m_nodes.size();im_x-f.m_n[0]->m_x, - f.m_n[2]->m_x-f.m_n[0]->m_x); - f.m_normal=n.normalized(); - f.m_n[0]->m_n+=n; - f.m_n[1]->m_n+=n; - f.m_n[2]->m_n+=n; - } - for(i=0,ni=m_nodes.size();iSIMD_EPSILON) - m_nodes[i].m_n /= len; - } -} - -// -void btSoftBody::updateBounds() -{ - if(m_ndbvt.m_root) - { - const btVector3& mins=m_ndbvt.m_root->volume.Mins(); - const btVector3& maxs=m_ndbvt.m_root->volume.Maxs(); - const btScalar csm=getCollisionShape()->getMargin(); - const btVector3 mrg=btVector3( csm, - csm, - csm)*1; // ??? to investigate... - m_bounds[0]=mins-mrg; - m_bounds[1]=maxs+mrg; - if(0!=getBroadphaseHandle()) - { - m_worldInfo->m_broadphase->setAabb( getBroadphaseHandle(), - m_bounds[0], - m_bounds[1], - m_worldInfo->m_dispatcher); - } - } - else - { - m_bounds[0]= - m_bounds[1]=btVector3(0,0,0); - } -} - - -// -void btSoftBody::updatePose() -{ - if(m_pose.m_bframe) - { - btSoftBody::Pose& pose=m_pose; - const btVector3 com=evaluateCom(); - /* Com */ - pose.m_com = com; - /* Rotation */ - btMatrix3x3 Apq; - const btScalar eps=SIMD_EPSILON; - Apq[0]=Apq[1]=Apq[2]=btVector3(0,0,0); - Apq[0].setX(eps);Apq[1].setY(eps*2);Apq[2].setZ(eps*3); - for(int i=0,ni=m_nodes.size();i1) - { - const btScalar idet=Clamp( 1/pose.m_scl.determinant(), - 1,m_cfg.maxvolume); - pose.m_scl=Mul(pose.m_scl,idet); - } - - } -} - -// -void btSoftBody::updateConstants() -{ - int i,ni; - - /* Links */ - for(i=0,ni=m_links.size();im_x-l.m_n[1]->m_x).length(); - l.m_c0 = (l.m_n[0]->m_im+l.m_n[1]->m_im)/m.m_kLST; - l.m_c1 = l.m_rl*l.m_rl; - } - /* Faces */ - for(i=0,ni=m_faces.size();im_x,f.m_n[1]->m_x,f.m_n[2]->m_x); - } - /* Area's */ - btAlignedObjectArray counts; - counts.resize(m_nodes.size(),0); - for(i=0,ni=m_nodes.size();im_area+=btFabs(f.m_ra); - } - } - for(i=0,ni=m_nodes.size();i0) - m_nodes[i].m_area/=(btScalar)counts[i]; - else - m_nodes[i].m_area=0; - } -} - -// -void btSoftBody::initializeClusters() -{ - int i; - -for( i=0;im_im>0?1/c.m_nodes[j]->m_im:0; - c.m_imass += c.m_masses[j]; - } - c.m_imass = 1/c.m_imass; - c.m_com = btSoftBody::clusterCom(&c); - c.m_lv = btVector3(0,0,0); - c.m_av = btVector3(0,0,0); - c.m_leaf = 0; - /* Inertia */ - btMatrix3x3& ii=c.m_locii; - ii[0]=ii[1]=ii[2]=btVector3(0,0,0); - { - int i,ni; - - for(i=0,ni=c.m_nodes.size();im_x-c.m_com; - const btVector3 q=k*k; - const btScalar m=c.m_masses[i]; - ii[0][0] += m*(q[1]+q[2]); - ii[1][1] += m*(q[0]+q[2]); - ii[2][2] += m*(q[0]+q[1]); - ii[0][1] -= m*k[0]*k[1]; - ii[0][2] -= m*k[0]*k[2]; - ii[1][2] -= m*k[1]*k[2]; - } - } - ii[1][0]=ii[0][1]; - ii[2][0]=ii[0][2]; - ii[2][1]=ii[1][2]; - ii=ii.inverse(); - /* Frame */ - c.m_framexform.setIdentity(); - c.m_framexform.setOrigin(c.m_com); - c.m_framerefs.resize(c.m_nodes.size()); - { - int i; - for(i=0;im_x-c.m_com; - } - } - } -} - -// -void btSoftBody::updateClusters() -{ -BT_PROFILE("UpdateClusters"); -int i; - -for(i=0;im_x-c.m_com; - const btVector3& b=c.m_framerefs[i]; - m[0]+=a[0]*b;m[1]+=a[1]*b;m[2]+=a[2]*b; - } - PolarDecompose(m,r,s); - c.m_framexform.setOrigin(c.m_com); - c.m_framexform.setBasis(r); - /* Inertia */ - #if 1/* Constant */ - c.m_invwi=c.m_framexform.getBasis()*c.m_locii*c.m_framexform.getBasis().transpose(); - #else - #if 0/* Sphere */ - const btScalar rk=(2*c.m_extents.length2())/(5*c.m_imass); - const btVector3 inertia(rk,rk,rk); - const btVector3 iin(btFabs(inertia[0])>SIMD_EPSILON?1/inertia[0]:0, - btFabs(inertia[1])>SIMD_EPSILON?1/inertia[1]:0, - btFabs(inertia[2])>SIMD_EPSILON?1/inertia[2]:0); - - c.m_invwi=c.m_xform.getBasis().scaled(iin)*c.m_xform.getBasis().transpose(); - #else/* Actual */ - c.m_invwi[0]=c.m_invwi[1]=c.m_invwi[2]=btVector3(0,0,0); - for(int i=0;im_x-c.m_com; - const btVector3 q=k*k; - const btScalar m=1/c.m_nodes[i]->m_im; - c.m_invwi[0][0] += m*(q[1]+q[2]); - c.m_invwi[1][1] += m*(q[0]+q[2]); - c.m_invwi[2][2] += m*(q[0]+q[1]); - c.m_invwi[0][1] -= m*k[0]*k[1]; - c.m_invwi[0][2] -= m*k[0]*k[2]; - c.m_invwi[1][2] -= m*k[1]*k[2]; - } - c.m_invwi[1][0]=c.m_invwi[0][1]; - c.m_invwi[2][0]=c.m_invwi[0][2]; - c.m_invwi[2][1]=c.m_invwi[1][2]; - c.m_invwi=c.m_invwi.inverse(); - #endif - #endif - /* Velocities */ - c.m_lv=btVector3(0,0,0); - c.m_av=btVector3(0,0,0); - { - int i; - - for(i=0;im_v*c.m_masses[i]; - c.m_lv += v; - c.m_av += cross(c.m_nodes[i]->m_x-c.m_com,v); - } - } - c.m_lv=c.m_imass*c.m_lv*(1-c.m_ldamping); - c.m_av=c.m_invwi*c.m_av*(1-c.m_adamping); - c.m_vimpulses[0] = - c.m_vimpulses[1] = btVector3(0,0,0); - c.m_dimpulses[0] = - c.m_dimpulses[1] = btVector3(0,0,0); - c.m_nvimpulses = 0; - c.m_ndimpulses = 0; - /* Matching */ - if(c.m_matching>0) - { - for(int j=0;jm_x; - btVector3 mx=mi; - for(int j=1;jm_x); - mx.setMax(c.m_nodes[j]->m_x); - } - const btDbvtVolume bounds=btDbvtVolume::FromMM(mi,mx); - if(c.m_leaf) - m_cdbvt.update(c.m_leaf,bounds,c.m_lv*m_sst.sdt*3,m_sst.radmrg); - else - c.m_leaf=m_cdbvt.insert(bounds,&c); - } - } - } -} - -// -void btSoftBody::cleanupClusters() -{ -for(int i=0;iTerminate(m_sst.sdt); - if(m_joints[i]->m_delete) - { - btAlignedFree(m_joints[i]); - m_joints.remove(m_joints[i--]); - } - } -} - -// -void btSoftBody::prepareClusters(int iterations) -{ -for(int i=0;iPrepare(m_sst.sdt,iterations); - } -} - - -// -void btSoftBody::solveClusters(btScalar sor) -{ -for(int i=0,ni=m_joints.size();iSolve(m_sst.sdt,sor); - } -} - -// -void btSoftBody::applyClusters(bool drift) -{ -BT_PROFILE("ApplyClusters"); -const btScalar f0=m_sst.sdt; -const btScalar f1=f0/2; -btAlignedObjectArray deltas; -btAlignedObjectArray weights; -deltas.resize(m_nodes.size(),btVector3(0,0,0)); -weights.resize(m_nodes.size(),0); -int i; - -if(drift) - { - for(i=0;im_x; - const btScalar q=c.m_masses[j]; - deltas[idx] += (v+cross(w,x-c.m_com))*q; - weights[idx] += q; - } - } - } - for(i=0;i0) m_nodes[i].m_x+=deltas[i]/weights[i]; - } -} - -// -void btSoftBody::dampClusters() -{ - int i; - -for(i=0;i0) - { - for(int j=0;j0) - { - const btVector3 vx=c.m_lv+cross(c.m_av,c.m_nodes[j]->m_q-c.m_com); - n.m_v += c.m_ndamping*(vx-n.m_v); - } - } - } - } -} - -// -void btSoftBody::Joint::Prepare(btScalar dt,int) -{ -m_bodies[0].activate(); -m_bodies[1].activate(); -} - -// -void btSoftBody::LJoint::Prepare(btScalar dt,int iterations) -{ -static const btScalar maxdrift=4; -Joint::Prepare(dt,iterations); -m_rpos[0] = m_bodies[0].xform()*m_refs[0]; -m_rpos[1] = m_bodies[1].xform()*m_refs[1]; -m_drift = Clamp(m_rpos[0]-m_rpos[1],maxdrift)*m_erp/dt; -m_rpos[0] -= m_bodies[0].xform().getOrigin(); -m_rpos[1] -= m_bodies[1].xform().getOrigin(); -m_massmatrix = ImpulseMatrix( m_bodies[0].invMass(),m_bodies[0].invWorldInertia(),m_rpos[0], - m_bodies[1].invMass(),m_bodies[1].invWorldInertia(),m_rpos[1]); -if(m_split>0) - { - m_sdrift = m_massmatrix*(m_drift*m_split); - m_drift *= 1-m_split; - } -m_drift /=(btScalar)iterations; -} - -// -void btSoftBody::LJoint::Solve(btScalar dt,btScalar sor) -{ -const btVector3 va=m_bodies[0].velocity(m_rpos[0]); -const btVector3 vb=m_bodies[1].velocity(m_rpos[1]); -const btVector3 vr=va-vb; -btSoftBody::Impulse impulse; -impulse.m_asVelocity = 1; -impulse.m_velocity = m_massmatrix*(m_drift+vr*m_cfm)*sor; -m_bodies[0].applyImpulse(-impulse,m_rpos[0]); -m_bodies[1].applyImpulse( impulse,m_rpos[1]); -} - -// -void btSoftBody::LJoint::Terminate(btScalar dt) -{ -if(m_split>0) - { - m_bodies[0].applyDImpulse(-m_sdrift,m_rpos[0]); - m_bodies[1].applyDImpulse( m_sdrift,m_rpos[1]); - } -} - -// -void btSoftBody::AJoint::Prepare(btScalar dt,int iterations) -{ -static const btScalar maxdrift=SIMD_PI/16; -m_icontrol->Prepare(this); -Joint::Prepare(dt,iterations); -m_axis[0] = m_bodies[0].xform().getBasis()*m_refs[0]; -m_axis[1] = m_bodies[1].xform().getBasis()*m_refs[1]; -m_drift = NormalizeAny(cross(m_axis[1],m_axis[0])); -m_drift *= btMin(maxdrift,btAcos(Clamp(dot(m_axis[0],m_axis[1]),-1,+1))); -m_drift *= m_erp/dt; -m_massmatrix= AngularImpulseMatrix(m_bodies[0].invWorldInertia(),m_bodies[1].invWorldInertia()); -if(m_split>0) - { - m_sdrift = m_massmatrix*(m_drift*m_split); - m_drift *= 1-m_split; - } -m_drift /=(btScalar)iterations; -} - -// -void btSoftBody::AJoint::Solve(btScalar dt,btScalar sor) -{ -const btVector3 va=m_bodies[0].angularVelocity(); -const btVector3 vb=m_bodies[1].angularVelocity(); -const btVector3 vr=va-vb; -const btScalar sp=dot(vr,m_axis[0]); -const btVector3 vc=vr-m_axis[0]*m_icontrol->Speed(this,sp); -btSoftBody::Impulse impulse; -impulse.m_asVelocity = 1; -impulse.m_velocity = m_massmatrix*(m_drift+vc*m_cfm)*sor; -m_bodies[0].applyAImpulse(-impulse); -m_bodies[1].applyAImpulse( impulse); -} - -// -void btSoftBody::AJoint::Terminate(btScalar dt) -{ -if(m_split>0) - { - m_bodies[0].applyDAImpulse(-m_sdrift); - m_bodies[1].applyDAImpulse( m_sdrift); - } -} - -// -void btSoftBody::CJoint::Prepare(btScalar dt,int iterations) -{ -Joint::Prepare(dt,iterations); -const bool dodrift=(m_life==0); -m_delete=(++m_life)>m_maxlife; -if(dodrift) - { - m_drift=m_drift*m_erp/dt; - if(m_split>0) - { - m_sdrift = m_massmatrix*(m_drift*m_split); - m_drift *= 1-m_split; - } - m_drift/=(btScalar)iterations; - } - else - { - m_drift=m_sdrift=btVector3(0,0,0); - } -} - -// -void btSoftBody::CJoint::Solve(btScalar dt,btScalar sor) -{ -const btVector3 va=m_bodies[0].velocity(m_rpos[0]); -const btVector3 vb=m_bodies[1].velocity(m_rpos[1]); -const btVector3 vrel=va-vb; -const btScalar rvac=dot(vrel,m_normal); -btSoftBody::Impulse impulse; -impulse.m_asVelocity = 1; -impulse.m_velocity = m_drift; -if(rvac<0) - { - const btVector3 iv=m_normal*rvac; - const btVector3 fv=vrel-iv; - impulse.m_velocity += iv+fv*m_friction; - } -impulse.m_velocity=m_massmatrix*impulse.m_velocity*sor; -m_bodies[0].applyImpulse(-impulse,m_rpos[0]); -m_bodies[1].applyImpulse( impulse,m_rpos[1]); -} - -// -void btSoftBody::CJoint::Terminate(btScalar dt) -{ -if(m_split>0) - { - m_bodies[0].applyDImpulse(-m_sdrift,m_rpos[0]); - m_bodies[1].applyDImpulse( m_sdrift,m_rpos[1]); - } -} - -// -void btSoftBody::applyForces() -{ - BT_PROFILE("SoftBody applyForces"); - const btScalar dt=m_sst.sdt; - const btScalar kLF=m_cfg.kLF; - const btScalar kDG=m_cfg.kDG; - const btScalar kPR=m_cfg.kPR; - const btScalar kVC=m_cfg.kVC; - const bool as_lift=kLF>0; - const bool as_drag=kDG>0; - const bool as_pressure=kPR!=0; - const bool as_volume=kVC>0; - const bool as_aero= as_lift || - as_drag ; - const bool as_vaero= as_aero && - (m_cfg.aeromodel=btSoftBody::eAeroModel::F_TwoSided); - const bool use_medium= as_aero; - const bool use_volume= as_pressure || - as_volume ; - btScalar volume=0; - btScalar ivolumetp=0; - btScalar dvolumetv=0; - btSoftBody::sMedium medium; - if(use_volume) - { - volume = getVolume(); - ivolumetp = 1/btFabs(volume)*kPR; - dvolumetv = (m_pose.m_volume-volume)*kVC; - } - /* Per vertex forces */ - int i,ni; - - for(i=0,ni=m_nodes.size();i0) - { - if(use_medium) - { - EvaluateMedium(m_worldInfo,n.m_x,medium); - /* Aerodynamics */ - if(as_vaero) - { - const btVector3 rel_v=n.m_v-medium.m_velocity; - const btScalar rel_v2=rel_v.length2(); - if(rel_v2>SIMD_EPSILON) - { - btVector3 nrm=n.m_n; - /* Setup normal */ - switch(m_cfg.aeromodel) - { - case btSoftBody::eAeroModel::V_Point: - nrm=NormalizeAny(rel_v);break; - case btSoftBody::eAeroModel::V_TwoSided: - nrm*=(btScalar)(dot(nrm,rel_v)<0?-1:+1);break; - } - const btScalar dvn=dot(rel_v,nrm); - /* Compute forces */ - if(dvn>0) - { - btVector3 force(0,0,0); - const btScalar c0 = n.m_area*dvn*rel_v2/2; - const btScalar c1 = c0*medium.m_density; - force += nrm*(-c1*kLF); - force += rel_v.normalized()*(-c1*kDG); - ApplyClampedForce(n,force,dt); - } - } - } - } - /* Pressure */ - if(as_pressure) - { - n.m_f += n.m_n*(n.m_area*ivolumetp); - } - /* Volume */ - if(as_volume) - { - n.m_f += n.m_n*(n.m_area*dvolumetv); - } - } - } - /* Per face forces */ - for(i=0,ni=m_faces.size();im_v+f.m_n[1]->m_v+f.m_n[2]->m_v)/3; - const btVector3 x=(f.m_n[0]->m_x+f.m_n[1]->m_x+f.m_n[2]->m_x)/3; - EvaluateMedium(m_worldInfo,x,medium); - const btVector3 rel_v=v-medium.m_velocity; - const btScalar rel_v2=rel_v.length2(); - if(rel_v2>SIMD_EPSILON) - { - btVector3 nrm=f.m_normal; - /* Setup normal */ - switch(m_cfg.aeromodel) - { - case btSoftBody::eAeroModel::F_TwoSided: - nrm*=(btScalar)(dot(nrm,rel_v)<0?-1:+1);break; - } - const btScalar dvn=dot(rel_v,nrm); - /* Compute forces */ - if(dvn>0) - { - btVector3 force(0,0,0); - const btScalar c0 = f.m_ra*dvn*rel_v2; - const btScalar c1 = c0*medium.m_density; - force += nrm*(-c1*kLF); - force += rel_v.normalized()*(-c1*kDG); - force /= 3; - for(int j=0;j<3;++j) ApplyClampedForce(*f.m_n[j],force,dt); - } - } - } - } -} - -// -void btSoftBody::PSolve_Anchors(btSoftBody* psb,btScalar kst,btScalar ti) -{ - const btScalar kAHR=psb->m_cfg.kAHR*kst; - const btScalar dt=psb->m_sst.sdt; - for(int i=0,ni=psb->m_anchors.size();im_anchors[i]; - const btTransform& t=a.m_body->getInterpolationWorldTransform(); - Node& n=*a.m_node; - const btVector3 wa=t*a.m_local; - const btVector3 va=a.m_body->getVelocityInLocalPoint(a.m_c1)*dt; - const btVector3 vb=n.m_x-n.m_q; - const btVector3 vr=(va-vb)+(wa-n.m_x)*kAHR; - const btVector3 impulse=a.m_c0*vr; - n.m_x+=impulse*a.m_c2; - a.m_body->applyImpulse(-impulse,a.m_c1); - } -} - -// -void btSoftBody::PSolve_RContacts(btSoftBody* psb,btScalar kst,btScalar ti) -{ - const btScalar dt=psb->m_sst.sdt; - const btScalar mrg=psb->getCollisionShape()->getMargin(); - for(int i=0,ni=psb->m_rcontacts.size();im_rcontacts[i]; - const sCti& cti=c.m_cti; - const btVector3 va=cti.m_body->getVelocityInLocalPoint(c.m_c1)*dt; - const btVector3 vb=c.m_node->m_x-c.m_node->m_q; - const btVector3 vr=vb-va; - const btScalar dn=dot(vr,cti.m_normal); - if(dn<=SIMD_EPSILON) - { - const btScalar dp=btMin(dot(c.m_node->m_x,cti.m_normal)+cti.m_offset,mrg); - const btVector3 fv=vr-cti.m_normal*dn; - const btVector3 impulse=c.m_c0*((vr-fv*c.m_c3+cti.m_normal*(dp*c.m_c4))*kst); - c.m_node->m_x-=impulse*c.m_c2; - c.m_cti.m_body->applyImpulse(impulse,c.m_c1); - } - } -} - -// -void btSoftBody::PSolve_SContacts(btSoftBody* psb,btScalar,btScalar ti) -{ -for(int i=0,ni=psb->m_scontacts.size();im_scontacts[i]; - const btVector3& nr=c.m_normal; - Node& n=*c.m_node; - Face& f=*c.m_face; - const btVector3 p=BaryEval( f.m_n[0]->m_x, - f.m_n[1]->m_x, - f.m_n[2]->m_x, - c.m_weights); - const btVector3 q=BaryEval( f.m_n[0]->m_q, - f.m_n[1]->m_q, - f.m_n[2]->m_q, - c.m_weights); - const btVector3 vr=(n.m_x-n.m_q)-(p-q); - btVector3 corr(0,0,0); - if(dot(vr,nr)<0) - { - const btScalar j=c.m_margin-(dot(nr,n.m_x)-dot(nr,p)); - corr+=c.m_normal*j; - } - corr -= ProjectOnPlane(vr,nr)*c.m_friction; - n.m_x += corr*c.m_cfm[0]; - f.m_n[0]->m_x -= corr*(c.m_cfm[1]*c.m_weights.x()); - f.m_n[1]->m_x -= corr*(c.m_cfm[1]*c.m_weights.y()); - f.m_n[2]->m_x -= corr*(c.m_cfm[1]*c.m_weights.z()); - } -} - -// -void btSoftBody::PSolve_Links(btSoftBody* psb,btScalar kst,btScalar ti) -{ - for(int i=0,ni=psb->m_links.size();im_links[i]; - if(l.m_c0>0) - { - Node& a=*l.m_n[0]; - Node& b=*l.m_n[1]; - const btVector3 del=b.m_x-a.m_x; - const btScalar len=del.length2(); - const btScalar k=((l.m_c1-len)/(l.m_c0*(l.m_c1+len)))*kst; - const btScalar t=k*a.m_im; - a.m_x-=del*(k*a.m_im); - b.m_x+=del*(k*b.m_im); - } - } -} - -// -void btSoftBody::VSolve_Links(btSoftBody* psb,btScalar kst) -{ -for(int i=0,ni=psb->m_links.size();im_links[i]; - Node** n=l.m_n; - const btScalar j=-dot(l.m_c3,n[0]->m_v-n[1]->m_v)*l.m_c2*kst; - n[0]->m_v+= l.m_c3*(j*n[0]->m_im); - n[1]->m_v-= l.m_c3*(j*n[1]->m_im); - } -} - -// -btSoftBody::psolver_t btSoftBody::getSolver(ePSolver::_ solver) -{ -switch(solver) - { - case ePSolver::Anchors: return(&btSoftBody::PSolve_Anchors); - case ePSolver::Linear: return(&btSoftBody::PSolve_Links); - case ePSolver::RContacts: return(&btSoftBody::PSolve_RContacts); - case ePSolver::SContacts: return(&btSoftBody::PSolve_SContacts); - } -return(0); -} - -// -btSoftBody::vsolver_t btSoftBody::getSolver(eVSolver::_ solver) -{ -switch(solver) - { - case eVSolver::Linear: return(&btSoftBody::VSolve_Links); - } -return(0); -} - -// -void btSoftBody::defaultCollisionHandler(btCollisionObject* pco) -{ -switch(m_cfg.collisions&fCollision::RVSmask) - { - case fCollision::SDF_RS: - { - btSoftColliders::CollideSDF_RS docollide; - btRigidBody* prb=btRigidBody::upcast(pco); - const btTransform wtr=prb->getInterpolationWorldTransform(); - const btTransform ctr=prb->getWorldTransform(); - const btScalar timemargin=(wtr.getOrigin()-ctr.getOrigin()).length(); - const btScalar basemargin=getCollisionShape()->getMargin(); - btVector3 mins; - btVector3 maxs; - btDbvtVolume volume; - pco->getCollisionShape()->getAabb( pco->getInterpolationWorldTransform(), - mins, - maxs); - volume=btDbvtVolume::FromMM(mins,maxs); - volume.Expand(btVector3(basemargin,basemargin,basemargin)); - docollide.psb = this; - docollide.prb = prb; - docollide.dynmargin = basemargin+timemargin; - docollide.stamargin = basemargin; - btDbvt::collideTV(m_ndbvt.m_root,volume,docollide); - } - break; - case fCollision::CL_RS: - { - btSoftColliders::CollideCL_RS collider; - collider.Process(this,btRigidBody::upcast(pco)); - } - break; - } -} - -// -void btSoftBody::defaultCollisionHandler(btSoftBody* psb) -{ -const int cf=m_cfg.collisions&psb->m_cfg.collisions; -switch(cf&fCollision::SVSmask) - { - case fCollision::CL_SS: - { - btSoftColliders::CollideCL_SS docollide; - docollide.Process(this,psb); - } - break; - case fCollision::VF_SS: - { - btSoftColliders::CollideVF_SS docollide; - /* common */ - docollide.mrg= getCollisionShape()->getMargin()+ - psb->getCollisionShape()->getMargin(); - /* psb0 nodes vs psb1 faces */ - docollide.psb[0]=this; - docollide.psb[1]=psb; - btDbvt::collideTT( docollide.psb[0]->m_ndbvt.m_root, - docollide.psb[1]->m_fdbvt.m_root, - docollide); - /* psb1 nodes vs psb0 faces */ - docollide.psb[0]=psb; - docollide.psb[1]=this; - btDbvt::collideTT( docollide.psb[0]->m_ndbvt.m_root, - docollide.psb[1]->m_fdbvt.m_root, - docollide); - } - break; - } -} diff --git a/extern/bullet2/src/BulletSoftBody/btSoftBody.h b/extern/bullet2/src/BulletSoftBody/btSoftBody.h deleted file mode 100644 index 834199c668a..00000000000 --- a/extern/bullet2/src/BulletSoftBody/btSoftBody.h +++ /dev/null @@ -1,810 +0,0 @@ -/* -Bullet Continuous Collision Detection and Physics Library -Copyright (c) 2003-2006 Erwin Coumans http://continuousphysics.com/Bullet/ - -This software is provided 'as-is', without any express or implied warranty. -In no event will the authors be held liable for any damages arising from the use of this software. -Permission is granted to anyone to use this software for any purpose, -including commercial applications, and to alter it and redistribute it freely, -subject to the following restrictions: - -1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. -2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. -3. This notice may not be removed or altered from any source distribution. -*/ -///btSoftBody implementation by Nathanael Presson - -#ifndef _BT_SOFT_BODY_H -#define _BT_SOFT_BODY_H - -#include "LinearMath/btAlignedObjectArray.h" -#include "LinearMath/btPoint3.h" -#include "LinearMath/btTransform.h" -#include "LinearMath/btIDebugDraw.h" -#include "BulletDynamics/Dynamics/btRigidBody.h" - -#include "BulletCollision/CollisionShapes/btConcaveShape.h" -#include "BulletCollision/CollisionDispatch/btCollisionCreateFunc.h" -#include "btSparseSDF.h" -#include "BulletCollision/BroadphaseCollision/btDbvt.h" - -class btBroadphaseInterface; -class btCollisionDispatcher; - -/* btSoftBodyWorldInfo */ -struct btSoftBodyWorldInfo -{ - btScalar air_density; - btScalar water_density; - btScalar water_offset; - btVector3 water_normal; - btBroadphaseInterface* m_broadphase; - btCollisionDispatcher* m_dispatcher; - btVector3 m_gravity; - btSparseSdf<3> m_sparsesdf; -}; - - -/// btSoftBody is work-in-progress -class btSoftBody : public btCollisionObject -{ -public: - // - // Enumerations - // - - ///eAeroModel - struct eAeroModel { enum _ { - V_Point, ///Vertex normals are oriented toward velocity - V_TwoSided, ///Vertex normals are fliped to match velocity - V_OneSided, ///Vertex normals are taken as it is - F_TwoSided, ///Face normals are fliped to match velocity - F_OneSided, ///Face normals are taken as it is - END - };}; - - ///eVSolver : velocities solvers - struct eVSolver { enum _ { - Linear, ///Linear solver - END - };}; - - ///ePSolver : positions solvers - struct ePSolver { enum _ { - Linear, ///Linear solver - Anchors, ///Anchor solver - RContacts, ///Rigid contacts solver - SContacts, ///Soft contacts solver - END - };}; - - ///eSolverPresets - struct eSolverPresets { enum _ { - Positions, - Velocities, - Default = Positions, - END - };}; - - ///eFeature - struct eFeature { enum _ { - None, - Node, - Link, - Face, - END - };}; - - typedef btAlignedObjectArray tVSolverArray; - typedef btAlignedObjectArray tPSolverArray; - - // - // Flags - // - - ///fCollision - struct fCollision { enum _ { - RVSmask = 0x000f, ///Rigid versus soft mask - SDF_RS = 0x0001, ///SDF based rigid vs soft - CL_RS = 0x0002, ///Cluster vs convex rigid vs soft - - SVSmask = 0x00f0, ///Rigid versus soft mask - VF_SS = 0x0010, ///Vertex vs face soft vs soft handling - CL_SS = 0x0020, ///Cluster vs cluster soft vs soft handling - /* presets */ - Default = SDF_RS, - END - };}; - - ///fMaterial - struct fMaterial { enum _ { - DebugDraw = 0x0001, /// Enable debug draw - /* presets */ - Default = DebugDraw, - END - };}; - - // - // API Types - // - - /* sRayCast */ - struct sRayCast - { - btSoftBody* body; /// soft body - eFeature::_ feature; /// feature type - int index; /// feature index - btScalar time; /// time of impact (rayorg+raydir*time) - }; - - /* ImplicitFn */ - struct ImplicitFn - { - virtual btScalar Eval(const btVector3& x)=0; - }; - - // - // Internal types - // - - typedef btAlignedObjectArray tScalarArray; - typedef btAlignedObjectArray tVector3Array; - - /* sCti is Softbody contact info */ - struct sCti - { - btRigidBody* m_body; /* Rigid body */ - btVector3 m_normal; /* Outward normal */ - btScalar m_offset; /* Offset from origin */ - }; - - /* sMedium */ - struct sMedium - { - btVector3 m_velocity; /* Velocity */ - btScalar m_pressure; /* Pressure */ - btScalar m_density; /* Density */ - }; - - /* Base type */ - struct Element - { - void* m_tag; // User data - Element() : m_tag(0) {} - }; - /* Material */ - struct Material : Element - { - btScalar m_kLST; // Linear stiffness coefficient [0,1] - btScalar m_kAST; // Area/Angular stiffness coefficient [0,1] - btScalar m_kVST; // Volume stiffness coefficient [0,1] - int m_flags; // Flags - }; - - /* Feature */ - struct Feature : Element - { - Material* m_material; // Material - }; - /* Node */ - struct Node : Feature - { - btVector3 m_x; // Position - btVector3 m_q; // Previous step position - btVector3 m_v; // Velocity - btVector3 m_f; // Force accumulator - btVector3 m_n; // Normal - btScalar m_im; // 1/mass - btScalar m_area; // Area - btDbvtNode* m_leaf; // Leaf data - int m_battach:1; // Attached - }; - /* Link */ - struct Link : Feature - { - Node* m_n[2]; // Node pointers - btScalar m_rl; // Rest length - int m_bbending:1; // Bending link - btScalar m_c0; // (ima+imb)*kLST - btScalar m_c1; // rl^2 - btScalar m_c2; // |gradient|^2/c0 - btVector3 m_c3; // gradient - }; - /* Face */ - struct Face : Feature - { - Node* m_n[3]; // Node pointers - btVector3 m_normal; // Normal - btScalar m_ra; // Rest area - btDbvtNode* m_leaf; // Leaf data - }; - /* RContact */ - struct RContact - { - sCti m_cti; // Contact infos - Node* m_node; // Owner node - btMatrix3x3 m_c0; // Impulse matrix - btVector3 m_c1; // Relative anchor - btScalar m_c2; // ima*dt - btScalar m_c3; // Friction - btScalar m_c4; // Hardness - }; - /* SContact */ - struct SContact - { - Node* m_node; // Node - Face* m_face; // Face - btVector3 m_weights; // Weigths - btVector3 m_normal; // Normal - btScalar m_margin; // Margin - btScalar m_friction; // Friction - btScalar m_cfm[2]; // Constraint force mixing - }; - /* Anchor */ - struct Anchor - { - Node* m_node; // Node pointer - btVector3 m_local; // Anchor position in body space - btRigidBody* m_body; // Body - btMatrix3x3 m_c0; // Impulse matrix - btVector3 m_c1; // Relative anchor - btScalar m_c2; // ima*dt - }; - /* Note */ - struct Note : Element - { - const char* m_text; // Text - btVector3 m_offset; // Offset - int m_rank; // Rank - Node* m_nodes[4]; // Nodes - btScalar m_coords[4]; // Coordinates - }; - /* Pose */ - struct Pose - { - bool m_bvolume; // Is valid - bool m_bframe; // Is frame - btScalar m_volume; // Rest volume - tVector3Array m_pos; // Reference positions - tScalarArray m_wgh; // Weights - btVector3 m_com; // COM - btMatrix3x3 m_rot; // Rotation - btMatrix3x3 m_scl; // Scale - btMatrix3x3 m_aqq; // Base scaling - }; - /* Cluster */ - struct Cluster - { - btAlignedObjectArray m_nodes; - tScalarArray m_masses; - tVector3Array m_framerefs; - btTransform m_framexform; - btScalar m_idmass; - btScalar m_imass; - btMatrix3x3 m_locii; - btMatrix3x3 m_invwi; - btVector3 m_com; - btVector3 m_vimpulses[2]; - btVector3 m_dimpulses[2]; - int m_nvimpulses; - int m_ndimpulses; - btVector3 m_lv; - btVector3 m_av; - btDbvtNode* m_leaf; - btScalar m_ndamping; - btScalar m_ldamping; - btScalar m_adamping; - btScalar m_matching; - bool m_collide; - Cluster() : m_leaf(0),m_ndamping(0),m_ldamping(0),m_adamping(0),m_matching(0) {} - }; - /* Impulse */ - struct Impulse - { - btVector3 m_velocity; - btVector3 m_drift; - int m_asVelocity:1; - int m_asDrift:1; - Impulse() : m_velocity(0,0,0),m_drift(0,0,0),m_asVelocity(0),m_asDrift(0) {} - Impulse operator -() const - { - Impulse i=*this; - i.m_velocity=-i.m_velocity; - i.m_drift=-i.m_drift; - return(i); - } - Impulse operator*(btScalar x) const - { - Impulse i=*this; - i.m_velocity*=x; - i.m_drift*=x; - return(i); - } - }; - /* Body */ - struct Body - { - Cluster* m_soft; - btRigidBody* m_rigid; - Body() : m_soft(0),m_rigid(0) {} - Body(Cluster* p) : m_soft(p),m_rigid(0) {} - Body(btRigidBody* p) : m_soft(0),m_rigid(p) {} - void activate() const - { - if(m_rigid) m_rigid->activate(); - } - const btMatrix3x3& invWorldInertia() const - { - static const btMatrix3x3 iwi(0,0,0,0,0,0,0,0,0); - if(m_rigid) return(m_rigid->getInvInertiaTensorWorld()); - if(m_soft) return(m_soft->m_invwi); - return(iwi); - } - btScalar invMass() const - { - if(m_rigid) return(m_rigid->getInvMass()); - if(m_soft) return(m_soft->m_imass); - return(0); - } - const btTransform& xform() const - { - static const btTransform identity=btTransform::getIdentity(); - if(m_rigid) return(m_rigid->getInterpolationWorldTransform()); - if(m_soft) return(m_soft->m_framexform); - return(identity); - } - btVector3 linearVelocity() const - { - if(m_rigid) return(m_rigid->getLinearVelocity()); - if(m_soft) return(m_soft->m_lv); - return(btVector3(0,0,0)); - } - btVector3 angularVelocity(const btVector3& rpos) const - { - if(m_rigid) return(cross(m_rigid->getAngularVelocity(),rpos)); - if(m_soft) return(cross(m_soft->m_av,rpos)); - return(btVector3(0,0,0)); - } - btVector3 angularVelocity() const - { - if(m_rigid) return(m_rigid->getAngularVelocity()); - if(m_soft) return(m_soft->m_av); - return(btVector3(0,0,0)); - } - btVector3 velocity(const btVector3& rpos) const - { - return(linearVelocity()+angularVelocity(rpos)); - } - void applyVImpulse(const btVector3& impulse,const btVector3& rpos) const - { - if(m_rigid) m_rigid->applyImpulse(impulse,rpos); - if(m_soft) btSoftBody::clusterVImpulse(m_soft,rpos,impulse); - } - void applyDImpulse(const btVector3& impulse,const btVector3& rpos) const - { - if(m_rigid) m_rigid->applyImpulse(impulse,rpos); - if(m_soft) btSoftBody::clusterDImpulse(m_soft,rpos,impulse); - } - void applyImpulse(const Impulse& impulse,const btVector3& rpos) const - { - if(impulse.m_asVelocity) applyVImpulse(impulse.m_velocity,rpos); - if(impulse.m_asDrift) applyDImpulse(impulse.m_drift,rpos); - } - void applyVAImpulse(const btVector3& impulse) const - { - if(m_rigid) m_rigid->applyTorqueImpulse(impulse); - if(m_soft) btSoftBody::clusterVAImpulse(m_soft,impulse); - } - void applyDAImpulse(const btVector3& impulse) const - { - if(m_rigid) m_rigid->applyTorqueImpulse(impulse); - if(m_soft) btSoftBody::clusterDAImpulse(m_soft,impulse); - } - void applyAImpulse(const Impulse& impulse) const - { - if(impulse.m_asVelocity) applyVAImpulse(impulse.m_velocity); - if(impulse.m_asDrift) applyDAImpulse(impulse.m_drift); - } - void applyDCImpulse(const btVector3& impulse) const - { - if(m_rigid) m_rigid->applyCentralImpulse(impulse); - if(m_soft) btSoftBody::clusterDCImpulse(m_soft,impulse); - } - }; - /* Joint */ - struct Joint - { - struct eType { enum _ { - Linear, - Angular, - Contact, - };}; - struct Specs - { - Specs() : erp(1),cfm(1),split(1) {} - btScalar erp; - btScalar cfm; - btScalar split; - }; - Body m_bodies[2]; - btVector3 m_refs[2]; - btScalar m_cfm; - btScalar m_erp; - btScalar m_split; - btVector3 m_drift; - btVector3 m_sdrift; - btMatrix3x3 m_massmatrix; - bool m_delete; - virtual ~Joint() {} - Joint() : m_delete(false) {} - virtual void Prepare(btScalar dt,int iterations); - virtual void Solve(btScalar dt,btScalar sor)=0; - virtual void Terminate(btScalar dt)=0; - virtual eType::_ Type() const=0; - }; - /* LJoint */ - struct LJoint : Joint - { - struct Specs : Joint::Specs - { - btVector3 position; - }; - btVector3 m_rpos[2]; - void Prepare(btScalar dt,int iterations); - void Solve(btScalar dt,btScalar sor); - void Terminate(btScalar dt); - eType::_ Type() const { return(eType::Linear); } - }; - /* AJoint */ - struct AJoint : Joint - { - struct IControl - { - virtual void Prepare(AJoint*) {} - virtual btScalar Speed(AJoint*,btScalar current) { return(current); } - static IControl* Default() { static IControl def;return(&def); } - }; - struct Specs : Joint::Specs - { - Specs() : icontrol(IControl::Default()) {} - btVector3 axis; - IControl* icontrol; - }; - btVector3 m_axis[2]; - IControl* m_icontrol; - void Prepare(btScalar dt,int iterations); - void Solve(btScalar dt,btScalar sor); - void Terminate(btScalar dt); - eType::_ Type() const { return(eType::Angular); } - }; - /* CJoint */ - struct CJoint : Joint - { - int m_life; - int m_maxlife; - btVector3 m_rpos[2]; - btVector3 m_normal; - btScalar m_friction; - void Prepare(btScalar dt,int iterations); - void Solve(btScalar dt,btScalar sor); - void Terminate(btScalar dt); - eType::_ Type() const { return(eType::Contact); } - }; - /* Config */ - struct Config - { - eAeroModel::_ aeromodel; // Aerodynamic model (default: V_Point) - btScalar kVCF; // Velocities correction factor (Baumgarte) - btScalar kDP; // Damping coefficient [0,1] - btScalar kDG; // Drag coefficient [0,+inf] - btScalar kLF; // Lift coefficient [0,+inf] - btScalar kPR; // Pressure coefficient [-inf,+inf] - btScalar kVC; // Volume conversation coefficient [0,+inf] - btScalar kDF; // Dynamic friction coefficient [0,1] - btScalar kMT; // Pose matching coefficient [0,1] - btScalar kCHR; // Rigid contacts hardness [0,1] - btScalar kKHR; // Kinetic contacts hardness [0,1] - btScalar kSHR; // Soft contacts hardness [0,1] - btScalar kAHR; // Anchors hardness [0,1] - btScalar kSRHR_CL; // Soft vs rigid hardness [0,1] (cluster only) - btScalar kSKHR_CL; // Soft vs kinetic hardness [0,1] (cluster only) - btScalar kSSHR_CL; // Soft vs soft hardness [0,1] (cluster only) - btScalar kSR_SPLT_CL; // Soft vs rigid impulse split [0,1] (cluster only) - btScalar kSK_SPLT_CL; // Soft vs rigid impulse split [0,1] (cluster only) - btScalar kSS_SPLT_CL; // Soft vs rigid impulse split [0,1] (cluster only) - btScalar maxvolume; // Maximum volume ratio for pose - btScalar timescale; // Time scale - int viterations; // Velocities solver iterations - int piterations; // Positions solver iterations - int diterations; // Drift solver iterations - int citerations; // Cluster solver iterations - int collisions; // Collisions flags - tVSolverArray m_vsequence; // Velocity solvers sequence - tPSolverArray m_psequence; // Position solvers sequence - tPSolverArray m_dsequence; // Drift solvers sequence - }; - /* SolverState */ - struct SolverState - { - btScalar sdt; // dt*timescale - btScalar isdt; // 1/sdt - btScalar velmrg; // velocity margin - btScalar radmrg; // radial margin - btScalar updmrg; // Update margin - }; - /* RayCaster */ - struct RayCaster : btDbvt::ICollide - { - btVector3 o; - btVector3 d; - btScalar mint; - Face* face; - int tests; - RayCaster(const btVector3& org,const btVector3& dir,btScalar mxt); - void Process(const btDbvtNode* leaf); - static inline btScalar rayTriangle(const btVector3& org, - const btVector3& dir, - const btVector3& a, - const btVector3& b, - const btVector3& c, - btScalar maxt=SIMD_INFINITY); - }; - - // - // Typedef's - // - - typedef void (*psolver_t)(btSoftBody*,btScalar,btScalar); - typedef void (*vsolver_t)(btSoftBody*,btScalar); - typedef btAlignedObjectArray tClusterArray; - typedef btAlignedObjectArray tNoteArray; - typedef btAlignedObjectArray tNodeArray; - typedef btAlignedObjectArray tLeafArray; - typedef btAlignedObjectArray tLinkArray; - typedef btAlignedObjectArray tFaceArray; - typedef btAlignedObjectArray tAnchorArray; - typedef btAlignedObjectArray tRContactArray; - typedef btAlignedObjectArray tSContactArray; - typedef btAlignedObjectArray tMaterialArray; - typedef btAlignedObjectArray tJointArray; - typedef btAlignedObjectArray tSoftBodyArray; - - // - // Fields - // - - Config m_cfg; // Configuration - SolverState m_sst; // Solver state - Pose m_pose; // Pose - void* m_tag; // User data - btSoftBodyWorldInfo* m_worldInfo; // World info - tNoteArray m_notes; // Notes - tNodeArray m_nodes; // Nodes - tLinkArray m_links; // Links - tFaceArray m_faces; // Faces - tAnchorArray m_anchors; // Anchors - tRContactArray m_rcontacts; // Rigid contacts - tSContactArray m_scontacts; // Soft contacts - tJointArray m_joints; // Joints - tMaterialArray m_materials; // Materials - btScalar m_timeacc; // Time accumulator - btVector3 m_bounds[2]; // Spatial bounds - bool m_bUpdateRtCst; // Update runtime constants - btDbvt m_ndbvt; // Nodes tree - btDbvt m_fdbvt; // Faces tree - btDbvt m_cdbvt; // Clusters tree - tClusterArray m_clusters; // Clusters - - // - // Api - // - - /* ctor */ - btSoftBody( btSoftBodyWorldInfo* worldInfo,int node_count, - const btVector3* x, - const btScalar* m); - /* dtor */ - virtual ~btSoftBody(); - /* Check for existing link */ - bool checkLink( int node0, - int node1) const; - bool checkLink( const Node* node0, - const Node* node1) const; - /* Check for existring face */ - bool checkFace( int node0, - int node1, - int node2) const; - /* Append material */ - Material* appendMaterial(); - /* Append note */ - void appendNote( const char* text, - const btVector3& o, - const btVector4& c=btVector4(1,0,0,0), - Node* n0=0, - Node* n1=0, - Node* n2=0, - Node* n3=0); - void appendNote( const char* text, - const btVector3& o, - Node* feature); - void appendNote( const char* text, - const btVector3& o, - Link* feature); - void appendNote( const char* text, - const btVector3& o, - Face* feature); - /* Append node */ - void appendNode( const btVector3& x,btScalar m); - /* Append link */ - void appendLink(int model=-1,Material* mat=0); - void appendLink( int node0, - int node1, - Material* mat=0, - bool bcheckexist=false); - void appendLink( Node* node0, - Node* node1, - Material* mat=0, - bool bcheckexist=false); - /* Append face */ - void appendFace(int model=-1,Material* mat=0); - void appendFace( int node0, - int node1, - int node2, - Material* mat=0); - /* Append anchor */ - void appendAnchor( int node, - btRigidBody* body); - /* Append linear joint */ - void appendLinearJoint(const LJoint::Specs& specs,Cluster* body0,Body body1); - void appendLinearJoint(const LJoint::Specs& specs,Body body=Body()); - void appendLinearJoint(const LJoint::Specs& specs,btSoftBody* body); - /* Append linear joint */ - void appendAngularJoint(const AJoint::Specs& specs,Cluster* body0,Body body1); - void appendAngularJoint(const AJoint::Specs& specs,Body body=Body()); - void appendAngularJoint(const AJoint::Specs& specs,btSoftBody* body); - /* Add force (or gravity) to the entire body */ - void addForce( const btVector3& force); - /* Add force (or gravity) to a node of the body */ - void addForce( const btVector3& force, - int node); - /* Add velocity to the entire body */ - void addVelocity( const btVector3& velocity); - /* Add velocity to a node of the body */ - void addVelocity( const btVector3& velocity, - int node); - /* Set mass */ - void setMass( int node, - btScalar mass); - /* Get mass */ - btScalar getMass( int node) const; - /* Get total mass */ - btScalar getTotalMass() const; - /* Set total mass (weighted by previous masses) */ - void setTotalMass( btScalar mass, - bool fromfaces=false); - /* Set total density */ - void setTotalDensity(btScalar density); - /* Transform */ - void transform( const btTransform& trs); - /* Translate */ - void translate( const btVector3& trs); - /* Rotate */ - void rotate( const btQuaternion& rot); - /* Scale */ - void scale( const btVector3& scl); - /* Set current state as pose */ - void setPose( bool bvolume, - bool bframe); - /* Return the volume */ - btScalar getVolume() const; - /* Cluster count */ - int clusterCount() const; - /* Cluster center of mass */ - static btVector3 clusterCom(const Cluster* cluster); - btVector3 clusterCom(int cluster) const; - /* Cluster velocity at rpos */ - static btVector3 clusterVelocity(const Cluster* cluster,const btVector3& rpos); - /* Cluster impulse */ - static void clusterVImpulse(Cluster* cluster,const btVector3& rpos,const btVector3& impulse); - static void clusterDImpulse(Cluster* cluster,const btVector3& rpos,const btVector3& impulse); - static void clusterImpulse(Cluster* cluster,const btVector3& rpos,const Impulse& impulse); - static void clusterVAImpulse(Cluster* cluster,const btVector3& impulse); - static void clusterDAImpulse(Cluster* cluster,const btVector3& impulse); - static void clusterAImpulse(Cluster* cluster,const Impulse& impulse); - static void clusterDCImpulse(Cluster* cluster,const btVector3& impulse); - /* Generate bending constraints based on distance in the adjency graph */ - int generateBendingConstraints( int distance, - Material* mat=0); - /* Randomize constraints to reduce solver bias */ - void randomizeConstraints(); - /* Generate clusters (K-mean) */ - int generateClusters(int k,int maxiterations=8192); - /* Refine */ - void refine(ImplicitFn* ifn,btScalar accurary,bool cut); - /* CutLink */ - bool cutLink(int node0,int node1,btScalar position); - bool cutLink(const Node* node0,const Node* node1,btScalar position); - /* Ray casting */ - bool rayCast(const btVector3& org, - const btVector3& dir, - sRayCast& results, - btScalar maxtime=SIMD_INFINITY); - /* Solver presets */ - void setSolver(eSolverPresets::_ preset); - /* predictMotion */ - void predictMotion(btScalar dt); - /* solveConstraints */ - void solveConstraints(); - /* staticSolve */ - void staticSolve(int iterations); - /* solveCommonConstraints */ - static void solveCommonConstraints(btSoftBody** bodies,int count,int iterations); - /* solveClusters */ - static void solveClusters(const btAlignedObjectArray& bodies); - /* integrateMotion */ - void integrateMotion(); - /* defaultCollisionHandlers */ - void defaultCollisionHandler(btCollisionObject* pco); - void defaultCollisionHandler(btSoftBody* psb); - - // - // Cast - // - - static const btSoftBody* upcast(const btCollisionObject* colObj) - { - if (colObj->getInternalType()==CO_SOFT_BODY) - return (const btSoftBody*)colObj; - return 0; - } - static btSoftBody* upcast(btCollisionObject* colObj) - { - if (colObj->getInternalType()==CO_SOFT_BODY) - return (btSoftBody*)colObj; - return 0; - } - - // - // ::btCollisionObject - // - - virtual void getAabb(btVector3& aabbMin,btVector3& aabbMax) const - { - aabbMin = m_bounds[0]; - aabbMax = m_bounds[1]; - } - // - // Private - // - void pointersToIndices(); - void indicesToPointers(const int* map=0); - int rayCast(const btVector3& org,const btVector3& dir, - btScalar& mint,eFeature::_& feature,int& index,bool bcountonly) const; - void initializeFaceTree(); - btVector3 evaluateCom() const; - bool checkContact(btRigidBody* prb,const btVector3& x,btScalar margin,btSoftBody::sCti& cti) const; - void updateNormals(); - void updateBounds(); - void updatePose(); - void updateConstants(); - void initializeClusters(); - void updateClusters(); - void cleanupClusters(); - void prepareClusters(int iterations); - void solveClusters(btScalar sor); - void applyClusters(bool drift); - void dampClusters(); - void applyForces(); - static void PSolve_Anchors(btSoftBody* psb,btScalar kst,btScalar ti); - static void PSolve_RContacts(btSoftBody* psb,btScalar kst,btScalar ti); - static void PSolve_SContacts(btSoftBody* psb,btScalar,btScalar ti); - static void PSolve_Links(btSoftBody* psb,btScalar kst,btScalar ti); - static void VSolve_Links(btSoftBody* psb,btScalar kst); - static psolver_t getSolver(ePSolver::_ solver); - static vsolver_t getSolver(eVSolver::_ solver); - -}; - - - -#endif //_BT_SOFT_BODY_H diff --git a/extern/bullet2/src/BulletSoftBody/btSoftBodyConcaveCollisionAlgorithm.cpp b/extern/bullet2/src/BulletSoftBody/btSoftBodyConcaveCollisionAlgorithm.cpp deleted file mode 100644 index 5e3211ed73b..00000000000 --- a/extern/bullet2/src/BulletSoftBody/btSoftBodyConcaveCollisionAlgorithm.cpp +++ /dev/null @@ -1,410 +0,0 @@ -/* -Bullet Continuous Collision Detection and Physics Library -Copyright (c) 2003-2006 Erwin Coumans http://continuousphysics.com/Bullet/ - -This software is provided 'as-is', without any express or implied warranty. -In no event will the authors be held liable for any damages arising from the use of this software. -Permission is granted to anyone to use this software for any purpose, -including commercial applications, and to alter it and redistribute it freely, -subject to the following restrictions: - -1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. -2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. -3. This notice may not be removed or altered from any source distribution. -*/ - - -#include "btSoftBodyConcaveCollisionAlgorithm.h" -#include "BulletCollision/CollisionDispatch/btCollisionObject.h" -#include "BulletCollision/CollisionShapes/btMultiSphereShape.h" -#include "BulletCollision/BroadphaseCollision/btBroadphaseProxy.h" -#include "BulletCollision/CollisionShapes/btConcaveShape.h" -#include "BulletCollision/CollisionDispatch/btManifoldResult.h" -#include "BulletCollision/NarrowPhaseCollision/btRaycastCallback.h" -#include "BulletCollision/CollisionShapes/btTriangleShape.h" -#include "BulletCollision/CollisionShapes/btSphereShape.h" -#include "BulletCollision/CollisionShapes/btTetrahedronShape.h" -#include "BulletCollision/CollisionShapes/btConvexHullShape.h" - - - -#include "LinearMath/btIDebugDraw.h" -#include "BulletCollision/NarrowPhaseCollision/btSubSimplexConvexCast.h" -#include "BulletSoftBody/btSoftBody.h" - -#define BT_SOFTBODY_TRIANGLE_EXTRUSION btScalar(0.3) - -btSoftBodyConcaveCollisionAlgorithm::btSoftBodyConcaveCollisionAlgorithm( const btCollisionAlgorithmConstructionInfo& ci, btCollisionObject* body0,btCollisionObject* body1,bool isSwapped) -: btCollisionAlgorithm(ci), -m_isSwapped(isSwapped), -m_btSoftBodyTriangleCallback(ci.m_dispatcher1,body0,body1,isSwapped) -{ -} - - - -btSoftBodyConcaveCollisionAlgorithm::~btSoftBodyConcaveCollisionAlgorithm() -{ -} - - - -btSoftBodyTriangleCallback::btSoftBodyTriangleCallback(btDispatcher* dispatcher,btCollisionObject* body0,btCollisionObject* body1,bool isSwapped): - m_dispatcher(dispatcher), - m_dispatchInfoPtr(0) -{ - m_softBody = (btSoftBody*) (isSwapped? body1:body0); - m_triBody = isSwapped? body0:body1; - - // - // create the manifold from the dispatcher 'manifold pool' - // -// m_manifoldPtr = m_dispatcher->getNewManifold(m_convexBody,m_triBody); - - clearCache(); -} - -btSoftBodyTriangleCallback::~btSoftBodyTriangleCallback() -{ - clearCache(); -// m_dispatcher->releaseManifold( m_manifoldPtr ); - -} - - -void btSoftBodyTriangleCallback::clearCache() -{ - //m_dispatcher->clearManifold(m_manifoldPtr); -}; - - -static const int maxParts = 1; -static const int maxTriangleIndex = 100*100; - -btCollisionShape* shapeCache[maxParts][maxTriangleIndex]; - - -void btSoftBodyTriangleCallback::processTriangle(btVector3* triangle,int partId, int triangleIndex) -{ - static bool hackedFirst = true; - if (hackedFirst) - { - hackedFirst = false; - int i,j; - for (i=0;i(m_triBody); - btCollisionAlgorithmConstructionInfo ci; - ci.m_dispatcher1 = m_dispatcher; - - ///debug drawing of the overlapping triangles - if (m_dispatchInfoPtr && m_dispatchInfoPtr->m_debugDraw && m_dispatchInfoPtr->m_debugDraw->getDebugMode() > 0) - { - btVector3 color(255,255,0); - btTransform& tr = ob->getWorldTransform(); - m_dispatchInfoPtr->m_debugDraw->drawLine(tr(triangle[0]),tr(triangle[1]),color); - m_dispatchInfoPtr->m_debugDraw->drawLine(tr(triangle[1]),tr(triangle[2]),color); - m_dispatchInfoPtr->m_debugDraw->drawLine(tr(triangle[2]),tr(triangle[0]),color); - - //btVector3 center = triangle[0] + triangle[1]+triangle[2]; - //center *= btScalar(0.333333); - //m_dispatchInfoPtr->m_debugDraw->drawLine(tr(triangle[0]),tr(center),color); - //m_dispatchInfoPtr->m_debugDraw->drawLine(tr(triangle[1]),tr(center),color); - //m_dispatchInfoPtr->m_debugDraw->drawLine(tr(triangle[2]),tr(center),color); - - } - - if (shapeCache[partId][triangleIndex]) - { - btCollisionShape* tm = shapeCache[partId][triangleIndex]; - - //copy over user pointers to temporary shape - tm->setUserPointer(ob->getRootCollisionShape()->getUserPointer()); - - btCollisionShape* tmpShape = ob->getCollisionShape(); - ob->internalSetTemporaryCollisionShape( tm ); - - - btCollisionAlgorithm* colAlgo = ci.m_dispatcher1->findAlgorithm(m_softBody,m_triBody,0);//m_manifoldPtr); - - colAlgo->processCollision(m_softBody,m_triBody,*m_dispatchInfoPtr,m_resultOut); - colAlgo->~btCollisionAlgorithm(); - ci.m_dispatcher1->freeCollisionAlgorithm(colAlgo); - ob->internalSetTemporaryCollisionShape( tmpShape); - return; - } - - //aabb filter is already applied! - - - - - - - - - //btCollisionObject* colObj = static_cast(m_convexProxy->m_clientObject); - -// if (m_softBody->getCollisionShape()->getShapeType()== - { -// btVector3 other; - btVector3 normal = (triangle[1]-triangle[0]).cross(triangle[2]-triangle[0]); - normal.normalize(); - normal*= BT_SOFTBODY_TRIANGLE_EXTRUSION; -// other=(triangle[0]+triangle[1]+triangle[2])*0.333333f; -// other+=normal*22.f; - btVector3 pts[6] = {triangle[0]+normal, - triangle[1]+normal, - triangle[2]+normal, - triangle[0]-normal, - triangle[1]-normal, - triangle[2]-normal}; - - btConvexHullShape* tm = new btConvexHullShape(&pts[0].getX(),6); - - -// btBU_Simplex1to4 tm(triangle[0],triangle[1],triangle[2],other); - - //btTriangleShape tm(triangle[0],triangle[1],triangle[2]); - // tm.setMargin(m_collisionMarginTriangle); - - //copy over user pointers to temporary shape - tm->setUserPointer(ob->getRootCollisionShape()->getUserPointer()); - - btCollisionShape* tmpShape = ob->getCollisionShape(); - ob->internalSetTemporaryCollisionShape( tm ); - - - btCollisionAlgorithm* colAlgo = ci.m_dispatcher1->findAlgorithm(m_softBody,m_triBody,0);//m_manifoldPtr); - ///this should use the btDispatcher, so the actual registered algorithm is used - // btConvexConvexAlgorithm cvxcvxalgo(m_manifoldPtr,ci,m_convexBody,m_triBody); - - //m_resultOut->setShapeIdentifiers(-1,-1,partId,triangleIndex); - // cvxcvxalgo.setShapeIdentifiers(-1,-1,partId,triangleIndex); -// cvxcvxalgo.processCollision(m_convexBody,m_triBody,*m_dispatchInfoPtr,m_resultOut); - colAlgo->processCollision(m_softBody,m_triBody,*m_dispatchInfoPtr,m_resultOut); - colAlgo->~btCollisionAlgorithm(); - ci.m_dispatcher1->freeCollisionAlgorithm(colAlgo); - ob->internalSetTemporaryCollisionShape( tmpShape ); -// delete tm; - - shapeCache[partId][triangleIndex] = tm; - - } - - - -} - - - -void btSoftBodyTriangleCallback::setTimeStepAndCounters(btScalar collisionMarginTriangle,const btDispatcherInfo& dispatchInfo,btManifoldResult* resultOut) -{ - m_dispatchInfoPtr = &dispatchInfo; - m_collisionMarginTriangle = collisionMarginTriangle; - m_resultOut = resultOut; - - //recalc aabbs -// btTransform softbodyInTriangleSpace; -// softbodyInTriangleSpace = m_triBody->getWorldTransform().inverse() * m_softBody->getWorldTransform(); -// btCollisionShape* convexShape = static_cast(m_convexBody->getCollisionShape()); - //CollisionShape* triangleShape = static_cast(triBody->m_collisionShape); - btVector3 aabbWorldSpaceMin,aabbWorldSpaceMax; - m_softBody->getAabb(aabbWorldSpaceMin,aabbWorldSpaceMax); - - btVector3 halfExtents = (aabbWorldSpaceMax-aabbWorldSpaceMin)*btScalar(0.5); - btVector3 softBodyCenter = (aabbWorldSpaceMax+aabbWorldSpaceMin)*btScalar(0.5); - - btTransform triInverse = m_triBody->getWorldTransform().inverse(); - - btMatrix3x3 abs_b = triInverse.getBasis().absolute(); - btPoint3 center = softBodyCenter + triInverse.getOrigin(); - - btVector3 extent = btVector3(abs_b[0].dot(halfExtents), - abs_b[1].dot(halfExtents), - abs_b[2].dot(halfExtents)); -// extent += btVector3(getMargin(),getMargin(),getMargin()); - - m_aabbMin = center - extent; - m_aabbMax = center + extent; - - btScalar extraMargin = collisionMarginTriangle+btScalar(BT_SOFTBODY_TRIANGLE_EXTRUSION); - btVector3 extra(extraMargin,extraMargin,extraMargin); - - m_aabbMax += extra; - m_aabbMin -= extra; - -/* btVector3 extra(2,2,2); - m_aabbMin = aabbWorldSpaceMin-extra; - m_aabbMax = aabbWorldSpaceMax+extra; -*/ - -} - -void btSoftBodyConcaveCollisionAlgorithm::clearCache() -{ - m_btSoftBodyTriangleCallback.clearCache(); - -} - -void btSoftBodyConcaveCollisionAlgorithm::processCollision (btCollisionObject* body0,btCollisionObject* body1,const btDispatcherInfo& dispatchInfo,btManifoldResult* resultOut) -{ - - - btCollisionObject* convexBody = m_isSwapped ? body1 : body0; - btCollisionObject* triBody = m_isSwapped ? body0 : body1; - - if (triBody->getCollisionShape()->isConcave()) - { - - - btCollisionObject* triOb = triBody; - btConcaveShape* concaveShape = static_cast( triOb->getCollisionShape()); - - // if (convexBody->getCollisionShape()->isConvex()) - { - btScalar collisionMarginTriangle = concaveShape->getMargin(); - -// resultOut->setPersistentManifold(m_btSoftBodyTriangleCallback.m_manifoldPtr); - m_btSoftBodyTriangleCallback.setTimeStepAndCounters(collisionMarginTriangle,dispatchInfo,resultOut); - - //Disable persistency. previously, some older algorithm calculated all contacts in one go, so you can clear it here. - //m_dispatcher->clearManifold(m_btSoftBodyTriangleCallback.m_manifoldPtr); - -// m_btSoftBodyTriangleCallback.m_manifoldPtr->setBodies(convexBody,triBody); - - - concaveShape->processAllTriangles( &m_btSoftBodyTriangleCallback,m_btSoftBodyTriangleCallback.getAabbMin(),m_btSoftBodyTriangleCallback.getAabbMax()); - - // resultOut->refreshContactPoints(); - - } - - } - -} - - -btScalar btSoftBodyConcaveCollisionAlgorithm::calculateTimeOfImpact(btCollisionObject* body0,btCollisionObject* body1,const btDispatcherInfo& dispatchInfo,btManifoldResult* resultOut) -{ - (void)resultOut; - (void)dispatchInfo; - btCollisionObject* convexbody = m_isSwapped ? body1 : body0; - btCollisionObject* triBody = m_isSwapped ? body0 : body1; - - - //quick approximation using raycast, todo: hook up to the continuous collision detection (one of the btConvexCast) - - //only perform CCD above a certain threshold, this prevents blocking on the long run - //because object in a blocked ccd state (hitfraction<1) get their linear velocity halved each frame... - btScalar squareMot0 = (convexbody->getInterpolationWorldTransform().getOrigin() - convexbody->getWorldTransform().getOrigin()).length2(); - if (squareMot0 < convexbody->getCcdSquareMotionThreshold()) - { - return btScalar(1.); - } - - //const btVector3& from = convexbody->m_worldTransform.getOrigin(); - //btVector3 to = convexbody->m_interpolationWorldTransform.getOrigin(); - //todo: only do if the motion exceeds the 'radius' - - btTransform triInv = triBody->getWorldTransform().inverse(); - btTransform convexFromLocal = triInv * convexbody->getWorldTransform(); - btTransform convexToLocal = triInv * convexbody->getInterpolationWorldTransform(); - - struct LocalTriangleSphereCastCallback : public btTriangleCallback - { - btTransform m_ccdSphereFromTrans; - btTransform m_ccdSphereToTrans; - btTransform m_meshTransform; - - btScalar m_ccdSphereRadius; - btScalar m_hitFraction; - - - LocalTriangleSphereCastCallback(const btTransform& from,const btTransform& to,btScalar ccdSphereRadius,btScalar hitFraction) - :m_ccdSphereFromTrans(from), - m_ccdSphereToTrans(to), - m_ccdSphereRadius(ccdSphereRadius), - m_hitFraction(hitFraction) - { - } - - - virtual void processTriangle(btVector3* triangle, int partId, int triangleIndex) - { - (void)partId; - (void)triangleIndex; - //do a swept sphere for now - btTransform ident; - ident.setIdentity(); - btConvexCast::CastResult castResult; - castResult.m_fraction = m_hitFraction; - btSphereShape pointShape(m_ccdSphereRadius); - btTriangleShape triShape(triangle[0],triangle[1],triangle[2]); - btVoronoiSimplexSolver simplexSolver; - btSubsimplexConvexCast convexCaster(&pointShape,&triShape,&simplexSolver); - //GjkConvexCast convexCaster(&pointShape,convexShape,&simplexSolver); - //ContinuousConvexCollision convexCaster(&pointShape,convexShape,&simplexSolver,0); - //local space? - - if (convexCaster.calcTimeOfImpact(m_ccdSphereFromTrans,m_ccdSphereToTrans, - ident,ident,castResult)) - { - if (m_hitFraction > castResult.m_fraction) - m_hitFraction = castResult.m_fraction; - } - - } - - }; - - - - - - if (triBody->getCollisionShape()->isConcave()) - { - btVector3 rayAabbMin = convexFromLocal.getOrigin(); - rayAabbMin.setMin(convexToLocal.getOrigin()); - btVector3 rayAabbMax = convexFromLocal.getOrigin(); - rayAabbMax.setMax(convexToLocal.getOrigin()); - btScalar ccdRadius0 = convexbody->getCcdSweptSphereRadius(); - rayAabbMin -= btVector3(ccdRadius0,ccdRadius0,ccdRadius0); - rayAabbMax += btVector3(ccdRadius0,ccdRadius0,ccdRadius0); - - btScalar curHitFraction = btScalar(1.); //is this available? - LocalTriangleSphereCastCallback raycastCallback(convexFromLocal,convexToLocal, - convexbody->getCcdSweptSphereRadius(),curHitFraction); - - raycastCallback.m_hitFraction = convexbody->getHitFraction(); - - btCollisionObject* concavebody = triBody; - - btConcaveShape* triangleMesh = (btConcaveShape*) concavebody->getCollisionShape(); - - if (triangleMesh) - { - triangleMesh->processAllTriangles(&raycastCallback,rayAabbMin,rayAabbMax); - } - - - - if (raycastCallback.m_hitFraction < convexbody->getHitFraction()) - { - convexbody->setHitFraction( raycastCallback.m_hitFraction); - return raycastCallback.m_hitFraction; - } - } - - return btScalar(1.); - -} diff --git a/extern/bullet2/src/BulletSoftBody/btSoftBodyConcaveCollisionAlgorithm.h b/extern/bullet2/src/BulletSoftBody/btSoftBodyConcaveCollisionAlgorithm.h deleted file mode 100644 index adb91329a4c..00000000000 --- a/extern/bullet2/src/BulletSoftBody/btSoftBodyConcaveCollisionAlgorithm.h +++ /dev/null @@ -1,118 +0,0 @@ -/* -Bullet Continuous Collision Detection and Physics Library -Copyright (c) 2003-2006 Erwin Coumans http://continuousphysics.com/Bullet/ - -This software is provided 'as-is', without any express or implied warranty. -In no event will the authors be held liable for any damages arising from the use of this software. -Permission is granted to anyone to use this software for any purpose, -including commercial applications, and to alter it and redistribute it freely, -subject to the following restrictions: - -1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. -2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. -3. This notice may not be removed or altered from any source distribution. -*/ - -#ifndef SOFT_BODY_CONCAVE_COLLISION_ALGORITHM_H -#define SOFT_BODY_CONCAVE_COLLISION_ALGORITHM_H - -#include "BulletCollision/BroadphaseCollision/btCollisionAlgorithm.h" -#include "BulletCollision/BroadphaseCollision/btDispatcher.h" -#include "BulletCollision/BroadphaseCollision/btBroadphaseInterface.h" -#include "BulletCollision/CollisionShapes/btTriangleCallback.h" -#include "BulletCollision/NarrowPhaseCollision/btPersistentManifold.h" -class btDispatcher; -#include "BulletCollision/BroadphaseCollision/btBroadphaseProxy.h" -#include "BulletCollision/CollisionDispatch/btCollisionCreateFunc.h" -class btSoftBody; - -///For each triangle in the concave mesh that overlaps with the AABB of a soft body (m_softBody), processTriangle is called. -class btSoftBodyTriangleCallback : public btTriangleCallback -{ - btSoftBody* m_softBody; - btCollisionObject* m_triBody; - - btVector3 m_aabbMin; - btVector3 m_aabbMax ; - - btManifoldResult* m_resultOut; - - btDispatcher* m_dispatcher; - const btDispatcherInfo* m_dispatchInfoPtr; - btScalar m_collisionMarginTriangle; - -public: -int m_triangleCount; - -// btPersistentManifold* m_manifoldPtr; - - btSoftBodyTriangleCallback(btDispatcher* dispatcher,btCollisionObject* body0,btCollisionObject* body1,bool isSwapped); - - void setTimeStepAndCounters(btScalar collisionMarginTriangle,const btDispatcherInfo& dispatchInfo,btManifoldResult* resultOut); - - virtual ~btSoftBodyTriangleCallback(); - - virtual void processTriangle(btVector3* triangle, int partId, int triangleIndex); - - void clearCache(); - - SIMD_FORCE_INLINE const btVector3& getAabbMin() const - { - return m_aabbMin; - } - SIMD_FORCE_INLINE const btVector3& getAabbMax() const - { - return m_aabbMax; - } - -}; - - - - -/// btSoftBodyConcaveCollisionAlgorithm supports collision between soft body shapes and (concave) trianges meshes. -class btSoftBodyConcaveCollisionAlgorithm : public btCollisionAlgorithm -{ - - bool m_isSwapped; - - btSoftBodyTriangleCallback m_btSoftBodyTriangleCallback; - -public: - - btSoftBodyConcaveCollisionAlgorithm( const btCollisionAlgorithmConstructionInfo& ci,btCollisionObject* body0,btCollisionObject* body1,bool isSwapped); - - virtual ~btSoftBodyConcaveCollisionAlgorithm(); - - virtual void processCollision (btCollisionObject* body0,btCollisionObject* body1,const btDispatcherInfo& dispatchInfo,btManifoldResult* resultOut); - - btScalar calculateTimeOfImpact(btCollisionObject* body0,btCollisionObject* body1,const btDispatcherInfo& dispatchInfo,btManifoldResult* resultOut); - - virtual void getAllContactManifolds(btManifoldArray& manifoldArray) - { - //we don't add any manifolds - } - - void clearCache(); - - struct CreateFunc :public btCollisionAlgorithmCreateFunc - { - virtual btCollisionAlgorithm* CreateCollisionAlgorithm(btCollisionAlgorithmConstructionInfo& ci, btCollisionObject* body0,btCollisionObject* body1) - { - void* mem = ci.m_dispatcher1->allocateCollisionAlgorithm(sizeof(btSoftBodyConcaveCollisionAlgorithm)); - return new(mem) btSoftBodyConcaveCollisionAlgorithm(ci,body0,body1,false); - } - }; - - struct SwappedCreateFunc :public btCollisionAlgorithmCreateFunc - { - virtual btCollisionAlgorithm* CreateCollisionAlgorithm(btCollisionAlgorithmConstructionInfo& ci, btCollisionObject* body0,btCollisionObject* body1) - { - void* mem = ci.m_dispatcher1->allocateCollisionAlgorithm(sizeof(btSoftBodyConcaveCollisionAlgorithm)); - return new(mem) btSoftBodyConcaveCollisionAlgorithm(ci,body0,body1,true); - } - }; - -}; - -#endif //SOFT_BODY_CONCAVE_COLLISION_ALGORITHM_H diff --git a/extern/bullet2/src/BulletSoftBody/btSoftBodyHelpers.cpp b/extern/bullet2/src/BulletSoftBody/btSoftBodyHelpers.cpp deleted file mode 100644 index e9ec81f4d2c..00000000000 --- a/extern/bullet2/src/BulletSoftBody/btSoftBodyHelpers.cpp +++ /dev/null @@ -1,656 +0,0 @@ -/* -Bullet Continuous Collision Detection and Physics Library -Copyright (c) 2003-2006 Erwin Coumans http://continuousphysics.com/Bullet/ - -This software is provided 'as-is', without any express or implied warranty. -In no event will the authors be held liable for any damages arising from the use of this software. -Permission is granted to anyone to use this software for any purpose, -including commercial applications, and to alter it and redistribute it freely, -subject to the following restrictions: - -1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. -2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. -3. This notice may not be removed or altered from any source distribution. -*/ -///btSoftBodyHelpers.cpp by Nathanael Presson - -#include "btSoftBodyInternals.h" -#include -#include -#include "btSoftBodyHelpers.h" -#include "LinearMath/btConvexHull.h" - -// -static void drawVertex( btIDebugDraw* idraw, - const btVector3& x,btScalar s,const btVector3& c) - { - idraw->drawLine(x-btVector3(s,0,0),x+btVector3(s,0,0),c); - idraw->drawLine(x-btVector3(0,s,0),x+btVector3(0,s,0),c); - idraw->drawLine(x-btVector3(0,0,s),x+btVector3(0,0,s),c); - } - -// -static void drawBox( btIDebugDraw* idraw, - const btVector3& mins, - const btVector3& maxs, - const btVector3& color) -{ -const btVector3 c[]={ btVector3(mins.x(),mins.y(),mins.z()), - btVector3(maxs.x(),mins.y(),mins.z()), - btVector3(maxs.x(),maxs.y(),mins.z()), - btVector3(mins.x(),maxs.y(),mins.z()), - btVector3(mins.x(),mins.y(),maxs.z()), - btVector3(maxs.x(),mins.y(),maxs.z()), - btVector3(maxs.x(),maxs.y(),maxs.z()), - btVector3(mins.x(),maxs.y(),maxs.z())}; -idraw->drawLine(c[0],c[1],color);idraw->drawLine(c[1],c[2],color); -idraw->drawLine(c[2],c[3],color);idraw->drawLine(c[3],c[0],color); -idraw->drawLine(c[4],c[5],color);idraw->drawLine(c[5],c[6],color); -idraw->drawLine(c[6],c[7],color);idraw->drawLine(c[7],c[4],color); -idraw->drawLine(c[0],c[4],color);idraw->drawLine(c[1],c[5],color); -idraw->drawLine(c[2],c[6],color);idraw->drawLine(c[3],c[7],color); -} - -// -static void drawTree( btIDebugDraw* idraw, - const btDbvtNode* node, - int depth, - const btVector3& ncolor, - const btVector3& lcolor, - int mindepth, - int maxdepth) -{ -if(node) - { - if(node->isinternal()&&((depthchilds[0],depth+1,ncolor,lcolor,mindepth,maxdepth); - drawTree(idraw,node->childs[1],depth+1,ncolor,lcolor,mindepth,maxdepth); - } - if(depth>=mindepth) - { - const btScalar scl=(btScalar)(node->isinternal()?1:1); - const btVector3 mi=node->volume.Center()-node->volume.Extents()*scl; - const btVector3 mx=node->volume.Center()+node->volume.Extents()*scl; - drawBox(idraw,mi,mx,node->isleaf()?lcolor:ncolor); - } - } -} - -// -template -static inline T sum(const btAlignedObjectArray& items) -{ -T v; -if(items.size()) - { - v=items[0]; - for(int i=1,ni=items.size();i -static inline void add(btAlignedObjectArray& items,const Q& value) -{ -for(int i=0,ni=items.size();i -static inline void mul(btAlignedObjectArray& items,const Q& value) -{ -for(int i=0,ni=items.size();i -static inline T average(const btAlignedObjectArray& items) -{ -const btScalar n=(btScalar)(items.size()>0?items.size():1); -return(sum(items)/n); -} - -// -static inline btScalar tetravolume(const btVector3& x0, - const btVector3& x1, - const btVector3& x2, - const btVector3& x3) -{ - const btVector3 a=x1-x0; - const btVector3 b=x2-x0; - const btVector3 c=x3-x0; - return(dot(a,cross(b,c))); -} - -// -#if 0 -static btVector3 stresscolor(btScalar stress) - { - static const btVector3 spectrum[]= { btVector3(1,0,1), - btVector3(0,0,1), - btVector3(0,1,1), - btVector3(0,1,0), - btVector3(1,1,0), - btVector3(1,0,0), - btVector3(1,0,0)}; - static const int ncolors=sizeof(spectrum)/sizeof(spectrum[0])-1; - static const btScalar one=1; - stress=btMax(0,btMin(1,stress))*ncolors; - const int sel=(int)stress; - const btScalar frc=stress-sel; - return(spectrum[sel]+(spectrum[sel+1]-spectrum[sel])*frc); - } -#endif - -// -void btSoftBodyHelpers::Draw( btSoftBody* psb, - btIDebugDraw* idraw, - int drawflags) -{ - const btScalar scl=(btScalar)0.1; - const btScalar nscl=scl*5; - const btVector3 lcolor=btVector3(0,0,0); - const btVector3 ncolor=btVector3(1,1,1); - const btVector3 ccolor=btVector3(1,0,0); - int i,j,nj; - - /* Nodes */ - if(0!=(drawflags&fDrawFlags::Nodes)) - { - for(i=0;im_nodes.size();++i) - { - const btSoftBody::Node& n=psb->m_nodes[i]; - if(0==(n.m_material->m_flags&btSoftBody::fMaterial::DebugDraw)) continue; - idraw->drawLine(n.m_x-btVector3(scl,0,0),n.m_x+btVector3(scl,0,0),btVector3(1,0,0)); - idraw->drawLine(n.m_x-btVector3(0,scl,0),n.m_x+btVector3(0,scl,0),btVector3(0,1,0)); - idraw->drawLine(n.m_x-btVector3(0,0,scl),n.m_x+btVector3(0,0,scl),btVector3(0,0,1)); - } - } - /* Links */ - if(0!=(drawflags&fDrawFlags::Links)) - { - for(i=0;im_links.size();++i) - { - const btSoftBody::Link& l=psb->m_links[i]; - if(0==(l.m_material->m_flags&btSoftBody::fMaterial::DebugDraw)) continue; - idraw->drawLine(l.m_n[0]->m_x,l.m_n[1]->m_x,lcolor); - } - } - /* Normals */ - if(0!=(drawflags&fDrawFlags::Normals)) - { - for(i=0;im_nodes.size();++i) - { - const btSoftBody::Node& n=psb->m_nodes[i]; - if(0==(n.m_material->m_flags&btSoftBody::fMaterial::DebugDraw)) continue; - const btVector3 d=n.m_n*nscl; - idraw->drawLine(n.m_x,n.m_x+d,ncolor); - idraw->drawLine(n.m_x,n.m_x-d,ncolor*0.5); - } - } - /* Contacts */ - if(0!=(drawflags&fDrawFlags::Contacts)) - { - static const btVector3 axis[]={btVector3(1,0,0), - btVector3(0,1,0), - btVector3(0,0,1)}; - for(i=0;im_rcontacts.size();++i) - { - const btSoftBody::RContact& c=psb->m_rcontacts[i]; - const btVector3 o= c.m_node->m_x-c.m_cti.m_normal* - (dot(c.m_node->m_x,c.m_cti.m_normal)+c.m_cti.m_offset); - const btVector3 x=cross(c.m_cti.m_normal,axis[c.m_cti.m_normal.minAxis()]).normalized(); - const btVector3 y=cross(x,c.m_cti.m_normal).normalized(); - idraw->drawLine(o-x*nscl,o+x*nscl,ccolor); - idraw->drawLine(o-y*nscl,o+y*nscl,ccolor); - idraw->drawLine(o,o+c.m_cti.m_normal*nscl*3,btVector3(1,1,0)); - } - } - /* Anchors */ - if(0!=(drawflags&fDrawFlags::Anchors)) - { - for(i=0;im_anchors.size();++i) - { - const btSoftBody::Anchor& a=psb->m_anchors[i]; - const btVector3 q=a.m_body->getWorldTransform()*a.m_local; - drawVertex(idraw,a.m_node->m_x,0.25,btVector3(1,0,0)); - drawVertex(idraw,q,0.25,btVector3(0,1,0)); - idraw->drawLine(a.m_node->m_x,q,btVector3(1,1,1)); - } - for(i=0;im_nodes.size();++i) - { - const btSoftBody::Node& n=psb->m_nodes[i]; - if(0==(n.m_material->m_flags&btSoftBody::fMaterial::DebugDraw)) continue; - if(n.m_im<=0) - { - drawVertex(idraw,n.m_x,0.25,btVector3(1,0,0)); - } - } - } - /* Faces */ - if(0!=(drawflags&fDrawFlags::Faces)) - { - const btScalar scl=(btScalar)0.8; - const btScalar alp=(btScalar)1; - const btVector3 col(0,(btScalar)0.7,0); - for(i=0;im_faces.size();++i) - { - const btSoftBody::Face& f=psb->m_faces[i]; - if(0==(f.m_material->m_flags&btSoftBody::fMaterial::DebugDraw)) continue; - const btVector3 x[]={f.m_n[0]->m_x,f.m_n[1]->m_x,f.m_n[2]->m_x}; - const btVector3 c=(x[0]+x[1]+x[2])/3; - idraw->drawTriangle((x[0]-c)*scl+c, - (x[1]-c)*scl+c, - (x[2]-c)*scl+c, - col,alp); - } - } - /* Clusters */ - if(0!=(drawflags&fDrawFlags::Clusters)) - { - srand(1806); - for(i=0;im_clusters.size();++i) - { - if(psb->m_clusters[i]->m_collide) - { - btVector3 color( rand()/(btScalar)RAND_MAX, - rand()/(btScalar)RAND_MAX, - rand()/(btScalar)RAND_MAX); - color=color.normalized()*0.75; - btAlignedObjectArray vertices; - vertices.resize(psb->m_clusters[i]->m_nodes.size()); - for(j=0,nj=vertices.size();jm_clusters[i]->m_nodes[j]->m_x; - } - HullDesc hdsc(QF_TRIANGLES,vertices.size(),&vertices[0]); - HullResult hres; - HullLibrary hlib; - hdsc.mMaxVertices=vertices.size(); - hlib.CreateConvexHull(hdsc,hres); - const btVector3 center=average(hres.m_OutputVertices); - add(hres.m_OutputVertices,-center); - mul(hres.m_OutputVertices,(btScalar)1); - add(hres.m_OutputVertices,center); - for(j=0;j<(int)hres.mNumFaces;++j) - { - const int idx[]={hres.m_Indices[j*3+0],hres.m_Indices[j*3+1],hres.m_Indices[j*3+2]}; - idraw->drawTriangle(hres.m_OutputVertices[idx[0]], - hres.m_OutputVertices[idx[1]], - hres.m_OutputVertices[idx[2]], - color,1); - } - hlib.ReleaseResult(hres); - } - /* Velocities */ - #if 0 - for(int j=0;jm_clusters[i].m_nodes.size();++j) - { - const btSoftBody::Cluster& c=psb->m_clusters[i]; - const btVector3 r=c.m_nodes[j]->m_x-c.m_com; - const btVector3 v=c.m_lv+cross(c.m_av,r); - idraw->drawLine(c.m_nodes[j]->m_x,c.m_nodes[j]->m_x+v,btVector3(1,0,0)); - } - #endif - /* Frame */ - btSoftBody::Cluster& c=*psb->m_clusters[i]; - idraw->drawLine(c.m_com,c.m_framexform*btVector3(10,0,0),btVector3(1,0,0)); - idraw->drawLine(c.m_com,c.m_framexform*btVector3(0,10,0),btVector3(0,1,0)); - idraw->drawLine(c.m_com,c.m_framexform*btVector3(0,0,10),btVector3(0,0,1)); - } - } - /* Notes */ - if(0!=(drawflags&fDrawFlags::Notes)) - { - for(i=0;im_notes.size();++i) - { - const btSoftBody::Note& n=psb->m_notes[i]; - btVector3 p=n.m_offset; - for(int j=0;jm_x*n.m_coords[j]; - } - idraw->draw3dText(p,n.m_text); - } - } - /* Node tree */ - if(0!=(drawflags&fDrawFlags::NodeTree)) DrawNodeTree(psb,idraw); - /* Face tree */ - if(0!=(drawflags&fDrawFlags::FaceTree)) DrawFaceTree(psb,idraw); - /* Cluster tree */ - if(0!=(drawflags&fDrawFlags::ClusterTree)) DrawClusterTree(psb,idraw); - /* Joints */ - if(0!=(drawflags&fDrawFlags::Joints)) - { - for(i=0;im_joints.size();++i) - { - const btSoftBody::Joint* pj=psb->m_joints[i]; - switch(pj->Type()) - { - case btSoftBody::Joint::eType::Linear: - { - const btSoftBody::LJoint* pjl=(const btSoftBody::LJoint*)pj; - const btVector3 a0=pj->m_bodies[0].xform()*pjl->m_refs[0]; - const btVector3 a1=pj->m_bodies[1].xform()*pjl->m_refs[1]; - idraw->drawLine(pj->m_bodies[0].xform().getOrigin(),a0,btVector3(1,1,0)); - idraw->drawLine(pj->m_bodies[1].xform().getOrigin(),a1,btVector3(0,1,1)); - drawVertex(idraw,a0,0.25,btVector3(1,1,0)); - drawVertex(idraw,a1,0.25,btVector3(0,1,1)); - } - break; - case btSoftBody::Joint::eType::Angular: - { - const btSoftBody::AJoint* pja=(const btSoftBody::AJoint*)pj; - const btVector3 o0=pj->m_bodies[0].xform().getOrigin(); - const btVector3 o1=pj->m_bodies[1].xform().getOrigin(); - const btVector3 a0=pj->m_bodies[0].xform().getBasis()*pj->m_refs[0]; - const btVector3 a1=pj->m_bodies[1].xform().getBasis()*pj->m_refs[1]; - idraw->drawLine(o0,o0+a0*10,btVector3(1,1,0)); - idraw->drawLine(o0,o0+a1*10,btVector3(1,1,0)); - idraw->drawLine(o1,o1+a0*10,btVector3(0,1,1)); - idraw->drawLine(o1,o1+a1*10,btVector3(0,1,1)); - } - } - } - } -} - -// -void btSoftBodyHelpers::DrawInfos( btSoftBody* psb, - btIDebugDraw* idraw, - bool masses, - bool areas, - bool /*stress*/) -{ - /* - for(int i=0;im_nodes.size();++i) - { - const btSoftBody::Node& n=psb->m_nodes[i]; - char text[2048]={0}; - char buff[1024]; - if(masses) - { - sprintf(buff," M(%.2f)",1/n.m_im); - strcat(text,buff); - } - if(areas) - { - sprintf(buff," A(%.2f)",n.m_area); - strcat(text,buff); - } - if(text[0]) idraw->draw3dText(n.m_x,text); - } - */ - -} - -// -void btSoftBodyHelpers::DrawNodeTree( btSoftBody* psb, - btIDebugDraw* idraw, - int mindepth, - int maxdepth) -{ -drawTree(idraw,psb->m_ndbvt.m_root,0,btVector3(1,0,1),btVector3(1,1,1),mindepth,maxdepth); -} - -// -void btSoftBodyHelpers::DrawFaceTree( btSoftBody* psb, - btIDebugDraw* idraw, - int mindepth, - int maxdepth) -{ -drawTree(idraw,psb->m_fdbvt.m_root,0,btVector3(0,1,0),btVector3(1,0,0),mindepth,maxdepth); -} - -// -void btSoftBodyHelpers::DrawClusterTree( btSoftBody* psb, - btIDebugDraw* idraw, - int mindepth, - int maxdepth) -{ -drawTree(idraw,psb->m_cdbvt.m_root,0,btVector3(0,1,1),btVector3(1,0,0),mindepth,maxdepth); -} - -// -void btSoftBodyHelpers::DrawFrame( btSoftBody* psb, - btIDebugDraw* idraw) -{ - if(psb->m_pose.m_bframe) - { - static const btScalar ascl=10; - static const btScalar nscl=(btScalar)0.1; - const btVector3 com=psb->m_pose.m_com; - const btMatrix3x3 trs=psb->m_pose.m_rot*psb->m_pose.m_scl; - const btVector3 Xaxis=(trs*btVector3(1,0,0)).normalized(); - const btVector3 Yaxis=(trs*btVector3(0,1,0)).normalized(); - const btVector3 Zaxis=(trs*btVector3(0,0,1)).normalized(); - idraw->drawLine(com,com+Xaxis*ascl,btVector3(1,0,0)); - idraw->drawLine(com,com+Yaxis*ascl,btVector3(0,1,0)); - idraw->drawLine(com,com+Zaxis*ascl,btVector3(0,0,1)); - for(int i=0;im_pose.m_pos.size();++i) - { - const btVector3 x=com+trs*psb->m_pose.m_pos[i]; - drawVertex(idraw,x,nscl,btVector3(1,0,1)); - } - } -} - -// -btSoftBody* btSoftBodyHelpers::CreateRope( btSoftBodyWorldInfo& worldInfo, const btVector3& from, - const btVector3& to, - int res, - int fixeds) -{ - /* Create nodes */ - const int r=res+2; - btVector3* x=new btVector3[r]; - btScalar* m=new btScalar[r]; - int i; - - for(i=0;isetMass(0,0); - if(fixeds&2) psb->setMass(r-1,0); - delete[] x; - delete[] m; - /* Create links */ - for(i=1;iappendLink(i-1,i); - } - /* Finished */ - return(psb); -} - -// -btSoftBody* btSoftBodyHelpers::CreatePatch(btSoftBodyWorldInfo& worldInfo,const btVector3& corner00, - const btVector3& corner10, - const btVector3& corner01, - const btVector3& corner11, - int resx, - int resy, - int fixeds, - bool gendiags) -{ -#define IDX(_x_,_y_) ((_y_)*rx+(_x_)) - /* Create nodes */ - if((resx<2)||(resy<2)) return(0); - const int rx=resx; - const int ry=resy; - const int tot=rx*ry; - btVector3* x=new btVector3[tot]; - btScalar* m=new btScalar[tot]; - int iy; - - for(iy=0;iysetMass(IDX(0,0),0); - if(fixeds&2) psb->setMass(IDX(rx-1,0),0); - if(fixeds&4) psb->setMass(IDX(0,ry-1),0); - if(fixeds&8) psb->setMass(IDX(rx-1,ry-1),0); - delete[] x; - delete[] m; - /* Create links and faces */ - for(iy=0;iyappendLink(idx,IDX(ix+1,iy)); - if(mdy) psb->appendLink(idx,IDX(ix,iy+1)); - if(mdx&&mdy) - { - if((ix+iy)&1) - { - psb->appendFace(IDX(ix,iy),IDX(ix+1,iy),IDX(ix+1,iy+1)); - psb->appendFace(IDX(ix,iy),IDX(ix+1,iy+1),IDX(ix,iy+1)); - if(gendiags) - { - psb->appendLink(IDX(ix,iy),IDX(ix+1,iy+1)); - } - } - else - { - psb->appendFace(IDX(ix,iy+1),IDX(ix,iy),IDX(ix+1,iy)); - psb->appendFace(IDX(ix,iy+1),IDX(ix+1,iy),IDX(ix+1,iy+1)); - if(gendiags) - { - psb->appendLink(IDX(ix+1,iy),IDX(ix,iy+1)); - } - } - } - } - } - /* Finished */ -#undef IDX - return(psb); -} - -// -btSoftBody* btSoftBodyHelpers::CreateEllipsoid(btSoftBodyWorldInfo& worldInfo,const btVector3& center, - const btVector3& radius, - int res) -{ - struct Hammersley - { - static void Generate(btVector3* x,int n) - { - for(int i=0;i>=1) if(j&1) t+=p; - btScalar w=2*t-1; - btScalar a=(SIMD_PI+2*i*SIMD_PI)/n; - btScalar s=btSqrt(1-w*w); - *x++=btVector3(s*btCos(a),s*btSin(a),w); - } - } - }; - btAlignedObjectArray vtx; - vtx.resize(3+res); - Hammersley::Generate(&vtx[0],vtx.size()); - for(int i=0;i chks; - btAlignedObjectArray vtx; - chks.resize(maxidx*maxidx,false); - vtx.resize(maxidx); - for(i=0,j=0,ni=maxidx*3;iappendLink(idx[j],idx[k]); - } - } -#undef IDX - psb->appendFace(idx[0],idx[1],idx[2]); - } - psb->randomizeConstraints(); - return(psb); -} - -// -btSoftBody* btSoftBodyHelpers::CreateFromConvexHull(btSoftBodyWorldInfo& worldInfo, const btVector3* vertices, - int nvertices) -{ - HullDesc hdsc(QF_TRIANGLES,nvertices,vertices); - HullResult hres; - HullLibrary hlib;/*??*/ - hdsc.mMaxVertices=nvertices; - hlib.CreateConvexHull(hdsc,hres); - btSoftBody* psb=new btSoftBody(&worldInfo,(int)hres.mNumOutputVertices, - &hres.m_OutputVertices[0],0); - for(int i=0;i<(int)hres.mNumFaces;++i) - { - const int idx[]={ hres.m_Indices[i*3+0], - hres.m_Indices[i*3+1], - hres.m_Indices[i*3+2]}; - if(idx[0]appendLink( idx[0],idx[1]); - if(idx[1]appendLink( idx[1],idx[2]); - if(idx[2]appendLink( idx[2],idx[0]); - psb->appendFace(idx[0],idx[1],idx[2]); - } - hlib.ReleaseResult(hres); - psb->randomizeConstraints(); - return(psb); -} diff --git a/extern/bullet2/src/BulletSoftBody/btSoftBodyHelpers.h b/extern/bullet2/src/BulletSoftBody/btSoftBodyHelpers.h deleted file mode 100644 index e9c6cb20657..00000000000 --- a/extern/bullet2/src/BulletSoftBody/btSoftBodyHelpers.h +++ /dev/null @@ -1,107 +0,0 @@ -/* -Bullet Continuous Collision Detection and Physics Library -Copyright (c) 2003-2008 Erwin Coumans http://continuousphysics.com/Bullet/ - -This software is provided 'as-is', without any express or implied warranty. -In no event will the authors be held liable for any damages arising from the use of this software. -Permission is granted to anyone to use this software for any purpose, -including commercial applications, and to alter it and redistribute it freely, -subject to the following restrictions: - -1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. -2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. -3. This notice may not be removed or altered from any source distribution. -*/ - -#ifndef SOFT_BODY_HELPERS_H -#define SOFT_BODY_HELPERS_H - -#include "btSoftBody.h" - -// -// Helpers -// - -/* fDrawFlags */ -struct fDrawFlags { enum _ { - Nodes = 0x0001, - Links = 0x0002, - Faces = 0x0004, - Tetras = 0x0008, - Normals = 0x0010, - Contacts = 0x0020, - Anchors = 0x0040, - Notes = 0x0080, - Clusters = 0x0100, - NodeTree = 0x0200, - FaceTree = 0x0400, - ClusterTree = 0x0800, - Joints = 0x1000, - /* presets */ - Std = Links+Faces+Tetras+Anchors+Notes+Joints, - StdTetra = Std-Faces+Tetras, -};}; - -struct btSoftBodyHelpers -{ - /* Draw body */ - static void Draw( btSoftBody* psb, - btIDebugDraw* idraw, - int drawflags=fDrawFlags::Std); - /* Draw body infos */ - static void DrawInfos( btSoftBody* psb, - btIDebugDraw* idraw, - bool masses, - bool areas, - bool stress); - /* Draw node tree */ - static void DrawNodeTree( btSoftBody* psb, - btIDebugDraw* idraw, - int mindepth=0, - int maxdepth=-1); - /* Draw face tree */ - static void DrawFaceTree( btSoftBody* psb, - btIDebugDraw* idraw, - int mindepth=0, - int maxdepth=-1); - /* Draw cluster tree */ - static void DrawClusterTree(btSoftBody* psb, - btIDebugDraw* idraw, - int mindepth=0, - int maxdepth=-1); - /* Draw rigid frame */ - static void DrawFrame( btSoftBody* psb, - btIDebugDraw* idraw); - /* Create a rope */ - static btSoftBody* CreateRope( btSoftBodyWorldInfo& worldInfo, - const btVector3& from, - const btVector3& to, - int res, - int fixeds); - /* Create a patch */ - static btSoftBody* CreatePatch(btSoftBodyWorldInfo& worldInfo, - const btVector3& corner00, - const btVector3& corner10, - const btVector3& corner01, - const btVector3& corner11, - int resx, - int resy, - int fixeds, - bool gendiags); - /* Create an ellipsoid */ - static btSoftBody* CreateEllipsoid(btSoftBodyWorldInfo& worldInfo, - const btVector3& center, - const btVector3& radius, - int res); - /* Create from trimesh */ - static btSoftBody* CreateFromTriMesh( btSoftBodyWorldInfo& worldInfo, - const btScalar* vertices, - const int* triangles, - int ntriangles); - /* Create from convex-hull */ - static btSoftBody* CreateFromConvexHull( btSoftBodyWorldInfo& worldInfo, - const btVector3* vertices, - int nvertices); -}; - -#endif //SOFT_BODY_HELPERS_H diff --git a/extern/bullet2/src/BulletSoftBody/btSoftBodyInternals.h b/extern/bullet2/src/BulletSoftBody/btSoftBodyInternals.h deleted file mode 100644 index 0c87770d714..00000000000 --- a/extern/bullet2/src/BulletSoftBody/btSoftBodyInternals.h +++ /dev/null @@ -1,895 +0,0 @@ -/* -Bullet Continuous Collision Detection and Physics Library -Copyright (c) 2003-2006 Erwin Coumans http://continuousphysics.com/Bullet/ - -This software is provided 'as-is', without any express or implied warranty. -In no event will the authors be held liable for any damages arising from the use of this software. -Permission is granted to anyone to use this software for any purpose, -including commercial applications, and to alter it and redistribute it freely, -subject to the following restrictions: - -1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. -2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. -3. This notice may not be removed or altered from any source distribution. -*/ -///btSoftBody implementation by Nathanael Presson - -#ifndef _BT_SOFT_BODY_INTERNALS_H -#define _BT_SOFT_BODY_INTERNALS_H - -#include "btSoftBody.h" - -#include "LinearMath/btQuickprof.h" -#include "BulletCollision/BroadphaseCollision/btBroadphaseInterface.h" -#include "BulletCollision/CollisionDispatch/btCollisionDispatcher.h" -#include "BulletCollision/CollisionShapes/btConvexInternalShape.h" -#include "BulletCollision/NarrowPhaseCollision/btGjkEpa2.h" - -// -// btSymMatrix -// -template -struct btSymMatrix -{ - btSymMatrix() : dim(0) {} - btSymMatrix(int n,const T& init=T()) { resize(n,init); } -void resize(int n,const T& init=T()) { dim=n;store.resize((n*(n+1))/2,init); } -int index(int c,int r) const { if(c>r) btSwap(c,r);btAssert(r store; -int dim; -}; - -// -// btSoftBodyCollisionShape -// -class btSoftBodyCollisionShape : public btConcaveShape -{ -public: - btSoftBody* m_body; - - btSoftBodyCollisionShape(btSoftBody* backptr) - { - m_body=backptr; - } - - virtual ~btSoftBodyCollisionShape() - { - - } - - void processAllTriangles(btTriangleCallback* /*callback*/,const btVector3& /*aabbMin*/,const btVector3& /*aabbMax*/) const - { - //not yet - btAssert(0); - } - - ///getAabb returns the axis aligned bounding box in the coordinate frame of the given transform t. - virtual void getAabb(const btTransform& t,btVector3& aabbMin,btVector3& aabbMax) const - { - /* t should be identity, but better be safe than...fast? */ - const btVector3 mins=m_body->m_bounds[0]; - const btVector3 maxs=m_body->m_bounds[1]; - const btVector3 crns[]={t*btVector3(mins.x(),mins.y(),mins.z()), - t*btVector3(maxs.x(),mins.y(),mins.z()), - t*btVector3(maxs.x(),maxs.y(),mins.z()), - t*btVector3(mins.x(),maxs.y(),mins.z()), - t*btVector3(mins.x(),mins.y(),maxs.z()), - t*btVector3(maxs.x(),mins.y(),maxs.z()), - t*btVector3(maxs.x(),maxs.y(),maxs.z()), - t*btVector3(mins.x(),maxs.y(),maxs.z())}; - aabbMin=aabbMax=crns[0]; - for(int i=1;i<8;++i) - { - aabbMin.setMin(crns[i]); - aabbMax.setMax(crns[i]); - } - } - - virtual int getShapeType() const - { - return SOFTBODY_SHAPE_PROXYTYPE; - } - virtual void setLocalScaling(const btVector3& /*scaling*/) - { - ///na - btAssert(0); - } - virtual const btVector3& getLocalScaling() const - { - static const btVector3 dummy(1,1,1); - return dummy; - } - virtual void calculateLocalInertia(btScalar /*mass*/,btVector3& /*inertia*/) const - { - ///not yet - btAssert(0); - } - virtual const char* getName()const - { - return "SoftBody"; - } - -}; - -// -// btSoftClusterCollisionShape -// -class btSoftClusterCollisionShape : public btConvexInternalShape -{ -public: - const btSoftBody::Cluster* m_cluster; - - btSoftClusterCollisionShape (const btSoftBody::Cluster* cluster) : m_cluster(cluster) { setMargin(0); } - - - virtual btVector3 localGetSupportingVertex(const btVector3& vec) const - { - btSoftBody::Node* const * n=&m_cluster->m_nodes[0]; - btScalar d=dot(vec,n[0]->m_x); - int j=0; - for(int i=1,ni=m_cluster->m_nodes.size();im_x); - if(k>d) { d=k;j=i; } - } - return(n[j]->m_x); - } - virtual btVector3 localGetSupportingVertexWithoutMargin(const btVector3& vec)const - { - return(localGetSupportingVertex(vec)); - } - //notice that the vectors should be unit length - virtual void batchedUnitVectorGetSupportingVertexWithoutMargin(const btVector3* vectors,btVector3* supportVerticesOut,int numVectors) const - {} - - - virtual void calculateLocalInertia(btScalar mass,btVector3& inertia) const - {} - - virtual void getAabb(const btTransform& t,btVector3& aabbMin,btVector3& aabbMax) const - {} - - virtual int getShapeType() const { return SOFTBODY_SHAPE_PROXYTYPE; } - - //debugging - virtual const char* getName()const {return "SOFTCLUSTER";} - - virtual void setMargin(btScalar margin) - { - btConvexInternalShape::setMargin(margin); - } - virtual btScalar getMargin() const - { - return getMargin(); - } -}; - -// -// Inline's -// - -// -template -static inline void ZeroInitialize(T& value) -{ -static const T zerodummy; -value=zerodummy; -} -// -template -static inline bool CompLess(const T& a,const T& b) -{ return(a -static inline bool CompGreater(const T& a,const T& b) -{ return(a>b); } -// -template -static inline T Lerp(const T& a,const T& b,btScalar t) -{ return(a+(b-a)*t); } -// -template -static inline T InvLerp(const T& a,const T& b,btScalar t) -{ return((b+a*t-b*t)/(a*b)); } -// -static inline btMatrix3x3 Lerp( const btMatrix3x3& a, - const btMatrix3x3& b, - btScalar t) -{ -btMatrix3x3 r; -r[0]=Lerp(a[0],b[0],t); -r[1]=Lerp(a[1],b[1],t); -r[2]=Lerp(a[2],b[2],t); -return(r); -} -// -static inline btVector3 Clamp(const btVector3& v,btScalar maxlength) -{ -const btScalar sql=v.length2(); -if(sql>(maxlength*maxlength)) - return((v*maxlength)/btSqrt(sql)); - else - return(v); -} -// -template -static inline T Clamp(const T& x,const T& l,const T& h) -{ return(xh?h:x); } -// -template -static inline T Sq(const T& x) -{ return(x*x); } -// -template -static inline T Cube(const T& x) -{ return(x*x*x); } -// -template -static inline T Sign(const T& x) -{ return((T)(x<0?-1:+1)); } -// -template -static inline bool SameSign(const T& x,const T& y) -{ return((x*y)>0); } -// -static inline btScalar ClusterMetric(const btVector3& x,const btVector3& y) -{ -const btVector3 d=x-y; -return(btFabs(d[0])+btFabs(d[1])+btFabs(d[2])); -} -// -static inline btMatrix3x3 ScaleAlongAxis(const btVector3& a,btScalar s) -{ - const btScalar xx=a.x()*a.x(); - const btScalar yy=a.y()*a.y(); - const btScalar zz=a.z()*a.z(); - const btScalar xy=a.x()*a.y(); - const btScalar yz=a.y()*a.z(); - const btScalar zx=a.z()*a.x(); - btMatrix3x3 m; - m[0]=btVector3(1-xx+xx*s,xy*s-xy,zx*s-zx); - m[1]=btVector3(xy*s-xy,1-yy+yy*s,yz*s-yz); - m[2]=btVector3(zx*s-zx,yz*s-yz,1-zz+zz*s); - return(m); -} -// -static inline btMatrix3x3 Cross(const btVector3& v) -{ - btMatrix3x3 m; - m[0]=btVector3(0,-v.z(),+v.y()); - m[1]=btVector3(+v.z(),0,-v.x()); - m[2]=btVector3(-v.y(),+v.x(),0); - return(m); -} -// -static inline btMatrix3x3 Diagonal(btScalar x) -{ - btMatrix3x3 m; - m[0]=btVector3(x,0,0); - m[1]=btVector3(0,x,0); - m[2]=btVector3(0,0,x); - return(m); -} -// -static inline btMatrix3x3 Add(const btMatrix3x3& a, - const btMatrix3x3& b) -{ - btMatrix3x3 r; - for(int i=0;i<3;++i) r[i]=a[i]+b[i]; - return(r); -} -// -static inline btMatrix3x3 Sub(const btMatrix3x3& a, - const btMatrix3x3& b) -{ - btMatrix3x3 r; - for(int i=0;i<3;++i) r[i]=a[i]-b[i]; - return(r); -} -// -static inline btMatrix3x3 Mul(const btMatrix3x3& a, - btScalar b) -{ - btMatrix3x3 r; - for(int i=0;i<3;++i) r[i]=a[i]*b; - return(r); -} -// -static inline void Orthogonalize(btMatrix3x3& m) -{ -m[2]=cross(m[0],m[1]).normalized(); -m[1]=cross(m[2],m[0]).normalized(); -m[0]=cross(m[1],m[2]).normalized(); -} -// -static inline btMatrix3x3 MassMatrix(btScalar im,const btMatrix3x3& iwi,const btVector3& r) -{ - const btMatrix3x3 cr=Cross(r); - return(Sub(Diagonal(im),cr*iwi*cr)); -} - -// -static inline btMatrix3x3 ImpulseMatrix( btScalar dt, - btScalar ima, - btScalar imb, - const btMatrix3x3& iwi, - const btVector3& r) -{ - return(Diagonal(1/dt)*Add(Diagonal(ima),MassMatrix(imb,iwi,r)).inverse()); -} - -// -static inline btMatrix3x3 ImpulseMatrix( btScalar ima,const btMatrix3x3& iia,const btVector3& ra, - btScalar imb,const btMatrix3x3& iib,const btVector3& rb) -{ -return(Add(MassMatrix(ima,iia,ra),MassMatrix(imb,iib,rb)).inverse()); -} - -// -static inline btMatrix3x3 AngularImpulseMatrix( const btMatrix3x3& iia, - const btMatrix3x3& iib) -{ -return(Add(iia,iib).inverse()); -} - -// -static inline btVector3 ProjectOnAxis( const btVector3& v, - const btVector3& a) -{ - return(a*dot(v,a)); -} -// -static inline btVector3 ProjectOnPlane( const btVector3& v, - const btVector3& a) -{ - return(v-ProjectOnAxis(v,a)); -} - -// -static inline void ProjectOrigin( const btVector3& a, - const btVector3& b, - btVector3& prj, - btScalar& sqd) -{ -const btVector3 d=b-a; -const btScalar m2=d.length2(); -if(m2>SIMD_EPSILON) - { - const btScalar t=Clamp(-dot(a,d)/m2,0,1); - const btVector3 p=a+d*t; - const btScalar l2=p.length2(); - if(l2SIMD_EPSILON) - { - const btVector3 n=q/btSqrt(m2); - const btScalar k=dot(a,n); - const btScalar k2=k*k; - if(k20)&& - (dot(cross(b-p,c-p),q)>0)&& - (dot(cross(c-p,a-p),q)>0)) - { - prj=p; - sqd=k2; - } - else - { - ProjectOrigin(a,b,prj,sqd); - ProjectOrigin(b,c,prj,sqd); - ProjectOrigin(c,a,prj,sqd); - } - } - } -} - -// -template -static inline T BaryEval( const T& a, - const T& b, - const T& c, - const btVector3& coord) -{ - return(a*coord.x()+b*coord.y()+c*coord.z()); -} -// -static inline btVector3 BaryCoord( const btVector3& a, - const btVector3& b, - const btVector3& c, - const btVector3& p) -{ -const btScalar w[]={ cross(a-p,b-p).length(), - cross(b-p,c-p).length(), - cross(c-p,a-p).length()}; -const btScalar isum=1/(w[0]+w[1]+w[2]); -return(btVector3(w[1]*isum,w[2]*isum,w[0]*isum)); -} - -// -static btScalar ImplicitSolve( btSoftBody::ImplicitFn* fn, - const btVector3& a, - const btVector3& b, - const btScalar accuracy, - const int maxiterations=256) -{ -btScalar span[2]={0,1}; -btScalar values[2]={fn->Eval(a),fn->Eval(b)}; -if(values[0]>values[1]) - { - btSwap(span[0],span[1]); - btSwap(values[0],values[1]); - } -if(values[0]>-accuracy) return(-1); -if(values[1]<+accuracy) return(-1); -for(int i=0;iEval(Lerp(a,b,t)); - if((t<=0)||(t>=1)) break; - if(btFabs(v)SIMD_EPSILON) - return(v/l); - else - return(btVector3(0,0,0)); -} - -// -static inline btDbvtVolume VolumeOf( const btSoftBody::Face& f, - btScalar margin) -{ -const btVector3* pts[]={ &f.m_n[0]->m_x, - &f.m_n[1]->m_x, - &f.m_n[2]->m_x}; -btDbvtVolume vol=btDbvtVolume::FromPoints(pts,3); -vol.Expand(btVector3(margin,margin,margin)); -return(vol); -} - -// -static inline btVector3 CenterOf( const btSoftBody::Face& f) -{ -return((f.m_n[0]->m_x+f.m_n[1]->m_x+f.m_n[2]->m_x)/3); -} - -// -static inline btScalar AreaOf( const btVector3& x0, - const btVector3& x1, - const btVector3& x2) -{ - const btVector3 a=x1-x0; - const btVector3 b=x2-x0; - const btVector3 cr=cross(a,b); - const btScalar area=cr.length(); - return(area); -} - -// -static inline btScalar VolumeOf( const btVector3& x0, - const btVector3& x1, - const btVector3& x2, - const btVector3& x3) -{ - const btVector3 a=x1-x0; - const btVector3 b=x2-x0; - const btVector3 c=x3-x0; - return(dot(a,cross(b,c))); -} - -// -static void EvaluateMedium( const btSoftBodyWorldInfo* wfi, - const btVector3& x, - btSoftBody::sMedium& medium) -{ - medium.m_velocity = btVector3(0,0,0); - medium.m_pressure = 0; - medium.m_density = wfi->air_density; - if(wfi->water_density>0) - { - const btScalar depth=-(dot(x,wfi->water_normal)+wfi->water_offset); - if(depth>0) - { - medium.m_density = wfi->water_density; - medium.m_pressure = depth*wfi->water_density*wfi->m_gravity.length(); - } - } -} - -// -static inline void ApplyClampedForce( btSoftBody::Node& n, - const btVector3& f, - btScalar dt) -{ - const btScalar dtim=dt*n.m_im; - if((f*dtim).length2()>n.m_v.length2()) - {/* Clamp */ - n.m_f-=ProjectOnAxis(n.m_v,f.normalized())/dtim; - } - else - {/* Apply */ - n.m_f+=f; - } -} - -// -static inline int MatchEdge( const btSoftBody::Node* a, - const btSoftBody::Node* b, - const btSoftBody::Node* ma, - const btSoftBody::Node* mb) -{ -if((a==ma)&&(b==mb)) return(0); -if((a==mb)&&(b==ma)) return(1); -return(-1); -} - -// -// btEigen : Extract eigen system, -// straitforward implementation of http://math.fullerton.edu/mathews/n2003/JacobiMethodMod.html -// outputs are NOT sorted. -// -struct btEigen -{ -static int system(btMatrix3x3& a,btMatrix3x3* vectors,btVector3* values=0) - { - static const int maxiterations=16; - static const btScalar accuracy=(btScalar)0.0001; - btMatrix3x3& v=*vectors; - int iterations=0; - vectors->setIdentity(); - do { - int p=0,q=1; - if(btFabs(a[p][q])accuracy) - { - const btScalar w=(a[q][q]-a[p][p])/(2*a[p][q]); - const btScalar z=btFabs(w); - const btScalar t=w/(z*(btSqrt(1+w*w)+z)); - if(t==t)/* [WARNING] let hope that one does not get thrown aways by some compilers... */ - { - const btScalar c=1/btSqrt(t*t+1); - const btScalar s=c*t; - mulPQ(a,c,s,p,q); - mulTPQ(a,c,s,p,q); - mulPQ(v,c,s,p,q); - } else break; - } else break; - } while((++iterations)accuracy) det=ndet; else break; - } - /* Final orthogonalization */ - Orthogonalize(q); - /* Compute 'S' */ - s=q.transpose()*m; - } - else - { - q.setIdentity(); - s.setIdentity(); - } -return(i); -} - -// -// btSoftColliders -// -struct btSoftColliders -{ - // - // ClusterBase - // - struct ClusterBase : btDbvt::ICollide - { - btScalar erp; - btScalar idt; - btScalar margin; - btScalar friction; - btScalar threshold; - ClusterBase() - { - erp =(btScalar)1; - idt =0; - margin =0; - friction =0; - threshold =(btScalar)0; - } - bool SolveContact( const btGjkEpaSolver2::sResults& res, - btSoftBody::Body ba,btSoftBody::Body bb, - btSoftBody::CJoint& joint) - { - if(res.distancedata; - btSoftClusterCollisionShape cshape(cluster); - const btConvexShape* rshape=(const btConvexShape*)prb->getCollisionShape(); - btGjkEpaSolver2::sResults res; - if(btGjkEpaSolver2::SignedDistance( &cshape,btTransform::getIdentity(), - rshape,prb->getInterpolationWorldTransform(), - btVector3(1,0,0),res)) - { - btSoftBody::CJoint joint; - if(SolveContact(res,cluster,prb,joint)) - { - btSoftBody::CJoint* pj=new(btAlignedAlloc(sizeof(btSoftBody::CJoint),16)) btSoftBody::CJoint(); - *pj=joint;psb->m_joints.push_back(pj); - if(prb->isStaticOrKinematicObject()) - { - pj->m_erp *= psb->m_cfg.kSKHR_CL; - pj->m_split *= psb->m_cfg.kSK_SPLT_CL; - } - else - { - pj->m_erp *= psb->m_cfg.kSRHR_CL; - pj->m_split *= psb->m_cfg.kSR_SPLT_CL; - } - } - } - } - void Process(btSoftBody* ps,btRigidBody* pr) - { - psb = ps; - prb = pr; - idt = ps->m_sst.isdt; - margin = ps->getCollisionShape()->getMargin()+ - pr->getCollisionShape()->getMargin(); - friction = btMin(psb->m_cfg.kDF,prb->getFriction()); - btVector3 mins; - btVector3 maxs; - btDbvtVolume volume; - pr->getCollisionShape()->getAabb(pr->getInterpolationWorldTransform(),mins,maxs); - volume=btDbvtVolume::FromMM(mins,maxs); - volume.Expand(btVector3(1,1,1)*margin); - btDbvt::collideTV(ps->m_cdbvt.m_root,volume,*this); - } - }; - // - // CollideCL_SS - // - struct CollideCL_SS : ClusterBase - { - btSoftBody* bodies[2]; - void Process(const btDbvtNode* la,const btDbvtNode* lb) - { - btSoftBody::Cluster* cla=(btSoftBody::Cluster*)la->data; - btSoftBody::Cluster* clb=(btSoftBody::Cluster*)lb->data; - btSoftClusterCollisionShape csa(cla); - btSoftClusterCollisionShape csb(clb); - btGjkEpaSolver2::sResults res; - if(btGjkEpaSolver2::SignedDistance( &csa,btTransform::getIdentity(), - &csb,btTransform::getIdentity(), - cla->m_com-clb->m_com,res)) - { - btSoftBody::CJoint joint; - if(SolveContact(res,cla,clb,joint)) - { - btSoftBody::CJoint* pj=new(btAlignedAlloc(sizeof(btSoftBody::CJoint),16)) btSoftBody::CJoint(); - *pj=joint;bodies[0]->m_joints.push_back(pj); - pj->m_erp *= btMax(bodies[0]->m_cfg.kSSHR_CL,bodies[1]->m_cfg.kSSHR_CL); - pj->m_split *= (bodies[0]->m_cfg.kSS_SPLT_CL+bodies[1]->m_cfg.kSS_SPLT_CL)/2; - } - } - } - void Process(btSoftBody* psa,btSoftBody* psb) - { - idt = psa->m_sst.isdt; - margin = (psa->getCollisionShape()->getMargin()+psb->getCollisionShape()->getMargin())/2; - friction = btMin(psa->m_cfg.kDF,psb->m_cfg.kDF); - bodies[0] = psa; - bodies[1] = psb; - btDbvt::collideTT(psa->m_cdbvt.m_root,psb->m_cdbvt.m_root,*this); - } - }; - // - // CollideSDF_RS - // - struct CollideSDF_RS : btDbvt::ICollide - { - void Process(const btDbvtNode* leaf) - { - btSoftBody::Node* node=(btSoftBody::Node*)leaf->data; - DoNode(*node); - } - void DoNode(btSoftBody::Node& n) const - { - const btScalar m=n.m_im>0?dynmargin:stamargin; - btSoftBody::RContact c; - if( (!n.m_battach)&& - psb->checkContact(prb,n.m_x,m,c.m_cti)) - { - const btScalar ima=n.m_im; - const btScalar imb=prb->getInvMass(); - const btScalar ms=ima+imb; - if(ms>0) - { - const btTransform& wtr=prb->getInterpolationWorldTransform(); - const btMatrix3x3& iwi=prb->getInvInertiaTensorWorld(); - const btVector3 ra=n.m_x-wtr.getOrigin(); - const btVector3 va=prb->getVelocityInLocalPoint(ra)*psb->m_sst.sdt; - const btVector3 vb=n.m_x-n.m_q; - const btVector3 vr=vb-va; - const btScalar dn=dot(vr,c.m_cti.m_normal); - const btVector3 fv=vr-c.m_cti.m_normal*dn; - const btScalar fc=psb->m_cfg.kDF*prb->getFriction(); - c.m_node = &n; - c.m_c0 = ImpulseMatrix(psb->m_sst.sdt,ima,imb,iwi,ra); - c.m_c1 = ra; - c.m_c2 = ima*psb->m_sst.sdt; - c.m_c3 = fv.length2()<(btFabs(dn)*fc)?0:1-fc; - c.m_c4 = prb->isStaticOrKinematicObject()?psb->m_cfg.kKHR:psb->m_cfg.kCHR; - psb->m_rcontacts.push_back(c); - prb->activate(); - } - } - } - btSoftBody* psb; - btRigidBody* prb; - btScalar dynmargin; - btScalar stamargin; - }; - // - // CollideVF_SS - // - struct CollideVF_SS : btDbvt::ICollide - { - void Process(const btDbvtNode* lnode, - const btDbvtNode* lface) - { - btSoftBody::Node* node=(btSoftBody::Node*)lnode->data; - btSoftBody::Face* face=(btSoftBody::Face*)lface->data; - btVector3 o=node->m_x; - btVector3 p; - btScalar d=SIMD_INFINITY; - ProjectOrigin( face->m_n[0]->m_x-o, - face->m_n[1]->m_x-o, - face->m_n[2]->m_x-o, - p,d); - const btScalar m=mrg+(o-node->m_q).length()*2; - if(d<(m*m)) - { - const btSoftBody::Node* n[]={face->m_n[0],face->m_n[1],face->m_n[2]}; - const btVector3 w=BaryCoord(n[0]->m_x,n[1]->m_x,n[2]->m_x,p+o); - const btScalar ma=node->m_im; - btScalar mb=BaryEval(n[0]->m_im,n[1]->m_im,n[2]->m_im,w); - if( (n[0]->m_im<=0)|| - (n[1]->m_im<=0)|| - (n[2]->m_im<=0)) - { - mb=0; - } - const btScalar ms=ma+mb; - if(ms>0) - { - btSoftBody::SContact c; - c.m_normal = p/-btSqrt(d); - c.m_margin = m; - c.m_node = node; - c.m_face = face; - c.m_weights = w; - c.m_friction = btMax(psb[0]->m_cfg.kDF,psb[1]->m_cfg.kDF); - c.m_cfm[0] = ma/ms*psb[0]->m_cfg.kSHR; - c.m_cfm[1] = mb/ms*psb[1]->m_cfg.kSHR; - psb[0]->m_scontacts.push_back(c); - } - } - } - btSoftBody* psb[2]; - btScalar mrg; - }; -}; - -#endif //_BT_SOFT_BODY_INTERNALS_H diff --git a/extern/bullet2/src/BulletSoftBody/btSoftBodyRigidBodyCollisionConfiguration.cpp b/extern/bullet2/src/BulletSoftBody/btSoftBodyRigidBodyCollisionConfiguration.cpp deleted file mode 100644 index e62f35567b0..00000000000 --- a/extern/bullet2/src/BulletSoftBody/btSoftBodyRigidBodyCollisionConfiguration.cpp +++ /dev/null @@ -1,108 +0,0 @@ -/* -Bullet Continuous Collision Detection and Physics Library -Copyright (c) 2003-2006 Erwin Coumans http://continuousphysics.com/Bullet/ - -This software is provided 'as-is', without any express or implied warranty. -In no event will the authors be held liable for any damages arising from the use of this software. -Permission is granted to anyone to use this software for any purpose, -including commercial applications, and to alter it and redistribute it freely, -subject to the following restrictions: - -1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. -2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. -3. This notice may not be removed or altered from any source distribution. -*/ - -#include "btSoftBodyRigidBodyCollisionConfiguration.h" -#include "btSoftRigidCollisionAlgorithm.h" -#include "btSoftBodyConcaveCollisionAlgorithm.h" -#include "btSoftSoftCollisionAlgorithm.h" - -#define ENABLE_SOFTBODY_CONCAVE_COLLISIONS 1 - -btSoftBodyRigidBodyCollisionConfiguration::btSoftBodyRigidBodyCollisionConfiguration(const btDefaultCollisionConstructionInfo& constructionInfo) -:btDefaultCollisionConfiguration(constructionInfo) -{ - void* mem; - - mem = btAlignedAlloc(sizeof(btSoftSoftCollisionAlgorithm::CreateFunc),16); - m_softSoftCreateFunc = new(mem) btSoftSoftCollisionAlgorithm::CreateFunc; - - mem = btAlignedAlloc(sizeof(btSoftRigidCollisionAlgorithm::CreateFunc),16); - m_softRigidConvexCreateFunc = new(mem) btSoftRigidCollisionAlgorithm::CreateFunc; - - mem = btAlignedAlloc(sizeof(btSoftRigidCollisionAlgorithm::CreateFunc),16); - m_swappedSoftRigidConvexCreateFunc = new(mem) btSoftRigidCollisionAlgorithm::CreateFunc; - m_swappedSoftRigidConvexCreateFunc->m_swapped=true; - -#ifdef ENABLE_SOFTBODY_CONCAVE_COLLISIONS - mem = btAlignedAlloc(sizeof(btSoftBodyConcaveCollisionAlgorithm::CreateFunc),16); - m_softRigidConcaveCreateFunc = new(mem) btSoftBodyConcaveCollisionAlgorithm::CreateFunc; - - mem = btAlignedAlloc(sizeof(btSoftBodyConcaveCollisionAlgorithm::CreateFunc),16); - m_swappedSoftRigidConcaveCreateFunc = new(mem) btSoftBodyConcaveCollisionAlgorithm::SwappedCreateFunc; - m_swappedSoftRigidConcaveCreateFunc->m_swapped=true; -#endif - -} - -btSoftBodyRigidBodyCollisionConfiguration::~btSoftBodyRigidBodyCollisionConfiguration() -{ - m_softSoftCreateFunc->~btCollisionAlgorithmCreateFunc(); - btAlignedFree( m_softSoftCreateFunc); - - m_softRigidConvexCreateFunc->~btCollisionAlgorithmCreateFunc(); - btAlignedFree( m_softRigidConvexCreateFunc); - - m_swappedSoftRigidConvexCreateFunc->~btCollisionAlgorithmCreateFunc(); - btAlignedFree( m_swappedSoftRigidConvexCreateFunc); - -#ifdef ENABLE_SOFTBODY_CONCAVE_COLLISIONS - m_softRigidConcaveCreateFunc->~btCollisionAlgorithmCreateFunc(); - btAlignedFree( m_softRigidConcaveCreateFunc); - - m_swappedSoftRigidConcaveCreateFunc->~btCollisionAlgorithmCreateFunc(); - btAlignedFree( m_swappedSoftRigidConcaveCreateFunc); -#endif -} - -///creation of soft-soft and soft-rigid, and otherwise fallback to base class implementation -btCollisionAlgorithmCreateFunc* btSoftBodyRigidBodyCollisionConfiguration::getCollisionAlgorithmCreateFunc(int proxyType0,int proxyType1) -{ - - ///try to handle the softbody interactions first - - if ((proxyType0 == SOFTBODY_SHAPE_PROXYTYPE ) && (proxyType1==SOFTBODY_SHAPE_PROXYTYPE)) - { - return m_softSoftCreateFunc; - } - - ///softbody versus convex - if (proxyType0 == SOFTBODY_SHAPE_PROXYTYPE && btBroadphaseProxy::isConvex(proxyType1)) - { - return m_softRigidConvexCreateFunc; - } - - ///convex versus soft body - if (btBroadphaseProxy::isConvex(proxyType0) && proxyType1 == SOFTBODY_SHAPE_PROXYTYPE ) - { - return m_swappedSoftRigidConvexCreateFunc; - } - -#ifdef ENABLE_SOFTBODY_CONCAVE_COLLISIONS - ///softbody versus convex - if (proxyType0 == SOFTBODY_SHAPE_PROXYTYPE && btBroadphaseProxy::isConcave(proxyType1)) - { - return m_softRigidConcaveCreateFunc; - } - - ///convex versus soft body - if (btBroadphaseProxy::isConcave(proxyType0) && proxyType1 == SOFTBODY_SHAPE_PROXYTYPE ) - { - return m_swappedSoftRigidConcaveCreateFunc; - } -#endif - - ///fallback to the regular rigid collision shape - return btDefaultCollisionConfiguration::getCollisionAlgorithmCreateFunc(proxyType0,proxyType1); -} diff --git a/extern/bullet2/src/BulletSoftBody/btSoftBodyRigidBodyCollisionConfiguration.h b/extern/bullet2/src/BulletSoftBody/btSoftBodyRigidBodyCollisionConfiguration.h deleted file mode 100644 index 41c3af96939..00000000000 --- a/extern/bullet2/src/BulletSoftBody/btSoftBodyRigidBodyCollisionConfiguration.h +++ /dev/null @@ -1,48 +0,0 @@ -/* -Bullet Continuous Collision Detection and Physics Library -Copyright (c) 2003-2006 Erwin Coumans http://continuousphysics.com/Bullet/ - -This software is provided 'as-is', without any express or implied warranty. -In no event will the authors be held liable for any damages arising from the use of this software. -Permission is granted to anyone to use this software for any purpose, -including commercial applications, and to alter it and redistribute it freely, -subject to the following restrictions: - -1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. -2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. -3. This notice may not be removed or altered from any source distribution. -*/ - -#ifndef BT_SOFTBODY_RIGIDBODY_COLLISION_CONFIGURATION -#define BT_SOFTBODY_RIGIDBODY_COLLISION_CONFIGURATION - -#include "BulletCollision/CollisionDispatch/btDefaultCollisionConfiguration.h" - -class btVoronoiSimplexSolver; -class btGjkEpaPenetrationDepthSolver; - - -///btSoftBodyRigidBodyCollisionConfiguration add softbody interaction on top of btDefaultCollisionConfiguration -class btSoftBodyRigidBodyCollisionConfiguration : public btDefaultCollisionConfiguration -{ - - //default CreationFunctions, filling the m_doubleDispatch table - btCollisionAlgorithmCreateFunc* m_softSoftCreateFunc; - btCollisionAlgorithmCreateFunc* m_softRigidConvexCreateFunc; - btCollisionAlgorithmCreateFunc* m_swappedSoftRigidConvexCreateFunc; - btCollisionAlgorithmCreateFunc* m_softRigidConcaveCreateFunc; - btCollisionAlgorithmCreateFunc* m_swappedSoftRigidConcaveCreateFunc; - -public: - - btSoftBodyRigidBodyCollisionConfiguration(const btDefaultCollisionConstructionInfo& constructionInfo = btDefaultCollisionConstructionInfo()); - - virtual ~btSoftBodyRigidBodyCollisionConfiguration(); - - ///creation of soft-soft and soft-rigid, and otherwise fallback to base class implementation - virtual btCollisionAlgorithmCreateFunc* getCollisionAlgorithmCreateFunc(int proxyType0,int proxyType1); - -}; - -#endif //BT_SOFTBODY_RIGIDBODY_COLLISION_CONFIGURATION - diff --git a/extern/bullet2/src/BulletSoftBody/btSoftRigidCollisionAlgorithm.cpp b/extern/bullet2/src/BulletSoftBody/btSoftRigidCollisionAlgorithm.cpp deleted file mode 100644 index 835a03b8e3c..00000000000 --- a/extern/bullet2/src/BulletSoftBody/btSoftRigidCollisionAlgorithm.cpp +++ /dev/null @@ -1,79 +0,0 @@ -/* -Bullet Continuous Collision Detection and Physics Library -Copyright (c) 2003-2006 Erwin Coumans http://continuousphysics.com/Bullet/ - -This software is provided 'as-is', without any express or implied warranty. -In no event will the authors be held liable for any damages arising from the use of this software. -Permission is granted to anyone to use this software for any purpose, -including commercial applications, and to alter it and redistribute it freely, -subject to the following restrictions: - -1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. -2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. -3. This notice may not be removed or altered from any source distribution. -*/ - -#include "btSoftRigidCollisionAlgorithm.h" -#include "BulletCollision/CollisionDispatch/btCollisionDispatcher.h" -#include "BulletCollision/CollisionShapes/btSphereShape.h" -#include "BulletCollision/CollisionShapes/btBoxShape.h" -#include "BulletCollision/CollisionDispatch/btCollisionObject.h" -#include "btSoftBody.h" -///TODO: include all the shapes that the softbody can collide with -///alternatively, implement special case collision algorithms (just like for rigid collision shapes) - -//#include - -btSoftRigidCollisionAlgorithm::btSoftRigidCollisionAlgorithm(btPersistentManifold* /*mf*/,const btCollisionAlgorithmConstructionInfo& ci,btCollisionObject* /*col0*/,btCollisionObject* /*col1*/, bool isSwapped) -: btCollisionAlgorithm(ci), -//m_ownManifold(false), -//m_manifoldPtr(mf), -m_isSwapped(isSwapped) -{ -} - - -btSoftRigidCollisionAlgorithm::~btSoftRigidCollisionAlgorithm() -{ - - //m_softBody->m_overlappingRigidBodies.remove(m_rigidCollisionObject); - - /*if (m_ownManifold) - { - if (m_manifoldPtr) - m_dispatcher->releaseManifold(m_manifoldPtr); - } - */ - -} - - -#include - -void btSoftRigidCollisionAlgorithm::processCollision (btCollisionObject* body0,btCollisionObject* body1,const btDispatcherInfo& dispatchInfo,btManifoldResult* resultOut) -{ - (void)dispatchInfo; - (void)resultOut; - //printf("btSoftRigidCollisionAlgorithm\n"); - - btSoftBody* softBody = m_isSwapped? (btSoftBody*)body1 : (btSoftBody*)body0; - btCollisionObject* rigidCollisionObject = m_isSwapped? body0 : body1; - - softBody->defaultCollisionHandler(rigidCollisionObject); - - -} - -btScalar btSoftRigidCollisionAlgorithm::calculateTimeOfImpact(btCollisionObject* col0,btCollisionObject* col1,const btDispatcherInfo& dispatchInfo,btManifoldResult* resultOut) -{ - (void)resultOut; - (void)dispatchInfo; - (void)col0; - (void)col1; - - //not yet - return btScalar(1.); -} - - - diff --git a/extern/bullet2/src/BulletSoftBody/btSoftRigidCollisionAlgorithm.h b/extern/bullet2/src/BulletSoftBody/btSoftRigidCollisionAlgorithm.h deleted file mode 100644 index 74327e6c635..00000000000 --- a/extern/bullet2/src/BulletSoftBody/btSoftRigidCollisionAlgorithm.h +++ /dev/null @@ -1,75 +0,0 @@ -/* -Bullet Continuous Collision Detection and Physics Library -Copyright (c) 2003-2006 Erwin Coumans http://continuousphysics.com/Bullet/ - -This software is provided 'as-is', without any express or implied warranty. -In no event will the authors be held liable for any damages arising from the use of this software. -Permission is granted to anyone to use this software for any purpose, -including commercial applications, and to alter it and redistribute it freely, -subject to the following restrictions: - -1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. -2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. -3. This notice may not be removed or altered from any source distribution. -*/ - -#ifndef SOFT_RIGID_COLLISION_ALGORITHM_H -#define SOFT_RIGID_COLLISION_ALGORITHM_H - -#include "BulletCollision/BroadphaseCollision/btCollisionAlgorithm.h" -#include "BulletCollision/BroadphaseCollision/btBroadphaseProxy.h" -#include "BulletCollision/CollisionDispatch/btCollisionCreateFunc.h" -class btPersistentManifold; -#include "BulletCollision/CollisionDispatch/btCollisionDispatcher.h" - -#include "LinearMath/btVector3.h" -class btSoftBody; - -/// btSoftRigidCollisionAlgorithm provides collision detection between btSoftBody and btRigidBody -class btSoftRigidCollisionAlgorithm : public btCollisionAlgorithm -{ -// bool m_ownManifold; -// btPersistentManifold* m_manifoldPtr; - - btSoftBody* m_softBody; - btCollisionObject* m_rigidCollisionObject; - - ///for rigid versus soft (instead of soft versus rigid), we use this swapped boolean - bool m_isSwapped; - -public: - - btSoftRigidCollisionAlgorithm(btPersistentManifold* mf,const btCollisionAlgorithmConstructionInfo& ci,btCollisionObject* col0,btCollisionObject* col1, bool isSwapped); - - virtual ~btSoftRigidCollisionAlgorithm(); - - virtual void processCollision (btCollisionObject* body0,btCollisionObject* body1,const btDispatcherInfo& dispatchInfo,btManifoldResult* resultOut); - - virtual btScalar calculateTimeOfImpact(btCollisionObject* body0,btCollisionObject* body1,const btDispatcherInfo& dispatchInfo,btManifoldResult* resultOut); - - virtual void getAllContactManifolds(btManifoldArray& manifoldArray) - { - //we don't add any manifolds - } - - - struct CreateFunc :public btCollisionAlgorithmCreateFunc - { - virtual btCollisionAlgorithm* CreateCollisionAlgorithm(btCollisionAlgorithmConstructionInfo& ci, btCollisionObject* body0,btCollisionObject* body1) - { - void* mem = ci.m_dispatcher1->allocateCollisionAlgorithm(sizeof(btSoftRigidCollisionAlgorithm)); - if (!m_swapped) - { - return new(mem) btSoftRigidCollisionAlgorithm(0,ci,body0,body1,false); - } else - { - return new(mem) btSoftRigidCollisionAlgorithm(0,ci,body0,body1,true); - } - } - }; - -}; - -#endif //SOFT_RIGID_COLLISION_ALGORITHM_H - - diff --git a/extern/bullet2/src/BulletSoftBody/btSoftRigidDynamicsWorld.cpp b/extern/bullet2/src/BulletSoftBody/btSoftRigidDynamicsWorld.cpp deleted file mode 100644 index 01b9fc0fd35..00000000000 --- a/extern/bullet2/src/BulletSoftBody/btSoftRigidDynamicsWorld.cpp +++ /dev/null @@ -1,126 +0,0 @@ -/* -Bullet Continuous Collision Detection and Physics Library -Copyright (c) 2003-2006 Erwin Coumans http://continuousphysics.com/Bullet/ - -This software is provided 'as-is', without any express or implied warranty. -In no event will the authors be held liable for any damages arising from the use of this software. -Permission is granted to anyone to use this software for any purpose, -including commercial applications, and to alter it and redistribute it freely, -subject to the following restrictions: - -1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. -2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. -3. This notice may not be removed or altered from any source distribution. -*/ - - -#include "btSoftRigidDynamicsWorld.h" -#include "LinearMath/btQuickprof.h" - -//softbody & helpers -#include "btSoftBody.h" -#include "btSoftBodyHelpers.h" - -btSoftRigidDynamicsWorld::btSoftRigidDynamicsWorld(btDispatcher* dispatcher,btBroadphaseInterface* pairCache,btConstraintSolver* constraintSolver,btCollisionConfiguration* collisionConfiguration) -:btDiscreteDynamicsWorld(dispatcher,pairCache,constraintSolver,collisionConfiguration) -{ -m_drawFlags = fDrawFlags::Std; -m_drawNodeTree = true; -m_drawFaceTree = false; -m_drawClusterTree = false; -} - -btSoftRigidDynamicsWorld::~btSoftRigidDynamicsWorld() -{ - -} - -void btSoftRigidDynamicsWorld::predictUnconstraintMotion(btScalar timeStep) -{ - btDiscreteDynamicsWorld::predictUnconstraintMotion( timeStep); - - for ( int i=0;ipredictMotion(timeStep); - } -} - -void btSoftRigidDynamicsWorld::internalSingleStepSimulation( btScalar timeStep) -{ - btDiscreteDynamicsWorld::internalSingleStepSimulation( timeStep ); - - ///solve soft bodies constraints - solveSoftBodiesConstraints(); - - ///update soft bodies - updateSoftBodies(); - -} - -void btSoftRigidDynamicsWorld::updateSoftBodies() -{ - BT_PROFILE("updateSoftBodies"); - - for ( int i=0;iintegrateMotion(); - } -} - -void btSoftRigidDynamicsWorld::solveSoftBodiesConstraints() -{ - BT_PROFILE("solveSoftConstraints"); - - if(m_softBodies.size()) - { - btSoftBody::solveClusters(m_softBodies); - } - - for(int i=0;isolveConstraints(); - } -} - -void btSoftRigidDynamicsWorld::addSoftBody(btSoftBody* body) -{ - m_softBodies.push_back(body); - - btCollisionWorld::addCollisionObject(body, - btBroadphaseProxy::DefaultFilter, - btBroadphaseProxy::AllFilter); - -} - -void btSoftRigidDynamicsWorld::removeSoftBody(btSoftBody* body) -{ - m_softBodies.remove(body); - - btCollisionWorld::removeCollisionObject(body); -} - -void btSoftRigidDynamicsWorld::debugDrawWorld() -{ - btDiscreteDynamicsWorld::debugDrawWorld(); - - if (getDebugDrawer()) - { - int i; - for ( i=0;im_softBodies.size();i++) - { - btSoftBody* psb=(btSoftBody*)this->m_softBodies[i]; - btSoftBodyHelpers::DrawFrame(psb,m_debugDrawer); - btSoftBodyHelpers::Draw(psb,m_debugDrawer,m_drawFlags); - if (m_debugDrawer && (m_debugDrawer->getDebugMode() & btIDebugDraw::DBG_DrawAabb)) - { - if(m_drawNodeTree) btSoftBodyHelpers::DrawNodeTree(psb,m_debugDrawer); - if(m_drawFaceTree) btSoftBodyHelpers::DrawFaceTree(psb,m_debugDrawer); - if(m_drawClusterTree) btSoftBodyHelpers::DrawClusterTree(psb,m_debugDrawer); - } - } - } -} diff --git a/extern/bullet2/src/BulletSoftBody/btSoftRigidDynamicsWorld.h b/extern/bullet2/src/BulletSoftBody/btSoftRigidDynamicsWorld.h deleted file mode 100644 index d0010b65aad..00000000000 --- a/extern/bullet2/src/BulletSoftBody/btSoftRigidDynamicsWorld.h +++ /dev/null @@ -1,73 +0,0 @@ -/* -Bullet Continuous Collision Detection and Physics Library -Copyright (c) 2003-2006 Erwin Coumans http://continuousphysics.com/Bullet/ - -This software is provided 'as-is', without any express or implied warranty. -In no event will the authors be held liable for any damages arising from the use of this software. -Permission is granted to anyone to use this software for any purpose, -including commercial applications, and to alter it and redistribute it freely, -subject to the following restrictions: - -1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. -2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. -3. This notice may not be removed or altered from any source distribution. -*/ - -#include "BulletDynamics/Dynamics/btDiscreteDynamicsWorld.h" - -#ifndef BT_SOFT_RIGID_DYNAMICS_WORLD_H -#define BT_SOFT_RIGID_DYNAMICS_WORLD_H - -class btSoftBody; -typedef btAlignedObjectArray btSoftBodyArray; - -class btSoftRigidDynamicsWorld : public btDiscreteDynamicsWorld -{ - - btSoftBodyArray m_softBodies; - int m_drawFlags; - bool m_drawNodeTree; - bool m_drawFaceTree; - bool m_drawClusterTree; - -protected: - - virtual void predictUnconstraintMotion(btScalar timeStep); - - virtual void internalSingleStepSimulation( btScalar timeStep); - - void updateSoftBodies(); - - void solveSoftBodiesConstraints(); - - - -public: - - btSoftRigidDynamicsWorld(btDispatcher* dispatcher,btBroadphaseInterface* pairCache,btConstraintSolver* constraintSolver,btCollisionConfiguration* collisionConfiguration); - - virtual ~btSoftRigidDynamicsWorld(); - - virtual void debugDrawWorld(); - - void addSoftBody(btSoftBody* body); - - void removeSoftBody(btSoftBody* body); - - int getDrawFlags() const { return(m_drawFlags); } - void setDrawFlags(int f) { m_drawFlags=f; } - - - btSoftBodyArray& getSoftBodyArray() - { - return m_softBodies; - } - - const btSoftBodyArray& getSoftBodyArray() const - { - return m_softBodies; - } - -}; - -#endif //BT_SOFT_RIGID_DYNAMICS_WORLD_H diff --git a/extern/bullet2/src/BulletSoftBody/btSoftSoftCollisionAlgorithm.cpp b/extern/bullet2/src/BulletSoftBody/btSoftSoftCollisionAlgorithm.cpp deleted file mode 100644 index 85a727944e0..00000000000 --- a/extern/bullet2/src/BulletSoftBody/btSoftSoftCollisionAlgorithm.cpp +++ /dev/null @@ -1,46 +0,0 @@ -/* -Bullet Continuous Collision Detection and Physics Library -Copyright (c) 2003-2006 Erwin Coumans http://continuousphysics.com/Bullet/ - -This software is provided 'as-is', without any express or implied warranty. -In no event will the authors be held liable for any damages arising from the use of this software. -Permission is granted to anyone to use this software for any purpose, -including commercial applications, and to alter it and redistribute it freely, -subject to the following restrictions: - -1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. -2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. -3. This notice may not be removed or altered from any source distribution. -*/ - -#include "btSoftSoftCollisionAlgorithm.h" -#include "BulletCollision/CollisionDispatch/btCollisionDispatcher.h" -#include "BulletCollision/CollisionShapes/btBoxShape.h" -#include "BulletCollision/CollisionDispatch/btCollisionObject.h" -#include "btSoftBody.h" - -#define USE_PERSISTENT_CONTACTS 1 - -btSoftSoftCollisionAlgorithm::btSoftSoftCollisionAlgorithm(btPersistentManifold* /*mf*/,const btCollisionAlgorithmConstructionInfo& ci,btCollisionObject* /*obj0*/,btCollisionObject* /*obj1*/) -: btCollisionAlgorithm(ci) -//m_ownManifold(false), -//m_manifoldPtr(mf) -{ -} - -btSoftSoftCollisionAlgorithm::~btSoftSoftCollisionAlgorithm() -{ -} - -void btSoftSoftCollisionAlgorithm::processCollision (btCollisionObject* body0,btCollisionObject* body1,const btDispatcherInfo& /*dispatchInfo*/,btManifoldResult* /*resultOut*/) -{ - btSoftBody* soft0 = (btSoftBody*)body0; - btSoftBody* soft1 = (btSoftBody*)body1; - soft0->defaultCollisionHandler(soft1); -} - -btScalar btSoftSoftCollisionAlgorithm::calculateTimeOfImpact(btCollisionObject* /*body0*/,btCollisionObject* /*body1*/,const btDispatcherInfo& /*dispatchInfo*/,btManifoldResult* /*resultOut*/) -{ - //not yet - return 1.f; -} diff --git a/extern/bullet2/src/BulletSoftBody/btSoftSoftCollisionAlgorithm.h b/extern/bullet2/src/BulletSoftBody/btSoftSoftCollisionAlgorithm.h deleted file mode 100644 index 7ca9c3415c9..00000000000 --- a/extern/bullet2/src/BulletSoftBody/btSoftSoftCollisionAlgorithm.h +++ /dev/null @@ -1,69 +0,0 @@ -/* -Bullet Continuous Collision Detection and Physics Library -Copyright (c) 2003-2006 Erwin Coumans http://continuousphysics.com/Bullet/ - -This software is provided 'as-is', without any express or implied warranty. -In no event will the authors be held liable for any damages arising from the use of this software. -Permission is granted to anyone to use this software for any purpose, -including commercial applications, and to alter it and redistribute it freely, -subject to the following restrictions: - -1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. -2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. -3. This notice may not be removed or altered from any source distribution. -*/ - -#ifndef SOFT_SOFT_COLLISION_ALGORITHM_H -#define SOFT_SOFT_COLLISION_ALGORITHM_H - -#include "BulletCollision/BroadphaseCollision/btCollisionAlgorithm.h" -#include "BulletCollision/BroadphaseCollision/btBroadphaseProxy.h" -#include "BulletCollision/BroadphaseCollision/btDispatcher.h" -#include "BulletCollision/CollisionDispatch/btCollisionCreateFunc.h" - -class btPersistentManifold; -class btSoftBody; - -///collision detection between two btSoftBody shapes -class btSoftSoftCollisionAlgorithm : public btCollisionAlgorithm -{ - bool m_ownManifold; - btPersistentManifold* m_manifoldPtr; - - btSoftBody* m_softBody0; - btSoftBody* m_softBody1; - - -public: - btSoftSoftCollisionAlgorithm(const btCollisionAlgorithmConstructionInfo& ci) - : btCollisionAlgorithm(ci) {} - - virtual void processCollision (btCollisionObject* body0,btCollisionObject* body1,const btDispatcherInfo& dispatchInfo,btManifoldResult* resultOut); - - virtual btScalar calculateTimeOfImpact(btCollisionObject* body0,btCollisionObject* body1,const btDispatcherInfo& dispatchInfo,btManifoldResult* resultOut); - - virtual void getAllContactManifolds(btManifoldArray& manifoldArray) - { - if (m_manifoldPtr && m_ownManifold) - manifoldArray.push_back(m_manifoldPtr); - } - - btSoftSoftCollisionAlgorithm(btPersistentManifold* mf,const btCollisionAlgorithmConstructionInfo& ci,btCollisionObject* body0,btCollisionObject* body1); - - virtual ~btSoftSoftCollisionAlgorithm(); - - struct CreateFunc :public btCollisionAlgorithmCreateFunc - { - virtual btCollisionAlgorithm* CreateCollisionAlgorithm(btCollisionAlgorithmConstructionInfo& ci, btCollisionObject* body0,btCollisionObject* body1) - { - int bbsize = sizeof(btSoftSoftCollisionAlgorithm); - void* ptr = ci.m_dispatcher1->allocateCollisionAlgorithm(bbsize); - return new(ptr) btSoftSoftCollisionAlgorithm(0,ci,body0,body1); - } - }; - -}; - -#endif //SOFT_SOFT_COLLISION_ALGORITHM_H - - diff --git a/extern/bullet2/src/BulletSoftBody/btSparseSDF.h b/extern/bullet2/src/BulletSoftBody/btSparseSDF.h deleted file mode 100644 index eafe74be1ae..00000000000 --- a/extern/bullet2/src/BulletSoftBody/btSparseSDF.h +++ /dev/null @@ -1,306 +0,0 @@ -/* -Bullet Continuous Collision Detection and Physics Library -Copyright (c) 2003-2006 Erwin Coumans http://continuousphysics.com/Bullet/ - -This software is provided 'as-is', without any express or implied warranty. -In no event will the authors be held liable for any damages arising from the use of this software. -Permission is granted to anyone to use this software for any purpose, -including commercial applications, and to alter it and redistribute it freely, -subject to the following restrictions: - -1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. -2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. -3. This notice may not be removed or altered from any source distribution. -*/ -///btSparseSdf implementation by Nathanael Presson - -#ifndef _14F9D17F_EAE8_4aba_B41C_292DB2AA70F3_ -#define _14F9D17F_EAE8_4aba_B41C_292DB2AA70F3_ - -#include "BulletCollision/CollisionDispatch/btCollisionObject.h" -#include "BulletCollision/NarrowPhaseCollision/btGjkEpa2.h" - -// Modified Paul Hsieh hash -template -unsigned int HsiehHash(const void* pdata) - { - const unsigned short* data=(const unsigned short*)pdata; - unsigned hash=DWORDLEN<<2,tmp; - for(int i=0;i>11; - } - hash^=hash<<3;hash+=hash>>5; - hash^=hash<<4;hash+=hash>>17; - hash^=hash<<25;hash+=hash>>6; - return(hash); - } - -template -struct btSparseSdf - { - // - // Inner types - // - struct IntFrac - { - int b; - int i; - btScalar f; - }; - struct Cell - { - btScalar d[CELLSIZE+1][CELLSIZE+1][CELLSIZE+1]; - int c[3]; - int puid; - unsigned hash; - btCollisionShape* pclient; - Cell* next; - }; - // - // Fields - // - - btAlignedObjectArray cells; - btScalar voxelsz; - int puid; - int ncells; - int nprobes; - int nqueries; - - // - // Methods - // - - // - void Initialize(int hashsize=2383) - { - cells.resize(hashsize,0); - Reset(); - } - // - void Reset() - { - for(int i=0,ni=cells.size();inext; - delete pc; - pc=pn; - } - } - voxelsz =0.25; - puid =0; - ncells =0; - nprobes =1; - nqueries =1; - } - // - void GarbageCollect(int lifetime=256) - { - const int life=puid-lifetime; - for(int i=0;inext; - if(pc->puidnext=pn; else root=pn; - delete pc;pc=pp;--ncells; - } - pp=pc;pc=pn; - } - } - //printf("GC[%d]: %d cells, PpQ: %f\r\n",puid,ncells,nprobes/(btScalar)nqueries); - nqueries=1; - nprobes=1; - ++puid; /* TODO: Reset puid's when int range limit is reached */ - /* else setup a priority list... */ - } - // - int RemoveReferences(btCollisionShape* pcs) - { - int refcount=0; - for(int i=0;inext; - if(pc->pclient==pcs) - { - if(pp) pp->next=pn; else root=pn; - delete pc;pc=pp;++refcount; - } - pp=pc;pc=pn; - } - } - return(refcount); - } - // - btScalar Evaluate( const btVector3& x, - btCollisionShape* shape, - btVector3& normal, - btScalar margin) - { - /* Lookup cell */ - const btVector3 scx=x/voxelsz; - const IntFrac ix=Decompose(scx.x()); - const IntFrac iy=Decompose(scx.y()); - const IntFrac iz=Decompose(scx.z()); - const unsigned h=Hash(ix.b,iy.b,iz.b,shape); - Cell*& root=cells[static_cast(h%cells.size())]; - Cell* c=root; - ++nqueries; - while(c) - { - ++nprobes; - if( (c->hash==h) && - (c->c[0]==ix.b) && - (c->c[1]==iy.b) && - (c->c[2]==iz.b) && - (c->pclient==shape)) - { break; } - else - { c=c->next; } - } - if(!c) - { - ++nprobes; - ++ncells; - c=new Cell(); - c->next=root;root=c; - c->pclient=shape; - c->hash=h; - c->c[0]=ix.b;c->c[1]=iy.b;c->c[2]=iz.b; - BuildCell(*c); - } - c->puid=puid; - /* Extract infos */ - const int o[]={ ix.i,iy.i,iz.i}; - const btScalar d[]={ c->d[o[0]+0][o[1]+0][o[2]+0], - c->d[o[0]+1][o[1]+0][o[2]+0], - c->d[o[0]+1][o[1]+1][o[2]+0], - c->d[o[0]+0][o[1]+1][o[2]+0], - c->d[o[0]+0][o[1]+0][o[2]+1], - c->d[o[0]+1][o[1]+0][o[2]+1], - c->d[o[0]+1][o[1]+1][o[2]+1], - c->d[o[0]+0][o[1]+1][o[2]+1]}; - /* Normal */ - #if 1 - const btScalar gx[]={ d[1]-d[0],d[2]-d[3], - d[5]-d[4],d[6]-d[7]}; - const btScalar gy[]={ d[3]-d[0],d[2]-d[1], - d[7]-d[4],d[6]-d[5]}; - const btScalar gz[]={ d[4]-d[0],d[5]-d[1], - d[7]-d[3],d[6]-d[2]}; - normal.setX(Lerp( Lerp(gx[0],gx[1],iy.f), - Lerp(gx[2],gx[3],iy.f),iz.f)); - normal.setY(Lerp( Lerp(gy[0],gy[1],ix.f), - Lerp(gy[2],gy[3],ix.f),iz.f)); - normal.setZ(Lerp( Lerp(gz[0],gz[1],ix.f), - Lerp(gz[2],gz[3],ix.f),iy.f)); - normal = normal.normalized(); - #else - normal = btVector3(d[1]-d[0],d[3]-d[0],d[4]-d[0]).normalized(); - #endif - /* Distance */ - const btScalar d0=Lerp(Lerp(d[0],d[1],ix.f), - Lerp(d[3],d[2],ix.f),iy.f); - const btScalar d1=Lerp(Lerp(d[4],d[5],ix.f), - Lerp(d[7],d[6],ix.f),iy.f); - return(Lerp(d0,d1,iz.f)-margin); - } - // - void BuildCell(Cell& c) - { - const btVector3 org=btVector3( (btScalar)c.c[0], - (btScalar)c.c[1], - (btScalar)c.c[2]) * - CELLSIZE*voxelsz; - for(int k=0;k<=CELLSIZE;++k) - { - const btScalar z=voxelsz*k+org.z(); - for(int j=0;j<=CELLSIZE;++j) - { - const btScalar y=voxelsz*j+org.y(); - for(int i=0;i<=CELLSIZE;++i) - { - const btScalar x=voxelsz*i+org.x(); - c.d[i][j][k]=DistanceToShape( btVector3(x,y,z), - c.pclient); - } - } - } - } - // - static inline btScalar DistanceToShape(const btVector3& x, - btCollisionShape* shape) - { - btTransform unit; - unit.setIdentity(); - if(shape->isConvex()) - { - btGjkEpaSolver2::sResults res; - btConvexShape* csh=static_cast(shape); - return(btGjkEpaSolver2::SignedDistance(x,0,csh,unit,res)); - } - return(0); - } - // - static inline IntFrac Decompose(btScalar x) - { - /* That one need a lot of improvements... */ - /* Remove test, faster floor... */ - IntFrac r; - x/=CELLSIZE; - const int o=x<0?(int)(-x+1):0; - x+=o;r.b=(int)x; - const btScalar k=(x-r.b)*CELLSIZE; - r.i=(int)k;r.f=k-r.i;r.b-=o; - return(r); - } - // - static inline btScalar Lerp(btScalar a,btScalar b,btScalar t) - { - return(a+(b-a)*t); - } - - - - // - static inline unsigned int Hash(int x,int y,int z,btCollisionShape* shape) - { - struct btS - { - int x,y,z; - void* p; - }; - - btS myset; - - myset.x=x;myset.y=y;myset.z=z;myset.p=shape; - const void* ptr = &myset; - - unsigned int result = HsiehHash (ptr); - - - return result; - } -}; - - -#endif diff --git a/extern/bullet2/src/LinearMath/btAabbUtil2.h b/extern/bullet2/src/LinearMath/btAabbUtil2.h index 8bb6b3af7c3..429163c8138 100644 --- a/extern/bullet2/src/LinearMath/btAabbUtil2.h +++ b/extern/bullet2/src/LinearMath/btAabbUtil2.h @@ -18,16 +18,11 @@ subject to the following restrictions: #define AABB_UTIL2 #include "btVector3.h" -#include "btMinMax.h" +#include "btSimdMinMax.h" -SIMD_FORCE_INLINE void AabbExpand (btVector3& aabbMin, - btVector3& aabbMax, - const btVector3& expansionMin, - const btVector3& expansionMax) -{ - aabbMin = aabbMin + expansionMin; - aabbMax = aabbMax + expansionMax; -} + +#define btMin(a,b) ((a < b ? a : b)) +#define btMax(a,b) ((a > b ? a : b)) /// conservative test for overlap between two aabbs @@ -72,41 +67,6 @@ SIMD_FORCE_INLINE int btOutcode(const btVector3& p,const btVector3& halfExtent) } -SIMD_FORCE_INLINE bool btRayAabb2(const btVector3& rayFrom, - const btVector3& rayInvDirection, - const unsigned int raySign[3], - const btVector3 bounds[2], - btScalar& tmin, - btScalar lambda_min, - btScalar lambda_max) -{ - btScalar tmax, tymin, tymax, tzmin, tzmax; - tmin = (bounds[raySign[0]][0] - rayFrom[0]) * rayInvDirection[0]; - tmax = (bounds[1-raySign[0]][0] - rayFrom[0]) * rayInvDirection[0]; - tymin = (bounds[raySign[1]][1] - rayFrom[1]) * rayInvDirection[1]; - tymax = (bounds[1-raySign[1]][1] - rayFrom[1]) * rayInvDirection[1]; - - if ( (tmin > tymax) || (tymin > tmax) ) - return false; - - if (tymin > tmin) - tmin = tymin; - - if (tymax < tmax) - tmax = tymax; - - tzmin = (bounds[raySign[2]][2] - rayFrom[2]) * rayInvDirection[2]; - tzmax = (bounds[1-raySign[2]][2] - rayFrom[2]) * rayInvDirection[2]; - - if ( (tmin > tzmax) || (tzmin > tmax) ) - return false; - if (tzmin > tmin) - tmin = tzmin; - if (tzmax < tmax) - tmax = tzmax; - return ( (tmin < lambda_max) && (tmax > lambda_min) ); -} - SIMD_FORCE_INLINE bool btRayAabb(const btVector3& rayFrom, const btVector3& rayTo, const btVector3& aabbMin, @@ -165,4 +125,3 @@ SIMD_FORCE_INLINE bool btRayAabb(const btVector3& rayFrom, #endif - diff --git a/extern/bullet2/src/LinearMath/btAlignedAllocator.cpp b/extern/bullet2/src/LinearMath/btAlignedAllocator.cpp index e120289e061..1f5877fa37e 100644 --- a/extern/bullet2/src/LinearMath/btAlignedAllocator.cpp +++ b/extern/bullet2/src/LinearMath/btAlignedAllocator.cpp @@ -15,187 +15,56 @@ subject to the following restrictions: #include "btAlignedAllocator.h" -int gNumAlignedAllocs = 0; -int gNumAlignedFree = 0; -int gTotalBytesAlignedAllocs = 0;//detect memory leaks -#if defined (BT_HAS_ALIGNED_ALLOCATOR) +#if defined (BT_HAS_ALIGNED_ALOCATOR) + #include -static void *btAlignedAllocDefault(size_t size, int alignment) +void* btAlignedAlloc (int size, int alignment) { - return _aligned_malloc(size, (size_t)alignment); + return _aligned_malloc(size,alignment); } -static void btAlignedFreeDefault(void *ptr) +void btAlignedFree (void* ptr) { _aligned_free(ptr); } -#elif defined(__CELLOS_LV2__) + +#else + +#ifdef __CELLOS_LV2__ + #include -static inline void *btAlignedAllocDefault(size_t size, int alignment) +int numAllocs = 0; +int numFree = 0; + +void* btAlignedAlloc (int size, int alignment) { + numAllocs++; return memalign(alignment, size); } -static inline void btAlignedFreeDefault(void *ptr) +void btAlignedFree (void* ptr) { + numFree++; free(ptr); } + #else -static inline void *btAlignedAllocDefault(size_t size, int alignment) -{ - void *ret; - char *real; - unsigned long offset; +///todo +///will add some multi-platform version that works without _aligned_malloc/_aligned_free - real = (char *)malloc(size + sizeof(void *) + (alignment-1)); - if (real) { - offset = (alignment - (unsigned long)(real + sizeof(void *))) & (alignment-1); - ret = (void *)((real + sizeof(void *)) + offset); - *((void **)(ret)-1) = (void *)(real); - } else { - ret = (void *)(real); - } - return (ret); +void* btAlignedAlloc (int size, int alignment) +{ + return new char[size]; } -static inline void btAlignedFreeDefault(void *ptr) +void btAlignedFree (void* ptr) { - void* real; - - if (ptr) { - real = *((void **)(ptr)-1); - free(real); - } + delete [] (char*) ptr; } +#endif // + #endif -static void *btAllocDefault(size_t size) -{ - return malloc(size); -} - -static void btFreeDefault(void *ptr) -{ - free(ptr); -} - -static btAlignedAllocFunc *sAlignedAllocFunc = btAlignedAllocDefault; -static btAlignedFreeFunc *sAlignedFreeFunc = btAlignedFreeDefault; -static btAllocFunc *sAllocFunc = btAllocDefault; -static btFreeFunc *sFreeFunc = btFreeDefault; - -void btAlignedAllocSetCustomAligned(btAlignedAllocFunc *allocFunc, btAlignedFreeFunc *freeFunc) -{ - sAlignedAllocFunc = allocFunc ? allocFunc : btAlignedAllocDefault; - sAlignedFreeFunc = freeFunc ? freeFunc : btAlignedFreeDefault; -} - -void btAlignedAllocSetCustom(btAllocFunc *allocFunc, btFreeFunc *freeFunc) -{ - sAllocFunc = allocFunc ? allocFunc : btAllocDefault; - sFreeFunc = freeFunc ? freeFunc : btFreeDefault; -} - -#ifdef BT_DEBUG_MEMORY_ALLOCATIONS -//this generic allocator provides the total allocated number of bytes -#include - -void* btAlignedAllocInternal (size_t size, int alignment,int line,char* filename) -{ - void *ret; - char *real; - unsigned long offset; - - gTotalBytesAlignedAllocs += size; - gNumAlignedAllocs++; - - - real = (char *)sAllocFunc(size + 2*sizeof(void *) + (alignment-1)); - if (real) { - offset = (alignment - (unsigned long)(real + 2*sizeof(void *))) & -(alignment-1); - ret = (void *)((real + 2*sizeof(void *)) + offset); - *((void **)(ret)-1) = (void *)(real); - *((int*)(ret)-2) = size; - - } else { - ret = (void *)(real);//?? - } - - printf("allocation#%d at address %x, from %s,line %d, size %d\n",gNumAlignedAllocs,real, filename,line,size); - - int* ptr = (int*)ret; - *ptr = 12; - return (ret); -} - -void btAlignedFreeInternal (void* ptr,int line,char* filename) -{ - - void* real; - gNumAlignedFree++; - - if (ptr) { - real = *((void **)(ptr)-1); - int size = *((int*)(ptr)-2); - gTotalBytesAlignedAllocs -= size; - - printf("free #%d at address %x, from %s,line %d, size %d\n",gNumAlignedFree,real, filename,line,size); - - sFreeFunc(real); - } else - { - printf("NULL ptr\n"); - } -} - -#else //BT_DEBUG_MEMORY_ALLOCATIONS - -void* btAlignedAllocInternal (size_t size, int alignment) -{ - gNumAlignedAllocs++; - void* ptr; -#if defined (BT_HAS_ALIGNED_ALLOCATOR) || defined(__CELLOS_LV2__) - ptr = sAlignedAllocFunc(size, alignment); -#else - char *real; - unsigned long offset; - - real = (char *)sAllocFunc(size + sizeof(void *) + (alignment-1)); - if (real) { - offset = (alignment - (unsigned long)(real + sizeof(void *))) & (alignment-1); - ptr = (void *)((real + sizeof(void *)) + offset); - *((void **)(ptr)-1) = (void *)(real); - } else { - ptr = (void *)(real); - } -#endif // defined (BT_HAS_ALIGNED_ALLOCATOR) || defined(__CELLOS_LV2__) -// printf("btAlignedAllocInternal %d, %x\n",size,ptr); - return ptr; -} - -void btAlignedFreeInternal (void* ptr) -{ - if (!ptr) - { - return; - } - - gNumAlignedFree++; -// printf("btAlignedFreeInternal %x\n",ptr); -#if defined (BT_HAS_ALIGNED_ALLOCATOR) || defined(__CELLOS_LV2__) - sAlignedFreeFunc(ptr); -#else - void* real; - - if (ptr) { - real = *((void **)(ptr)-1); - sFreeFunc(real); - } -#endif // defined (BT_HAS_ALIGNED_ALLOCATOR) || defined(__CELLOS_LV2__) -} - -#endif //BT_DEBUG_MEMORY_ALLOCATIONS diff --git a/extern/bullet2/src/LinearMath/btAlignedAllocator.h b/extern/bullet2/src/LinearMath/btAlignedAllocator.h index a252f324d77..07585717f45 100644 --- a/extern/bullet2/src/LinearMath/btAlignedAllocator.h +++ b/extern/bullet2/src/LinearMath/btAlignedAllocator.h @@ -21,39 +21,15 @@ subject to the following restrictions: ///that is better portable and more predictable #include "btScalar.h" -//#define BT_DEBUG_MEMORY_ALLOCATIONS 1 -#ifdef BT_DEBUG_MEMORY_ALLOCATIONS -#define btAlignedAlloc(a,b) \ - btAlignedAllocInternal(a,b,__LINE__,__FILE__) +void* btAlignedAlloc (int size, int alignment); -#define btAlignedFree(ptr) \ - btAlignedFreeInternal(ptr,__LINE__,__FILE__) +void btAlignedFree (void* ptr); -void* btAlignedAllocInternal (size_t size, int alignment,int line,char* filename); -void btAlignedFreeInternal (void* ptr,int line,char* filename); - -#else - void* btAlignedAllocInternal (size_t size, int alignment); - void btAlignedFreeInternal (void* ptr); - - #define btAlignedAlloc(a,b) btAlignedAllocInternal(a,b) - #define btAlignedFree(ptr) btAlignedFreeInternal(ptr) - -#endif typedef int size_type; -typedef void *(btAlignedAllocFunc)(size_t size, int alignment); -typedef void (btAlignedFreeFunc)(void *memblock); -typedef void *(btAllocFunc)(size_t size); -typedef void (btFreeFunc)(void *memblock); -void btAlignedAllocSetCustomAligned(btAlignedAllocFunc *allocFunc, btAlignedFreeFunc *freeFunc); -void btAlignedAllocSetCustom(btAllocFunc *allocFunc, btFreeFunc *freeFunc); - -///The btAlignedAllocator is a portable class for aligned memory allocations. -///Default implementations for unaligned and aligned allocations can be overridden by a custom allocator using btAlignedAllocSetCustom and btAlignedAllocSetCustomAligned. template < typename T , unsigned Alignment > class btAlignedAllocator { diff --git a/extern/bullet2/src/LinearMath/btAlignedObjectArray.h b/extern/bullet2/src/LinearMath/btAlignedObjectArray.h index 5598f0d7236..8bef5eb5d06 100644 --- a/extern/bullet2/src/LinearMath/btAlignedObjectArray.h +++ b/extern/bullet2/src/LinearMath/btAlignedObjectArray.h @@ -39,8 +39,8 @@ subject to the following restrictions: #endif //BT_USE_PLACEMENT_NEW -///The btAlignedObjectArray template class uses a subset of the stl::vector interface for its methods -///It is developed to replace stl::vector to avoid portability issues, including STL alignment issues to add SIMD/SSE data +///btAlignedObjectArray uses a subset of the stl::vector interface for its methods +///It is developed to replace stl::vector to avoid STL alignment issues to add SIMD/SSE data template //template class btAlignedObjectArray @@ -50,8 +50,6 @@ class btAlignedObjectArray int m_size; int m_capacity; T* m_data; - //PCK: added this line - bool m_ownsMemory; protected: SIMD_FORCE_INLINE int allocSize(int size) @@ -71,8 +69,6 @@ class btAlignedObjectArray SIMD_FORCE_INLINE void init() { - //PCK: added this line - m_ownsMemory = true; m_data = 0; m_size = 0; m_capacity = 0; @@ -96,11 +92,7 @@ class btAlignedObjectArray SIMD_FORCE_INLINE void deallocate() { if(m_data) { - //PCK: enclosed the deallocation in this block - if (m_ownsMemory) - { - m_allocator.deallocate(m_data); - } + m_allocator.deallocate(m_data); m_data = 0; } } @@ -231,9 +223,6 @@ class btAlignedObjectArray destroy(0,size()); deallocate(); - - //PCK: added this line - m_ownsMemory = true; m_data = s; @@ -253,46 +242,6 @@ class btAlignedObjectArray } }; - template - void quickSortInternal(L CompareFunc,int lo, int hi) - { - // lo is the lower index, hi is the upper index - // of the region of array a that is to be sorted - int i=lo, j=hi; - T x=m_data[(lo+hi)/2]; - - // partition - do - { - while (CompareFunc(m_data[i],x)) - i++; - while (CompareFunc(x,m_data[j])) - j--; - if (i<=j) - { - swap(i,j); - i++; j--; - } - } while (i<=j); - - // recursion - if (lo - void quickSort(L CompareFunc) - { - //don't sort 0 or 1 elements - if (size()>1) - { - quickSortInternal(CompareFunc,0,size()-1); - } - } - ///heap sort from http://www.csse.monash.edu.au/~lloyd/tildeAlgDS/Sort/Heap/ template @@ -411,16 +360,8 @@ class btAlignedObjectArray } } - //PCK: whole function - void initializeFromBuffer(void *buffer, int size, int capacity) - { - clear(); - m_ownsMemory = false; - m_data = (T*)buffer; - m_size = size; - m_capacity = capacity; - } - }; #endif //BT_OBJECT_ARRAY__ + + diff --git a/extern/bullet2/src/LinearMath/btDefaultMotionState.h b/extern/bullet2/src/LinearMath/btDefaultMotionState.h index d758f77ed81..d4ec8e8879c 100644 --- a/extern/bullet2/src/LinearMath/btDefaultMotionState.h +++ b/extern/bullet2/src/LinearMath/btDefaultMotionState.h @@ -1,7 +1,7 @@ #ifndef DEFAULT_MOTION_STATE_H #define DEFAULT_MOTION_STATE_H -///The btDefaultMotionState provides a common implementation to synchronize world transforms with offsets. +///btDefaultMotionState provides a common implementation to synchronize world transforms with offsets struct btDefaultMotionState : public btMotionState { btTransform m_graphicsWorldTrans; diff --git a/extern/bullet2/src/LinearMath/btGeometryUtil.cpp b/extern/bullet2/src/LinearMath/btGeometryUtil.cpp index 5ac230f712f..3d0fb122a6b 100644 --- a/extern/bullet2/src/LinearMath/btGeometryUtil.cpp +++ b/extern/bullet2/src/LinearMath/btGeometryUtil.cpp @@ -22,12 +22,7 @@ subject to the following restrictions: can be used by probes that are checking whether the library is actually installed. */ -extern "C" -{ - void btBulletMathProbe (); - - void btBulletMathProbe () {} -} +extern "C" void btBulletMathProbe () {} bool btGeometryUtil::isPointInsidePlanes(const btAlignedObjectArray& planeEquations, const btVector3& point, btScalar margin) @@ -62,8 +57,6 @@ bool btGeometryUtil::areVerticesBehindPlane(const btVector3& planeNormal, const return true; } -bool notExist(const btVector3& planeEquation,const btAlignedObjectArray& planeEquations); - bool notExist(const btVector3& planeEquation,const btAlignedObjectArray& planeEquations) { int numbrushes = planeEquations.size(); diff --git a/extern/bullet2/src/LinearMath/btGeometryUtil.h b/extern/bullet2/src/LinearMath/btGeometryUtil.h index a4b13b45609..766cd75c383 100644 --- a/extern/bullet2/src/LinearMath/btGeometryUtil.h +++ b/extern/bullet2/src/LinearMath/btGeometryUtil.h @@ -19,7 +19,6 @@ subject to the following restrictions: #include "btVector3.h" #include "btAlignedObjectArray.h" -///The btGeometryUtil helper class provides a few methods to convert between plane equations and vertices. class btGeometryUtil { public: diff --git a/extern/bullet2/src/LinearMath/btIDebugDraw.h b/extern/bullet2/src/LinearMath/btIDebugDraw.h index 563615a9a32..5f40ca39157 100644 --- a/extern/bullet2/src/LinearMath/btIDebugDraw.h +++ b/extern/bullet2/src/LinearMath/btIDebugDraw.h @@ -31,9 +31,6 @@ DEALINGS IN THE SOFTWARE. #include "btVector3.h" -///The btIDebugDraw interface class allows hooking up a debug renderer to visually debug simulations. -///Typical use case: create a debug drawer object, and assign it to a btCollisionWorld or btDynamicsWorld using setDebugDrawer and call debugDrawWorld. -///A class that implements the btIDebugDraw interface has to implement the drawLine method at a minimum. class btIDebugDraw { public: @@ -58,24 +55,11 @@ class btIDebugDraw virtual ~btIDebugDraw() {}; virtual void drawLine(const btVector3& from,const btVector3& to,const btVector3& color)=0; - - virtual void drawTriangle(const btVector3& v0,const btVector3& v1,const btVector3& v2,const btVector3& /*n0*/,const btVector3& /*n1*/,const btVector3& /*n2*/,const btVector3& color, btScalar alpha) - { - drawTriangle(v0,v1,v2,color,alpha); - } - virtual void drawTriangle(const btVector3& v0,const btVector3& v1,const btVector3& v2,const btVector3& color, btScalar /*alpha*/) - { - drawLine(v0,v1,color); - drawLine(v1,v2,color); - drawLine(v2,v0,color); - } virtual void drawContactPoint(const btVector3& PointOnB,const btVector3& normalOnB,btScalar distance,int lifeTime,const btVector3& color)=0; virtual void reportErrorWarning(const char* warningString) = 0; - virtual void draw3dText(const btVector3& location,const char* textString) = 0; - virtual void setDebugMode(int debugMode) =0; virtual int getDebugMode() const = 0; diff --git a/extern/bullet2/src/LinearMath/btMatrix3x3.h b/extern/bullet2/src/LinearMath/btMatrix3x3.h index ca1a801402f..94f53c3c0a5 100644 --- a/extern/bullet2/src/LinearMath/btMatrix3x3.h +++ b/extern/bullet2/src/LinearMath/btMatrix3x3.h @@ -22,9 +22,6 @@ subject to the following restrictions: #include "btQuaternion.h" - -///The btMatrix3x3 class implements a 3x3 rotation matrix, to perform linear algebra in combination with btQuaternion, btTransform and btVector3. -///Make sure to only include a pure orthogonal matrix without scaling. class btMatrix3x3 { public: btMatrix3x3 () {} @@ -359,7 +356,7 @@ class btMatrix3x3 { m_el[0].y() * m[0].z() + m_el[1].y() * m[1].z() + m_el[2].y() * m[2].z(), m_el[0].z() * m[0].x() + m_el[1].z() * m[1].x() + m_el[2].z() * m[2].x(), m_el[0].z() * m[0].y() + m_el[1].z() * m[1].y() + m_el[2].z() * m[2].y(), - m_el[0].z() * m[0].z() + m_el[1].z() * m[1].z() + m_el[2].z() * m[2].z()); + m_el[0].z() * m[0].z() + m_el[1].z() * m[1].z() + m_el[2].z() * m[2].x()); } SIMD_FORCE_INLINE btMatrix3x3 @@ -409,11 +406,5 @@ class btMatrix3x3 { } */ -SIMD_FORCE_INLINE bool operator==(const btMatrix3x3& m1, const btMatrix3x3& m2) -{ - return ( m1[0][0] == m2[0][0] && m1[1][0] == m2[1][0] && m1[2][0] == m2[2][0] && - m1[0][1] == m2[0][1] && m1[1][1] == m2[1][1] && m1[2][1] == m2[2][1] && - m1[0][2] == m2[0][2] && m1[1][2] == m2[1][2] && m1[2][2] == m2[2][2] ); -} #endif diff --git a/extern/bullet2/src/LinearMath/btMinMax.h b/extern/bullet2/src/LinearMath/btMinMax.h index 5e27d62a4a4..1b8a3633f38 100644 --- a/extern/bullet2/src/LinearMath/btMinMax.h +++ b/extern/bullet2/src/LinearMath/btMinMax.h @@ -18,15 +18,15 @@ subject to the following restrictions: #define GEN_MINMAX_H template -SIMD_FORCE_INLINE const T& btMin(const T& a, const T& b) +SIMD_FORCE_INLINE const T& GEN_min(const T& a, const T& b) { - return a < b ? a : b ; + return b < a ? b : a; } template -SIMD_FORCE_INLINE const T& btMax(const T& a, const T& b) +SIMD_FORCE_INLINE const T& GEN_max(const T& a, const T& b) { - return a > b ? a : b; + return a < b ? b : a; } template @@ -36,7 +36,7 @@ SIMD_FORCE_INLINE const T& GEN_clamped(const T& a, const T& lb, const T& ub) } template -SIMD_FORCE_INLINE void btSetMin(T& a, const T& b) +SIMD_FORCE_INLINE void GEN_set_min(T& a, const T& b) { if (b < a) { @@ -45,7 +45,7 @@ SIMD_FORCE_INLINE void btSetMin(T& a, const T& b) } template -SIMD_FORCE_INLINE void btSetMax(T& a, const T& b) +SIMD_FORCE_INLINE void GEN_set_max(T& a, const T& b) { if (a < b) { diff --git a/extern/bullet2/src/LinearMath/btMotionState.h b/extern/bullet2/src/LinearMath/btMotionState.h index 94318140902..1975e5ff900 100644 --- a/extern/bullet2/src/LinearMath/btMotionState.h +++ b/extern/bullet2/src/LinearMath/btMotionState.h @@ -18,7 +18,7 @@ subject to the following restrictions: #include "btTransform.h" -///The btMotionState interface class allows the dynamics world to synchronize and interpolate the updated world transforms with graphics +///btMotionState allows the dynamics world to synchronize the updated world transforms with graphics ///For optimizations, potentially only moving objects get synchronized (using setWorldPosition/setWorldOrientation) class btMotionState { diff --git a/extern/bullet2/src/LinearMath/btQuadWord.h b/extern/bullet2/src/LinearMath/btQuadWord.h index 2e80fc2ca47..961ac484d20 100644 --- a/extern/bullet2/src/LinearMath/btQuadWord.h +++ b/extern/bullet2/src/LinearMath/btQuadWord.h @@ -17,31 +17,19 @@ subject to the following restrictions: #define SIMD_QUADWORD_H #include "btScalar.h" -#include "btMinMax.h" -#include -///The btQuadWordStorage class is base class for btVector3 and btQuaternion. -///Some issues under PS3 Linux with IBM 2.1 SDK, gcc compiler prevent from using aligned quadword. todo: look into this -///ATTRIBUTE_ALIGNED16(class) btQuadWordStorage -class btQuadWordStorage -{ -protected: - - btScalar m_x; - btScalar m_y; - btScalar m_z; - btScalar m_unusedW; - -public: - -}; - ///btQuadWord is base-class for vectors, points -class btQuadWord : public btQuadWordStorage +class btQuadWord { + protected: + btScalar m_x; + btScalar m_y; + btScalar m_z; + btScalar m_unusedW; + public: // SIMD_FORCE_INLINE btScalar& operator[](int i) { return (&m_x)[i]; } @@ -73,8 +61,6 @@ class btQuadWord : public btQuadWordStorage SIMD_FORCE_INLINE operator btScalar *() { return &m_x; } SIMD_FORCE_INLINE operator const btScalar *() const { return &m_x; } - - SIMD_FORCE_INLINE void setValue(const btScalar& x, const btScalar& y, const btScalar& z) { m_x=x; @@ -103,36 +89,47 @@ class btQuadWord : public btQuadWordStorage { } - SIMD_FORCE_INLINE btQuadWord(const btQuadWordStorage& q) + SIMD_FORCE_INLINE btQuadWord(const btScalar& x, const btScalar& y, const btScalar& z) + :m_x(x),m_y(y),m_z(z) + //todo, remove this in release/simd ? + ,m_unusedW(btScalar(0.)) { - *((btQuadWordStorage*)this) = q; - } - - SIMD_FORCE_INLINE btQuadWord(const btScalar& x, const btScalar& y, const btScalar& z) - { - m_x = x, m_y = y, m_z = z, m_unusedW = 0.0f; } SIMD_FORCE_INLINE btQuadWord(const btScalar& x, const btScalar& y, const btScalar& z,const btScalar& w) + :m_x(x),m_y(y),m_z(z),m_unusedW(w) { - m_x = x, m_y = y, m_z = z, m_unusedW = w; } SIMD_FORCE_INLINE void setMax(const btQuadWord& other) { - btSetMax(m_x, other.m_x); - btSetMax(m_y, other.m_y); - btSetMax(m_z, other.m_z); - btSetMax(m_unusedW, other.m_unusedW); + if (other.m_x > m_x) + m_x = other.m_x; + + if (other.m_y > m_y) + m_y = other.m_y; + + if (other.m_z > m_z) + m_z = other.m_z; + + if (other.m_unusedW > m_unusedW) + m_unusedW = other.m_unusedW; } SIMD_FORCE_INLINE void setMin(const btQuadWord& other) { - btSetMin(m_x, other.m_x); - btSetMin(m_y, other.m_y); - btSetMin(m_z, other.m_z); - btSetMin(m_unusedW, other.m_unusedW); + if (other.m_x < m_x) + m_x = other.m_x; + + if (other.m_y < m_y) + m_y = other.m_y; + + if (other.m_z < m_z) + m_z = other.m_z; + + if (other.m_unusedW < m_unusedW) + m_unusedW = other.m_unusedW; } diff --git a/extern/bullet2/src/LinearMath/btQuaternion.h b/extern/bullet2/src/LinearMath/btQuaternion.h index 264751b33e7..50334970ba6 100644 --- a/extern/bullet2/src/LinearMath/btQuaternion.h +++ b/extern/bullet2/src/LinearMath/btQuaternion.h @@ -19,7 +19,6 @@ subject to the following restrictions: #include "btVector3.h" -///The btQuaternion implements quaternion to perform linear algebra rotations in combination with btMatrix3x3, btVector3 and btTransform. class btQuaternion : public btQuadWord { public: btQuaternion() {} @@ -159,7 +158,7 @@ public: btQuaternion inverse() const { - return btQuaternion(-m_x, -m_y, -m_z, m_unusedW); + return btQuaternion(m_x, m_y, m_z, -m_unusedW); } SIMD_FORCE_INLINE btQuaternion @@ -286,7 +285,7 @@ slerp(const btQuaternion& q1, const btQuaternion& q2, const btScalar& t) } SIMD_FORCE_INLINE btVector3 -quatRotate(const btQuaternion& rotation, const btVector3& v) +quatRotate(btQuaternion& rotation, btVector3& v) { btQuaternion q = rotation * v; q *= rotation.inverse(); @@ -294,7 +293,7 @@ quatRotate(const btQuaternion& rotation, const btVector3& v) } SIMD_FORCE_INLINE btQuaternion -shortestArcQuat(const btVector3& v0, const btVector3& v1) // Game Programming Gems 2.10. make sure v0,v1 are normalized +shortestArcQuat(btVector3& v0,btVector3& v1) // Game Programming Gems 2.10. make sure v0,v1 are normalized { btVector3 c = v0.cross(v1); btScalar d = v0.dot(v1); @@ -309,7 +308,7 @@ shortestArcQuat(const btVector3& v0, const btVector3& v1) // Game Programming Ge } SIMD_FORCE_INLINE btQuaternion -shortestArcQuatNormalize2(btVector3& v0,btVector3& v1) +shortestArcQuatNormalize(btVector3& v0,btVector3& v1) { v0.normalize(); v1.normalize(); @@ -320,4 +319,3 @@ shortestArcQuatNormalize2(btVector3& v0,btVector3& v1) - diff --git a/extern/bullet2/src/LinearMath/btQuickprof.cpp b/extern/bullet2/src/LinearMath/btQuickprof.cpp index e5b1196149b..37a0c8c3be5 100644 --- a/extern/bullet2/src/LinearMath/btQuickprof.cpp +++ b/extern/bullet2/src/LinearMath/btQuickprof.cpp @@ -1,282 +1,38 @@ /* +Copyright (c) 2006 Tyler Streeter -/*************************************************************************************************** -** -** profile.cpp -** -** Real-Time Hierarchical Profiling for Game Programming Gems 3 -** -** by Greg Hjelstrom & Byon Garrabrant -** -***************************************************************************************************/ +This software is provided 'as-is', without any express or implied warranty. +In no event will the authors be held liable for any damages arising from the use of this software. +Permission is granted to anyone to use this software for any purpose, +including commercial applications, and to alter it and redistribute it freely, +subject to the following restrictions: + +1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. +2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. +3. This notice may not be removed or altered from any source distribution. + +*/ + + +// Please visit the project website (http://quickprof.sourceforge.net) +// for usage instructions. // Credits: The Clock class was inspired by the Timer classes in // Ogre (www.ogre3d.org). #include "LinearMath/btQuickprof.h" +#ifdef USE_QUICKPROF -#ifdef USE_BT_CLOCK - -static btClock gProfileClock; - -inline void Profile_Get_Ticks(unsigned long int * ticks) -{ - *ticks = gProfileClock.getTimeMicroseconds(); -} - -inline float Profile_Get_Tick_Rate(void) -{ -// return 1000000.f; - return 1000.f; - -} - - - -/*************************************************************************************************** -** -** CProfileNode -** -***************************************************************************************************/ - -/*********************************************************************************************** - * INPUT: * - * name - pointer to a static string which is the name of this profile node * - * parent - parent pointer * - * * - * WARNINGS: * - * The name is assumed to be a static pointer, only the pointer is stored and compared for * - * efficiency reasons. * - *=============================================================================================*/ -CProfileNode::CProfileNode( const char * name, CProfileNode * parent ) : - Name( name ), - TotalCalls( 0 ), - TotalTime( 0 ), - StartTime( 0 ), - RecursionCounter( 0 ), - Parent( parent ), - Child( NULL ), - Sibling( NULL ) -{ - Reset(); -} - - -void CProfileNode::CleanupMemory() -{ - delete ( Child); - Child = NULL; - delete ( Sibling); - Sibling = NULL; -} - -CProfileNode::~CProfileNode( void ) -{ - delete ( Child); - delete ( Sibling); -} - - -/*********************************************************************************************** - * INPUT: * - * name - static string pointer to the name of the node we are searching for * - * * - * WARNINGS: * - * All profile names are assumed to be static strings so this function uses pointer compares * - * to find the named node. * - *=============================================================================================*/ -CProfileNode * CProfileNode::Get_Sub_Node( const char * name ) -{ - // Try to find this sub node - CProfileNode * child = Child; - while ( child ) { - if ( child->Name == name ) { - return child; - } - child = child->Sibling; - } - - // We didn't find it, so add it - - CProfileNode * node = new CProfileNode( name, this ); - node->Sibling = Child; - Child = node; - return node; -} - - -void CProfileNode::Reset( void ) -{ - TotalCalls = 0; - TotalTime = 0.0f; - gProfileClock.reset(); - - if ( Child ) { - Child->Reset(); - } - if ( Sibling ) { - Sibling->Reset(); - } -} - - -void CProfileNode::Call( void ) -{ - TotalCalls++; - if (RecursionCounter++ == 0) { - Profile_Get_Ticks(&StartTime); - } -} - - -bool CProfileNode::Return( void ) -{ - if ( --RecursionCounter == 0 && TotalCalls != 0 ) { - unsigned long int time; - Profile_Get_Ticks(&time); - time-=StartTime; - TotalTime += (float)time / Profile_Get_Tick_Rate(); - } - return ( RecursionCounter == 0 ); -} - - -/*************************************************************************************************** -** -** CProfileIterator -** -***************************************************************************************************/ -CProfileIterator::CProfileIterator( CProfileNode * start ) -{ - CurrentParent = start; - CurrentChild = CurrentParent->Get_Child(); -} - - -void CProfileIterator::First(void) -{ - CurrentChild = CurrentParent->Get_Child(); -} - - -void CProfileIterator::Next(void) -{ - CurrentChild = CurrentChild->Get_Sibling(); -} - - -bool CProfileIterator::Is_Done(void) -{ - return CurrentChild == NULL; -} - - -void CProfileIterator::Enter_Child( int index ) -{ - CurrentChild = CurrentParent->Get_Child(); - while ( (CurrentChild != NULL) && (index != 0) ) { - index--; - CurrentChild = CurrentChild->Get_Sibling(); - } - - if ( CurrentChild != NULL ) { - CurrentParent = CurrentChild; - CurrentChild = CurrentParent->Get_Child(); - } -} - - -void CProfileIterator::Enter_Parent( void ) -{ - if ( CurrentParent->Get_Parent() != NULL ) { - CurrentParent = CurrentParent->Get_Parent(); - } - CurrentChild = CurrentParent->Get_Child(); -} - - -/*************************************************************************************************** -** -** CProfileManager -** -***************************************************************************************************/ - -CProfileNode CProfileManager::Root( "Root", NULL ); -CProfileNode * CProfileManager::CurrentNode = &CProfileManager::Root; -int CProfileManager::FrameCounter = 0; -unsigned long int CProfileManager::ResetTime = 0; - - -/*********************************************************************************************** - * CProfileManager::Start_Profile -- Begin a named profile * - * * - * Steps one level deeper into the tree, if a child already exists with the specified name * - * then it accumulates the profiling; otherwise a new child node is added to the profile tree. * - * * - * INPUT: * - * name - name of this profiling record * - * * - * WARNINGS: * - * The string used is assumed to be a static string; pointer compares are used throughout * - * the profiling code for efficiency. * - *=============================================================================================*/ -void CProfileManager::Start_Profile( const char * name ) -{ - if (name != CurrentNode->Get_Name()) { - CurrentNode = CurrentNode->Get_Sub_Node( name ); - } - - CurrentNode->Call(); -} - - -/*********************************************************************************************** - * CProfileManager::Stop_Profile -- Stop timing and record the results. * - *=============================================================================================*/ -void CProfileManager::Stop_Profile( void ) -{ - // Return will indicate whether we should back up to our parent (we may - // be profiling a recursive function) - if (CurrentNode->Return()) { - CurrentNode = CurrentNode->Get_Parent(); - } -} - - -/*********************************************************************************************** - * CProfileManager::Reset -- Reset the contents of the profiling system * - * * - * This resets everything except for the tree structure. All of the timing data is reset. * - *=============================================================================================*/ -void CProfileManager::Reset( void ) -{ - Root.Reset(); - Root.Call(); - FrameCounter = 0; - Profile_Get_Ticks(&ResetTime); -} - - -/*********************************************************************************************** - * CProfileManager::Increment_Frame_Counter -- Increment the frame counter * - *=============================================================================================*/ -void CProfileManager::Increment_Frame_Counter( void ) -{ - FrameCounter++; -} - - -/*********************************************************************************************** - * CProfileManager::Get_Time_Since_Reset -- returns the elapsed time since last reset * - *=============================================================================================*/ -float CProfileManager::Get_Time_Since_Reset( void ) -{ - unsigned long int time; - Profile_Get_Ticks(&time); - time -= ResetTime; - return (float)time / Profile_Get_Tick_Rate(); -} - -#endif //USE_BT_CLOCK - +// Note: We must declare these private static variables again here to +// avoid link errors. +bool btProfiler::mEnabled = false; +btClock btProfiler::mClock; +unsigned long int btProfiler::mCurrentCycleStartMicroseconds = 0; +unsigned long int btProfiler::mLastCycleDurationMicroseconds = 0; +std::map btProfiler::mProfileBlocks; +std::ofstream btProfiler::mOutputFile; +bool btProfiler::mFirstFileOutput = true; +btProfiler::BlockTimingMethod btProfiler::mFileOutputMethod; +unsigned long int btProfiler::mCycleNumber = 0; +#endif //USE_QUICKPROF diff --git a/extern/bullet2/src/LinearMath/btQuickprof.h b/extern/bullet2/src/LinearMath/btQuickprof.h index b033940ca5c..a885967c5fa 100644 --- a/extern/bullet2/src/LinearMath/btQuickprof.h +++ b/extern/bullet2/src/LinearMath/btQuickprof.h @@ -1,11 +1,20 @@ +/* +Copyright (c) 2006 Tyler Streeter -/*************************************************************************************************** -** -** Real-Time Hierarchical Profiling for Game Programming Gems 3 -** -** by Greg Hjelstrom & Byon Garrabrant -** -***************************************************************************************************/ +This software is provided 'as-is', without any express or implied warranty. +In no event will the authors be held liable for any damages arising from the use of this software. +Permission is granted to anyone to use this software for any purpose, +including commercial applications, and to alter it and redistribute it freely, +subject to the following restrictions: + +1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. +2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. +3. This notice may not be removed or altered from any source distribution. + +*/ + +// Please visit the project website (http://quickprof.sourceforge.net) +// for usage instructions. // Credits: The Clock class was inspired by the Timer classes in // Ogre (www.ogre3d.org). @@ -14,10 +23,9 @@ #define QUICK_PROF_H #include "btScalar.h" -#include "LinearMath/btAlignedAllocator.h" -#include -//To disable built-in profiling, please comment out next line -//#define BT_NO_PROFILE 1 + +//#define USE_QUICKPROF 1 +//Don't use quickprof for now, because it contains STL. TODO: replace STL by Bullet container classes. //if you don't need btClock, you can comment next line @@ -26,332 +34,678 @@ #ifdef USE_BT_CLOCK #ifdef __CELLOS_LV2__ #include -#include #include +typedef uint64_t __int64; #endif #if defined (SUNOS) || defined (__SUNOS__) -#include + #include #endif #if defined(WIN32) || defined(_WIN32) -#define USE_WINDOWS_TIMERS -#define WIN32_LEAN_AND_MEAN -#define NOWINRES -#define NOMCX -#define NOIME + #define USE_WINDOWS_TIMERS + #define WIN32_LEAN_AND_MEAN + #define NOWINRES + #define NOMCX + #define NOIME #ifdef _XBOX -#include + #include #else -#include + #include #endif -#include + #include #else -#include + #include #endif #define mymin(a,b) (a > b ? a : b) -///The btClock is a portable basic clock that measures accurate time in seconds, use for profiling. +/// basic clock class btClock -{ -public: - btClock() { -#ifdef USE_WINDOWS_TIMERS - QueryPerformanceFrequency(&mClockFrequency); -#endif - reset(); - } - - ~btClock() - { - } - - /// Resets the initial reference time. - void reset() - { -#ifdef USE_WINDOWS_TIMERS - QueryPerformanceCounter(&mStartTime); - mStartTick = GetTickCount(); - mPrevElapsedTime = 0; -#else -#ifdef __CELLOS_LV2__ - - typedef uint64_t ClockSize; - ClockSize newTime; - //__asm __volatile__( "mftb %0" : "=r" (newTime) : : "memory"); - SYS_TIMEBASE_GET( newTime ); - mStartTime = newTime; -#else - gettimeofday(&mStartTime, 0); -#endif - -#endif - } - - /// Returns the time in ms since the last call to reset or since - /// the btClock was created. - unsigned long int getTimeMilliseconds() - { -#ifdef USE_WINDOWS_TIMERS - LARGE_INTEGER currentTime; - QueryPerformanceCounter(¤tTime); - LONGLONG elapsedTime = currentTime.QuadPart - - mStartTime.QuadPart; - - // Compute the number of millisecond ticks elapsed. - unsigned long msecTicks = (unsigned long)(1000 * elapsedTime / - mClockFrequency.QuadPart); - - // Check for unexpected leaps in the Win32 performance counter. - // (This is caused by unexpected data across the PCI to ISA - // bridge, aka south bridge. See Microsoft KB274323.) - unsigned long elapsedTicks = GetTickCount() - mStartTick; - signed long msecOff = (signed long)(msecTicks - elapsedTicks); - if (msecOff < -100 || msecOff > 100) + public: + btClock() { - // Adjust the starting time forwards. - LONGLONG msecAdjustment = mymin(msecOff * - mClockFrequency.QuadPart / 1000, elapsedTime - - mPrevElapsedTime); - mStartTime.QuadPart += msecAdjustment; - elapsedTime -= msecAdjustment; - - // Recompute the number of millisecond ticks elapsed. - msecTicks = (unsigned long)(1000 * elapsedTime / - mClockFrequency.QuadPart); +#ifdef USE_WINDOWS_TIMERS + QueryPerformanceFrequency(&mClockFrequency); +#endif + reset(); } - // Store the current elapsed time for adjustments next time. - mPrevElapsedTime = elapsedTime; + ~btClock() + { + } - return msecTicks; + /// Resets the initial reference time. + void reset() + { +#ifdef USE_WINDOWS_TIMERS + QueryPerformanceCounter(&mStartTime); + mStartTick = GetTickCount(); + mPrevElapsedTime = 0; #else - #ifdef __CELLOS_LV2__ - uint64_t freq=sys_time_get_timebase_frequency(); - double dFreq=((double) freq) / 1000.0; - typedef uint64_t ClockSize; - ClockSize newTime; - SYS_TIMEBASE_GET( newTime ); - //__asm __volatile__( "mftb %0" : "=r" (newTime) : : "memory"); - return (unsigned long int)((double(newTime-mStartTime)) / dFreq); + typedef uint64_t __int64; + typedef __int64 ClockSize; + ClockSize newTime; + __asm __volatile__( "mftb %0" : "=r" (newTime) : : "memory"); + mStartTime = newTime; +#else + gettimeofday(&mStartTime, 0); +#endif + +#endif + } + + /// Returns the time in ms since the last call to reset or since + /// the btClock was created. + unsigned long int getTimeMilliseconds() + { +#ifdef USE_WINDOWS_TIMERS + LARGE_INTEGER currentTime; + QueryPerformanceCounter(¤tTime); + LONGLONG elapsedTime = currentTime.QuadPart - + mStartTime.QuadPart; + + // Compute the number of millisecond ticks elapsed. + unsigned long msecTicks = (unsigned long)(1000 * elapsedTime / + mClockFrequency.QuadPart); + + // Check for unexpected leaps in the Win32 performance counter. + // (This is caused by unexpected data across the PCI to ISA + // bridge, aka south bridge. See Microsoft KB274323.) + unsigned long elapsedTicks = GetTickCount() - mStartTick; + signed long msecOff = (signed long)(msecTicks - elapsedTicks); + if (msecOff < -100 || msecOff > 100) + { + // Adjust the starting time forwards. + LONGLONG msecAdjustment = mymin(msecOff * + mClockFrequency.QuadPart / 1000, elapsedTime - + mPrevElapsedTime); + mStartTime.QuadPart += msecAdjustment; + elapsedTime -= msecAdjustment; + + // Recompute the number of millisecond ticks elapsed. + msecTicks = (unsigned long)(1000 * elapsedTime / + mClockFrequency.QuadPart); + } + + // Store the current elapsed time for adjustments next time. + mPrevElapsedTime = elapsedTime; + + return msecTicks; +#else + +#ifdef __CELLOS_LV2__ + __int64 freq=sys_time_get_timebase_frequency(); + double dFreq=((double) freq) / 1000.0; + typedef uint64_t __int64; + typedef __int64 ClockSize; + ClockSize newTime; + __asm __volatile__( "mftb %0" : "=r" (newTime) : : "memory"); + + return (newTime-mStartTime) / dFreq; #else - struct timeval currentTime; - gettimeofday(¤tTime, 0); - return (currentTime.tv_sec - mStartTime.tv_sec) * 1000 + - (currentTime.tv_usec - mStartTime.tv_usec) / 1000; + struct timeval currentTime; + gettimeofday(¤tTime, 0); + return (currentTime.tv_sec - mStartTime.tv_sec) * 1000 + + (currentTime.tv_usec - mStartTime.tv_usec) / 1000; #endif //__CELLOS_LV2__ #endif - } - - /// Returns the time in us since the last call to reset or since - /// the Clock was created. - unsigned long int getTimeMicroseconds() - { -#ifdef USE_WINDOWS_TIMERS - LARGE_INTEGER currentTime; - QueryPerformanceCounter(¤tTime); - LONGLONG elapsedTime = currentTime.QuadPart - - mStartTime.QuadPart; - - // Compute the number of millisecond ticks elapsed. - unsigned long msecTicks = (unsigned long)(1000 * elapsedTime / - mClockFrequency.QuadPart); - - // Check for unexpected leaps in the Win32 performance counter. - // (This is caused by unexpected data across the PCI to ISA - // bridge, aka south bridge. See Microsoft KB274323.) - unsigned long elapsedTicks = GetTickCount() - mStartTick; - signed long msecOff = (signed long)(msecTicks - elapsedTicks); - if (msecOff < -100 || msecOff > 100) - { - // Adjust the starting time forwards. - LONGLONG msecAdjustment = mymin(msecOff * - mClockFrequency.QuadPart / 1000, elapsedTime - - mPrevElapsedTime); - mStartTime.QuadPart += msecAdjustment; - elapsedTime -= msecAdjustment; } - // Store the current elapsed time for adjustments next time. - mPrevElapsedTime = elapsedTime; + /// Returns the time in us since the last call to reset or since + /// the Clock was created. + unsigned long int getTimeMicroseconds() + { +#ifdef USE_WINDOWS_TIMERS + LARGE_INTEGER currentTime; + QueryPerformanceCounter(¤tTime); + LONGLONG elapsedTime = currentTime.QuadPart - + mStartTime.QuadPart; - // Convert to microseconds. - unsigned long usecTicks = (unsigned long)(1000000 * elapsedTime / - mClockFrequency.QuadPart); + // Compute the number of millisecond ticks elapsed. + unsigned long msecTicks = (unsigned long)(1000 * elapsedTime / + mClockFrequency.QuadPart); - return usecTicks; + // Check for unexpected leaps in the Win32 performance counter. + // (This is caused by unexpected data across the PCI to ISA + // bridge, aka south bridge. See Microsoft KB274323.) + unsigned long elapsedTicks = GetTickCount() - mStartTick; + signed long msecOff = (signed long)(msecTicks - elapsedTicks); + if (msecOff < -100 || msecOff > 100) + { + // Adjust the starting time forwards. + LONGLONG msecAdjustment = mymin(msecOff * + mClockFrequency.QuadPart / 1000, elapsedTime - + mPrevElapsedTime); + mStartTime.QuadPart += msecAdjustment; + elapsedTime -= msecAdjustment; + } + + // Store the current elapsed time for adjustments next time. + mPrevElapsedTime = elapsedTime; + + // Convert to microseconds. + unsigned long usecTicks = (unsigned long)(1000000 * elapsedTime / + mClockFrequency.QuadPart); + + return usecTicks; #else #ifdef __CELLOS_LV2__ - uint64_t freq=sys_time_get_timebase_frequency(); - double dFreq=((double) freq)/ 1000000.0; - typedef uint64_t ClockSize; - ClockSize newTime; - //__asm __volatile__( "mftb %0" : "=r" (newTime) : : "memory"); - SYS_TIMEBASE_GET( newTime ); - - return (unsigned long int)((double(newTime-mStartTime)) / dFreq); + __int64 freq=sys_time_get_timebase_frequency(); + double dFreq=((double) freq)/ 1000000.0; + typedef uint64_t __int64; + typedef __int64 ClockSize; + ClockSize newTime; + __asm __volatile__( "mftb %0" : "=r" (newTime) : : "memory"); + + return (newTime-mStartTime) / dFreq; #else - struct timeval currentTime; - gettimeofday(¤tTime, 0); - return (currentTime.tv_sec - mStartTime.tv_sec) * 1000000 + - (currentTime.tv_usec - mStartTime.tv_usec); + struct timeval currentTime; + gettimeofday(¤tTime, 0); + return (currentTime.tv_sec - mStartTime.tv_sec) * 1000000 + + (currentTime.tv_usec - mStartTime.tv_usec); #endif//__CELLOS_LV2__ #endif - } + } -private: + private: #ifdef USE_WINDOWS_TIMERS - LARGE_INTEGER mClockFrequency; - DWORD mStartTick; - LONGLONG mPrevElapsedTime; - LARGE_INTEGER mStartTime; + LARGE_INTEGER mClockFrequency; + DWORD mStartTick; + LONGLONG mPrevElapsedTime; + LARGE_INTEGER mStartTime; #else #ifdef __CELLOS_LV2__ - uint64_t mStartTime; + uint64_t mStartTime; #else - struct timeval mStartTime; + struct timeval mStartTime; #endif #endif //__CELLOS_LV2__ -}; + }; #endif //USE_BT_CLOCK +#ifdef USE_QUICKPROF -///A node in the Profile Hierarchy Tree -class CProfileNode { +#include +#include +#include +#include -public: - CProfileNode( const char * name, CProfileNode * parent ); - ~CProfileNode( void ); - CProfileNode * Get_Sub_Node( const char * name ); - CProfileNode * Get_Parent( void ) { return Parent; } - CProfileNode * Get_Sibling( void ) { return Sibling; } - CProfileNode * Get_Child( void ) { return Child; } - void CleanupMemory(); - void Reset( void ); - void Call( void ); - bool Return( void ); +namespace hidden +{ + /// A simple data structure representing a single timed block + /// of code. + struct ProfileBlock + { + ProfileBlock() + { + currentBlockStartMicroseconds = 0; + currentCycleTotalMicroseconds = 0; + lastCycleTotalMicroseconds = 0; + totalMicroseconds = 0; + } - const char * Get_Name( void ) { return Name; } - int Get_Total_Calls( void ) { return TotalCalls; } - float Get_Total_Time( void ) { return TotalTime; } + /// The starting time (in us) of the current block update. + unsigned long int currentBlockStartMicroseconds; -protected: + /// The accumulated time (in us) spent in this block during the + /// current profiling cycle. + unsigned long int currentCycleTotalMicroseconds; - const char * Name; - int TotalCalls; - float TotalTime; - unsigned long int StartTime; - int RecursionCounter; + /// The accumulated time (in us) spent in this block during the + /// past profiling cycle. + unsigned long int lastCycleTotalMicroseconds; + + /// The total accumulated time (in us) spent in this block. + unsigned long int totalMicroseconds; + }; - CProfileNode * Parent; - CProfileNode * Child; - CProfileNode * Sibling; }; -///An iterator to navigate through the tree -class CProfileIterator +/// A static class that manages timing for a set of profiling blocks. +class btProfiler { public: - // Access all the children of the current parent - void First(void); - void Next(void); - bool Is_Done(void); - bool Is_Root(void) { return (CurrentParent->Get_Parent() == 0); } - - void Enter_Child( int index ); // Make the given child the new parent - void Enter_Largest_Child( void ); // Make the largest child the new parent - void Enter_Parent( void ); // Make the current parent's parent the new parent - - // Access the current child - const char * Get_Current_Name( void ) { return CurrentChild->Get_Name(); } - int Get_Current_Total_Calls( void ) { return CurrentChild->Get_Total_Calls(); } - float Get_Current_Total_Time( void ) { return CurrentChild->Get_Total_Time(); } - - // Access the current parent - const char * Get_Current_Parent_Name( void ) { return CurrentParent->Get_Name(); } - int Get_Current_Parent_Total_Calls( void ) { return CurrentParent->Get_Total_Calls(); } - float Get_Current_Parent_Total_Time( void ) { return CurrentParent->Get_Total_Time(); } - -protected: - - CProfileNode * CurrentParent; - CProfileNode * CurrentChild; - - CProfileIterator( CProfileNode * start ); - friend class CProfileManager; -}; - - -///The Manager for the Profile system -class CProfileManager { -public: - static void Start_Profile( const char * name ); - static void Stop_Profile( void ); - - static void CleanupMemory(void) + /// A set of ways to retrieve block timing data. + enum BlockTimingMethod { - Root.CleanupMemory(); + /// The total time spent in the block (in seconds) since the + /// profiler was initialized. + BLOCK_TOTAL_SECONDS, + + /// The total time spent in the block (in ms) since the + /// profiler was initialized. + BLOCK_TOTAL_MILLISECONDS, + + /// The total time spent in the block (in us) since the + /// profiler was initialized. + BLOCK_TOTAL_MICROSECONDS, + + /// The total time spent in the block, as a % of the total + /// elapsed time since the profiler was initialized. + BLOCK_TOTAL_PERCENT, + + /// The time spent in the block (in seconds) in the most recent + /// profiling cycle. + BLOCK_CYCLE_SECONDS, + + /// The time spent in the block (in ms) in the most recent + /// profiling cycle. + BLOCK_CYCLE_MILLISECONDS, + + /// The time spent in the block (in us) in the most recent + /// profiling cycle. + BLOCK_CYCLE_MICROSECONDS, + + /// The time spent in the block (in seconds) in the most recent + /// profiling cycle, as a % of the total cycle time. + BLOCK_CYCLE_PERCENT + }; + + /// Initializes the profiler. This must be called first. If this is + /// never called, the profiler is effectively disabled; all other + /// functions will return immediately. The first parameter + /// is the name of an output data file; if this string is not empty, + /// data will be saved on every profiling cycle; if this string is + /// empty, no data will be saved to a file. The second parameter + /// determines which timing method is used when printing data to the + /// output file. + inline static void init(const std::string outputFilename="", + BlockTimingMethod outputMethod=BLOCK_CYCLE_MILLISECONDS); + + /// Cleans up allocated memory. + inline static void destroy(); + + /// Begins timing the named block of code. + inline static void beginBlock(const std::string& name); + + /// Updates the accumulated time spent in the named block by adding + /// the elapsed time since the last call to startBlock for this block + /// name. + inline static void endBlock(const std::string& name); + + /// Returns the time spent in the named block according to the + /// given timing method. See comments on BlockTimingMethod for details. + inline static double getBlockTime(const std::string& name, + BlockTimingMethod method=BLOCK_CYCLE_MILLISECONDS); + + /// Defines the end of a profiling cycle. Use this regularly if you + /// want to generate detailed timing information. This must not be + /// called within a timing block. + inline static void endProfilingCycle(); + + /// A helper function that creates a string of statistics for + /// each timing block. This is mainly for printing an overall + /// summary to the command line. + inline static std::string createStatsString( + BlockTimingMethod method=BLOCK_TOTAL_PERCENT); + +//private: + inline btProfiler(); + + inline ~btProfiler(); + + /// Prints an error message to standard output. + inline static void printError(const std::string& msg) + { + //btAssert(0); + std::cout << "[QuickProf error] " << msg << std::endl; } - static void Reset( void ); - static void Increment_Frame_Counter( void ); - static int Get_Frame_Count_Since_Reset( void ) { return FrameCounter; } - static float Get_Time_Since_Reset( void ); + /// Determines whether the profiler is enabled. + static bool mEnabled; - static CProfileIterator * Get_Iterator( void ) - { - - return new CProfileIterator( &Root ); - } - static void Release_Iterator( CProfileIterator * iterator ) { delete ( iterator); } + /// The clock used to time profile blocks. + static btClock mClock; -private: - static CProfileNode Root; - static CProfileNode * CurrentNode; - static int FrameCounter; - static unsigned long int ResetTime; + /// The starting time (in us) of the current profiling cycle. + static unsigned long int mCurrentCycleStartMicroseconds; + + /// The duration (in us) of the most recent profiling cycle. + static unsigned long int mLastCycleDurationMicroseconds; + + /// Internal map of named profile blocks. + static std::map mProfileBlocks; + + /// The data file used if this feature is enabled in 'init.' + static std::ofstream mOutputFile; + + /// Tracks whether we have begun print data to the output file. + static bool mFirstFileOutput; + + /// The method used when printing timing data to an output file. + static BlockTimingMethod mFileOutputMethod; + + /// The number of the current profiling cycle. + static unsigned long int mCycleNumber; }; -///ProfileSampleClass is a simple way to profile a function's scope -///Use the BT_PROFILE macro at the start of scope to time -class CProfileSample { -public: - CProfileSample( const char * name ) - { - CProfileManager::Start_Profile( name ); +btProfiler::btProfiler() +{ + // This never gets called because a btProfiler instance is never + // created. +} + +btProfiler::~btProfiler() +{ + // This never gets called because a btProfiler instance is never + // created. +} + +void btProfiler::init(const std::string outputFilename, + BlockTimingMethod outputMethod) +{ + mEnabled = true; + + if (!outputFilename.empty()) + { + mOutputFile.open(outputFilename.c_str()); } - ~CProfileSample( void ) - { - CProfileManager::Stop_Profile(); + mFileOutputMethod = outputMethod; + + mClock.reset(); + + // Set the start time for the first cycle. + mCurrentCycleStartMicroseconds = mClock.getTimeMicroseconds(); +} + +void btProfiler::destroy() +{ + if (!mEnabled) + { + return; } -}; -#if !defined(BT_NO_PROFILE) -#define BT_PROFILE( name ) CProfileSample __profile( name ) -#else -#define BT_PROFILE( name ) -#endif + if (mOutputFile.is_open()) + { + mOutputFile.close(); + } + + // Destroy all ProfileBlocks. + while (!mProfileBlocks.empty()) + { + delete (*mProfileBlocks.begin()).second; + mProfileBlocks.erase(mProfileBlocks.begin()); + } +} + +void btProfiler::beginBlock(const std::string& name) +{ + if (!mEnabled) + { + return; + } + + if (name.empty()) + { + printError("Cannot allow unnamed profile blocks."); + return; + } + + hidden::ProfileBlock* block = mProfileBlocks[name]; + + if (!block) + { + // Create a new ProfileBlock. + mProfileBlocks[name] = new hidden::ProfileBlock(); + block = mProfileBlocks[name]; + } + + // We do this at the end to get more accurate results. + block->currentBlockStartMicroseconds = mClock.getTimeMicroseconds(); +} + +void btProfiler::endBlock(const std::string& name) +{ + if (!mEnabled) + { + return; + } + + // We do this at the beginning to get more accurate results. + unsigned long int endTick = mClock.getTimeMicroseconds(); + + hidden::ProfileBlock* block = mProfileBlocks[name]; + + if (!block) + { + // The named block does not exist. Print an error. + printError("The profile block named '" + name + + "' does not exist."); + return; + } + + unsigned long int blockDuration = endTick - + block->currentBlockStartMicroseconds; + block->currentCycleTotalMicroseconds += blockDuration; + block->totalMicroseconds += blockDuration; +} + +double btProfiler::getBlockTime(const std::string& name, + BlockTimingMethod method) +{ + if (!mEnabled) + { + return 0; + } + + hidden::ProfileBlock* block = mProfileBlocks[name]; + + if (!block) + { + // The named block does not exist. Print an error. + printError("The profile block named '" + name + + "' does not exist."); + return 0; + } + + double result = 0; + + switch(method) + { + case BLOCK_TOTAL_SECONDS: + result = (double)block->totalMicroseconds * (double)0.000001; + break; + case BLOCK_TOTAL_MILLISECONDS: + result = (double)block->totalMicroseconds * (double)0.001; + break; + case BLOCK_TOTAL_MICROSECONDS: + result = (double)block->totalMicroseconds; + break; + case BLOCK_TOTAL_PERCENT: + { + double timeSinceInit = (double)mClock.getTimeMicroseconds(); + if (timeSinceInit <= 0) + { + result = 0; + } + else + { + result = 100.0 * (double)block->totalMicroseconds / + timeSinceInit; + } + break; + } + case BLOCK_CYCLE_SECONDS: + result = (double)block->lastCycleTotalMicroseconds * + (double)0.000001; + break; + case BLOCK_CYCLE_MILLISECONDS: + result = (double)block->lastCycleTotalMicroseconds * + (double)0.001; + break; + case BLOCK_CYCLE_MICROSECONDS: + result = (double)block->lastCycleTotalMicroseconds; + break; + case BLOCK_CYCLE_PERCENT: + { + if (0 == mLastCycleDurationMicroseconds) + { + // We have not yet finished a cycle, so just return zero + // percent to avoid a divide by zero error. + result = 0; + } + else + { + result = 100.0 * (double)block->lastCycleTotalMicroseconds / + mLastCycleDurationMicroseconds; + } + break; + } + default: + break; + } + + return result; +} + +void btProfiler::endProfilingCycle() +{ + if (!mEnabled) + { + return; + } + + // Store the duration of the cycle that just finished. + mLastCycleDurationMicroseconds = mClock.getTimeMicroseconds() - + mCurrentCycleStartMicroseconds; + + // For each block, update data for the cycle that just finished. + std::map::iterator iter; + for (iter = mProfileBlocks.begin(); iter != mProfileBlocks.end(); ++iter) + { + hidden::ProfileBlock* block = (*iter).second; + block->lastCycleTotalMicroseconds = + block->currentCycleTotalMicroseconds; + block->currentCycleTotalMicroseconds = 0; + } + + if (mOutputFile.is_open()) + { + // Print data to the output file. + if (mFirstFileOutput) + { + // On the first iteration, print a header line that shows the + // names of each profiling block. + mOutputFile << "#cycle, "; + + for (iter = mProfileBlocks.begin(); iter != mProfileBlocks.end(); + ++iter) + { + mOutputFile << (*iter).first << ", "; + } + + mOutputFile << std::endl; + mFirstFileOutput = false; + } + + mOutputFile << mCycleNumber << ", "; + + for (iter = mProfileBlocks.begin(); iter != mProfileBlocks.end(); + ++iter) + { + mOutputFile << getBlockTime((*iter).first, mFileOutputMethod) + << ", "; + } + + mOutputFile << std::endl; + } + + ++mCycleNumber; + mCurrentCycleStartMicroseconds = mClock.getTimeMicroseconds(); +} + +std::string btProfiler::createStatsString(BlockTimingMethod method) +{ + if (!mEnabled) + { + return ""; + } + + std::string s; + std::string suffix; + + switch(method) + { + case BLOCK_TOTAL_SECONDS: + suffix = "s"; + break; + case BLOCK_TOTAL_MILLISECONDS: + suffix = "ms"; + break; + case BLOCK_TOTAL_MICROSECONDS: + suffix = "us"; + break; + case BLOCK_TOTAL_PERCENT: + { + suffix = "%"; + break; + } + case BLOCK_CYCLE_SECONDS: + suffix = "s"; + break; + case BLOCK_CYCLE_MILLISECONDS: + suffix = "ms"; + break; + case BLOCK_CYCLE_MICROSECONDS: + suffix = "us"; + break; + case BLOCK_CYCLE_PERCENT: + { + suffix = "%"; + break; + } + default: + break; + } + + std::map::iterator iter; + for (iter = mProfileBlocks.begin(); iter != mProfileBlocks.end(); ++iter) + { + if (iter != mProfileBlocks.begin()) + { + s += "\n"; + } + + char blockTime[64]; + sprintf(blockTime, "%lf", getBlockTime((*iter).first, method)); + + s += (*iter).first; + s += ": "; + s += blockTime; + s += " "; + s += suffix; + } + + return s; +} +#define BEGIN_PROFILE(a) btProfiler::beginBlock(a) +#define END_PROFILE(a) btProfiler::endBlock(a) +#else //USE_QUICKPROF +#define BEGIN_PROFILE(a) +#define END_PROFILE(a) + +#endif //USE_QUICKPROF #endif //QUICK_PROF_H diff --git a/extern/bullet2/src/LinearMath/btScalar.h b/extern/bullet2/src/LinearMath/btScalar.h index 1fee626d0c0..01ad93e786a 100644 --- a/extern/bullet2/src/LinearMath/btScalar.h +++ b/extern/bullet2/src/LinearMath/btScalar.h @@ -18,47 +18,25 @@ subject to the following restrictions: #define SIMD___SCALAR_H #include -#include //size_t for MSVC 6.0 #include #include #include -#define BT_BULLET_VERSION 271 - -inline int btGetVersion() -{ - return BT_BULLET_VERSION; -} - -#if defined(DEBUG) || defined (_DEBUG) -#define BT_DEBUG -#endif - - #ifdef WIN32 #if defined(__MINGW32__) || defined(__CYGWIN__) || (defined (_MSC_VER) && _MSC_VER < 1300) - #define SIMD_FORCE_INLINE inline #define ATTRIBUTE_ALIGNED16(a) a - #define ATTRIBUTE_ALIGNED128(a) a #else - #define BT_HAS_ALIGNED_ALLOCATOR - #pragma warning(disable : 4324) // disable padding warning -// #pragma warning(disable:4530) // Disable the exception disable but used in MSCV Stl warning. -// #pragma warning(disable:4996) //Turn off warnings about deprecated C routines -// #pragma warning(disable:4786) // Disable the "debug name too long" warning - + #define BT_HAS_ALIGNED_ALOCATOR + #pragma warning(disable:4530) + #pragma warning(disable:4996) + #pragma warning(disable:4786) #define SIMD_FORCE_INLINE __forceinline #define ATTRIBUTE_ALIGNED16(a) __declspec(align(16)) a - #define ATTRIBUTE_ALIGNED128(a) __declspec (align(128)) a #ifdef _XBOX #define BT_USE_VMX128 - - #include - #define BT_HAVE_NATIVE_FSEL - #define btFsel(a,b,c) __fsel((a),(b),(c)) #else #define BT_USE_SSE #endif @@ -68,63 +46,29 @@ inline int btGetVersion() #define btAssert assert //btFullAssert is optional, slows down a lot #define btFullAssert(x) - - #define btLikely(_c) _c - #define btUnlikely(_c) _c - #else #if defined (__CELLOS_LV2__) #define SIMD_FORCE_INLINE inline #define ATTRIBUTE_ALIGNED16(a) a __attribute__ ((aligned (16))) - #define ATTRIBUTE_ALIGNED128(a) a __attribute__ ((aligned (128))) #ifndef assert #include #endif #define btAssert assert //btFullAssert is optional, slows down a lot #define btFullAssert(x) - - #define btLikely(_c) _c - #define btUnlikely(_c) _c - #else -#ifdef USE_LIBSPE2 - - #define SIMD_FORCE_INLINE __inline - #define ATTRIBUTE_ALIGNED16(a) a __attribute__ ((aligned (16))) - #define ATTRIBUTE_ALIGNED128(a) a __attribute__ ((aligned (128))) - #ifndef assert - #include - #endif - #define btAssert assert - //btFullAssert is optional, slows down a lot - #define btFullAssert(x) - - - #define btLikely(_c) __builtin_expect((_c), 1) - #define btUnlikely(_c) __builtin_expect((_c), 0) - - -#else //non-windows systems #define SIMD_FORCE_INLINE inline #define ATTRIBUTE_ALIGNED16(a) a - #define ATTRIBUTE_ALIGNED128(a) a #ifndef assert #include #endif #define btAssert assert //btFullAssert is optional, slows down a lot #define btFullAssert(x) - #define btLikely(_c) _c - #define btUnlikely(_c) _c - - -#endif // LIBSPE2 - #endif //__CELLOS_LV2__ #endif @@ -137,7 +81,6 @@ inline int btGetVersion() #endif #endif -///The btScalar type abstracts floating point numbers, to easily switch between double and single floating point precision. #if defined(BT_USE_DOUBLE_PRECISION) typedef double btScalar; #else @@ -145,14 +88,6 @@ typedef float btScalar; #endif -#define BT_DECLARE_ALIGNED_ALLOCATOR() \ - SIMD_FORCE_INLINE void* operator new(size_t sizeInBytes) { return btAlignedAlloc(sizeInBytes,16); } \ - SIMD_FORCE_INLINE void operator delete(void* ptr) { btAlignedFree(ptr); } \ - SIMD_FORCE_INLINE void* operator new(size_t, void* ptr) { return ptr; } \ - SIMD_FORCE_INLINE void operator delete(void*, void*) { } \ - - - #if defined(BT_USE_DOUBLE_PRECISION) || defined(BT_FORCE_DOUBLE_FUNCTIONS) SIMD_FORCE_INLINE btScalar btSqrt(btScalar x) { return sqrt(x); } @@ -170,34 +105,12 @@ SIMD_FORCE_INLINE btScalar btPow(btScalar x,btScalar y) { return pow(x,y); } #else -SIMD_FORCE_INLINE btScalar btSqrt(btScalar y) -{ -#ifdef USE_APPROXIMATION - double x, z, tempf; - unsigned long *tfptr = ((unsigned long *)&tempf) + 1; - - tempf = y; - *tfptr = (0xbfcdd90a - *tfptr)>>1; /* estimate of 1/sqrt(y) */ - x = tempf; - z = y*btScalar(0.5); /* hoist out the “/2” */ - x = (btScalar(1.5)*x)-(x*x)*(x*z); /* iteration formula */ - x = (btScalar(1.5)*x)-(x*x)*(x*z); - x = (btScalar(1.5)*x)-(x*x)*(x*z); - x = (btScalar(1.5)*x)-(x*x)*(x*z); - x = (btScalar(1.5)*x)-(x*x)*(x*z); - return x*y; -#else - return sqrtf(y); -#endif -} +SIMD_FORCE_INLINE btScalar btSqrt(btScalar x) { return sqrtf(x); } SIMD_FORCE_INLINE btScalar btFabs(btScalar x) { return fabsf(x); } SIMD_FORCE_INLINE btScalar btCos(btScalar x) { return cosf(x); } SIMD_FORCE_INLINE btScalar btSin(btScalar x) { return sinf(x); } SIMD_FORCE_INLINE btScalar btTan(btScalar x) { return tanf(x); } -SIMD_FORCE_INLINE btScalar btAcos(btScalar x) { - btAssert(x <= btScalar(1.)); - return acosf(x); -} +SIMD_FORCE_INLINE btScalar btAcos(btScalar x) { return acosf(x); } SIMD_FORCE_INLINE btScalar btAsin(btScalar x) { return asinf(x); } SIMD_FORCE_INLINE btScalar btAtan(btScalar x) { return atanf(x); } SIMD_FORCE_INLINE btScalar btAtan2(btScalar x, btScalar y) { return atan2f(x, y); } @@ -246,6 +159,14 @@ SIMD_FORCE_INLINE bool btGreaterEqual (btScalar a, btScalar eps) { return (!((a) <= eps)); } +/*SIMD_FORCE_INLINE btScalar btCos(btScalar x) { return cosf(x); } +SIMD_FORCE_INLINE btScalar btSin(btScalar x) { return sinf(x); } +SIMD_FORCE_INLINE btScalar btTan(btScalar x) { return tanf(x); } +SIMD_FORCE_INLINE btScalar btAcos(btScalar x) { return acosf(x); } +SIMD_FORCE_INLINE btScalar btAsin(btScalar x) { return asinf(x); } +SIMD_FORCE_INLINE btScalar btAtan(btScalar x) { return atanf(x); } +SIMD_FORCE_INLINE btScalar btAtan2(btScalar x, btScalar y) { return atan2f(x, y); } +*/ SIMD_FORCE_INLINE int btIsNegative(btScalar x) { return x < btScalar(0.0) ? 1 : 0; @@ -256,151 +177,5 @@ SIMD_FORCE_INLINE btScalar btDegrees(btScalar x) { return x * SIMD_DEGS_PER_RAD; #define BT_DECLARE_HANDLE(name) typedef struct name##__ { int unused; } *name -#ifndef btFsel -SIMD_FORCE_INLINE btScalar btFsel(btScalar a, btScalar b, btScalar c) -{ - return a >= 0 ? b : c; -} -#endif -#define btFsels(a,b,c) (btScalar)btFsel(a,b,c) - - -SIMD_FORCE_INLINE bool btMachineIsLittleEndian() -{ - long int i = 1; - const char *p = (const char *) &i; - if (p[0] == 1) // Lowest address contains the least significant byte - return true; - else - return false; -} - - - -///btSelect avoids branches, which makes performance much better for consoles like Playstation 3 and XBox 360 -///Thanks Phil Knight. See also http://www.cellperformance.com/articles/2006/04/more_techniques_for_eliminatin_1.html -SIMD_FORCE_INLINE unsigned btSelect(unsigned condition, unsigned valueIfConditionNonZero, unsigned valueIfConditionZero) -{ - // Set testNz to 0xFFFFFFFF if condition is nonzero, 0x00000000 if condition is zero - // Rely on positive value or'ed with its negative having sign bit on - // and zero value or'ed with its negative (which is still zero) having sign bit off - // Use arithmetic shift right, shifting the sign bit through all 32 bits - unsigned testNz = (unsigned)(((int)condition | -(int)condition) >> 31); - unsigned testEqz = ~testNz; - return ((valueIfConditionNonZero & testNz) | (valueIfConditionZero & testEqz)); -} -SIMD_FORCE_INLINE int btSelect(unsigned condition, int valueIfConditionNonZero, int valueIfConditionZero) -{ - unsigned testNz = (unsigned)(((int)condition | -(int)condition) >> 31); - unsigned testEqz = ~testNz; - return static_cast((valueIfConditionNonZero & testNz) | (valueIfConditionZero & testEqz)); -} -SIMD_FORCE_INLINE float btSelect(unsigned condition, float valueIfConditionNonZero, float valueIfConditionZero) -{ -#ifdef BT_HAVE_NATIVE_FSEL - return (float)btFsel((btScalar)condition - btScalar(1.0f), valueIfConditionNonZero, valueIfConditionZero); -#else - return (condition != 0) ? valueIfConditionNonZero : valueIfConditionZero; -#endif -} - -template SIMD_FORCE_INLINE void btSwap(T& a, T& b) -{ - T tmp = a; - a = b; - b = tmp; -} - - -//PCK: endian swapping functions -SIMD_FORCE_INLINE unsigned btSwapEndian(unsigned val) -{ - return (((val & 0xff000000) >> 24) | ((val & 0x00ff0000) >> 8) | ((val & 0x0000ff00) << 8) | ((val & 0x000000ff) << 24)); -} - -SIMD_FORCE_INLINE unsigned short btSwapEndian(unsigned short val) -{ - return static_cast(((val & 0xff00) >> 8) | ((val & 0x00ff) << 8)); -} - -SIMD_FORCE_INLINE unsigned btSwapEndian(int val) -{ - return btSwapEndian((unsigned)val); -} - -SIMD_FORCE_INLINE unsigned short btSwapEndian(short val) -{ - return btSwapEndian((unsigned short) val); -} - -///btSwapFloat uses using char pointers to swap the endianness -////btSwapFloat/btSwapDouble will NOT return a float, because the machine might 'correct' invalid floating point values -///Not all values of sign/exponent/mantissa are valid floating point numbers according to IEEE 754. -///When a floating point unit is faced with an invalid value, it may actually change the value, or worse, throw an exception. -///In most systems, running user mode code, you wouldn't get an exception, but instead the hardware/os/runtime will 'fix' the number for you. -///so instead of returning a float/double, we return integer/long long integer -SIMD_FORCE_INLINE unsigned int btSwapEndianFloat(float d) -{ - unsigned int a = 0; - unsigned char *dst = (unsigned char *)&a; - unsigned char *src = (unsigned char *)&d; - - dst[0] = src[3]; - dst[1] = src[2]; - dst[2] = src[1]; - dst[3] = src[0]; - return a; -} - -// unswap using char pointers -SIMD_FORCE_INLINE float btUnswapEndianFloat(unsigned int a) -{ - float d = 0.0f; - unsigned char *src = (unsigned char *)&a; - unsigned char *dst = (unsigned char *)&d; - - dst[0] = src[3]; - dst[1] = src[2]; - dst[2] = src[1]; - dst[3] = src[0]; - - return d; -} - - -// swap using char pointers -SIMD_FORCE_INLINE void btSwapEndianDouble(double d, unsigned char* dst) -{ - unsigned char *src = (unsigned char *)&d; - - dst[0] = src[7]; - dst[1] = src[6]; - dst[2] = src[5]; - dst[3] = src[4]; - dst[4] = src[3]; - dst[5] = src[2]; - dst[6] = src[1]; - dst[7] = src[0]; - -} - -// unswap using char pointers -SIMD_FORCE_INLINE double btUnswapEndianDouble(const unsigned char *src) -{ - double d = 0.0; - unsigned char *dst = (unsigned char *)&d; - - dst[0] = src[7]; - dst[1] = src[6]; - dst[2] = src[5]; - dst[3] = src[4]; - dst[4] = src[3]; - dst[5] = src[2]; - dst[6] = src[1]; - dst[7] = src[0]; - - return d; -} - #endif //SIMD___SCALAR_H diff --git a/extern/bullet2/src/LinearMath/btStackAlloc.h b/extern/bullet2/src/LinearMath/btStackAlloc.h index 050d44bdfe9..d219b453537 100644 --- a/extern/bullet2/src/LinearMath/btStackAlloc.h +++ b/extern/bullet2/src/LinearMath/btStackAlloc.h @@ -21,7 +21,6 @@ Nov.2006 #define BT_STACK_ALLOC #include "btScalar.h" //for btAssert -#include "btAlignedAllocator.h" struct btBlock { @@ -29,7 +28,7 @@ struct btBlock unsigned char* address; }; -///The StackAlloc class provides some fast stack-based memory allocator (LIFO last-in first-out) +///StackAlloc provides some fast stack-based memory allocator (LIFO last-in first-out) class btStackAlloc { public: @@ -40,7 +39,7 @@ public: inline void create(unsigned int size) { destroy(); - data = (unsigned char*) btAlignedAlloc(size,16); + data = new unsigned char[size]; totalsize = size; } inline void destroy() @@ -50,20 +49,12 @@ public: if(usedsize==0) { - if(!ischild && data) - btAlignedFree(data); - + if(!ischild) delete[] data; data = 0; usedsize = 0; } } - - int getAvailableMemory() const - { - return static_cast(totalsize - usedsize); - } - unsigned char* allocate(unsigned int size) { const unsigned int nus(usedsize+size); @@ -77,7 +68,7 @@ public: return(0); } - SIMD_FORCE_INLINE btBlock* beginBlock() + inline btBlock* beginBlock() { btBlock* pb = (btBlock*)allocate(sizeof(btBlock)); pb->previous = current; @@ -85,7 +76,7 @@ public: current = pb; return(pb); } - SIMD_FORCE_INLINE void endBlock(btBlock* block) + inline void endBlock(btBlock* block) { btAssert(block==current); //Raise(L"Unmatched blocks"); diff --git a/extern/bullet2/src/LinearMath/btTransform.h b/extern/bullet2/src/LinearMath/btTransform.h index a8cdb428100..2d55fec83a4 100644 --- a/extern/bullet2/src/LinearMath/btTransform.h +++ b/extern/bullet2/src/LinearMath/btTransform.h @@ -21,8 +21,7 @@ subject to the following restrictions: #include "btMatrix3x3.h" -///The btTransform class supports rigid transforms with only translation and rotation and no scaling/shear. -///It can be used in combination with btVector3, btQuaternion and btMatrix3x3 linear algebra classes. +///btTransform supports rigid transforms (only translation and rotation, no scaling/shear) class btTransform { @@ -93,7 +92,13 @@ public: m_basis.getRotation(q); return q; } - + template + void setValue(const Scalar2 *m) + { + m_basis.setValue(m); + m_origin.setValue(&m[12]); + } + void setFromOpenGLMatrix(const btScalar *m) { @@ -189,13 +194,8 @@ btTransform::operator*(const btTransform& t) const { return btTransform(m_basis * t.m_basis, (*this)(t.m_origin)); -} +} -SIMD_FORCE_INLINE bool operator==(const btTransform& t1, const btTransform& t2) -{ - return ( t1.getBasis() == t2.getBasis() && - t1.getOrigin() == t2.getOrigin() ); -} #endif @@ -204,4 +204,3 @@ SIMD_FORCE_INLINE bool operator==(const btTransform& t1, const btTransform& t2) - diff --git a/extern/bullet2/src/LinearMath/btTransformUtil.h b/extern/bullet2/src/LinearMath/btTransformUtil.h index 86ee1da5edf..bc42fd166b6 100644 --- a/extern/bullet2/src/LinearMath/btTransformUtil.h +++ b/extern/bullet2/src/LinearMath/btTransformUtil.h @@ -25,7 +25,7 @@ subject to the following restrictions: #define btRecipSqrt(x) ((btScalar)(btScalar(1.0)/btSqrt(btScalar(x)))) /* reciprocal square root */ -SIMD_FORCE_INLINE btVector3 btAabbSupport(const btVector3& halfExtents,const btVector3& supportDir) +inline btVector3 btAabbSupport(const btVector3& halfExtents,const btVector3& supportDir) { return btVector3(supportDir.x() < btScalar(0.0) ? -halfExtents.x() : halfExtents.x(), supportDir.y() < btScalar(0.0) ? -halfExtents.y() : halfExtents.y(), @@ -33,7 +33,7 @@ SIMD_FORCE_INLINE btVector3 btAabbSupport(const btVector3& halfExtents,const btV } -SIMD_FORCE_INLINE void btPlaneSpace1 (const btVector3& n, btVector3& p, btVector3& q) +inline void btPlaneSpace1 (const btVector3& n, btVector3& p, btVector3& q) { if (btFabs(n.z()) > SIMDSQRT12) { // choose p in y-z plane @@ -70,9 +70,7 @@ public: predictedOrn += (angvel * predictedOrn) * (timeStep * btScalar(0.5)); predictedOrn.normalize(); #else - //Exponential map - //google for "Practical Parameterization of Rotations Using the Exponential Map", F. Sebastian Grassia - + //exponential map btVector3 axis; btScalar fAngle = angvel.length(); //limit the angular motion @@ -123,10 +121,6 @@ public: dmat.getRotation(dorn); #endif//USE_QUATERNION_DIFF - ///floating point inaccuracy can lead to w component > 1..., which breaks - - dorn.normalize(); - angle = dorn.getAngle(); axis = btVector3(dorn.x(),dorn.y(),dorn.z()); axis[3] = btScalar(0.); diff --git a/extern/bullet2/src/LinearMath/btVector3.h b/extern/bullet2/src/LinearMath/btVector3.h index 96548c6ba60..74d41ad2a19 100644 --- a/extern/bullet2/src/LinearMath/btVector3.h +++ b/extern/bullet2/src/LinearMath/btVector3.h @@ -27,10 +27,6 @@ class btVector3 : public btQuadWord { public: SIMD_FORCE_INLINE btVector3() {} - SIMD_FORCE_INLINE btVector3(const btQuadWordStorage& q) - : btQuadWord(q) - { - } SIMD_FORCE_INLINE btVector3(const btScalar& x, const btScalar& y, const btScalar& z) @@ -47,7 +43,6 @@ public: SIMD_FORCE_INLINE btVector3& operator+=(const btVector3& v) { - m_x += v.x(); m_y += v.y(); m_z += v.z(); return *this; } @@ -404,50 +399,4 @@ public: }; - -///btSwapVector3Endian swaps vector endianness, useful for network and cross-platform serialization -SIMD_FORCE_INLINE void btSwapScalarEndian(const btScalar& sourceVal, btScalar& destVal) -{ - #ifdef BT_USE_DOUBLE_PRECISION - unsigned char* dest = (unsigned char*) &destVal; - unsigned char* src = (unsigned char*) &sourceVal; - dest[0] = src[7]; - dest[1] = src[6]; - dest[2] = src[5]; - dest[3] = src[4]; - dest[4] = src[3]; - dest[5] = src[2]; - dest[6] = src[1]; - dest[7] = src[0]; -#else - unsigned char* dest = (unsigned char*) &destVal; - unsigned char* src = (unsigned char*) &sourceVal; - dest[0] = src[3]; - dest[1] = src[2]; - dest[2] = src[1]; - dest[3] = src[0]; -#endif //BT_USE_DOUBLE_PRECISION -} -///btSwapVector3Endian swaps vector endianness, useful for network and cross-platform serialization -SIMD_FORCE_INLINE void btSwapVector3Endian(const btVector3& sourceVec, btVector3& destVec) -{ - for (int i=0;i<4;i++) - { - btSwapScalarEndian(sourceVec[i],destVec[i]); - } - -} - -///btUnSwapVector3Endian swaps vector endianness, useful for network and cross-platform serialization -SIMD_FORCE_INLINE void btUnSwapVector3Endian(btVector3& vector) -{ - - btVector3 swappedVec; - for (int i=0;i<4;i++) - { - btSwapScalarEndian(vector[i],swappedVec[i]); - } - vector = swappedVec; -} - #endif //SIMD__VECTOR3_H diff --git a/extern/bullet2/src/btBulletCollisionCommon.h b/extern/bullet2/src/btBulletCollisionCommon.h index b21d8b4f66c..8417ccc671f 100644 --- a/extern/bullet2/src/btBulletCollisionCommon.h +++ b/extern/bullet2/src/btBulletCollisionCommon.h @@ -32,26 +32,23 @@ subject to the following restrictions: #include "BulletCollision/CollisionShapes/btConvexHullShape.h" #include "BulletCollision/CollisionShapes/btTriangleMesh.h" #include "BulletCollision/CollisionShapes/btConvexTriangleMeshShape.h" -#include "BulletCollision/CollisionShapes/btBvhTriangleMeshShape.h" #include "BulletCollision/CollisionShapes/btTriangleMeshShape.h" #include "BulletCollision/CollisionShapes/btTriangleIndexVertexArray.h" #include "BulletCollision/CollisionShapes/btCompoundShape.h" #include "BulletCollision/CollisionShapes/btTetrahedronShape.h" #include "BulletCollision/CollisionShapes/btEmptyShape.h" +#include "BulletCollision/CollisionShapes/btBvhTriangleMeshShape.h" #include "BulletCollision/CollisionShapes/btMultiSphereShape.h" -#include "BulletCollision/CollisionShapes/btUniformScalingShape.h" ///Narrowphase Collision Detector #include "BulletCollision/CollisionDispatch/btSphereSphereCollisionAlgorithm.h" #include "BulletCollision/CollisionDispatch/btSphereBoxCollisionAlgorithm.h" -#include "BulletCollision/CollisionDispatch/btDefaultCollisionConfiguration.h" ///Dispatching and generation of collision pairs (broadphase) #include "BulletCollision/CollisionDispatch/btCollisionDispatcher.h" #include "BulletCollision/BroadphaseCollision/btSimpleBroadphase.h" #include "BulletCollision/BroadphaseCollision/btAxisSweep3.h" -#include "BulletCollision/BroadphaseCollision/btMultiSapBroadphase.h" -#include "BulletCollision/BroadphaseCollision/btDbvtBroadphase.h" + ///Math library & Utils #include "LinearMath/btQuaternion.h" diff --git a/extern/bullet2/src/btBulletDynamicsCommon.h b/extern/bullet2/src/btBulletDynamicsCommon.h index ce9bb1d968b..25f016cba8a 100644 --- a/extern/bullet2/src/btBulletDynamicsCommon.h +++ b/extern/bullet2/src/btBulletDynamicsCommon.h @@ -20,8 +20,6 @@ subject to the following restrictions: #include "btBulletCollisionCommon.h" #include "BulletDynamics/Dynamics/btDiscreteDynamicsWorld.h" -#include "BulletDynamics/Dynamics/btContinuousDynamicsWorld.h" - #include "BulletDynamics/Dynamics/btSimpleDynamicsWorld.h" #include "BulletDynamics/Dynamics/btRigidBody.h" @@ -29,13 +27,9 @@ subject to the following restrictions: #include "BulletDynamics/ConstraintSolver/btHingeConstraint.h" #include "BulletDynamics/ConstraintSolver/btConeTwistConstraint.h" #include "BulletDynamics/ConstraintSolver/btGeneric6DofConstraint.h" -#include "BulletDynamics/ConstraintSolver/btSliderConstraint.h" + #include "BulletDynamics/ConstraintSolver/btSequentialImpulseConstraintSolver.h" -///Optional ODE quickstep constraint solver, redistributed under ZLib license -#include "BulletDynamics/ConstraintSolver/btOdeQuickstepConstraintSolver.h" -#include "BulletDynamics/ConstraintSolver/btOdeTypedJoint.h" - ///Vehicle simulation, with wheel contact simulated by raycasts #include "BulletDynamics/Vehicle/btRaycastVehicle.h" diff --git a/source/gameengine/Converter/KX_BlenderSceneConverter.cpp b/source/gameengine/Converter/KX_BlenderSceneConverter.cpp index f5fb8ce852d..de91bce2ab1 100644 --- a/source/gameengine/Converter/KX_BlenderSceneConverter.cpp +++ b/source/gameengine/Converter/KX_BlenderSceneConverter.cpp @@ -245,11 +245,6 @@ struct BlenderDebugDraw : public btIDebugDraw { return m_debugMode; } - ///todo: find out if Blender can do this - virtual void draw3dText(const btVector3& location,const char* textString) - { - - } }; diff --git a/source/gameengine/Physics/Bullet/CcdPhysicsController.cpp b/source/gameengine/Physics/Bullet/CcdPhysicsController.cpp index e85238b49c3..2ec96c75a68 100644 --- a/source/gameengine/Physics/Bullet/CcdPhysicsController.cpp +++ b/source/gameengine/Physics/Bullet/CcdPhysicsController.cpp @@ -126,14 +126,13 @@ void CcdPhysicsController::CreateRigidbody() m_bulletMotionState = new BlenderBulletMotionState(m_MotionState); - btRigidBody::btRigidBodyConstructionInfo rbci(m_cci.m_mass,m_bulletMotionState,m_collisionShape,m_cci.m_localInertiaTensor * m_cci.m_inertiaFactor); - rbci.m_linearDamping = m_cci.m_linearDamping; - rbci.m_angularDamping = m_cci.m_angularDamping; - rbci.m_friction = m_cci.m_friction; - rbci.m_restitution = m_cci.m_restitution; - - m_body = new btRigidBody(rbci); - + m_body = new btRigidBody(m_cci.m_mass, + m_bulletMotionState, + m_collisionShape, + m_cci.m_localInertiaTensor * m_cci.m_inertiaFactor, + m_cci.m_linearDamping,m_cci.m_angularDamping, + m_cci.m_friction,m_cci.m_restitution); + // // init the rigidbody properly // diff --git a/source/gameengine/Physics/Bullet/CcdPhysicsEnvironment.cpp b/source/gameengine/Physics/Bullet/CcdPhysicsEnvironment.cpp index f9242e6876f..d14ddf8f65c 100644 --- a/source/gameengine/Physics/Bullet/CcdPhysicsEnvironment.cpp +++ b/source/gameengine/Physics/Bullet/CcdPhysicsEnvironment.cpp @@ -330,21 +330,30 @@ m_filterCallback(NULL) { m_triggerCallbacks[i] = 0; } - m_collisionConfiguration = new btDefaultCollisionConfiguration(); - if (!dispatcher) { - dispatcher = new btCollisionDispatcher(m_collisionConfiguration); + dispatcher = new btCollisionDispatcher(); m_ownDispatcher = dispatcher; } - m_broadphase = new btDbvtBroadphase(); + if(!pairCache) + { + + //todo: calculate/let user specify this world sizes + btVector3 worldMin(-10000,-10000,-10000); + btVector3 worldMax(10000,10000,10000); + + pairCache = new btAxisSweep3(worldMin,worldMax); + // remember that this was allocated by us so that we can release it + m_ownPairCache = pairCache; + //broadphase = new btSimpleBroadphase(); + } m_filterCallback = new CcdOverlapFilterCallBack(this); - m_broadphase->getOverlappingPairCache()->setOverlapFilterCallback(m_filterCallback); + pairCache->setOverlapFilterCallback(m_filterCallback); setSolverType(1);//issues with quickstep and memory allocations - m_dynamicsWorld = new btDiscreteDynamicsWorld(dispatcher,m_broadphase,m_solver,m_collisionConfiguration); + m_dynamicsWorld = new btDiscreteDynamicsWorld(dispatcher,pairCache,m_solver); m_debugDrawer = 0; m_gravity = btVector3(0.f,-10.f,0.f); m_dynamicsWorld->setGravity(m_gravity); @@ -510,9 +519,6 @@ bool CcdPhysicsEnvironment::proceedDeltaTime(double curTime,float timeStep) veh->SyncWheels(); } - m_dynamicsWorld->debugDrawWorld(); - - CallbackTriggers(); return true; @@ -573,7 +579,7 @@ void CcdPhysicsEnvironment::setSolverDamping(float damping) void CcdPhysicsEnvironment::setLinearAirDamping(float damping) { - //gLinearAirDamping = damping; + gLinearAirDamping = damping; } void CcdPhysicsEnvironment::setUseEpa(bool epa) @@ -592,7 +598,7 @@ void CcdPhysicsEnvironment::setSolverType(int solverType) { m_solver = new btSequentialImpulseConstraintSolver(); -// ((btSequentialImpulseConstraintSolver*)m_solver)->setSolverMode(btSequentialImpulseConstraintSolver::SOLVER_USE_WARMSTARTING | btSequentialImpulseConstraintSolver::SOLVER_RANDMIZE_ORDER); + ((btSequentialImpulseConstraintSolver*)m_solver)->setSolverMode(btSequentialImpulseConstraintSolver::SOLVER_USE_WARMSTARTING | btSequentialImpulseConstraintSolver::SOLVER_RANDMIZE_ORDER); break; } } @@ -654,10 +660,9 @@ int CcdPhysicsEnvironment::createUniversalD6Constraint( { - bool useReferenceFrameA = true; genericConstraint = new btGeneric6DofConstraint( *rb0,*rb1, - frameInA,frameInB,useReferenceFrameA); + frameInA,frameInB); genericConstraint->setLinearLowerLimit(linearMinLimits); genericConstraint->setLinearUpperLimit(linearMaxLimits); genericConstraint->setAngularLowerLimit(angularMinLimits); @@ -737,15 +742,14 @@ struct FilterClosestRayResultCallback : public btCollisionWorld::ClosestRayResul // save shape information as ClosestRayResultCallback::AddSingleResult() does not do it if (rayResult.m_localShapeInfo) { - m_hitTriangleShape = NULL;//rayResult.m_localShapeInfo->m_triangleShape; - m_hitTriangleIndex = 0;//rayResult.m_localShapeInfo->m_triangleIndex; + m_hitTriangleShape = rayResult.m_localShapeInfo->m_triangleShape; + m_hitTriangleIndex = rayResult.m_localShapeInfo->m_triangleIndex; } else { m_hitTriangleShape = NULL; m_hitTriangleIndex = 0; } - bool normalInWorldspace = true; - return ClosestRayResultCallback::addSingleResult(rayResult,normalInWorldspace); + return ClosestRayResultCallback::AddSingleResult(rayResult); } }; @@ -771,11 +775,8 @@ PHY_IPhysicsController* CcdPhysicsEnvironment::rayTest(PHY_IRayCastFilterCallbac memset(&result, 0, sizeof(result)); // don't collision with sensor object - rayCallback.m_collisionFilterMask = CcdConstructionInfo::AllFilter ^ CcdConstructionInfo::SensorFilter; - //, ,filterCallback.m_faceNormal); - - m_dynamicsWorld->rayTest(rayFrom,rayTo,rayCallback); - if (rayCallback.hasHit()) + m_dynamicsWorld->rayTest(rayFrom,rayTo,rayCallback, CcdConstructionInfo::AllFilter ^ CcdConstructionInfo::SensorFilter,filterCallback.m_faceNormal); + if (rayCallback.HasHit()) { CcdPhysicsController* controller = static_cast(rayCallback.m_collisionObject->getUserPointer()); result.m_controller = controller; @@ -880,12 +881,6 @@ CcdPhysicsEnvironment::~CcdPhysicsEnvironment() if (NULL != m_filterCallback) delete m_filterCallback; - - if (NULL != m_collisionConfiguration) - delete m_collisionConfiguration; - - if (NULL != m_broadphase) - delete m_broadphase; } @@ -898,7 +893,7 @@ void CcdPhysicsEnvironment::setConstraintParam(int constraintId,int param,float { //param = 1..12, min0,max0,min1,max1...min6,max6 btGeneric6DofConstraint* genCons = (btGeneric6DofConstraint*)typedConstraint; - genCons->setLimit(param,value0,value1); + genCons->SetLimit(param,value0,value1); break; }; default: @@ -1244,11 +1239,10 @@ int CcdPhysicsEnvironment::createConstraint(class PHY_IPhysicsController* ctrl btTransform globalFrameA = rb0->getCenterOfMassTransform() * frameInA; frameInB = inv * globalFrameA; - bool useReferenceFrameA = true; - + genericConstraint = new btGeneric6DofConstraint( *rb0,*rb1, - frameInA,frameInB,useReferenceFrameA); + frameInA,frameInB); } else @@ -1269,10 +1263,9 @@ int CcdPhysicsEnvironment::createConstraint(class PHY_IPhysicsController* ctrl ///frameInB in worldspace frameInB = rb0->getCenterOfMassTransform() * frameInA; - bool useReferenceFrameA = true; genericConstraint = new btGeneric6DofConstraint( *rb0,s_fixedObject2, - frameInA,frameInB,useReferenceFrameA); + frameInA,frameInB); } if (genericConstraint) diff --git a/source/gameengine/Physics/Bullet/CcdPhysicsEnvironment.h b/source/gameengine/Physics/Bullet/CcdPhysicsEnvironment.h index 3cf5a943e3f..667e310dcb3 100644 --- a/source/gameengine/Physics/Bullet/CcdPhysicsEnvironment.h +++ b/source/gameengine/Physics/Bullet/CcdPhysicsEnvironment.h @@ -56,10 +56,6 @@ class CcdPhysicsEnvironment : public PHY_IPhysicsEnvironment protected: btIDebugDraw* m_debugDrawer; - - class btDefaultCollisionConfiguration* m_collisionConfiguration; - class btBroadphaseInterface* m_broadphase; - //solver iterations int m_numIterations; From 19d5a5da452bf5d07bc9409577141401c1e2e0be Mon Sep 17 00:00:00 2001 From: Benoit Bolsee Date: Wed, 3 Sep 2008 12:54:46 +0000 Subject: [PATCH 2/9] Update MSVC project files after GSoC merge --- projectfiles_vc7/blender/blenkernel/BKE_blenkernel.vcproj | 6 ++++++ projectfiles_vc7/gameengine/ketsji/KX_ketsji.vcproj | 8 ++++---- 2 files changed, 10 insertions(+), 4 deletions(-) diff --git a/projectfiles_vc7/blender/blenkernel/BKE_blenkernel.vcproj b/projectfiles_vc7/blender/blenkernel/BKE_blenkernel.vcproj index 42dcc843091..69db0a95006 100644 --- a/projectfiles_vc7/blender/blenkernel/BKE_blenkernel.vcproj +++ b/projectfiles_vc7/blender/blenkernel/BKE_blenkernel.vcproj @@ -506,6 +506,9 @@ + + @@ -723,6 +726,9 @@ + + diff --git a/projectfiles_vc7/gameengine/ketsji/KX_ketsji.vcproj b/projectfiles_vc7/gameengine/ketsji/KX_ketsji.vcproj index 4e362faed69..a358a868143 100644 --- a/projectfiles_vc7/gameengine/ketsji/KX_ketsji.vcproj +++ b/projectfiles_vc7/gameengine/ketsji/KX_ketsji.vcproj @@ -126,7 +126,7 @@ Date: Wed, 3 Sep 2008 23:51:55 +0000 Subject: [PATCH 3/9] fix for 2 python refcounting errors --- source/blender/python/BPY_interface.c | 11 ++++------- source/gameengine/Ketsji/KX_PythonInit.cpp | 6 ++++-- 2 files changed, 8 insertions(+), 9 deletions(-) diff --git a/source/blender/python/BPY_interface.c b/source/blender/python/BPY_interface.c index 05ea2d77ab9..05254bca8c0 100644 --- a/source/blender/python/BPY_interface.c +++ b/source/blender/python/BPY_interface.c @@ -292,7 +292,7 @@ void syspath_append( char *dirname ) short ok=1; PyErr_Clear( ); - dir = Py_BuildValue( "s", dirname ); + dir = PyString_FromString( dirname ); mod_sys = PyImport_ImportModule( "sys" ); /* new ref */ @@ -308,32 +308,29 @@ void syspath_append( char *dirname ) } if (PySequence_Contains(path, dir)==0) { /* Only add if we need to */ - if (ok && PyList_Append( path, dir ) != 0) + if (ok && PyList_Append( path, dir ) != 0) /* decref below */ ok = 0; /* append failed */ if( (ok==0) || PyErr_Occurred( ) ) Py_FatalError( "could import or build sys.path, can't continue" ); } + Py_DECREF( dir ); Py_XDECREF( mod_sys ); } void init_syspath( int first_time ) { - PyObject *path; PyObject *mod, *d; char *progname; char execdir[FILE_MAXDIR]; /*defines from DNA_space_types.h */ int n; - - - path = Py_BuildValue( "s", bprogname ); mod = PyImport_ImportModule( "Blender.sys" ); if( mod ) { d = PyModule_GetDict( mod ); - EXPP_dict_set_item_str( d, "progname", path ); + EXPP_dict_set_item_str( d, "progname", PyString_FromString( bprogname ) ); Py_DECREF( mod ); } else printf( "Warning: could not set Blender.sys.progname\n" ); diff --git a/source/gameengine/Ketsji/KX_PythonInit.cpp b/source/gameengine/Ketsji/KX_PythonInit.cpp index e9fb0278d76..4b6a38f18c0 100644 --- a/source/gameengine/Ketsji/KX_PythonInit.cpp +++ b/source/gameengine/Ketsji/KX_PythonInit.cpp @@ -274,7 +274,7 @@ static PyObject* gPyGetBlendFileList(PyObject*, PyObject* args) { char cpath[sizeof(G.sce)]; char *searchpath = NULL; - PyObject* list; + PyObject* list, *value; DIR *dp; struct dirent *dirp; @@ -300,7 +300,9 @@ static PyObject* gPyGetBlendFileList(PyObject*, PyObject* args) while ((dirp = readdir(dp)) != NULL) { if (BLI_testextensie(dirp->d_name, ".blend")) { - PyList_Append(list, PyString_FromString(dirp->d_name)); + value = PyString_FromString(dirp->d_name); + PyList_Append(list, value); + Py_DECREF(value); } } From a7348dd43ee764d11cb0db66ca054c979c3b6bfe Mon Sep 17 00:00:00 2001 From: Brecht Van Lommel Date: Thu, 4 Sep 2008 00:27:05 +0000 Subject: [PATCH 4/9] Bugfix: yafray export crash if new hsv texture blend types were used, the code here needed to be updated. --- source/blender/makesdna/DNA_texture_types.h | 1 + source/blender/yafray/intern/export_File.cpp | 2 +- source/blender/yafray/intern/export_Plugin.cpp | 2 +- 3 files changed, 3 insertions(+), 2 deletions(-) diff --git a/source/blender/makesdna/DNA_texture_types.h b/source/blender/makesdna/DNA_texture_types.h index 8a79ce845d7..111dc08ee02 100644 --- a/source/blender/makesdna/DNA_texture_types.h +++ b/source/blender/makesdna/DNA_texture_types.h @@ -367,6 +367,7 @@ typedef struct TexMapping { #define MTEX_BLEND_SAT 11 #define MTEX_BLEND_VAL 12 #define MTEX_BLEND_COLOR 13 +#define MTEX_NUM_BLENDTYPES 14 /* **************** EnvMap ********************* */ diff --git a/source/blender/yafray/intern/export_File.cpp b/source/blender/yafray/intern/export_File.cpp index f8bbdad5f65..f42e00daf6d 100644 --- a/source/blender/yafray/intern/export_File.cpp +++ b/source/blender/yafray/intern/export_File.cpp @@ -881,7 +881,7 @@ void yafrayFileRender_t::writeShader(const string &shader_name, Material* matr, ostr << "\t\t\n"; // blendtype, would have been nice if the order would have been the same as for ramps... - const string blendtype[9] = {"mix", "mul", "add", "sub", "divide", "darken", "difference", "lighten", "screen"}; + const string blendtype[MTEX_NUM_BLENDTYPES] = {"mix", "mul", "add", "sub", "divide", "darken", "difference", "lighten", "screen", "hue", "sat", "val", "color"}; ostr << "\t\tblendtype] << "\" />\n"; // texture color (for use with MUL and/or no_rgb etc..) diff --git a/source/blender/yafray/intern/export_Plugin.cpp b/source/blender/yafray/intern/export_Plugin.cpp index 77d53c4ed96..a7d5653892f 100644 --- a/source/blender/yafray/intern/export_Plugin.cpp +++ b/source/blender/yafray/intern/export_Plugin.cpp @@ -782,7 +782,7 @@ void yafrayPluginRender_t::writeShader(const string &shader_name, Material* matr mparams["input"] = yafray::parameter_t(shader_name + temp); // blendtype, would have been nice if the order would have been the same as for ramps... - const string blendtype[9] = {"mix", "mul", "add", "sub", "divide", "darken", "difference", "lighten", "screen"}; + const string blendtype[MTEX_NUM_BLENDTYPES] = {"mix", "mul", "add", "sub", "divide", "darken", "difference", "lighten", "screen", "hue", "sat", "val", "color"}; mparams["mode"] = yafray::parameter_t(blendtype[(int)mtex->blendtype]); // texture color (for use with MUL and/or no_rgb etc..) From e356c4d5d4fce6aec2a308d93c6e8625d2e8cc8b Mon Sep 17 00:00:00 2001 From: Campbell Barton Date: Thu, 4 Sep 2008 12:11:47 +0000 Subject: [PATCH 5/9] pin option for sensors and actuators, this helps in cases where you want to use a logic brick in 2 states, linking the sensor to a second state's controller can be tricky. This way you can pin a sensor or actuator, change the visible state and link it to another controller. The pin button will only be displayed when states view is enabled and the logic brick is expanded or when it is alredy pinned. --- source/blender/makesdna/DNA_actuator_types.h | 1 + source/blender/makesdna/DNA_sensor_types.h | 1 + source/blender/src/buttons_logic.c | 32 +++++++++++++++----- 3 files changed, 26 insertions(+), 8 deletions(-) diff --git a/source/blender/makesdna/DNA_actuator_types.h b/source/blender/makesdna/DNA_actuator_types.h index 59d0555b452..d08cf42867d 100644 --- a/source/blender/makesdna/DNA_actuator_types.h +++ b/source/blender/makesdna/DNA_actuator_types.h @@ -300,6 +300,7 @@ typedef struct FreeCamera { #define ACT_NEW 4 #define ACT_LINKED 8 #define ACT_VISIBLE 16 +#define ACT_PIN 32 /* link codes */ #define LINK_SENSOR 0 diff --git a/source/blender/makesdna/DNA_sensor_types.h b/source/blender/makesdna/DNA_sensor_types.h index 3e0075c00bd..1fd97fe0158 100644 --- a/source/blender/makesdna/DNA_sensor_types.h +++ b/source/blender/makesdna/DNA_sensor_types.h @@ -218,6 +218,7 @@ typedef struct bJoystickSensor { #define SENS_NEW 4 #define SENS_NOT 8 #define SENS_VISIBLE 16 +#define SENS_PIN 32 /* sensor->pulse */ #define SENS_PULSE_CONT 0 diff --git a/source/blender/src/buttons_logic.c b/source/blender/src/buttons_logic.c index 0b6986c2c8e..ec268af7d86 100644 --- a/source/blender/src/buttons_logic.c +++ b/source/blender/src/buttons_logic.c @@ -3105,6 +3105,9 @@ void logic_buts(void) int a, iact, stbit, offset; short xco, yco, count, width, ycoo; char *pupstr, name[32]; + /* pin is a bool used for actuator and sensor drawing with states + * pin so changing states dosnt hide the logic brick */ + char pin; wrld= G.scene->world; @@ -3365,18 +3368,25 @@ void logic_buts(void) sens= ob->sensors.first; while(sens) { if (!(G.buts->scaflag & BUTS_SENS_STATE) || - sens->totlinks == 0 || /* always display sensor without links so that is can be edited */ - is_sensor_linked(block, sens)) { + (sens->totlinks == 0) || /* always display sensor without links so that is can be edited */ + (sens->flag & SENS_PIN && G.buts->scaflag & BUTS_SENS_STATE) || /* states can hide some sensors, pinned sensors ignore the visible state */ + (is_sensor_linked(block, sens)) + ) { + /* should we draw the pin? - for now always draw when there is a state */ + pin = (G.buts->scaflag & BUTS_SENS_STATE && (sens->flag & SENS_SHOW || sens->flag & SENS_PIN)) ? 1:0 ; + sens->flag |= SENS_VISIBLE; uiBlockSetEmboss(block, UI_EMBOSSM); uiDefIconButBitS(block, TOG, SENS_DEL, B_DEL_SENS, ICON_X, xco, yco, 22, 19, &sens->flag, 0, 0, 0, 0, "Delete Sensor"); + if (pin) + uiDefIconButBitS(block, ICONTOG, SENS_PIN, B_REDR, (sens->flag & SENS_PIN) ? ICON_PIN_DEHLT:ICON_PIN_HLT, (short)(xco+width-44), yco, 22, 19, &sens->flag, 0, 0, 0, 0, "Display when not linked to a visible states controller"); uiDefIconButBitS(block, ICONTOG, SENS_SHOW, B_REDR, ICON_RIGHTARROW, (short)(xco+width-22), yco, 22, 19, &sens->flag, 0, 0, 0, 0, "Sensor settings"); ycoo= yco; if(sens->flag & SENS_SHOW) { uiDefButS(block, MENU, B_CHANGE_SENS, sensor_pup(), (short)(xco+22), yco, 80, 19, &sens->type, 0, 0, 0, 0, "Sensor type"); - but= uiDefBut(block, TEX, 1, "", (short)(xco+102), yco, (short)(width-124), 19, sens->name, 0, 31, 0, 0, "Sensor name"); + but= uiDefBut(block, TEX, 1, "", (short)(xco+102), yco, (short)(width-(pin?146:124)), 19, sens->name, 0, 31, 0, 0, "Sensor name"); uiButSetFunc(but, make_unique_prop_names_cb, sens->name, (void*) 0); sens->otype= sens->type; @@ -3437,16 +3447,22 @@ void logic_buts(void) while(act) { if (!(G.buts->scaflag & BUTS_ACT_STATE) || !(act->flag & ACT_LINKED) || /* always display actuators without links so that is can be edited */ - (act->flag & ACT_VISIBLE)) { /* this actuator has visible connection, display it */ + (act->flag & ACT_VISIBLE) || /* this actuator has visible connection, display it */ + (act->flag & ACT_PIN && G.buts->scaflag & BUTS_ACT_STATE)) { + + pin = (G.buts->scaflag & BUTS_ACT_STATE && (act->flag & SENS_SHOW || act->flag & SENS_PIN)) ? 1:0 ; + act->flag |= ACT_VISIBLE; /* mark the actuator as visible to help implementing the up/down action */ uiBlockSetEmboss(block, UI_EMBOSSM); uiDefIconButBitS(block, TOG, ACT_DEL, B_DEL_ACT, ICON_X, xco, yco, 22, 19, &act->flag, 0, 0, 0, 0, "Delete Actuator"); - uiDefIconButBitS(block, ICONTOG, ACT_SHOW, B_REDR, ICON_RIGHTARROW, (short)(xco+width-22), yco, 22, 19, &act->flag, 0, 0, 0, 0, "Actuator settings"); - + if (pin) + uiDefIconButBitS(block, ICONTOG, ACT_PIN, B_REDR, (act->flag & ACT_PIN) ? ICON_PIN_DEHLT:ICON_PIN_HLT, (short)(xco+width-44), yco, 22, 19, &act->flag, 0, 0, 0, 0, "Display when not linked to a visible states controller"); + uiDefIconButBitS(block, ICONTOG, ACT_SHOW, B_REDR, ICON_RIGHTARROW, (short)(xco+width-22), yco, 22, 19, &act->flag, 0, 0, 0, 0, "Display the actuator"); + if(act->flag & ACT_SHOW) { act->otype= act->type; uiDefButS(block, MENU, B_CHANGE_ACT, actuator_pup(ob), (short)(xco+22), yco, 90, 19, &act->type, 0, 0, 0, 0, "Actuator type"); - but= uiDefBut(block, TEX, 1, "", (short)(xco+112), yco, (short)(width-134), 19, act->name, 0, 31, 0, 0, "Actuator name"); + but= uiDefBut(block, TEX, 1, "", (short)(xco+112), yco, (short)(width-(pin?156:134)), 19, act->name, 0, 31, 0, 0, "Actuator name"); uiButSetFunc(but, make_unique_prop_names_cb, act->name, (void*) 0); ycoo= yco; @@ -3458,7 +3474,7 @@ void logic_buts(void) glRecti((short)(xco+22), yco, (short)(xco+width-22),(short)(yco+19)); but= uiDefBut(block, LABEL, 0, actuator_name(act->type), (short)(xco+22), yco, 90, 19, act, 0, 0, 0, 0, "Actuator type"); uiButSetFunc(but, sca_move_actuator, act, NULL); - but= uiDefBut(block, LABEL, 0, act->name, (short)(xco+112), yco, (short)(width-134), 19, act, 0, 0, 0, 0, "Actuator name"); + but= uiDefBut(block, LABEL, 0, act->name, (short)(xco+112), yco, (short)(width-156), 19, act, 0, 0, 0, 0, "Actuator name"); uiButSetFunc(but, sca_move_actuator, act, NULL); ycoo= yco; } From 05056f2e1db5d0919c6a38873742a045d45a6027 Mon Sep 17 00:00:00 2001 From: Campbell Barton Date: Thu, 4 Sep 2008 12:17:01 +0000 Subject: [PATCH 6/9] overlapping UI causing problems, forgot the label has a function assigned to it --- source/blender/src/buttons_logic.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/source/blender/src/buttons_logic.c b/source/blender/src/buttons_logic.c index ec268af7d86..9c66b7831bb 100644 --- a/source/blender/src/buttons_logic.c +++ b/source/blender/src/buttons_logic.c @@ -3398,7 +3398,7 @@ void logic_buts(void) glRecti(xco+22, yco, xco+width-22,yco+19); but= uiDefBut(block, LABEL, 0, sensor_name(sens->type), (short)(xco+22), yco, 80, 19, sens, 0, 0, 0, 0, ""); uiButSetFunc(but, sca_move_sensor, sens, NULL); - but= uiDefBut(block, LABEL, 0, sens->name, (short)(xco+102), yco, (short)(width-124), 19, sens, 0, 31, 0, 0, ""); + but= uiDefBut(block, LABEL, 0, sens->name, (short)(xco+102), yco, (short)(width-(pin?146:124)), 19, sens, 0, 31, 0, 0, ""); uiButSetFunc(but, sca_move_sensor, sens, NULL); } @@ -3474,7 +3474,7 @@ void logic_buts(void) glRecti((short)(xco+22), yco, (short)(xco+width-22),(short)(yco+19)); but= uiDefBut(block, LABEL, 0, actuator_name(act->type), (short)(xco+22), yco, 90, 19, act, 0, 0, 0, 0, "Actuator type"); uiButSetFunc(but, sca_move_actuator, act, NULL); - but= uiDefBut(block, LABEL, 0, act->name, (short)(xco+112), yco, (short)(width-156), 19, act, 0, 0, 0, 0, "Actuator name"); + but= uiDefBut(block, LABEL, 0, act->name, (short)(xco+112), yco, (short)(width-(pin?156:134)), 19, act, 0, 0, 0, 0, "Actuator name"); uiButSetFunc(but, sca_move_actuator, act, NULL); ycoo= yco; } From f0eaf424ab7488b93f18c634ba825c3b734ad913 Mon Sep 17 00:00:00 2001 From: Kent Mein Date: Thu, 4 Sep 2008 15:29:43 +0000 Subject: [PATCH 7/9] Added SDL headers so gamestuff compiles with Makefiles again. Kent --- source/gameengine/Ketsji/Makefile | 1 + 1 file changed, 1 insertion(+) diff --git a/source/gameengine/Ketsji/Makefile b/source/gameengine/Ketsji/Makefile index 59cc6c8ca7e..995237adf2c 100644 --- a/source/gameengine/Ketsji/Makefile +++ b/source/gameengine/Ketsji/Makefile @@ -35,6 +35,7 @@ include nan_compile.mk CCFLAGS += $(LEVEL_1_CPP_WARNINGS) +CPPFLAGS += $(NAN_SDLCFLAGS) CPPFLAGS += $(OGL_CPPFLAGS) CPPFLAGS += -I$(NAN_GLEW)/include CPPFLAGS += -I$(OPENGL_HEADERS) From 2167e5c341f656b2f664b1052d181e8aa32fe698 Mon Sep 17 00:00:00 2001 From: Kent Mein Date: Thu, 4 Sep 2008 16:40:20 +0000 Subject: [PATCH 8/9] Cleaned up some small warnings. Kent --- source/blender/include/BIF_drawtext.h | 1 + source/blender/src/drawtext.c | 3 +-- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/source/blender/include/BIF_drawtext.h b/source/blender/include/BIF_drawtext.h index bc4d5e3f9c8..51000f8c81a 100644 --- a/source/blender/include/BIF_drawtext.h +++ b/source/blender/include/BIF_drawtext.h @@ -33,6 +33,7 @@ struct ScrArea; struct SpaceText; struct Text; +struct TextLine; void unlink_text(struct Text *text); diff --git a/source/blender/src/drawtext.c b/source/blender/src/drawtext.c index daa2d52d485..3f21d32c2d4 100644 --- a/source/blender/src/drawtext.c +++ b/source/blender/src/drawtext.c @@ -138,8 +138,6 @@ static void get_selection_buffer(Text *text); static int check_bracket(char ch); static int check_delim(char ch); static int check_digit(char ch); -static int check_builtinfuncs(char *string); -static int check_specialvars(char *string); static int check_identifier(char ch); static int check_whitespace(char ch); @@ -595,6 +593,7 @@ static void set_cursor_to_pos (SpaceText *st, int x, int y, int sel) chop= 1; chars= 0; curs= 0; + endj= 0; for (i=0, j=0; loop; j++) { /* Mimic replacement of tabs */ From cb89decfdcf5e6b2f26376d416633f4ccf0c532d Mon Sep 17 00:00:00 2001 From: Brecht Van Lommel Date: Thu, 4 Sep 2008 20:51:28 +0000 Subject: [PATCH 9/9] Merge of first part of changes from the apricot branch, especially the features that are needed to run the game. Compile tested with scons, make, but not cmake, that seems to have an issue not related to these changes. The changes include: * GLSL support in the viewport and game engine, enable in the game menu in textured draw mode. * Synced and merged part of the duplicated blender and gameengine/ gameplayer drawing code. * Further refactoring of game engine drawing code, especially mesh storage changed a lot. * Optimizations in game engine armatures to avoid recomputations. * A python function to get the framerate estimate in game. * An option take object color into account in materials. * An option to restrict shadow casters to a lamp's layers. * Increase from 10 to 18 texture slots for materials, lamps, word. An extra texture slot shows up once the last slot is used. * Memory limit for undo, not enabled by default yet because it needs the .B.blend to be changed. * Multiple undo for image painting. * An offset for dupligroups, so not all objects in a group have to be at the origin. --- blenderplayer/CMakeLists.txt | 1 + config/darwin-config.py | 1 - extern/glew/SConscript | 2 +- extern/glew/include/GL/glew.h | 7 +- extern/glew/src/glew.c | 2 + intern/guardedalloc/MEM_guardedalloc.h | 10 +- intern/guardedalloc/intern/mallocn.c | 21 +- intern/memutil/MEM_Allocator.h | 1 + intern/memutil/MEM_CacheLimiter.h | 12 +- .../memutil/intern/MEM_CacheLimiterC-Api.cpp | 8 +- intern/moto/include/GEN_Map.h | 13 + intern/moto/include/MT_Matrix4x4.h | 1 + intern/moto/include/MT_Matrix4x4.inl | 14 +- release/scripts/sysinfo.py | 2 + source/Makefile | 3 +- source/blender/CMakeLists.txt | 2 +- source/blender/Makefile | 2 +- source/blender/SConscript | 1 + source/blender/blenkernel/BKE_DerivedMesh.h | 49 +- .../blender/blenkernel/BKE_bad_level_calls.h | 4 - source/blender/blenkernel/BKE_colortools.h | 1 + source/blender/blenkernel/BKE_global.h | 9 +- source/blender/blenkernel/BKE_mesh.h | 1 - source/blender/blenkernel/BKE_node.h | 8 + source/blender/blenkernel/BKE_texture.h | 1 + source/blender/blenkernel/BKE_utildefines.h | 2 + source/blender/blenkernel/CMakeLists.txt | 2 +- source/blender/blenkernel/SConscript | 1 + .../blenkernel/bad_level_call_stubs/stubs.c | 4 - .../blender/blenkernel/intern/DerivedMesh.c | 407 ++++- source/blender/blenkernel/intern/Makefile | 4 + source/blender/blenkernel/intern/action.c | 2 + source/blender/blenkernel/intern/anim.c | 15 +- source/blender/blenkernel/intern/blender.c | 36 +- .../blender/blenkernel/intern/cdderivedmesh.c | 138 +- source/blender/blenkernel/intern/colortools.c | 21 + source/blender/blenkernel/intern/image.c | 11 +- source/blender/blenkernel/intern/ipo.c | 25 +- source/blender/blenkernel/intern/material.c | 7 + source/blender/blenkernel/intern/mesh.c | 39 - source/blender/blenkernel/intern/node.c | 114 ++ source/blender/blenkernel/intern/object.c | 6 +- .../blender/blenkernel/intern/subsurf_ccg.c | 172 +- source/blender/blenkernel/intern/texture.c | 12 + source/blender/blenlib/BLI_arithb.h | 1 + source/blender/blenlib/BLI_blenlib.h | 1 - source/blender/blenlib/intern/arithb.c | 8 + source/blender/blenloader/intern/readfile.c | 11 +- source/blender/gpu/CMakeLists.txt | 34 + source/blender/gpu/GPU_draw.h | 116 ++ source/blender/gpu/GPU_extensions.h | 144 ++ source/blender/gpu/GPU_material.h | 169 ++ source/blender/gpu/Makefile | 37 + source/blender/gpu/SConscript | 11 + source/blender/gpu/intern/Makefile | 53 + source/blender/gpu/intern/gpu_codegen.c | 1439 +++++++++++++++ source/blender/gpu/intern/gpu_codegen.h | 87 + source/blender/gpu/intern/gpu_draw.c | 1167 +++++++++++++ source/blender/gpu/intern/gpu_extensions.c | 987 +++++++++++ source/blender/gpu/intern/gpu_material.c | 1460 ++++++++++++++++ .../gpu/intern/gpu_shader_material.glsl | 1543 +++++++++++++++++ .../gpu/intern/gpu_shader_material.glsl.c | 1026 +++++++++++ .../blender/gpu/intern/gpu_shader_vertex.glsl | 12 + .../gpu/intern/gpu_shader_vertex.glsl.c | 13 + source/blender/include/BDR_drawmesh.h | 43 +- source/blender/include/BDR_drawobject.h | 3 +- source/blender/include/BDR_imagepaint.h | 4 +- source/blender/include/BIF_gl.h | 15 +- source/blender/include/BIF_meshtools.h | 2 + source/blender/include/BSE_drawview.h | 6 +- source/blender/makesdna/DNA_brush_types.h | 4 +- source/blender/makesdna/DNA_group_types.h | 2 +- source/blender/makesdna/DNA_image_types.h | 4 +- source/blender/makesdna/DNA_ipo_types.h | 28 +- source/blender/makesdna/DNA_lamp_types.h | 16 +- source/blender/makesdna/DNA_material_types.h | 11 +- source/blender/makesdna/DNA_object_types.h | 2 + source/blender/makesdna/DNA_scene_types.h | 2 +- source/blender/makesdna/DNA_userdef_types.h | 1 + source/blender/makesdna/DNA_world_types.h | 4 +- source/blender/nodes/CMakeLists.txt | 2 +- source/blender/nodes/SConscript | 1 + .../blender/nodes/intern/CMP_nodes/Makefile | 1 + source/blender/nodes/intern/Makefile | 2 + .../blender/nodes/intern/SHD_nodes/Makefile | 2 + .../nodes/intern/SHD_nodes/SHD_camera.c | 10 +- .../nodes/intern/SHD_nodes/SHD_curves.c | 24 +- .../blender/nodes/intern/SHD_nodes/SHD_geom.c | 16 +- .../nodes/intern/SHD_nodes/SHD_hueSatVal.c | 9 +- .../nodes/intern/SHD_nodes/SHD_invert.c | 8 +- .../nodes/intern/SHD_nodes/SHD_mapping.c | 17 +- .../nodes/intern/SHD_nodes/SHD_material.c | 79 +- .../blender/nodes/intern/SHD_nodes/SHD_math.c | 43 +- .../nodes/intern/SHD_nodes/SHD_mixRgb.c | 14 +- .../nodes/intern/SHD_nodes/SHD_normal.c | 11 +- .../nodes/intern/SHD_nodes/SHD_output.c | 16 +- .../blender/nodes/intern/SHD_nodes/SHD_rgb.c | 11 +- .../nodes/intern/SHD_nodes/SHD_sepcombRGB.c | 16 +- .../nodes/intern/SHD_nodes/SHD_squeeze.c | 8 +- .../nodes/intern/SHD_nodes/SHD_texture.c | 17 +- .../nodes/intern/SHD_nodes/SHD_valToRgb.c | 20 +- .../nodes/intern/SHD_nodes/SHD_value.c | 9 +- .../nodes/intern/SHD_nodes/SHD_vectMath.c | 31 +- source/blender/nodes/intern/SHD_util.h | 2 + source/blender/python/CMakeLists.txt | 6 +- source/blender/python/SConscript | 4 + source/blender/python/api2_2x/Blender.c | 22 +- source/blender/python/api2_2x/Group.c | 31 + source/blender/python/api2_2x/Image.c | 4 +- source/blender/python/api2_2x/Lamp.c | 18 +- source/blender/python/api2_2x/MTex.c | 10 +- source/blender/python/api2_2x/Makefile | 6 + source/blender/python/api2_2x/Material.c | 3 +- source/blender/python/api2_2x/doc/Group.py | 2 + source/blender/radiosity/CMakeLists.txt | 2 +- source/blender/radiosity/SConscript | 2 +- .../blender/radiosity/intern/source/Makefile | 1 + .../render/intern/include/render_types.h | 3 +- .../blender/render/intern/source/pipeline.c | 2 +- .../blender/render/intern/source/rayshade.c | 5 +- source/blender/render/intern/source/shadbuf.c | 4 +- .../render/intern/source/shadeoutput.c | 16 +- source/blender/render/intern/source/zbuf.c | 2 +- source/blender/src/CMakeLists.txt | 2 +- source/blender/src/Makefile | 1 + source/blender/src/SConscript | 3 +- source/blender/src/buttons_object.c | 33 +- source/blender/src/buttons_shading.c | 138 +- source/blender/src/drawarmature.c | 3 + source/blender/src/drawmesh.c | 771 +------- source/blender/src/drawobject.c | 325 ++-- source/blender/src/drawview.c | 279 ++- source/blender/src/editdeform.c | 2 +- source/blender/src/editface.c | 7 +- source/blender/src/editipo_lib.c | 10 +- source/blender/src/editlattice.c | 2 +- source/blender/src/editmode_undo.c | 40 +- source/blender/src/editview.c | 2 +- source/blender/src/header_image.c | 6 +- source/blender/src/header_info.c | 115 +- source/blender/src/header_view3d.c | 2 +- source/blender/src/headerbuttons.c | 7 +- source/blender/src/imagepaint.c | 309 +++- source/blender/src/meshtools.c | 5 +- source/blender/src/playanim.c | 20 +- source/blender/src/previewrender.c | 32 + source/blender/src/renderwin.c | 17 +- source/blender/src/sculptmode.c | 7 +- source/blender/src/sequence.c | 12 +- source/blender/src/space.c | 51 +- source/blender/src/toets.c | 4 +- source/blender/src/usiblender.c | 21 +- source/blender/src/verse_image.c | 2 +- source/creator/CMakeLists.txt | 3 + source/creator/Makefile | 2 + source/creator/SConscript | 2 +- source/creator/creator.c | 8 +- .../BlenderRoutines/BL_KetsjiEmbedStart.cpp | 20 +- .../gameengine/BlenderRoutines/CMakeLists.txt | 1 + .../BlenderRoutines/KX_BlenderGL.cpp | 75 - .../gameengine/BlenderRoutines/KX_BlenderGL.h | 3 - .../BlenderRoutines/KX_BlenderRenderTools.cpp | 269 ++- .../BlenderRoutines/KX_BlenderRenderTools.h | 67 +- source/gameengine/BlenderRoutines/Makefile | 5 +- source/gameengine/BlenderRoutines/SConscript | 5 +- .../Converter/BL_ArmatureObject.cpp | 74 +- .../gameengine/Converter/BL_ArmatureObject.h | 8 +- .../Converter/BL_BlenderDataConversion.cpp | 140 +- .../Converter/BL_DeformableGameObject.cpp | 8 +- .../gameengine/Converter/BL_MeshDeformer.cpp | 89 +- source/gameengine/Converter/BL_MeshDeformer.h | 3 +- .../Converter/BL_ShapeActionActuator.cpp | 1 - .../gameengine/Converter/BL_ShapeDeformer.cpp | 3 - .../gameengine/Converter/BL_ShapeDeformer.h | 11 - .../gameengine/Converter/BL_SkinDeformer.cpp | 47 +- source/gameengine/Converter/BL_SkinDeformer.h | 16 +- .../Converter/BL_SkinMeshObject.cpp | 74 +- .../gameengine/Converter/BL_SkinMeshObject.h | 45 +- source/gameengine/Converter/CMakeLists.txt | 1 + .../Converter/KX_BlenderSceneConverter.cpp | 25 +- .../Converter/KX_BlenderSceneConverter.h | 2 + .../Converter/KX_ConvertActuators.cpp | 2 +- source/gameengine/Converter/Makefile | 1 + source/gameengine/Converter/SConscript | 2 +- .../GamePlayer/common/CMakeLists.txt | 2 +- .../GamePlayer/common/GPC_RenderTools.cpp | 545 +++--- .../GamePlayer/common/GPC_RenderTools.h | 153 +- source/gameengine/GamePlayer/common/Makefile | 5 +- .../gameengine/GamePlayer/common/SConscript | 2 +- .../common/unix/GPU_PolygonMaterial.h | 4 +- .../GamePlayer/ghost/CMakeLists.txt | 1 + .../GamePlayer/ghost/GPG_Application.cpp | 34 +- .../GamePlayer/ghost/GPG_Application.h | 6 +- .../gameengine/GamePlayer/ghost/GPG_ghost.cpp | 16 +- source/gameengine/GamePlayer/ghost/Makefile | 5 +- source/gameengine/GamePlayer/ghost/SConscript | 4 +- source/gameengine/Ketsji/BL_BlenderShader.cpp | 124 +- source/gameengine/Ketsji/BL_BlenderShader.h | 10 +- source/gameengine/Ketsji/BL_Material.h | 6 +- source/gameengine/Ketsji/BL_Shader.cpp | 12 +- source/gameengine/Ketsji/BL_Shader.h | 2 +- source/gameengine/Ketsji/CMakeLists.txt | 1 + .../gameengine/Ketsji/KX_BlenderMaterial.cpp | 126 +- source/gameengine/Ketsji/KX_BlenderMaterial.h | 3 +- .../Ketsji/KX_ConvertPhysicsObjects.cpp | 136 +- source/gameengine/Ketsji/KX_GameObject.cpp | 100 +- source/gameengine/Ketsji/KX_GameObject.h | 83 +- source/gameengine/Ketsji/KX_ISceneConverter.h | 4 + source/gameengine/Ketsji/KX_KetsjiEngine.cpp | 32 +- source/gameengine/Ketsji/KX_KetsjiEngine.h | 7 + source/gameengine/Ketsji/KX_Light.cpp | 57 +- source/gameengine/Ketsji/KX_Light.h | 11 +- source/gameengine/Ketsji/KX_MeshProxy.cpp | 13 +- source/gameengine/Ketsji/KX_PolyProxy.cpp | 18 +- .../gameengine/Ketsji/KX_PolygonMaterial.cpp | 50 +- source/gameengine/Ketsji/KX_PolygonMaterial.h | 2 - source/gameengine/Ketsji/KX_PythonInit.cpp | 89 +- source/gameengine/Ketsji/KX_PythonInit.h | 2 +- .../KX_SG_BoneParentNodeRelationship.cpp | 2 +- source/gameengine/Ketsji/KX_Scene.cpp | 31 +- source/gameengine/Ketsji/KX_Scene.h | 10 +- source/gameengine/Ketsji/KX_VertexProxy.cpp | 14 +- .../Ketsji/KX_VisibilityActuator.cpp | 2 +- source/gameengine/Ketsji/Makefile | 6 +- source/gameengine/Ketsji/SConscript | 5 +- .../Physics/Bullet/CcdPhysicsController.cpp | 34 +- .../Physics/Bullet/CcdPhysicsController.h | 3 +- source/gameengine/PyDoc/GameLogic.py | 9 +- source/gameengine/PyDoc/Rasterizer.py | 17 + source/gameengine/Rasterizer/Makefile | 4 - .../Rasterizer/RAS_BucketManager.cpp | 267 +-- .../gameengine/Rasterizer/RAS_BucketManager.h | 21 +- .../Rasterizer/RAS_IPolygonMaterial.cpp | 25 +- .../Rasterizer/RAS_IPolygonMaterial.h | 9 +- .../gameengine/Rasterizer/RAS_IRasterizer.h | 42 +- .../Rasterizer/RAS_IRenderTools.cpp | 24 +- .../gameengine/Rasterizer/RAS_IRenderTools.h | 39 +- .../Rasterizer/RAS_MaterialBucket.cpp | 592 +++++-- .../Rasterizer/RAS_MaterialBucket.h | 219 ++- .../gameengine/Rasterizer/RAS_MeshObject.cpp | 993 +++++------ source/gameengine/Rasterizer/RAS_MeshObject.h | 242 +-- .../RAS_OpenGLRasterizer/CMakeLists.txt | 1 + .../Rasterizer/RAS_OpenGLRasterizer/Makefile | 5 +- .../RAS_ListRasterizer.cpp | 84 +- .../RAS_OpenGLRasterizer/RAS_ListRasterizer.h | 24 +- .../RAS_OpenGLRasterizer.cpp | 756 ++------ .../RAS_OpenGLRasterizer.h | 46 +- .../RAS_VAOpenGLRasterizer.cpp | 234 ++- .../RAS_VAOpenGLRasterizer.h | 18 +- .../RAS_OpenGLRasterizer/SConscript | 5 +- source/gameengine/Rasterizer/RAS_Polygon.cpp | 87 +- source/gameengine/Rasterizer/RAS_Polygon.h | 56 +- source/gameengine/Rasterizer/RAS_TexVert.cpp | 30 +- source/gameengine/Rasterizer/RAS_TexVert.h | 28 +- source/gameengine/Rasterizer/SConscript | 5 +- source/kernel/gen_system/GEN_Map.h | 13 + source/nan_definitions.mk | 3 - tools/btools.py | 2 - 258 files changed, 13813 insertions(+), 5271 deletions(-) create mode 100644 source/blender/gpu/CMakeLists.txt create mode 100644 source/blender/gpu/GPU_draw.h create mode 100644 source/blender/gpu/GPU_extensions.h create mode 100644 source/blender/gpu/GPU_material.h create mode 100644 source/blender/gpu/Makefile create mode 100644 source/blender/gpu/SConscript create mode 100644 source/blender/gpu/intern/Makefile create mode 100644 source/blender/gpu/intern/gpu_codegen.c create mode 100644 source/blender/gpu/intern/gpu_codegen.h create mode 100644 source/blender/gpu/intern/gpu_draw.c create mode 100644 source/blender/gpu/intern/gpu_extensions.c create mode 100644 source/blender/gpu/intern/gpu_material.c create mode 100644 source/blender/gpu/intern/gpu_shader_material.glsl create mode 100644 source/blender/gpu/intern/gpu_shader_material.glsl.c create mode 100644 source/blender/gpu/intern/gpu_shader_vertex.glsl create mode 100644 source/blender/gpu/intern/gpu_shader_vertex.glsl.c diff --git a/blenderplayer/CMakeLists.txt b/blenderplayer/CMakeLists.txt index d90639562d2..e32390466c7 100644 --- a/blenderplayer/CMakeLists.txt +++ b/blenderplayer/CMakeLists.txt @@ -90,6 +90,7 @@ IF(UNIX) bf_soundsystem bf_kernel bf_nodes + bf_gpu bf_imbuf bf_avi kx_network diff --git a/config/darwin-config.py b/config/darwin-config.py index 8fd6c3251ba..48455d2ce8c 100644 --- a/config/darwin-config.py +++ b/config/darwin-config.py @@ -143,7 +143,6 @@ BF_FTGL_LIB = 'extern_ftgl' WITH_BF_GAMEENGINE='true' WITH_BF_PLAYER='true' -WITH_BF_GLEXT= '1' WITH_BF_ODE = 'false' BF_ODE = LIBDIR + '/ode' diff --git a/extern/glew/SConscript b/extern/glew/SConscript index 32b3b478113..3badbeb040e 100644 --- a/extern/glew/SConscript +++ b/extern/glew/SConscript @@ -9,4 +9,4 @@ sources = ['src/glew.c'] defs = '' incs = 'include' -env.BlenderLib ( 'extern_glew', sources, Split(incs), Split(defs), libtype=['intern', 'player'], priority=[25, 50]) +env.BlenderLib ( 'extern_glew', sources, Split(incs), Split(defs), libtype=['blender', 'player'], priority=[50, 50]) diff --git a/extern/glew/include/GL/glew.h b/extern/glew/include/GL/glew.h index fd3fe10b938..6b88e6eb4c9 100644 --- a/extern/glew/include/GL/glew.h +++ b/extern/glew/include/GL/glew.h @@ -58,8 +58,11 @@ ** version 1.2.1 Specification. */ -/* added this here for blender, should be moved elsewhere */ +#define BLENDER_CHANGES + +#ifdef BLENDER_CHANGES #define GLEW_STATIC +#endif #ifndef __glew_h__ #define __glew_h__ @@ -1805,6 +1808,7 @@ typedef void (GLAPIENTRY * PFNGLVERTEXATTRIB4UIVPROC) (GLuint index, const GLuin typedef void (GLAPIENTRY * PFNGLVERTEXATTRIB4USVPROC) (GLuint index, const GLushort* v); typedef void (GLAPIENTRY * PFNGLVERTEXATTRIBPOINTERPROC) (GLuint index, GLint size, GLenum type, GLboolean normalized, GLsizei stride, const GLvoid* pointer); +#ifndef BLENDER_CHANGES #define glAttachShader GLEW_GET_FUN(__glewAttachShader) #define glBindAttribLocation GLEW_GET_FUN(__glewBindAttribLocation) #define glBlendEquationSeparate GLEW_GET_FUN(__glewBlendEquationSeparate) @@ -1898,6 +1902,7 @@ typedef void (GLAPIENTRY * PFNGLVERTEXATTRIBPOINTERPROC) (GLuint index, GLint si #define glVertexAttrib4uiv GLEW_GET_FUN(__glewVertexAttrib4uiv) #define glVertexAttrib4usv GLEW_GET_FUN(__glewVertexAttrib4usv) #define glVertexAttribPointer GLEW_GET_FUN(__glewVertexAttribPointer) +#endif #define GLEW_VERSION_2_0 GLEW_GET_VAR(__GLEW_VERSION_2_0) diff --git a/extern/glew/src/glew.c b/extern/glew/src/glew.c index 593f0e58f7c..f20463630dc 100644 --- a/extern/glew/src/glew.c +++ b/extern/glew/src/glew.c @@ -1836,6 +1836,7 @@ static GLboolean _glewInit_GL_VERSION_2_0 (GLEW_CONTEXT_ARG_DEF_INIT) { GLboolean r = GL_FALSE; +#ifndef BLENDER_CHANGES r = ((glAttachShader = (PFNGLATTACHSHADERPROC)glewGetProcAddress((const GLubyte*)"glAttachShader")) == NULL) || r; r = ((glBindAttribLocation = (PFNGLBINDATTRIBLOCATIONPROC)glewGetProcAddress((const GLubyte*)"glBindAttribLocation")) == NULL) || r; r = ((glBlendEquationSeparate = (PFNGLBLENDEQUATIONSEPARATEPROC)glewGetProcAddress((const GLubyte*)"glBlendEquationSeparate")) == NULL) || r; @@ -1929,6 +1930,7 @@ static GLboolean _glewInit_GL_VERSION_2_0 (GLEW_CONTEXT_ARG_DEF_INIT) r = ((glVertexAttrib4uiv = (PFNGLVERTEXATTRIB4UIVPROC)glewGetProcAddress((const GLubyte*)"glVertexAttrib4uiv")) == NULL) || r; r = ((glVertexAttrib4usv = (PFNGLVERTEXATTRIB4USVPROC)glewGetProcAddress((const GLubyte*)"glVertexAttrib4usv")) == NULL) || r; r = ((glVertexAttribPointer = (PFNGLVERTEXATTRIBPOINTERPROC)glewGetProcAddress((const GLubyte*)"glVertexAttribPointer")) == NULL) || r; +#endif return r; } diff --git a/intern/guardedalloc/MEM_guardedalloc.h b/intern/guardedalloc/MEM_guardedalloc.h index d004e7952cc..1d4c753802b 100644 --- a/intern/guardedalloc/MEM_guardedalloc.h +++ b/intern/guardedalloc/MEM_guardedalloc.h @@ -58,8 +58,8 @@ #ifndef MEM_MALLOCN_H #define MEM_MALLOCN_H -/* Needed for FILE* */ -#include "stdio.h" +#include "stdio.h" /* needed for FILE* */ +#include "BLO_sys_types.h" /* needed for uintptr_t */ #ifdef __cplusplus extern "C" { @@ -123,6 +123,12 @@ extern "C" { /** Attempt to enforce OSX (or other OS's) to have malloc and stack nonzero */ void MEM_set_memory_debug(void); + /* Memory usage stats + * - MEM_get_memory_in_use is all memory + * - MEM_get_mapped_memory_in_use is a subset of all memory */ + uintptr_t MEM_get_memory_in_use(void); + uintptr_t MEM_get_mapped_memory_in_use(void); + int MEM_get_memory_blocks_in_use(void); #ifdef __cplusplus } diff --git a/intern/guardedalloc/intern/mallocn.c b/intern/guardedalloc/intern/mallocn.c index a36549d0cc7..7bdca7339fc 100644 --- a/intern/guardedalloc/intern/mallocn.c +++ b/intern/guardedalloc/intern/mallocn.c @@ -49,8 +49,6 @@ #include "MEM_guardedalloc.h" -#include "BLO_sys_types.h" // needed for intptr_t - /* --------------------------------------------------------------------- */ /* Data definition */ /* --------------------------------------------------------------------- */ @@ -113,8 +111,8 @@ static const char *check_memlist(MemHead *memh); /* --------------------------------------------------------------------- */ -volatile int totblock= 0; -volatile uintptr_t mem_in_use= 0, mmap_in_use= 0; +static volatile int totblock= 0; +static volatile uintptr_t mem_in_use= 0, mmap_in_use= 0; static volatile struct localListBase _membase; static volatile struct localListBase *membase = &_membase; @@ -698,4 +696,19 @@ static const char *check_memlist(MemHead *memh) return(name); } +uintptr_t MEM_get_memory_in_use(void) +{ + return mem_in_use; +} + +uintptr_t MEM_get_mapped_memory_in_use(void) +{ + return mmap_in_use; +} + +int MEM_get_memory_blocks_in_use(void) +{ + return totblock; +} + /* eof */ diff --git a/intern/memutil/MEM_Allocator.h b/intern/memutil/MEM_Allocator.h index d5ae94cc6b8..b2c3c5e82e2 100644 --- a/intern/memutil/MEM_Allocator.h +++ b/intern/memutil/MEM_Allocator.h @@ -25,6 +25,7 @@ #define __MEM_Allocator_h_included__ 1 #include "guardedalloc/MEM_guardedalloc.h" +#include "guardedalloc/BLO_sys_types.h" #ifdef _MSC_VER #if _MSC_VER < 1300 // 1200 == VC++ 6.0 according to boost diff --git a/intern/memutil/MEM_CacheLimiter.h b/intern/memutil/MEM_CacheLimiter.h index cada06ae523..43149efc977 100644 --- a/intern/memutil/MEM_CacheLimiter.h +++ b/intern/memutil/MEM_CacheLimiter.h @@ -61,11 +61,8 @@ class MEM_CacheLimiter; #ifndef __MEM_cache_limiter_c_api_h_included__ extern "C" { - extern void MEM_CacheLimiter_set_maximum(int m); - extern int MEM_CacheLimiter_get_maximum(); - // this is rather _ugly_! - extern int mem_in_use; - extern int mmap_in_use; + extern void MEM_CacheLimiter_set_maximum(intptr_t m); + extern intptr_t MEM_CacheLimiter_get_maximum(); }; #endif @@ -141,7 +138,10 @@ public: delete handle; } void enforce_limits() { - int max = MEM_CacheLimiter_get_maximum(); + intptr_t max = MEM_CacheLimiter_get_maximum(); + intptr_t mem_in_use= MEM_get_memory_in_use(); + intptr_t mmap_in_use= MEM_get_mapped_memory_in_use(); + if (max == 0) { return; } diff --git a/intern/memutil/intern/MEM_CacheLimiterC-Api.cpp b/intern/memutil/intern/MEM_CacheLimiterC-Api.cpp index 4cf0ef305d4..d998c9a3e80 100644 --- a/intern/memutil/intern/MEM_CacheLimiterC-Api.cpp +++ b/intern/memutil/intern/MEM_CacheLimiterC-Api.cpp @@ -27,18 +27,18 @@ #include "MEM_CacheLimiter.h" #include "MEM_CacheLimiterC-Api.h" -static int & get_max() +static intptr_t & get_max() { - static int m = 32*1024*1024; + static intptr_t m = 32*1024*1024; return m; } -void MEM_CacheLimiter_set_maximum(int m) +void MEM_CacheLimiter_set_maximum(intptr_t m) { get_max() = m; } -int MEM_CacheLimiter_get_maximum() +intptr_t MEM_CacheLimiter_get_maximum() { return get_max(); } diff --git a/intern/moto/include/GEN_Map.h b/intern/moto/include/GEN_Map.h index 9f56924419e..d85e9af175b 100644 --- a/intern/moto/include/GEN_Map.h +++ b/intern/moto/include/GEN_Map.h @@ -50,6 +50,19 @@ public: m_buckets[i] = 0; } } + + GEN_Map(const GEN_Map& map) + { + m_num_buckets = map.m_num_buckets; + m_buckets = new Entry *[m_num_buckets]; + + for (int i = 0; i < m_num_buckets; ++i) { + m_buckets[i] = 0; + + for(Entry *entry = map.m_buckets[i]; entry; entry=entry->m_next) + insert(entry->m_key, entry->m_value); + } + } int size() { int count=0; diff --git a/intern/moto/include/MT_Matrix4x4.h b/intern/moto/include/MT_Matrix4x4.h index 823541347b7..b4ee84a718b 100644 --- a/intern/moto/include/MT_Matrix4x4.h +++ b/intern/moto/include/MT_Matrix4x4.h @@ -212,6 +212,7 @@ public: MT_Matrix4x4 transposed() const; void transpose(); + MT_Matrix4x4 inverse() const; void invert(); protected: diff --git a/intern/moto/include/MT_Matrix4x4.inl b/intern/moto/include/MT_Matrix4x4.inl index a2aa893a6b3..074bd6e4b05 100644 --- a/intern/moto/include/MT_Matrix4x4.inl +++ b/intern/moto/include/MT_Matrix4x4.inl @@ -52,14 +52,14 @@ GEN_INLINE void MT_Matrix4x4::invert() { } } -/* We do things slightly different here, because the invert() modifies - * the buffer itself. This makes it impossible to make this op right - * away. Like other, still missing facilities, I will repair this - * later. */ -/* GEN_INLINE T_Matrix4x4 MT_Matrix4x4::inverse() const */ -/* { */ -/* } */ +GEN_INLINE MT_Matrix4x4 MT_Matrix4x4::inverse() const +{ + MT_Matrix4x4 invmat = *this; + invmat.invert(); + + return invmat; +} GEN_INLINE MT_Matrix4x4& MT_Matrix4x4::operator*=(const MT_Matrix4x4& m) { diff --git a/release/scripts/sysinfo.py b/release/scripts/sysinfo.py index 9f24885829c..3a671e7221e 100644 --- a/release/scripts/sysinfo.py +++ b/release/scripts/sysinfo.py @@ -94,6 +94,8 @@ output = Blender.Text.New(output_filename) output.write(header + "\n\n") +output.write("%s\n\n" % Blender.Get('buildinfo')) + output.write("Platform: %s\n========\n\n" % sys.platform) output.write("Python:\n======\n\n") diff --git a/source/Makefile b/source/Makefile index 91dd17d73dd..aebeb8f30c2 100644 --- a/source/Makefile +++ b/source/Makefile @@ -104,6 +104,8 @@ COMLIB += $(NAN_OPENNL)/lib/$(DEBUG_DIR)libopennl.a COMLIB += $(NAN_SUPERLU)/lib/$(DEBUG_DIR)libsuperlu.a COMLIB += $(OCGDIR)/blender/avi/$(DEBUG_DIR)libavi.a COMLIB += $(NAN_JPEG)/lib/libjpeg.a +COMLIB += $(OCGDIR)/blender/gpu/$(DEBUG_DIR)libgpu.a +COMLIB += $(NAN_GLEW)/lib/libglew.a ifneq ($(NAN_NO_KETSJI),true) COMLIB += $(OCGDIR)/gameengine/bloutines/$(DEBUG_DIR)libbloutines.a @@ -157,7 +159,6 @@ COMLIB += $(NAN_BMFONT)/lib/$(DEBUG_DIR)libbmfont.a COMLIB += $(NAN_PNG)/lib/libpng.a COMLIB += $(OCGDIR)/blender/yafray/$(DEBUG_DIR)libyafrayexport.a COMLIB += $(OCGDIR)/blender/blenlib/$(DEBUG_DIR)libblenlib.a -COMLIB += $(NAN_GLEW)/lib/libglew.a ifeq ($(WITH_QUICKTIME), true) COMLIB += $(OCGDIR)/blender/blenderqt/$(DEBUG_DIR)libblenderqt.a diff --git a/source/blender/CMakeLists.txt b/source/blender/CMakeLists.txt index 966bf5f7be4..a21eadf15fa 100644 --- a/source/blender/CMakeLists.txt +++ b/source/blender/CMakeLists.txt @@ -24,7 +24,7 @@ # # ***** END GPL LICENSE BLOCK ***** -SUBDIRS(avi nodes blenkernel blenlib blenloader blenpluginapi imbuf imbuf/intern/cineon makesdna python radiosity readblenfile render src yafray) +SUBDIRS(avi nodes blenkernel blenlib blenloader blenpluginapi imbuf imbuf/intern/cineon gpu makesdna python radiosity readblenfile render src yafray) IF(WITH_INTERNATIONAL) SUBDIRS(ftfont) diff --git a/source/blender/Makefile b/source/blender/Makefile index 937512f34bd..52abd2cdddb 100644 --- a/source/blender/Makefile +++ b/source/blender/Makefile @@ -33,7 +33,7 @@ include nan_definitions.mk DIRS = blenloader readblenfile DIRS += avi imbuf render radiosity blenlib blenkernel blenpluginapi DIRS += makesdna src yafray -DIRS += python nodes +DIRS += python nodes gpu ifeq ($(WITH_FREETYPE2), true) DIRS += ftfont diff --git a/source/blender/SConscript b/source/blender/SConscript index 56a661238f8..25745c0e51a 100644 --- a/source/blender/SConscript +++ b/source/blender/SConscript @@ -7,6 +7,7 @@ SConscript(['avi/SConscript', 'blenlib/SConscript', 'blenloader/SConscript', 'blenpluginapi/SConscript', + 'gpu/SConscript', 'imbuf/SConscript', 'imbuf/intern/cineon/SConscript', 'makesdna/SConscript', diff --git a/source/blender/blenkernel/BKE_DerivedMesh.h b/source/blender/blenkernel/BKE_DerivedMesh.h index 7dc10c53e22..171a73f72c4 100644 --- a/source/blender/blenkernel/BKE_DerivedMesh.h +++ b/source/blender/blenkernel/BKE_DerivedMesh.h @@ -55,6 +55,7 @@ struct EditMesh; struct ModifierData; struct MCol; struct ColorBand; +struct GPUVertexAttribs; /* number of sub-elements each mesh element has (for interpolation) */ #define SUB_ELEMS_VERT 0 @@ -198,7 +199,8 @@ struct DerivedMesh { * * Also called for *final* editmode DerivedMeshes */ - void (*drawFacesSolid)(DerivedMesh *dm, int (*setMaterial)(int)); + void (*drawFacesSolid)(DerivedMesh *dm, + int (*setMaterial)(int, void *attribs)); /* Draw all faces * o If useTwoSided, draw front and back using col arrays @@ -215,6 +217,13 @@ struct DerivedMesh { int (*setDrawOptions)(struct MTFace *tface, struct MCol *mcol, int matnr)); + /* Draw all faces with GLSL materials + * o setMaterial is called for every different material nr + * o Only if setMaterial returns true + */ + void (*drawFacesGLSL)(DerivedMesh *dm, + int (*setMaterial)(int, void *attribs)); + /* Draw mapped faces (no color, or texture) * o Only if !setDrawOptions or * setDrawOptions(userData, mapped-face-index, drawSmooth_r) @@ -241,6 +250,15 @@ struct DerivedMesh { int index), void *userData); + /* Draw mapped faces with GLSL materials + * o setMaterial is called for every different material nr + * o setDrawOptions is called for every face + * o Only if setMaterial and setDrawOptions return true + */ + void (*drawMappedFacesGLSL)(DerivedMesh *dm, + int (*setMaterial)(int, void *attribs), + int (*setDrawOptions)(void *userData, int index), void *userData); + /* Draw mapped edges as lines * o Only if !setDrawOptions or setDrawOptions(userData, mapped-edge) * returns true @@ -437,6 +455,35 @@ void weight_to_rgb(float input, float *fr, float *fg, float *fb); /* determines required DerivedMesh data according to view and edit modes */ CustomDataMask get_viewedit_datamask(); +/* convert layers requested by a GLSL material to actually available layers in + * the DerivedMesh, with both a pointer for arrays and an offset for editmesh */ +typedef struct DMVertexAttribs { + struct { + struct MTFace *array; + int emOffset, glIndex; + } tface[MAX_MTFACE]; + + struct { + struct MCol *array; + int emOffset, glIndex; + } mcol[MAX_MCOL]; + + struct { + float (*array)[3]; + int emOffset, glIndex; + } tang; + + struct { + float (*array)[3]; + int emOffset, glIndex; + } orco; + + int tottface, totmcol, tottang, totorco; +} DMVertexAttribs; + +void DM_vertex_attributes_from_gpu(DerivedMesh *dm, + struct GPUVertexAttribs *gattribs, DMVertexAttribs *attribs); + void DM_add_tangent_layer(DerivedMesh *dm); #endif diff --git a/source/blender/blenkernel/BKE_bad_level_calls.h b/source/blender/blenkernel/BKE_bad_level_calls.h index 3e45749c26a..8dee9a27f49 100644 --- a/source/blender/blenkernel/BKE_bad_level_calls.h +++ b/source/blender/blenkernel/BKE_bad_level_calls.h @@ -115,10 +115,6 @@ void free_editArmature(void); void docenter_new(void); int saveover(char *str); -/* image.c */ -#include "DNA_image_types.h" -void free_realtime_image(Image *ima); // has to become a callback, opengl stuff - /* ipo.c */ void copy_view3d_lock(short val); // was a hack, to make scene layer ipo's possible diff --git a/source/blender/blenkernel/BKE_colortools.h b/source/blender/blenkernel/BKE_colortools.h index e78882220a9..555b467b1d6 100644 --- a/source/blender/blenkernel/BKE_colortools.h +++ b/source/blender/blenkernel/BKE_colortools.h @@ -57,6 +57,7 @@ void curvemapping_do_ibuf(struct CurveMapping *cumap, struct ImBuf *ibuf); void curvemapping_premultiply(struct CurveMapping *cumap, int restore); int curvemapping_RGBA_does_something(struct CurveMapping *cumap); void curvemapping_initialize(struct CurveMapping *cumap); +void curvemapping_table_RGBA(struct CurveMapping *cumap, float **array, int *size); #endif diff --git a/source/blender/blenkernel/BKE_global.h b/source/blender/blenkernel/BKE_global.h index 8c9634cba06..1cc336db69e 100644 --- a/source/blender/blenkernel/BKE_global.h +++ b/source/blender/blenkernel/BKE_global.h @@ -218,8 +218,15 @@ typedef struct Global { #define G_FILE_NO_UI (1 << 10) #define G_FILE_GAME_TO_IPO (1 << 11) #define G_FILE_GAME_MAT (1 << 12) -#define G_FILE_DIAPLAY_LISTS (1 << 13) +#define G_FILE_DISPLAY_LISTS (1 << 13) #define G_FILE_SHOW_PHYSICS (1 << 14) +#define G_FILE_GAME_MAT_GLSL (1 << 15) +#define G_FILE_GLSL_NO_LIGHTS (1 << 16) +#define G_FILE_GLSL_NO_SHADERS (1 << 17) +#define G_FILE_GLSL_NO_SHADOWS (1 << 18) +#define G_FILE_GLSL_NO_RAMPS (1 << 19) +#define G_FILE_GLSL_NO_NODES (1 << 20) +#define G_FILE_GLSL_NO_EXTRA_TEX (1 << 21) /* G.windowstate */ #define G_WINDOWSTATE_USERDEF 0 diff --git a/source/blender/blenkernel/BKE_mesh.h b/source/blender/blenkernel/BKE_mesh.h index d4ae76e8984..2ca4b3aa39a 100644 --- a/source/blender/blenkernel/BKE_mesh.h +++ b/source/blender/blenkernel/BKE_mesh.h @@ -68,7 +68,6 @@ void mball_to_mesh(struct ListBase *lb, struct Mesh *me); void nurbs_to_mesh(struct Object *ob); void free_dverts(struct MDeformVert *dvert, int totvert); void copy_dverts(struct MDeformVert *dst, struct MDeformVert *src, int totvert); /* __NLA */ -int update_realtime_texture(struct MTFace *tface, double time); void mesh_delete_material_index(struct Mesh *me, int index); void mesh_set_smooth_flag(struct Object *meshOb, int enableSmooth); diff --git a/source/blender/blenkernel/BKE_node.h b/source/blender/blenkernel/BKE_node.h index b3b68a9b3ff..01c54663c6d 100644 --- a/source/blender/blenkernel/BKE_node.h +++ b/source/blender/blenkernel/BKE_node.h @@ -47,6 +47,9 @@ struct rctf; struct ListBase; struct RenderData; struct Scene; +struct GPUMaterial; +struct GPUNode; +struct GPUNodeStack; #define SOCK_IN 1 #define SOCK_OUT 2 @@ -91,6 +94,9 @@ typedef struct bNodeType { void *pynode; /* holds pointer to python script */ void *pydict; /* holds pointer to python script dictionary (scope)*/ + /* gpu */ + int (*gpufunc)(struct GPUMaterial *mat, struct bNode *node, struct GPUNodeStack *in, struct GPUNodeStack *out); + } bNodeType; /* node->exec, now in use for composites (#define for break is same as ready yes) */ @@ -252,6 +258,8 @@ void nodeShaderSynchronizeID(struct bNode *node, int copyto); extern void (*node_shader_lamp_loop)(struct ShadeInput *, struct ShadeResult *); void set_node_shader_lamp_loop(void (*lamp_loop_func)(struct ShadeInput *, struct ShadeResult *)); +void ntreeGPUMaterialNodes(struct bNodeTree *ntree, struct GPUMaterial *mat); + /* ************** COMPOSITE NODES *************** */ diff --git a/source/blender/blenkernel/BKE_texture.h b/source/blender/blenkernel/BKE_texture.h index c162a04e055..cfcae3c44bc 100644 --- a/source/blender/blenkernel/BKE_texture.h +++ b/source/blender/blenkernel/BKE_texture.h @@ -53,6 +53,7 @@ void free_plugin_tex(struct PluginTex *pit); void init_colorband(struct ColorBand *coba, int rangetype); struct ColorBand *add_colorband(int rangetype); int do_colorband(struct ColorBand *coba, float in, float out[4]); +void colorband_table_RGBA(struct ColorBand *coba, float **array, int *size); void default_tex(struct Tex *tex); struct Tex *add_texture(char *name); diff --git a/source/blender/blenkernel/BKE_utildefines.h b/source/blender/blenkernel/BKE_utildefines.h index f389521ffa0..d647a74c6e2 100644 --- a/source/blender/blenkernel/BKE_utildefines.h +++ b/source/blender/blenkernel/BKE_utildefines.h @@ -55,6 +55,8 @@ #define ELEM7(a, b, c, d, e, f, g, h) ( ELEM3(a, b, c, d) || ELEM4(a, e, f, g, h) ) #define ELEM8(a, b, c, d, e, f, g, h, i) ( ELEM4(a, b, c, d, e) || ELEM4(a, f, g, h, i) ) #define ELEM9(a, b, c, d, e, f, g, h, i, j) ( ELEM4(a, b, c, d, e) || ELEM5(a, f, g, h, i, j) ) +#define ELEM10(a, b, c, d, e, f, g, h, i, j, k) ( ELEM4(a, b, c, d, e) || ELEM6(a, f, g, h, i, j, k) ) +#define ELEM11(a, b, c, d, e, f, g, h, i, j, k, l) ( ELEM4(a, b, c, d, e) || ELEM7(a, f, g, h, i, j, k, l) ) /* shift around elements */ #define SHIFT3(type, a, b, c) { type tmp; tmp = a; a = c; c = b; b = tmp; } diff --git a/source/blender/blenkernel/CMakeLists.txt b/source/blender/blenkernel/CMakeLists.txt index 9088b410e27..0345711c9c3 100644 --- a/source/blender/blenkernel/CMakeLists.txt +++ b/source/blender/blenkernel/CMakeLists.txt @@ -32,7 +32,7 @@ SET(INC ../imbuf ../avi ../../../intern/elbeem/extern ../../../intern/opennl/extern ../../../intern/iksolver/extern ../blenloader ../quicktime ../../../intern/bmfont ../../../extern/bullet2/src - ../nodes + ../nodes ../../../extern/glew/include ../gpu ${SDL_INC} ${ZLIB_INC} ${PYTHON_INC} diff --git a/source/blender/blenkernel/SConscript b/source/blender/blenkernel/SConscript index 1bb98239a68..db67251f44e 100644 --- a/source/blender/blenkernel/SConscript +++ b/source/blender/blenkernel/SConscript @@ -10,6 +10,7 @@ incs += ' #/intern/iksolver/extern ../blenloader ../quicktime' incs += ' #/extern/bullet2/src' incs += ' #/intern/bmfont' incs += ' #/intern/opennl/extern' +incs += ' ../gpu #/extern/glew/include' incs += ' ' + env['BF_PYTHON_INC'] incs += ' ' + env['BF_OPENGL_INC'] diff --git a/source/blender/blenkernel/bad_level_call_stubs/stubs.c b/source/blender/blenkernel/bad_level_call_stubs/stubs.c index 561d8d7c2a6..4b6cb5e0999 100644 --- a/source/blender/blenkernel/bad_level_call_stubs/stubs.c +++ b/source/blender/blenkernel/bad_level_call_stubs/stubs.c @@ -176,10 +176,6 @@ void free_editMesh(struct EditMesh *em){} void docenter_new(void){} int saveover(char *str){ return 0;} -/* image.c */ -#include "DNA_image_types.h" -void free_realtime_image(Image *ima){} // has to become a callback, opengl stuff - /* ipo.c */ void copy_view3d_lock(short val){} // was a hack, to make scene layer ipo's possible diff --git a/source/blender/blenkernel/intern/DerivedMesh.c b/source/blender/blenkernel/intern/DerivedMesh.c index 1dabab98a6e..328dcada01a 100644 --- a/source/blender/blenkernel/intern/DerivedMesh.c +++ b/source/blender/blenkernel/intern/DerivedMesh.c @@ -88,6 +88,10 @@ #include "BIF_gl.h" #include "BIF_glutil.h" +#include "GPU_draw.h" +#include "GPU_extensions.h" +#include "GPU_material.h" + // headers for fluidsim bobj meshes #include #include "LBM_fluidsim.h" @@ -411,6 +415,8 @@ void DM_swap_face_data(DerivedMesh *dm, int index, int *corner_indices) CustomData_swap(&dm->faceData, index, corner_indices); } +/// + static DerivedMesh *getMeshDerivedMesh(Mesh *me, Object *ob, float (*vertCos)[3]) { DerivedMesh *dm = CDDM_from_mesh(me, ob); @@ -894,6 +900,162 @@ static void emDM_drawMappedFacesTex(DerivedMesh *dm, int (*setDrawOptions)(void emDM_drawFacesTex_common(dm, NULL, setDrawOptions, userData); } +static void emDM_drawMappedFacesGLSL(DerivedMesh *dm, + int (*setMaterial)(int, void *attribs), + int (*setDrawOptions)(void *userData, int index), void *userData) +{ + EditMeshDerivedMesh *emdm= (EditMeshDerivedMesh*) dm; + EditMesh *em= emdm->em; + float (*vertexCos)[3]= emdm->vertexCos; + float (*vertexNos)[3]= emdm->vertexNos; + EditVert *eve; + EditFace *efa; + DMVertexAttribs attribs; + GPUVertexAttribs gattribs; + MTFace *tf; + int transp, new_transp, orig_transp, tfoffset; + int i, b, matnr, new_matnr, dodraw, layer; + + dodraw = 0; + matnr = -1; + + transp = GPU_get_material_blend_mode(); + orig_transp = transp; + layer = CustomData_get_layer_index(&em->fdata, CD_MTFACE); + tfoffset = (layer == -1)? -1: em->fdata.layers[layer].offset; + + memset(&attribs, 0, sizeof(attribs)); + + /* always use smooth shading even for flat faces, else vertex colors wont interpolate */ + glShadeModel(GL_SMOOTH); + + for (i=0,eve=em->verts.first; eve; eve= eve->next) + eve->tmp.l = (long) i++; + +#define PASSATTRIB(efa, eve, vert) { \ + if(attribs.totorco) { \ + float *orco = attribs.orco.array[eve->tmp.l]; \ + glVertexAttrib3fvARB(attribs.orco.glIndex, orco); \ + } \ + for(b = 0; b < attribs.tottface; b++) { \ + MTFace *tf = (MTFace*)((char*)efa->data + attribs.tface[b].emOffset); \ + glVertexAttrib2fvARB(attribs.tface[b].glIndex, tf->uv[vert]); \ + } \ + for(b = 0; b < attribs.totmcol; b++) { \ + MCol *cp = (MCol*)((char*)efa->data + attribs.mcol[b].emOffset); \ + GLubyte col[4]; \ + col[0]= cp->b; col[1]= cp->g; col[2]= cp->r; col[3]= cp->a; \ + glVertexAttrib4ubvARB(attribs.mcol[b].glIndex, col); \ + } \ + if(attribs.tottang) { \ + float *tang = attribs.tang.array[i*4 + vert]; \ + glVertexAttrib3fvARB(attribs.tang.glIndex, tang); \ + } \ +} + + for (i=0,efa= em->faces.first; efa; i++,efa= efa->next) { + int drawSmooth= (efa->flag & ME_SMOOTH); + + if(setDrawOptions && !setDrawOptions(userData, i)) + continue; + + new_matnr = efa->mat_nr + 1; + if(new_matnr != matnr) { + dodraw = setMaterial(matnr = new_matnr, &gattribs); + if(dodraw) + DM_vertex_attributes_from_gpu(dm, &gattribs, &attribs); + } + + if(tfoffset != -1) { + tf = (MTFace*)((char*)efa->data)+tfoffset; + new_transp = tf->transp; + + if(new_transp != transp) { + if(new_transp == GPU_BLEND_SOLID && orig_transp != GPU_BLEND_SOLID) + GPU_set_material_blend_mode(orig_transp); + else + GPU_set_material_blend_mode(new_transp); + transp = new_transp; + } + } + + if(dodraw) { + glBegin(efa->v4?GL_QUADS:GL_TRIANGLES); + if (!drawSmooth) { + if(vertexCos) glNormal3fv(emdm->faceNos[i]); + else glNormal3fv(efa->n); + + PASSATTRIB(efa, efa->v1, 0); + if(vertexCos) glVertex3fv(vertexCos[(int) efa->v1->tmp.l]); + else glVertex3fv(efa->v1->co); + + PASSATTRIB(efa, efa->v2, 1); + if(vertexCos) glVertex3fv(vertexCos[(int) efa->v2->tmp.l]); + else glVertex3fv(efa->v2->co); + + PASSATTRIB(efa, efa->v3, 2); + if(vertexCos) glVertex3fv(vertexCos[(int) efa->v3->tmp.l]); + else glVertex3fv(efa->v3->co); + + if(efa->v4) { + PASSATTRIB(efa, efa->v4, 3); + if(vertexCos) glVertex3fv(vertexCos[(int) efa->v4->tmp.l]); + else glVertex3fv(efa->v4->co); + } + } else { + PASSATTRIB(efa, efa->v1, 0); + if(vertexCos) { + glNormal3fv(vertexNos[(int) efa->v1->tmp.l]); + glVertex3fv(vertexCos[(int) efa->v1->tmp.l]); + } + else { + glNormal3fv(efa->v1->no); + glVertex3fv(efa->v1->co); + } + + PASSATTRIB(efa, efa->v2, 1); + if(vertexCos) { + glNormal3fv(vertexNos[(int) efa->v2->tmp.l]); + glVertex3fv(vertexCos[(int) efa->v2->tmp.l]); + } + else { + glNormal3fv(efa->v2->no); + glVertex3fv(efa->v2->co); + } + + PASSATTRIB(efa, efa->v3, 2); + if(vertexCos) { + glNormal3fv(vertexNos[(int) efa->v3->tmp.l]); + glVertex3fv(vertexCos[(int) efa->v3->tmp.l]); + } + else { + glNormal3fv(efa->v3->no); + glVertex3fv(efa->v3->co); + } + + if(efa->v4) { + PASSATTRIB(efa, efa->v4, 3); + if(vertexCos) { + glNormal3fv(vertexNos[(int) efa->v4->tmp.l]); + glVertex3fv(vertexCos[(int) efa->v4->tmp.l]); + } + else { + glNormal3fv(efa->v4->no); + glVertex3fv(efa->v4->co); + } + } + } + glEnd(); + } + } +} + +static void emDM_drawFacesGLSL(DerivedMesh *dm, + int (*setMaterial)(int, void *attribs)) +{ + dm->drawMappedFacesGLSL(dm, setMaterial, NULL, NULL); +} + static void emDM_getMinMax(DerivedMesh *dm, float min_r[3], float max_r[3]) { EditMeshDerivedMesh *emdm= (EditMeshDerivedMesh*) dm; @@ -1099,6 +1261,43 @@ void emDM_copyFaceArray(DerivedMesh *dm, MFace *face_r) } } +static void *emDM_getFaceDataArray(DerivedMesh *dm, int type) +{ + EditMeshDerivedMesh *emdm= (EditMeshDerivedMesh*) dm; + EditMesh *em= emdm->em; + EditFace *efa; + char *data, *emdata; + void *datalayer; + int index, offset, size; + + datalayer = DM_get_face_data_layer(dm, type); + if(datalayer) + return datalayer; + + /* layers are store per face for editmesh, we convert to a temporary + * data layer array in the derivedmesh when these are requested */ + if(type == CD_MTFACE || type == CD_MCOL) { + index = CustomData_get_layer_index(&em->fdata, type); + + if(index != -1) { + offset = em->fdata.layers[index].offset; + size = CustomData_sizeof(type); + + DM_add_face_layer(dm, type, CD_CALLOC, NULL); + index = CustomData_get_layer_index(&dm->faceData, type); + dm->faceData.layers[index].flag |= CD_FLAG_TEMPORARY; + + data = datalayer = DM_get_face_data_layer(dm, type); + for(efa=em->faces.first; efa; efa=efa->next, data+=size) { + emdata = CustomData_em_get(&em->fdata, efa->data, type); + memcpy(data, emdata, size); + } + } + } + + return datalayer; +} + static void emDM_release(DerivedMesh *dm) { EditMeshDerivedMesh *emdm= (EditMeshDerivedMesh*) dm; @@ -1134,6 +1333,7 @@ static DerivedMesh *getEditMeshDerivedMesh(EditMesh *em, Object *ob, emdm->dm.copyVertArray = emDM_copyVertArray; emdm->dm.copyEdgeArray = emDM_copyEdgeArray; emdm->dm.copyFaceArray = emDM_copyFaceArray; + emdm->dm.getFaceDataArray = emDM_getFaceDataArray; emdm->dm.foreachMappedVert = emDM_foreachMappedVert; emdm->dm.foreachMappedEdge = emDM_foreachMappedEdge; @@ -1144,7 +1344,9 @@ static DerivedMesh *getEditMeshDerivedMesh(EditMesh *em, Object *ob, emdm->dm.drawMappedEdgesInterp = emDM_drawMappedEdgesInterp; emdm->dm.drawMappedFaces = emDM_drawMappedFaces; emdm->dm.drawMappedFacesTex = emDM_drawMappedFacesTex; + emdm->dm.drawMappedFacesGLSL = emDM_drawMappedFacesGLSL; emdm->dm.drawFacesTex = emDM_drawFacesTex; + emdm->dm.drawFacesGLSL = emDM_drawFacesGLSL; emdm->dm.drawUVEdges = emDM_drawUVEdges; emdm->dm.release = emDM_release; @@ -1574,7 +1776,7 @@ static void vDM_drawUVEdges(DerivedMesh *dm) } /* draw all VerseFaces */ -static void vDM_drawFacesSolid(DerivedMesh *dm, int (*setMaterial)(int)) +static void vDM_drawFacesSolid(DerivedMesh *dm, int (*setMaterial)(int, void *attribs)) { VDerivedMesh *vdm = (VDerivedMesh*)dm; struct VerseFace *vface; @@ -1674,6 +1876,8 @@ static void vDM_drawMappedFacesTex( int (*setDrawParams)(void *userData, int index), void *userData) { + /* not supported yet */ + vDM_drawFacesTex(dm, NULL); } /**/ @@ -1815,19 +2019,23 @@ CustomDataMask get_viewedit_datamask() ScrArea *sa; /* check if we need tfaces & mcols due to face select or texture paint */ - if(FACESEL_PAINT_TEST || G.f & G_TEXTUREPAINT) { + if(FACESEL_PAINT_TEST || G.f & G_TEXTUREPAINT) mask |= CD_MASK_MTFACE | CD_MASK_MCOL; - } else { - /* check if we need tfaces & mcols due to view mode */ - for(sa = G.curscreen->areabase.first; sa; sa = sa->next) { - if(sa->spacetype == SPACE_VIEW3D) { - View3D *view = sa->spacedata.first; - if(view->drawtype == OB_SHADED) { - /* this includes normals for mesh_create_shadedColors */ - mask |= CD_MASK_MTFACE | CD_MASK_MCOL | CD_MASK_NORMAL | CD_MASK_ORCO; - } - if((view->drawtype == OB_TEXTURE) || ((view->drawtype == OB_SOLID) && (view->flag2 & V3D_SOLID_TEX))) { - mask |= CD_MASK_MTFACE | CD_MASK_MCOL; + + /* check if we need tfaces & mcols due to view mode */ + for(sa = G.curscreen->areabase.first; sa; sa = sa->next) { + if(sa->spacetype == SPACE_VIEW3D) { + View3D *view = sa->spacedata.first; + if(view->drawtype == OB_SHADED) { + /* this includes normals for mesh_create_shadedColors */ + mask |= CD_MASK_MTFACE | CD_MASK_MCOL | CD_MASK_NORMAL | CD_MASK_ORCO; + } + if((view->drawtype == OB_TEXTURE) || ((view->drawtype == OB_SOLID) && (view->flag2 & V3D_SOLID_TEX))) { + mask |= CD_MASK_MTFACE | CD_MASK_MCOL; + + if((G.fileflags & G_FILE_GAME_MAT) && + (G.fileflags & G_FILE_GAME_MAT_GLSL)) { + mask |= CD_MASK_ORCO; } } } @@ -1840,13 +2048,41 @@ CustomDataMask get_viewedit_datamask() return mask; } -static DerivedMesh *create_orco_dm(Object *ob, Mesh *me) +static float *get_editmesh_orco_verts(EditMesh *em) +{ + EditVert *eve; + float *orco; + int a, totvert; + + /* these may not really be the orco's, but it's only for preview. + * could be solver better once, but isn't simple */ + + totvert= 0; + for(eve=em->verts.first; eve; eve=eve->next) + totvert++; + + orco = MEM_mallocN(sizeof(float)*3*totvert, "EditMesh Orco"); + + for(a=0, eve=em->verts.first; eve; eve=eve->next, a+=3) + VECCOPY(orco+a, eve->co); + + return orco; +} + +static DerivedMesh *create_orco_dm(Object *ob, Mesh *me, EditMesh *em) { DerivedMesh *dm; float (*orco)[3]; - dm= CDDM_from_mesh(me, ob); - orco= (float(*)[3])get_mesh_orco_verts(ob); + if(em) { + dm= CDDM_from_editmesh(em, me); + orco= (float(*)[3])get_editmesh_orco_verts(em); + } + else { + dm= CDDM_from_mesh(me, ob); + orco= (float(*)[3])get_mesh_orco_verts(ob); + } + CDDM_apply_vert_coords(dm, orco); CDDM_calc_normals(dm); MEM_freeN(orco); @@ -1854,7 +2090,7 @@ static DerivedMesh *create_orco_dm(Object *ob, Mesh *me) return dm; } -static void add_orco_dm(Object *ob, DerivedMesh *dm, DerivedMesh *orcodm) +static void add_orco_dm(Object *ob, EditMesh *em, DerivedMesh *dm, DerivedMesh *orcodm) { float (*orco)[3], (*layerorco)[3]; int totvert; @@ -1869,8 +2105,10 @@ static void add_orco_dm(Object *ob, DerivedMesh *dm, DerivedMesh *orcodm) else dm->getVertCos(dm, orco); } - else - orco= (float(*)[3])get_mesh_orco_verts(ob); + else { + if(em) orco= (float(*)[3])get_editmesh_orco_verts(em); + else orco= (float(*)[3])get_mesh_orco_verts(ob); + } transform_mesh_orco_verts(ob->data, orco, totvert, 0); @@ -2016,7 +2254,7 @@ static void mesh_calc_modifiers(Object *ob, float (*inputVertexCos)[3], if(dm && mti->requiredDataMask) { mask = mti->requiredDataMask(md); if(mask & CD_MASK_ORCO) - add_orco_dm(ob, dm, orcodm); + add_orco_dm(ob, NULL, dm, orcodm); } /* How to apply modifier depends on (a) what we already have as @@ -2069,7 +2307,7 @@ static void mesh_calc_modifiers(Object *ob, float (*inputVertexCos)[3], mask= (CustomDataMask)curr->link; if(mask & CD_MASK_ORCO) { if(!orcodm) - orcodm= create_orco_dm(ob, me); + orcodm= create_orco_dm(ob, me, NULL); mask &= ~CD_MASK_ORCO; DM_set_only_copy(orcodm, mask); @@ -2146,10 +2384,10 @@ static void mesh_calc_modifiers(Object *ob, float (*inputVertexCos)[3], /* add an orco layer if needed */ if(dataMask & CD_MASK_ORCO) { - add_orco_dm(ob, finaldm, orcodm); + add_orco_dm(ob, NULL, finaldm, orcodm); if(deform_r && *deform_r) - add_orco_dm(ob, *deform_r, NULL); + add_orco_dm(ob, NULL, *deform_r, NULL); } *final_r = finaldm; @@ -2205,7 +2443,8 @@ static void editmesh_calc_modifiers(DerivedMesh **cage_r, EditMesh *em = G.editMesh; ModifierData *md; float (*deformedVerts)[3] = NULL; - DerivedMesh *dm; + CustomDataMask mask; + DerivedMesh *dm, *orcodm = NULL; int i, numVerts = 0, cageIndex = modifiers_getCageIndex(ob, NULL); LinkNode *datamasks, *curr; @@ -2230,6 +2469,13 @@ static void editmesh_calc_modifiers(DerivedMesh **cage_r, if(!editmesh_modifier_is_enabled(md, dm)) continue; + /* add an orco layer if needed by this modifier */ + if(dm && mti->requiredDataMask) { + mask = mti->requiredDataMask(md); + if(mask & CD_MASK_ORCO) + add_orco_dm(ob, em, dm, orcodm); + } + /* How to apply modifier depends on (a) what we already have as * a result of previous modifiers (could be a DerivedMesh or just * deformed vertices) and (b) what type the modifier is. @@ -2280,6 +2526,23 @@ static void editmesh_calc_modifiers(DerivedMesh **cage_r, } } + /* create an orco derivedmesh in parallel */ + mask= (CustomDataMask)curr->link; + if(mask & CD_MASK_ORCO) { + if(!orcodm) + orcodm= create_orco_dm(ob, ob->data, em); + + mask &= ~CD_MASK_ORCO; + DM_set_only_copy(orcodm, mask); + ndm = mti->applyModifierEM(md, ob, em, orcodm); + + if(ndm) { + /* if the modifier returned a new dm, release the old one */ + if(orcodm && orcodm != ndm) orcodm->release(orcodm); + orcodm = ndm; + } + } + /* set the DerivedMesh to only copy needed data */ DM_set_only_copy(dm, (CustomDataMask)curr->link); @@ -2338,6 +2601,13 @@ static void editmesh_calc_modifiers(DerivedMesh **cage_r, deformedVerts = NULL; } + /* add an orco layer if needed */ + if(dataMask & CD_MASK_ORCO) + add_orco_dm(ob, em, *final_r, orcodm); + + if(orcodm) + orcodm->release(orcodm); + if(deformedVerts) MEM_freeN(deformedVerts); } @@ -2632,7 +2902,7 @@ void multires_render_final(Object *ob, Mesh *me, DerivedMesh **dm, float *vert_c old->release(old); if(dataMask & CD_MASK_ORCO) - add_orco_dm(ob, *dm, NULL); + add_orco_dm(ob, NULL, *dm, NULL); /* Restore the original verts */ me->mr->newlvl= BLI_countlist(&me->mr->levels); @@ -2847,6 +3117,8 @@ int editmesh_get_first_deform_matrices(float (**deformmats)[3][3], float (**defo return numleft; } +/* ******************* GLSL ******************** */ + void DM_add_tangent_layer(DerivedMesh *dm) { /* mesh vars */ @@ -2967,6 +3239,91 @@ void DM_add_tangent_layer(DerivedMesh *dm) MEM_freeN(vtangents); } +void DM_vertex_attributes_from_gpu(DerivedMesh *dm, GPUVertexAttribs *gattribs, DMVertexAttribs *attribs) +{ + CustomData *vdata, *fdata, *tfdata = NULL; + int a, b, layer; + + /* From the layers requested by the GLSL shader, figure out which ones are + * actually available for this derivedmesh, and retrieve the pointers */ + + memset(attribs, 0, sizeof(DMVertexAttribs)); + + vdata = &dm->vertData; + fdata = &dm->faceData; + + /* ugly hack, editmesh derivedmesh doesn't copy face data, this way we + * can use offsets instead */ + if(dm->release == emDM_release) + tfdata = &((EditMeshDerivedMesh*)dm)->em->fdata; + else + tfdata = fdata; + + /* add a tangent layer if necessary */ + for(b = 0; b < gattribs->totlayer; b++) + if(gattribs->layer[b].type == CD_TANGENT) + if(CustomData_get_layer_index(fdata, CD_TANGENT) == -1) + DM_add_tangent_layer(dm); + + for(b = 0; b < gattribs->totlayer; b++) { + if(gattribs->layer[b].type == CD_MTFACE) { + /* uv coordinates */ + if(gattribs->layer[b].name[0]) + layer = CustomData_get_named_layer_index(tfdata, CD_MTFACE, + gattribs->layer[b].name); + else + layer = CustomData_get_active_layer_index(tfdata, CD_MTFACE); + + if(layer != -1) { + a = attribs->tottface++; + + attribs->tface[a].array = tfdata->layers[layer].data; + attribs->tface[a].emOffset = tfdata->layers[layer].offset; + attribs->tface[a].glIndex = gattribs->layer[b].glindex; + } + } + else if(gattribs->layer[b].type == CD_MCOL) { + /* vertex colors */ + if(gattribs->layer[b].name[0]) + layer = CustomData_get_named_layer_index(tfdata, CD_MCOL, + gattribs->layer[b].name); + else + layer = CustomData_get_active_layer_index(tfdata, CD_MCOL); + + if(layer != -1) { + a = attribs->totmcol++; + + attribs->mcol[a].array = tfdata->layers[layer].data; + attribs->mcol[a].emOffset = tfdata->layers[layer].offset; + attribs->mcol[a].glIndex = gattribs->layer[b].glindex; + } + } + else if(gattribs->layer[b].type == CD_TANGENT) { + /* tangents */ + layer = CustomData_get_layer_index(fdata, CD_TANGENT); + + if(layer != -1) { + attribs->tottang = 1; + + attribs->tang.array = fdata->layers[layer].data; + attribs->tang.emOffset = fdata->layers[layer].offset; + attribs->tang.glIndex = gattribs->layer[b].glindex; + } + } + else if(gattribs->layer[b].type == CD_ORCO) { + /* original coordinates */ + layer = CustomData_get_layer_index(vdata, CD_ORCO); + + if(layer != -1) { + attribs->totorco = 1; + + attribs->orco.array = vdata->layers[layer].data; + attribs->orco.emOffset = vdata->layers[layer].offset; + attribs->orco.glIndex = gattribs->layer[b].glindex; + } + } + } +} /* ************************* fluidsim bobj file handling **************************** */ diff --git a/source/blender/blenkernel/intern/Makefile b/source/blender/blenkernel/intern/Makefile index 74c6c551a83..8921ea5d3b7 100644 --- a/source/blender/blenkernel/intern/Makefile +++ b/source/blender/blenkernel/intern/Makefile @@ -36,6 +36,7 @@ include nan_compile.mk CFLAGS += $(LEVEL_1_C_WARNINGS) # OpenGL and Python +CPPFLAGS += -I$(NAN_GLEW)/include CPPFLAGS += -I$(OPENGL_HEADERS) CPPFLAGS += -I$(NAN_PYTHON)/include/python$(NAN_PYTHON_VERSION) @@ -74,6 +75,9 @@ CPPFLAGS += -I$(NAN_ZLIB)/include #path to nodes CPPFLAGS += -I../../nodes +#path to gpu +CPPFLAGS += -I../../gpu + # path to our own external headerfiles CPPFLAGS += -I.. diff --git a/source/blender/blenkernel/intern/action.c b/source/blender/blenkernel/intern/action.c index 5b96bf11056..2648233aca5 100644 --- a/source/blender/blenkernel/intern/action.c +++ b/source/blender/blenkernel/intern/action.c @@ -347,6 +347,8 @@ static void copy_pose_channel_data(bPoseChannel *pchan, const bPoseChannel *chan VECCOPY(pchan->loc, chan->loc); VECCOPY(pchan->size, chan->size); QUATCOPY(pchan->quat, chan->quat); + Mat4CpyMat4(pchan->chan_mat, (float(*)[4])chan->chan_mat); + Mat4CpyMat4(pchan->pose_mat, (float(*)[4])chan->pose_mat); pchan->flag= chan->flag; con= chan->constraints.first; diff --git a/source/blender/blenkernel/intern/anim.c b/source/blender/blenkernel/intern/anim.c index 1592c3e5504..e2ce4b9f6f3 100644 --- a/source/blender/blenkernel/intern/anim.c +++ b/source/blender/blenkernel/intern/anim.c @@ -303,7 +303,7 @@ static void group_duplilist(ListBase *lb, Object *ob, int level, int animated) DupliObject *dob; Group *group; GroupObject *go; - float mat[4][4]; + float mat[4][4], tmat[4][4]; if(ob->dup_group==NULL) return; group= ob->dup_group; @@ -320,7 +320,15 @@ static void group_duplilist(ListBase *lb, Object *ob, int level, int animated) /* note, if you check on layer here, render goes wrong... it still deforms verts and uses parent imat */ if(go->ob!=ob) { - Mat4MulMat4(mat, go->ob->obmat, ob->obmat); + /* Group Dupli Offset, should apply after everything else */ + if (group->dupli_ofs[0] || group->dupli_ofs[1] || group->dupli_ofs[2]) { + Mat4CpyMat4(tmat, go->ob->obmat); + VecSubf(tmat[3], tmat[3], group->dupli_ofs); + Mat4MulMat4(mat, tmat, ob->obmat); + } else { + Mat4MulMat4(mat, go->ob->obmat, ob->obmat); + } + dob= new_dupli_object(lb, go->ob, mat, ob->lay, 0, OB_DUPLIGROUP, animated); dob->no_draw= (dob->origlay & group->layer)==0; @@ -1059,7 +1067,8 @@ static void object_duplilist_recursive(ID *id, Object *ob, ListBase *duplilist, } } -/* note; group dupli's already set transform matrix. see note in group_duplilist() */ +/* Returns a list of DupliObject + * note; group dupli's already set transform matrix. see note in group_duplilist() */ ListBase *object_duplilist(Scene *sce, Object *ob) { ListBase *duplilist= MEM_mallocN(sizeof(ListBase), "duplilist"); diff --git a/source/blender/blenkernel/intern/blender.c b/source/blender/blenkernel/intern/blender.c index aca51e56c6e..1fe6447752e 100644 --- a/source/blender/blenkernel/intern/blender.c +++ b/source/blender/blenkernel/intern/blender.c @@ -525,6 +525,7 @@ typedef struct UndoElem { char str[FILE_MAXDIR+FILE_MAXFILE]; char name[MAXUNDONAME]; MemFile memfile; + uintptr_t undosize; } UndoElem; static ListBase undobase={NULL, NULL}; @@ -555,6 +556,7 @@ static int read_undosave(UndoElem *uel) /* name can be a dynamic string */ void BKE_write_undo(char *name) { + uintptr_t maxmem, totmem, memused; int nr, success; UndoElem *uel; @@ -616,8 +618,36 @@ void BKE_write_undo(char *name) if(curundo->prev) prevfile= &(curundo->prev->memfile); + memused= MEM_get_memory_in_use(); success= BLO_write_file_mem(prevfile, &curundo->memfile, G.fileflags, &err); - + curundo->undosize= MEM_get_memory_in_use() - memused; + } + + if(U.undomemory != 0) { + /* limit to maximum memory (afterwards, we can't know in advance) */ + totmem= 0; + maxmem= ((uintptr_t)U.undomemory)*1024*1024; + + /* keep at least two (original + other) */ + uel= undobase.last; + while(uel && uel->prev) { + totmem+= uel->undosize; + if(totmem>maxmem) break; + uel= uel->prev; + } + + if(uel) { + if(uel->prev && uel->prev->prev) + uel= uel->prev; + + while(undobase.first!=uel) { + UndoElem *first= undobase.first; + BLI_remlink(&undobase, first); + /* the merge is because of compression */ + BLO_merge_memfile(&first->memfile, &first->next->memfile); + MEM_freeN(first); + } + } } } @@ -683,14 +713,14 @@ char *BKE_undo_menu_string(void) UndoElem *uel; DynStr *ds= BLI_dynstr_new(); char *menu; - + BLI_dynstr_append(ds, "Global Undo History %t"); for(uel= undobase.first; uel; uel= uel->next) { BLI_dynstr_append(ds, "|"); BLI_dynstr_append(ds, uel->name); } - + menu= BLI_dynstr_get_cstring(ds); BLI_dynstr_free(ds); diff --git a/source/blender/blenkernel/intern/cdderivedmesh.c b/source/blender/blenkernel/intern/cdderivedmesh.c index 472df3d0f26..9d5dcb8109b 100644 --- a/source/blender/blenkernel/intern/cdderivedmesh.c +++ b/source/blender/blenkernel/intern/cdderivedmesh.c @@ -58,6 +58,10 @@ #include "MEM_guardedalloc.h" +#include "GPU_draw.h" +#include "GPU_extensions.h" +#include "GPU_material.h" + #include #include @@ -243,7 +247,7 @@ static void cdDM_drawLooseEdges(DerivedMesh *dm) glEnd(); } -static void cdDM_drawFacesSolid(DerivedMesh *dm, int (*setMaterial)(int)) +static void cdDM_drawFacesSolid(DerivedMesh *dm, int (*setMaterial)(int, void *attribs)) { CDDerivedMesh *cddm = (CDDerivedMesh*) dm; MVert *mvert = cddm->mvert; @@ -271,7 +275,7 @@ static void cdDM_drawFacesSolid(DerivedMesh *dm, int (*setMaterial)(int)) || new_shademodel != shademodel) { glEnd(); - drawCurrentMat = setMaterial(matnr = new_matnr); + drawCurrentMat = setMaterial(matnr = new_matnr, NULL); glShadeModel(shademodel = new_shademodel); glBegin(glmode = new_glmode); @@ -556,6 +560,134 @@ static void cdDM_drawMappedFacesTex(DerivedMesh *dm, int (*setDrawOptions)(void cdDM_drawFacesTex_common(dm, NULL, setDrawOptions, userData); } +static void cdDM_drawMappedFacesGLSL(DerivedMesh *dm, int (*setMaterial)(int, void *attribs), int (*setDrawOptions)(void *userData, int index), void *userData) +{ + CDDerivedMesh *cddm = (CDDerivedMesh*) dm; + GPUVertexAttribs gattribs; + DMVertexAttribs attribs; + MVert *mvert = cddm->mvert; + MFace *mface = cddm->mface; + MTFace *tf = dm->getFaceDataArray(dm, CD_MTFACE); + float (*nors)[3] = dm->getFaceDataArray(dm, CD_NORMAL); + int a, b, dodraw, smoothnormal, matnr, new_matnr; + int transp, new_transp, orig_transp; + int orig, *index = dm->getFaceDataArray(dm, CD_ORIGINDEX); + + matnr = -1; + smoothnormal = 0; + dodraw = 0; + transp = GPU_get_material_blend_mode(); + orig_transp = transp; + + memset(&attribs, 0, sizeof(attribs)); + + glShadeModel(GL_SMOOTH); + glBegin(GL_QUADS); + + for(a = 0; a < dm->numFaceData; a++, mface++) { + new_matnr = mface->mat_nr + 1; + + if(new_matnr != matnr) { + glEnd(); + + dodraw = setMaterial(matnr = new_matnr, &gattribs); + if(dodraw) + DM_vertex_attributes_from_gpu(dm, &gattribs, &attribs); + + glBegin(GL_QUADS); + } + + if(!dodraw) { + continue; + } + else if(setDrawOptions) { + orig = index[a]; + + if(orig == ORIGINDEX_NONE) + continue; + else if(!setDrawOptions(userData, orig)) + continue; + } + + if(tf) { + new_transp = tf[a].transp; + + if(new_transp != transp) { + glEnd(); + + if(new_transp == GPU_BLEND_SOLID && orig_transp != GPU_BLEND_SOLID) + GPU_set_material_blend_mode(orig_transp); + else + GPU_set_material_blend_mode(new_transp); + transp = new_transp; + + glBegin(GL_QUADS); + } + } + + smoothnormal = (mface->flag & ME_SMOOTH); + + if(!smoothnormal) { + if(nors) { + glNormal3fv(nors[a]); + } + else { + /* TODO ideally a normal layer should always be available */ + float nor[3]; + if(mface->v4) { + CalcNormFloat4(mvert[mface->v1].co, mvert[mface->v2].co, + mvert[mface->v3].co, mvert[mface->v4].co, + nor); + } else { + CalcNormFloat(mvert[mface->v1].co, mvert[mface->v2].co, + mvert[mface->v3].co, nor); + } + glNormal3fv(nor); + } + } + +#define PASSVERT(index, vert) { \ + if(attribs.totorco) \ + glVertexAttrib3fvARB(attribs.orco.glIndex, attribs.orco.array[index]); \ + for(b = 0; b < attribs.tottface; b++) { \ + MTFace *tf = &attribs.tface[b].array[a]; \ + glVertexAttrib2fvARB(attribs.tface[b].glIndex, tf->uv[vert]); \ + } \ + for(b = 0; b < attribs.totmcol; b++) { \ + MCol *cp = &attribs.mcol[b].array[a*4 + vert]; \ + GLubyte col[4]; \ + col[0]= cp->b; col[1]= cp->g; col[2]= cp->r; col[3]= cp->a; \ + glVertexAttrib4ubvARB(attribs.mcol[b].glIndex, col); \ + } \ + if(attribs.tottang) { \ + float *tang = attribs.tang.array[a*4 + vert]; \ + glVertexAttrib3fvARB(attribs.tang.glIndex, tang); \ + } \ + if(smoothnormal) \ + glNormal3sv(mvert[index].no); \ + glVertex3fv(mvert[index].co); \ +} + + PASSVERT(mface->v1, 0); + PASSVERT(mface->v2, 1); + PASSVERT(mface->v3, 2); + if(mface->v4) + PASSVERT(mface->v4, 3) + else + PASSVERT(mface->v3, 2) + +#undef PASSVERT + } + glEnd(); + + glShadeModel(GL_FLAT); +} + +static void cdDM_drawFacesGLSL(DerivedMesh *dm, int (*setMaterial)(int, void *attribs)) +{ + dm->drawMappedFacesGLSL(dm, setMaterial, NULL, NULL); +} + static void cdDM_drawMappedEdges(DerivedMesh *dm, int (*setDrawOptions)(void *userData, int index), void *userData) { CDDerivedMesh *cddm = (CDDerivedMesh*) dm; @@ -713,8 +845,10 @@ static CDDerivedMesh *cdDM_create(const char *desc) dm->drawFacesSolid = cdDM_drawFacesSolid; dm->drawFacesColored = cdDM_drawFacesColored; dm->drawFacesTex = cdDM_drawFacesTex; + dm->drawFacesGLSL = cdDM_drawFacesGLSL; dm->drawMappedFaces = cdDM_drawMappedFaces; dm->drawMappedFacesTex = cdDM_drawMappedFacesTex; + dm->drawMappedFacesGLSL = cdDM_drawMappedFacesGLSL; dm->foreachMappedVert = cdDM_foreachMappedVert; dm->foreachMappedEdge = cdDM_foreachMappedEdge; diff --git a/source/blender/blenkernel/intern/colortools.c b/source/blender/blenkernel/intern/colortools.c index 295b8fe3552..45b8bb7935c 100644 --- a/source/blender/blenkernel/intern/colortools.c +++ b/source/blender/blenkernel/intern/colortools.c @@ -730,3 +730,24 @@ void curvemapping_initialize(CurveMapping *cumap) curvemap_make_table(cumap->cm+a, &cumap->clipr); } } + +void curvemapping_table_RGBA(CurveMapping *cumap, float **array, int *size) +{ + int a; + + *size = CM_TABLE+1; + *array = MEM_callocN(sizeof(float)*(*size)*4, "CurveMapping"); + curvemapping_initialize(cumap); + + for(a=0; a<*size; a++) { + if(cumap->cm[0].table) + (*array)[a*4+0]= cumap->cm[0].table[a].y; + if(cumap->cm[1].table) + (*array)[a*4+1]= cumap->cm[1].table[a].y; + if(cumap->cm[2].table) + (*array)[a*4+2]= cumap->cm[2].table[a].y; + if(cumap->cm[3].table) + (*array)[a*4+3]= cumap->cm[3].table[a].y; + } +} + diff --git a/source/blender/blenkernel/intern/image.c b/source/blender/blenkernel/intern/image.c index 07537e3a81c..27fa00ac239 100644 --- a/source/blender/blenkernel/intern/image.c +++ b/source/blender/blenkernel/intern/image.c @@ -53,6 +53,7 @@ #include "DNA_packedFile_types.h" #include "DNA_scene_types.h" #include "DNA_camera_types.h" +#include "DNA_sequence_types.h" #include "DNA_texture_types.h" #include "DNA_userdef_types.h" @@ -77,15 +78,15 @@ #include "RE_pipeline.h" -/* bad level; call to free_realtime_image */ -#include "BKE_bad_level_calls.h" - /* for stamp drawing to an image */ #include "BMF_Api.h" #include "blendef.h" #include "BSE_time.h" +#include "GPU_extensions.h" +#include "GPU_draw.h" + #include "BLO_sys_types.h" // for intptr_t support /* max int, to indicate we don't store sequences in ibuf */ @@ -240,7 +241,7 @@ static void image_free_buffers(Image *ima) ima->rr= NULL; } - free_realtime_image(ima); + GPU_free_image(ima); ima->ok= IMA_OK; } @@ -620,7 +621,7 @@ void free_old_images() This gives textures a "second chance" to be used before dying. */ if(ima->bindcode || ima->repbind) { - free_realtime_image(ima); + GPU_free_image(ima); ima->lastused = ctime; } /* Otherwise, just kill the buffers */ diff --git a/source/blender/blenkernel/intern/ipo.c b/source/blender/blenkernel/intern/ipo.c index 1a6c8f51d9c..e8a25aaaf80 100644 --- a/source/blender/blenkernel/intern/ipo.c +++ b/source/blender/blenkernel/intern/ipo.c @@ -1390,6 +1390,14 @@ void *get_ipo_poin(ID *id, IpoCurve *icu, int *type) else if(icu->adrcode & MA_MAP8) mtex= ma->mtex[7]; else if(icu->adrcode & MA_MAP9) mtex= ma->mtex[8]; else if(icu->adrcode & MA_MAP10) mtex= ma->mtex[9]; + else if(icu->adrcode & MA_MAP12) mtex= ma->mtex[11]; + else if(icu->adrcode & MA_MAP11) mtex= ma->mtex[10]; + else if(icu->adrcode & MA_MAP13) mtex= ma->mtex[12]; + else if(icu->adrcode & MA_MAP14) mtex= ma->mtex[13]; + else if(icu->adrcode & MA_MAP15) mtex= ma->mtex[14]; + else if(icu->adrcode & MA_MAP16) mtex= ma->mtex[15]; + else if(icu->adrcode & MA_MAP17) mtex= ma->mtex[16]; + else if(icu->adrcode & MA_MAP18) mtex= ma->mtex[17]; if(mtex) { poin= give_mtex_poin(mtex, icu->adrcode & (MA_MAP1-1) ); @@ -1479,7 +1487,14 @@ void *get_ipo_poin(ID *id, IpoCurve *icu, int *type) else if(icu->adrcode & MA_MAP8) mtex= wo->mtex[7]; else if(icu->adrcode & MA_MAP9) mtex= wo->mtex[8]; else if(icu->adrcode & MA_MAP10) mtex= wo->mtex[9]; - + else if(icu->adrcode & MA_MAP11) mtex= wo->mtex[10]; + else if(icu->adrcode & MA_MAP12) mtex= wo->mtex[11]; + else if(icu->adrcode & MA_MAP13) mtex= wo->mtex[12]; + else if(icu->adrcode & MA_MAP14) mtex= wo->mtex[13]; + else if(icu->adrcode & MA_MAP15) mtex= wo->mtex[14]; + else if(icu->adrcode & MA_MAP16) mtex= wo->mtex[15]; + else if(icu->adrcode & MA_MAP17) mtex= wo->mtex[16]; + else if(icu->adrcode & MA_MAP18) mtex= wo->mtex[17]; if(mtex) { poin= give_mtex_poin(mtex, icu->adrcode & (MA_MAP1-1) ); } @@ -1524,6 +1539,14 @@ void *get_ipo_poin(ID *id, IpoCurve *icu, int *type) else if(icu->adrcode & MA_MAP8) mtex= la->mtex[7]; else if(icu->adrcode & MA_MAP9) mtex= la->mtex[8]; else if(icu->adrcode & MA_MAP10) mtex= la->mtex[9]; + else if(icu->adrcode & MA_MAP11) mtex= la->mtex[10]; + else if(icu->adrcode & MA_MAP12) mtex= la->mtex[11]; + else if(icu->adrcode & MA_MAP13) mtex= la->mtex[12]; + else if(icu->adrcode & MA_MAP14) mtex= la->mtex[13]; + else if(icu->adrcode & MA_MAP15) mtex= la->mtex[14]; + else if(icu->adrcode & MA_MAP16) mtex= la->mtex[15]; + else if(icu->adrcode & MA_MAP17) mtex= la->mtex[16]; + else if(icu->adrcode & MA_MAP18) mtex= la->mtex[17]; if(mtex) { poin= give_mtex_poin(mtex, icu->adrcode & (MA_MAP1-1) ); diff --git a/source/blender/blenkernel/intern/material.c b/source/blender/blenkernel/intern/material.c index 3983eecdaba..f05b84f6e90 100644 --- a/source/blender/blenkernel/intern/material.c +++ b/source/blender/blenkernel/intern/material.c @@ -61,6 +61,8 @@ #include "BPY_extern.h" +#include "GPU_material.h" + /* used in UI and render */ Material defmaterial; @@ -96,6 +98,9 @@ void free_material(Material *ma) ntreeFreeTree(ma->nodetree); MEM_freeN(ma->nodetree); } + + if(ma->gpumaterial.first) + GPU_material_free(ma); } void init_material(Material *ma) @@ -207,6 +212,8 @@ Material *copy_material(Material *ma) if(ma->nodetree) { man->nodetree= ntreeCopyTree(ma->nodetree, 0); /* 0 == full new tree */ } + + man->gpumaterial.first= man->gpumaterial.last= NULL; return man; } diff --git a/source/blender/blenkernel/intern/mesh.c b/source/blender/blenkernel/intern/mesh.c index 43e48c3bacd..77b9ea4fa2d 100644 --- a/source/blender/blenkernel/intern/mesh.c +++ b/source/blender/blenkernel/intern/mesh.c @@ -79,45 +79,6 @@ #include "BLI_editVert.h" #include "BLI_arithb.h" -int update_realtime_texture(MTFace *tface, double time) -{ - Image *ima; - int inc = 0; - float diff; - int newframe; - - ima = tface->tpage; - - if (!ima) - return 0; - - if (ima->lastupdate<0) - ima->lastupdate = 0; - - if (ima->lastupdate>time) - ima->lastupdate=(float)time; - - if(ima->tpageflag & IMA_TWINANIM) { - if(ima->twend >= ima->xrep*ima->yrep) ima->twend= ima->xrep*ima->yrep-1; - - /* check: is the bindcode not in the array? Then free. (still to do) */ - - diff = (float)(time-ima->lastupdate); - - inc = (int)(diff*(float)ima->animspeed); - - ima->lastupdate+=((float)inc/(float)ima->animspeed); - - newframe = ima->lastframe+inc; - - if (newframe > (int)ima->twend) - newframe = (int)ima->twsta-1 + (newframe-ima->twend)%(ima->twend-ima->twsta); - - ima->lastframe = newframe; - } - return inc; -} - void mesh_update_customdata_pointers(Mesh *me) { me->mvert = CustomData_get_layer(&me->vdata, CD_MVERT); diff --git a/source/blender/blenkernel/intern/node.c b/source/blender/blenkernel/intern/node.c index 4e36df35a14..4dfe651c01f 100644 --- a/source/blender/blenkernel/intern/node.c +++ b/source/blender/blenkernel/intern/node.c @@ -68,6 +68,9 @@ #include "SHD_node.h" +#include "GPU_extensions.h" +#include "GPU_material.h" + static ListBase empty_list = {NULL, NULL}; ListBase node_all_composit = {NULL, NULL}; ListBase node_all_shaders = {NULL, NULL}; @@ -2352,6 +2355,117 @@ void ntreeCompositExecTree(bNodeTree *ntree, RenderData *rd, int do_preview) ntreeEndExecTree(ntree); } +/* GPU material from shader nodes */ + +static void gpu_from_node_stack(ListBase *sockets, bNodeStack **ns, GPUNodeStack *gs) +{ + bNodeSocket *sock; + int i; + + for (sock=sockets->first, i=0; sock; sock=sock->next, i++) { + memset(&gs[i], 0, sizeof(gs[i])); + + QUATCOPY(gs[i].vec, ns[i]->vec); + gs[i].link= ns[i]->data; + + if (sock->type == SOCK_VALUE) + gs[i].type= GPU_FLOAT; + else if (sock->type == SOCK_VECTOR) + gs[i].type= GPU_VEC3; + else if (sock->type == SOCK_RGBA) + gs[i].type= GPU_VEC4; + else + gs[i].type= GPU_NONE; + + gs[i].name = ""; + gs[i].hasinput= ns[i]->hasinput; + gs[i].hasoutput= ns[i]->hasinput; + gs[i].sockettype= ns[i]->sockettype; + } + + gs[i].type= GPU_NONE; +} + +static void data_from_gpu_stack(ListBase *sockets, bNodeStack **ns, GPUNodeStack *gs) +{ + bNodeSocket *sock; + int i; + + for (sock=sockets->first, i=0; sock; sock=sock->next, i++) { + ns[i]->data= gs[i].link; + ns[i]->hasinput= gs[i].hasinput; + ns[i]->hasoutput= gs[i].hasoutput; + ns[i]->sockettype= gs[i].sockettype; + } +} + +static void gpu_node_group_execute(bNodeStack *stack, GPUMaterial *mat, bNode *gnode, bNodeStack **in, bNodeStack **out) +{ + bNode *node; + bNodeTree *ntree= (bNodeTree *)gnode->id; + bNodeStack *nsin[MAX_SOCKET]; /* arbitrary... watch this */ + bNodeStack *nsout[MAX_SOCKET]; /* arbitrary... watch this */ + GPUNodeStack gpuin[MAX_SOCKET+1], gpuout[MAX_SOCKET+1]; + int doit = 0; + + if(ntree==NULL) return; + + stack+= gnode->stack_index; + + for(node= ntree->nodes.first; node; node= node->next) { + if(node->typeinfo->gpufunc) { + group_node_get_stack(node, stack, nsin, nsout, in, out); + + doit = 0; + + /* for groups, only execute outputs for edited group */ + if(node->typeinfo->nclass==NODE_CLASS_OUTPUT) { + if(gnode->flag & NODE_GROUP_EDIT) + if(node->flag & NODE_DO_OUTPUT) + doit = 1; + } + else + doit = 1; + + if(doit) { + gpu_from_node_stack(&node->inputs, nsin, gpuin); + gpu_from_node_stack(&node->outputs, nsout, gpuout); + if(node->typeinfo->gpufunc(mat, node, gpuin, gpuout)) + data_from_gpu_stack(&node->outputs, nsout, gpuout); + } + } + } +} + +void ntreeGPUMaterialNodes(bNodeTree *ntree, GPUMaterial *mat) +{ + bNode *node; + bNodeStack *stack; + bNodeStack *nsin[MAX_SOCKET]; /* arbitrary... watch this */ + bNodeStack *nsout[MAX_SOCKET]; /* arbitrary... watch this */ + GPUNodeStack gpuin[MAX_SOCKET+1], gpuout[MAX_SOCKET+1]; + + if((ntree->init & NTREE_EXEC_INIT)==0) + ntreeBeginExecTree(ntree); + + stack= ntree->stack; + + for(node= ntree->nodes.first; node; node= node->next) { + if(node->typeinfo->gpufunc) { + node_get_stack(node, stack, nsin, nsout); + gpu_from_node_stack(&node->inputs, nsin, gpuin); + gpu_from_node_stack(&node->outputs, nsout, gpuout); + if(node->typeinfo->gpufunc(mat, node, gpuin, gpuout)) + data_from_gpu_stack(&node->outputs, nsout, gpuout); + } + else if(node->type==NODE_GROUP && node->id) { + node_get_stack(node, stack, nsin, nsout); + gpu_node_group_execute(stack, mat, node, nsin, nsout); + } + } + + ntreeEndExecTree(ntree); +} /* **************** call to switch lamploop for material node ************ */ diff --git a/source/blender/blenkernel/intern/object.c b/source/blender/blenkernel/intern/object.c index 7b36e46d45e..8879b498ad9 100644 --- a/source/blender/blenkernel/intern/object.c +++ b/source/blender/blenkernel/intern/object.c @@ -112,6 +112,8 @@ #include "BPY_extern.h" +#include "GPU_material.h" + #include "blendef.h" /* Local function protos */ @@ -268,6 +270,7 @@ void free_object(Object *ob) } if(ob->soft) sbFree(ob->soft); if(ob->fluidsimSettings) fluidsimSettingsFree(ob->fluidsimSettings); + if(ob->gpulamp.first) GPU_lamp_free(ob); } static void unlink_object__unlinkModifierLinks(void *userData, Object *ob, Object **obpoin) @@ -918,7 +921,7 @@ Object *add_only_object(int type, char *name) QuatOne(ob->dquat); #endif - ob->col[0]= ob->col[1]= ob->col[2]= 0.0; + ob->col[0]= ob->col[1]= ob->col[2]= 1.0; ob->col[3]= 1.0; ob->loc[0]= ob->loc[1]= ob->loc[2]= 0.0; @@ -1226,6 +1229,7 @@ Object *copy_object(Object *ob) obn->vnode = NULL; #endif + obn->gpulamp.first = obn->gpulamp.last = NULL; return obn; } diff --git a/source/blender/blenkernel/intern/subsurf_ccg.c b/source/blender/blenkernel/intern/subsurf_ccg.c index bba79bd6d28..f334fc39daa 100644 --- a/source/blender/blenkernel/intern/subsurf_ccg.c +++ b/source/blender/blenkernel/intern/subsurf_ccg.c @@ -61,6 +61,10 @@ #include "BIF_gl.h" +#include "GPU_draw.h" +#include "GPU_extensions.h" +#include "GPU_material.h" + #include "CCGSubSurf.h" typedef struct _VertData { @@ -1599,7 +1603,7 @@ static void ccgDM_glNormalFast(float *a, float *b, float *c, float *d) } /* Only used by non-editmesh types */ -static void ccgDM_drawFacesSolid(DerivedMesh *dm, int (*setMaterial)(int)) { +static void ccgDM_drawFacesSolid(DerivedMesh *dm, int (*setMaterial)(int, void *attribs)) { CCGDerivedMesh *ccgdm = (CCGDerivedMesh*) dm; CCGSubSurf *ss = ccgdm->ss; CCGFaceIterator *fi = ccgSubSurf_getFaceIterator(ss); @@ -1621,7 +1625,7 @@ static void ccgDM_drawFacesSolid(DerivedMesh *dm, int (*setMaterial)(int)) { mat_nr= 0; } - if (!setMaterial(mat_nr+1)) + if (!setMaterial(mat_nr+1, NULL)) continue; glShadeModel(drawSmooth? GL_SMOOTH: GL_FLAT); @@ -1666,6 +1670,168 @@ static void ccgDM_drawFacesSolid(DerivedMesh *dm, int (*setMaterial)(int)) { ccgFaceIterator_free(fi); } + + /* Only used by non-editmesh types */ +static void ccgDM_drawMappedFacesGLSL(DerivedMesh *dm, int (*setMaterial)(int, void *attribs), int (*setDrawOptions)(void *userData, int index), void *userData) { + CCGDerivedMesh *ccgdm = (CCGDerivedMesh*) dm; + CCGSubSurf *ss = ccgdm->ss; + CCGFaceIterator *fi = ccgSubSurf_getFaceIterator(ss); + GPUVertexAttribs gattribs; + DMVertexAttribs attribs; + MTFace *tf = dm->getFaceDataArray(dm, CD_MTFACE); + int gridSize = ccgSubSurf_getGridSize(ss); + int gridFaces = gridSize - 1; + int edgeSize = ccgSubSurf_getEdgeSize(ss); + int transp, orig_transp, new_transp; + char *faceFlags = DM_get_face_data_layer(dm, CD_FLAGS); + int a, b, i, doDraw, numVerts, matnr, new_matnr, totface; + + doDraw = 0; + numVerts = 0; + matnr = -1; + transp = GPU_get_material_blend_mode(); + orig_transp = transp; + + memset(&attribs, 0, sizeof(attribs)); + +#define PASSATTRIB(dx, dy, vert) { \ + if(attribs.totorco) { \ + index = getFaceIndex(ss, f, S, x+dx, y+dy, edgeSize, gridSize); \ + glVertexAttrib3fvARB(attribs.orco.glIndex, attribs.orco.array[index]); \ + } \ + for(b = 0; b < attribs.tottface; b++) { \ + MTFace *tf = &attribs.tface[b].array[a]; \ + glVertexAttrib2fvARB(attribs.tface[b].glIndex, tf->uv[vert]); \ + } \ + for(b = 0; b < attribs.totmcol; b++) { \ + MCol *cp = &attribs.mcol[b].array[a*4 + vert]; \ + GLubyte col[4]; \ + col[0]= cp->b; col[1]= cp->g; col[2]= cp->r; col[3]= cp->a; \ + glVertexAttrib4ubvARB(attribs.mcol[b].glIndex, col); \ + } \ + if(attribs.tottang) { \ + float *tang = attribs.tang.array[a*4 + vert]; \ + glVertexAttrib3fvARB(attribs.tang.glIndex, tang); \ + } \ +} + + totface = ccgSubSurf_getNumFaces(ss); + for(a = 0, i = 0; i < totface; i++) { + CCGFace *f = ccgdm->faceMap[i].face; + int S, x, y, drawSmooth; + int index = GET_INT_FROM_POINTER(ccgSubSurf_getFaceFaceHandle(ss, f)); + int origIndex = ccgDM_getFaceMapIndex(ccgdm, ss, f); + + numVerts = ccgSubSurf_getFaceNumVerts(ss, f); + + if(faceFlags) { + drawSmooth = (faceFlags[index*4] & ME_SMOOTH); + new_matnr= faceFlags[index*4 + 1] + 1; + } + else { + drawSmooth = 1; + new_matnr= 1; + } + + if(new_matnr != matnr) { + doDraw = setMaterial(matnr = new_matnr, &gattribs); + if(doDraw) + DM_vertex_attributes_from_gpu(dm, &gattribs, &attribs); + } + + if(!doDraw || (setDrawOptions && !setDrawOptions(userData, origIndex))) { + a += gridFaces*gridFaces*numVerts; + continue; + } + + if(tf) { + new_transp = tf[i].transp; + + if(new_transp != transp) { + if(new_transp == GPU_BLEND_SOLID && orig_transp != GPU_BLEND_SOLID) + GPU_set_material_blend_mode(orig_transp); + else + GPU_set_material_blend_mode(new_transp); + transp = new_transp; + } + } + + glShadeModel(drawSmooth? GL_SMOOTH: GL_FLAT); + for (S=0; Sno); + glVertex3fv(vda->co); + + PASSATTRIB(0, 1, 1); + glNormal3fv(vdb->no); + glVertex3fv(vdb->co); + + if(x != gridFaces-1) + a++; + } + + vda = &faceGridData[(y+0)*gridSize + x]; + vdb = &faceGridData[(y+1)*gridSize + x]; + + PASSATTRIB(0, 0, 3); + glNormal3fv(vda->no); + glVertex3fv(vda->co); + + PASSATTRIB(0, 1, 2); + glNormal3fv(vdb->no); + glVertex3fv(vdb->co); + + glEnd(); + + a++; + } + } else { + glBegin(GL_QUADS); + for (y=0; ydrawMappedFacesGLSL(dm, setMaterial, NULL, NULL); +} + static void ccgDM_drawFacesColored(DerivedMesh *dm, int useTwoSided, unsigned char *col1, unsigned char *col2) { CCGDerivedMesh *ccgdm = (CCGDerivedMesh*) dm; CCGSubSurf *ss = ccgdm->ss; @@ -2143,8 +2309,10 @@ static CCGDerivedMesh *getCCGDerivedMesh(CCGSubSurf *ss, ccgdm->dm.drawFacesSolid = ccgDM_drawFacesSolid; ccgdm->dm.drawFacesColored = ccgDM_drawFacesColored; ccgdm->dm.drawFacesTex = ccgDM_drawFacesTex; + ccgdm->dm.drawFacesGLSL = ccgDM_drawFacesGLSL; ccgdm->dm.drawMappedFaces = ccgDM_drawMappedFaces; ccgdm->dm.drawMappedFacesTex = ccgDM_drawMappedFacesTex; + ccgdm->dm.drawMappedFacesGLSL = ccgDM_drawMappedFacesGLSL; ccgdm->dm.drawUVEdges = ccgDM_drawUVEdges; ccgdm->dm.drawMappedEdgesInterp = ccgDM_drawMappedEdgesInterp; diff --git a/source/blender/blenkernel/intern/texture.c b/source/blender/blenkernel/intern/texture.c index 936381c85cc..bb726887d32 100644 --- a/source/blender/blenkernel/intern/texture.c +++ b/source/blender/blenkernel/intern/texture.c @@ -53,6 +53,7 @@ #include "DNA_world_types.h" #include "DNA_brush_types.h" #include "DNA_node_types.h" +#include "DNA_color_types.h" #include "DNA_scene_types.h" #include "IMB_imbuf_types.h" @@ -390,6 +391,17 @@ int do_colorband(ColorBand *coba, float in, float out[4]) return 1; /* OK */ } +void colorband_table_RGBA(ColorBand *coba, float **array, int *size) +{ + int a; + + *size = CM_TABLE+1; + *array = MEM_callocN(sizeof(float)*(*size)*4, "ColorBand"); + + for(a=0; a<*size; a++) + do_colorband(coba, (float)a/(float)CM_TABLE, &(*array)[a*4]); +} + /* ******************* TEX ************************ */ void free_texture(Tex *tex) diff --git a/source/blender/blenlib/BLI_arithb.h b/source/blender/blenlib/BLI_arithb.h index c22b6f79e08..4448231b2b4 100644 --- a/source/blender/blenlib/BLI_arithb.h +++ b/source/blender/blenlib/BLI_arithb.h @@ -260,6 +260,7 @@ void Vec2Mulf(float *v1, float f); void Vec2Addf(float *v, float *v1, float *v2); void Vec2Subf(float *v, float *v1, float *v2); void Vec2Copyf(float *v1, float *v2); +void Vec2Lerpf(float *target, float *a, float *b, float t); void AxisAngleToQuat(float *q, float *axis, float angle); void vectoquat(float *vec, short axis, short upflag, float *q); diff --git a/source/blender/blenlib/BLI_blenlib.h b/source/blender/blenlib/BLI_blenlib.h index e24ccad12fb..c59cd2dab4e 100644 --- a/source/blender/blenlib/BLI_blenlib.h +++ b/source/blender/blenlib/BLI_blenlib.h @@ -73,7 +73,6 @@ extern ListBase fillvertbase; * @attention Defined in scanfill.c */ extern ListBase filledgebase; -extern int totblock; extern char btempdir[]; /* creator.c temp dir used instead of U.tempdir, set with BLI_where_is_temp( btempdir, 1 ); */ diff --git a/source/blender/blenlib/intern/arithb.c b/source/blender/blenlib/intern/arithb.c index 8bd7ad405af..50f8ba0fcde 100644 --- a/source/blender/blenlib/intern/arithb.c +++ b/source/blender/blenlib/intern/arithb.c @@ -2113,6 +2113,14 @@ void VecLerpf(float *target, float *a, float *b, float t) target[2]= s*a[2] + t*b[2]; } +void Vec2Lerpf(float *target, float *a, float *b, float t) +{ + float s = 1.0f-t; + + target[0]= s*a[0] + t*b[0]; + target[1]= s*a[1] + t*b[1]; +} + void VecMidf(float *v, float *v1, float *v2) { v[0]= 0.5f*(v1[0]+ v2[0]); diff --git a/source/blender/blenloader/intern/readfile.c b/source/blender/blenloader/intern/readfile.c index 6affec0e104..a2b1828c399 100644 --- a/source/blender/blenloader/intern/readfile.c +++ b/source/blender/blenloader/intern/readfile.c @@ -1138,6 +1138,8 @@ void blo_make_image_pointer_map(FileData *fd) Link *ibuf= ima->ibufs.first; for(; ibuf; ibuf= ibuf->next) oldnewmap_insert(fd->imamap, ibuf, ibuf, 0); + if(ima->gputexture) + oldnewmap_insert(fd->imamap, ima->gputexture, ima->gputexture, 0); } for(; sce; sce= sce->id.next) { if(sce->nodetree) { @@ -1172,8 +1174,11 @@ void blo_end_image_pointer_map(FileData *fd) if(NULL==newimaadr(fd, ibuf)) { /* so was restored */ BLI_remlink(&ima->ibufs, ibuf); ima->bindcode= 0; + ima->gputexture= NULL; } } + + ima->gputexture= newimaadr(fd, ima->gputexture); } for(; sce; sce= sce->id.next) { if(sce->nodetree) { @@ -2340,8 +2345,10 @@ static void direct_link_image(FileData *fd, Image *ima) ima->ibufs.first= ima->ibufs.last= NULL; /* if not restored, we keep the binded opengl index */ - if(ima->ibufs.first==NULL) + if(ima->ibufs.first==NULL) { ima->bindcode= 0; + ima->gputexture= NULL; + } ima->anim= NULL; ima->rr= NULL; @@ -2552,6 +2559,7 @@ static void direct_link_material(FileData *fd, Material *ma) direct_link_nodetree(fd, ma->nodetree); ma->preview = direct_link_preview_image(fd, ma->preview); + ma->gpumaterial.first = ma->gpumaterial.last = NULL; } /* ************ READ PARTICLE SETTINGS ***************** */ @@ -3390,6 +3398,7 @@ static void direct_link_object(FileData *fd, Object *ob) ob->bb= NULL; ob->derivedDeform= NULL; ob->derivedFinal= NULL; + ob->gpulamp.first= ob->gpulamp.last= NULL; } /* ************ READ SCENE ***************** */ diff --git a/source/blender/gpu/CMakeLists.txt b/source/blender/gpu/CMakeLists.txt new file mode 100644 index 00000000000..4d376f47d91 --- /dev/null +++ b/source/blender/gpu/CMakeLists.txt @@ -0,0 +1,34 @@ +# $Id: CMakeLists.txt 14444 2008-04-16 22:40:48Z hos $ +# ***** BEGIN GPL LICENSE BLOCK ***** +# +# This program is free software; you can redistribute it and/or +# modify it under the terms of the GNU General Public License +# as published by the Free Software Foundation; either version 2 +# of the License, or (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program; if not, write to the Free Software Foundation, +# Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +# +# The Original Code is Copyright (C) 2006, Blender Foundation +# All rights reserved. +# +# The Original Code is: all of this file. +# +# Contributor(s): Jacques Beaurain. +# +# ***** END GPL LICENSE BLOCK ***** + +FILE(GLOB SRC intern/*.c) + +SET(INC + . ../blenlib ../blenkernel ../makesdna ../include + ../../../extern/glew/include ../../../intern/guardedalloc ../imbuf) + +BLENDERLIB(bf_gpu "${SRC}" "${INC}") + diff --git a/source/blender/gpu/GPU_draw.h b/source/blender/gpu/GPU_draw.h new file mode 100644 index 00000000000..2399e7b6a8c --- /dev/null +++ b/source/blender/gpu/GPU_draw.h @@ -0,0 +1,116 @@ +/** + * $Id$ + * + * ***** BEGIN GPL LICENSE BLOCK ***** + * + * This shader is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. The Blender + * Foundation also sells licenses for use in proprietary software under + * the Blender License. See http://www.blender.org/BL/ for information + * about this. + * + * This shader is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this shader; if not, write to the Free Software Foundation, + * Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. + * + * The Original Code is Copyright (C) 2005 Blender Foundation. + * All rights reserved. + * + * The Original Code is: all of this file. + * + * Contributor(s): Brecht Van Lommel. + * + * ***** END GPL LICENSE BLOCK ***** + */ + +#ifndef GPU_GAME_H +#define GPU_GAME_H + +#ifdef __cplusplus +extern "C" { +#endif + +struct MTFace; +struct Image; +struct Scene; +struct Object; + +/* OpenGL drawing functions related to shading. These are also + * shared with the game engine, where there were previously + * duplicates of some of these functions. */ + +/* Initialize + * - sets the default Blender opengl state, if in doubt, check + * the contents of this function + * - this is called when starting Blender, for opengl rendering, + * and for switching back from the game engine for example. */ + +void GPU_state_init(void); + +/* Material drawing + * - first the state is initialized by a particular object and + * it's materials + * - after this, materials can be quickly enabled by their number, + * GPU_enable_material returns 0 if drawing should be skipped + * - after drawing, the material must be disabled again */ + +void GPU_set_object_materials(struct Scene *scene, struct Object *ob, + int glsl, int *do_alpha_pass); +int GPU_enable_material(int nr, void *attribs); +void GPU_disable_material(void); + +void GPU_set_material_blend_mode(int blendmode); +int GPU_get_material_blend_mode(void); + +/* TexFace drawing + * - this is mutually exclusive with material drawing, a mesh should + * be drawn using one or the other + * - passing NULL clears the state again */ + +int GPU_set_tpage(struct MTFace *tface); + +/* Lights + * - returns how many lights were enabled + * - this affects fixed functions materials and texface, not glsl */ + +int GPU_default_lights(void); +int GPU_scene_object_lights(struct Scene *scene, struct Object *ob, + int lay, float viewmat[][4]); + +/* Text render + * - based on moving uv coordinates */ + +void GPU_render_text(struct MTFace *tface, int mode, + const char *textstr, int textlen, unsigned int *col, + float *v1, float *v2, float *v3, float *v4, int glattrib); + +/* Mipmap settings + * - these will free textures on changes */ + +void GPU_set_mipmap(int mipmap); +void GPU_set_linear_mipmap(int linear); +void GPU_paint_set_mipmap(int mipmap); + +/* Image updates and free + * - these deal with images bound as opengl textures */ + +void GPU_paint_update_image(struct Image *ima, int x, int y, int w, int h); +void GPU_update_images_framechange(void); +int GPU_update_image_time(struct Image *ima, double time); +int GPU_verify_image(struct Image *ima, int tftile, int tfmode, int compare); +void GPU_free_image(struct Image *ima); +void GPU_free_images(void); + +#ifdef __cplusplus +} +#endif + +#endif + diff --git a/source/blender/gpu/GPU_extensions.h b/source/blender/gpu/GPU_extensions.h new file mode 100644 index 00000000000..d3faa81ebb1 --- /dev/null +++ b/source/blender/gpu/GPU_extensions.h @@ -0,0 +1,144 @@ +/** + * $Id$ + * + * ***** BEGIN GPL LICENSE BLOCK ***** + * + * This shader is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. The Blender + * Foundation also sells licenses for use in proprietary software under + * the Blender License. See http://www.blender.org/BL/ for information + * about this. + * + * This shader is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this shader; if not, write to the Free Software Foundation, + * Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. + * + * The Original Code is Copyright (C) 2005 Blender Foundation. + * All rights reserved. + * + * The Original Code is: all of this file. + * + * Contributor(s): Brecht Van Lommel. + * + * ***** END GPL LICENSE BLOCK ***** + */ + +#ifndef GPU_EXTENSIONS_H +#define GPU_EXTENSIONS_H + +#ifdef __cplusplus +extern "C" { +#endif + +/* GPU extensions support */ + +struct Image; +struct ImageUser; + +struct GPUTexture; +typedef struct GPUTexture GPUTexture; + +struct GPUFrameBuffer; +typedef struct GPUFrameBuffer GPUFrameBuffer; + +struct GPUShader; +typedef struct GPUShader GPUShader; + +void GPU_extensions_init(void); /* call this before running any of the functions below */ +void GPU_extensions_exit(void); +int GPU_extensions_minimum_support(void); +int GPU_print_error(char *str); + +/* GPU Texture + - always returns unsigned char RGBA textures + - if texture with non square dimensions is created, depending on the + graphics card capabilities the texture may actually be stored in a + larger texture with power of two dimensions. the actual dimensions + may be querd with GPU_texture_opengl_width/height. GPU_texture_coord_2f + calls glTexCoord2f with the coordinates adjust for this. + - can use reference counting: + - reference counter after GPU_texture_create is 1 + - GPU_texture_ref increases by one + - GPU_texture_free decreases by one, and frees if 0 + - if created with from_blender, will not free the texture +*/ + +GPUTexture *GPU_texture_create_1D(int w, float *pixels); +GPUTexture *GPU_texture_create_2D(int w, int h, float *pixels); +GPUTexture *GPU_texture_create_depth(int w, int h); +GPUTexture *GPU_texture_from_blender(struct Image *ima, + struct ImageUser *iuser, double time); +void GPU_texture_free(GPUTexture *tex); + +void GPU_texture_ref(GPUTexture *tex); + +void GPU_texture_bind(GPUTexture *tex, int number); +void GPU_texture_unbind(GPUTexture *tex); + +GPUFrameBuffer *GPU_texture_framebuffer(GPUTexture *tex); + +int GPU_texture_target(GPUTexture *tex); +int GPU_texture_opengl_width(GPUTexture *tex); +int GPU_texture_opengl_height(GPUTexture *tex); + +/* GPU Framebuffer + - this is a wrapper for an OpenGL framebuffer object (FBO). in practice + multiple FBO's may be created, to get around limitations on the number + of attached textures and the dimension requirements. + - after any of the GPU_framebuffer_* functions, GPU_framebuffer_restore must + be called before rendering to the window framebuffer again */ + +GPUFrameBuffer *GPU_framebuffer_create(); +int GPU_framebuffer_texture_attach(GPUFrameBuffer *fb, GPUTexture *tex); +void GPU_framebuffer_texture_detach(GPUFrameBuffer *fb, GPUTexture *tex); +void GPU_framebuffer_texture_bind(GPUFrameBuffer *fb, GPUTexture *tex); +void GPU_framebuffer_texture_unbind(GPUFrameBuffer *fb, GPUTexture *tex); +void GPU_framebuffer_free(GPUFrameBuffer *fb); + +void GPU_framebuffer_restore(); + +/* GPU Shader + - only for fragment shaders now + - must call texture bind before setting a texture as uniform! */ + +GPUShader *GPU_shader_create(const char *vertexcode, const char *fragcode, GPUShader *lib); +GPUShader *GPU_shader_create_lib(const char *code); +void GPU_shader_free(GPUShader *shader); + +void GPU_shader_bind(GPUShader *shader); +void GPU_shader_unbind(); + +int GPU_shader_get_uniform(GPUShader *shader, char *name); +void GPU_shader_uniform_vector(GPUShader *shader, int location, int length, + int arraysize, float *value); +void GPU_shader_uniform_texture(GPUShader *shader, int location, GPUTexture *tex); + +int GPU_shader_get_attribute(GPUShader *shader, char *name); + +/* Vertex attributes for shaders */ + +#define GPU_MAX_ATTRIB 32 + +typedef struct GPUVertexAttribs { + struct { + int type; + int glindex; + char name[32]; + } layer[GPU_MAX_ATTRIB]; + + int totlayer; +} GPUVertexAttribs; + +#ifdef __cplusplus +} +#endif + +#endif + diff --git a/source/blender/gpu/GPU_material.h b/source/blender/gpu/GPU_material.h new file mode 100644 index 00000000000..560421f7edf --- /dev/null +++ b/source/blender/gpu/GPU_material.h @@ -0,0 +1,169 @@ +/** + * $Id$ + * + * ***** BEGIN GPL LICENSE BLOCK ***** + * + * This shader is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. The Blender + * Foundation also sells licenses for use in proprietary software under + * the Blender License. See http://www.blender.org/BL/ for information + * about this. + * + * This shader is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this shader; if not, write to the Free Software Foundation, + * Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. + * + * The Original Code is Copyright (C) 2005 Blender Foundation. + * All rights reserved. + * + * The Original Code is: all of this file. + * + * Contributor(s): Brecht Van Lommel. + * + * ***** END GPL LICENSE BLOCK ***** + */ + +#ifndef __GPU_MATERIAL__ +#define __GPU_MATERIAL__ + +#ifdef __cplusplus +extern "C" { +#endif + +struct Image; +struct ImageUser; +struct Material; +struct Object; +struct Lamp; +struct bNode; +struct LinkNode; +struct Scene; +struct GPUVertexAttribs; +struct GPUNode; +struct GPUNodeLink; +struct GPUNodeStack; +struct GPUMaterial; +struct GPUTexture; +struct GPULamp; + +typedef struct GPUNode GPUNode; +typedef struct GPUNodeLink GPUNodeLink; +typedef struct GPUMaterial GPUMaterial; +typedef struct GPULamp GPULamp; + +/* Functions to create GPU Materials nodes */ + +typedef enum GPUType { + GPU_NONE = 0, + GPU_FLOAT = 1, + GPU_VEC2 = 2, + GPU_VEC3 = 3, + GPU_VEC4 = 4, + GPU_MAT3 = 9, + GPU_MAT4 = 16, + GPU_TEX1D = 1001, + GPU_TEX2D = 1002, + GPU_SHADOW2D = 1003, + GPU_ATTRIB = 3001 +} GPUType; + +typedef enum GPUBuiltin { + GPU_VIEW_MATRIX = 1, + GPU_OBJECT_MATRIX = 2, + GPU_INVERSE_VIEW_MATRIX = 4, + GPU_INVERSE_OBJECT_MATRIX = 8, + GPU_VIEW_POSITION = 16, + GPU_VIEW_NORMAL = 32, + GPU_OBCOLOR = 64 +} GPUBuiltin; + +typedef enum GPUBlendMode { + GPU_BLEND_SOLID = 0, + GPU_BLEND_ADD = 1, + GPU_BLEND_ALPHA = 2, + GPU_BLEND_CLIP = 4 +} GPUBlendMode; + +typedef struct GPUNodeStack { + GPUType type; + char *name; + float vec[4]; + struct GPUNodeLink *link; + short hasinput; + short hasoutput; + short sockettype; +} GPUNodeStack; + +GPUNodeLink *GPU_attribute(int type, char *name); +GPUNodeLink *GPU_uniform(float *num); +GPUNodeLink *GPU_dynamic_uniform(float *num); +GPUNodeLink *GPU_image(struct Image *ima, struct ImageUser *iuser); +GPUNodeLink *GPU_texture(int size, float *pixels); +GPUNodeLink *GPU_dynamic_texture(struct GPUTexture *tex); +GPUNodeLink *GPU_socket(GPUNodeStack *sock); +GPUNodeLink *GPU_builtin(GPUBuiltin builtin); + +int GPU_link(GPUMaterial *mat, char *name, ...); +int GPU_stack_link(GPUMaterial *mat, char *name, GPUNodeStack *in, GPUNodeStack *out, ...); + +void GPU_material_output_link(GPUMaterial *material, GPUNodeLink *link); +void GPU_material_enable_alpha(GPUMaterial *material); +GPUBlendMode GPU_material_blend_mode(GPUMaterial *material, float obcol[4]); + +/* High level functions to create and use GPU materials */ + +GPUMaterial *GPU_material_from_blender(struct Scene *scene, struct Material *ma); +void GPU_material_free(struct Material *ma); + +void GPU_materials_free(); + +void GPU_material_bind(GPUMaterial *material, int lay, double time); +void GPU_material_bind_uniforms(GPUMaterial *material, float obmat[][4], float viewmat[][4], float viewinv[][4], float obcol[4]); +void GPU_material_unbind(GPUMaterial *material); +int GPU_material_bound(GPUMaterial *material); + +void GPU_material_vertex_attributes(GPUMaterial *material, + struct GPUVertexAttribs *attrib); + +/* Exported shading */ + +typedef struct GPUShadeInput { + GPUMaterial *gpumat; + struct Material *mat; + + GPUNodeLink *rgb, *specrgb, *vn, *view, *vcol, *ref; + GPUNodeLink *alpha, *refl, *spec, *emit, *har, *amb; +} GPUShadeInput; + +typedef struct GPUShadeResult { + GPUNodeLink *diff, *spec, *combined, *alpha; +} GPUShadeResult; + +void GPU_shadeinput_set(GPUMaterial *mat, struct Material *ma, GPUShadeInput *shi); +void GPU_shaderesult_set(GPUShadeInput *shi, GPUShadeResult *shr); + +/* Lamps */ + +GPULamp *GPU_lamp_from_blender(struct Scene *scene, struct Object *ob, struct Object *par); +void GPU_lamp_free(struct Object *ob); + +int GPU_lamp_has_shadow_buffer(GPULamp *lamp); +void GPU_lamp_shadow_buffer_bind(GPULamp *lamp, float viewmat[][4], int *winsize, float winmat[][4]); +void GPU_lamp_shadow_buffer_unbind(GPULamp *lamp); + +void GPU_lamp_update(GPULamp *lamp, float obmat[][4]); +int GPU_lamp_shadow_layer(GPULamp *lamp); + +#ifdef __cplusplus +} +#endif + +#endif /*__GPU_MATERIAL__*/ + diff --git a/source/blender/gpu/Makefile b/source/blender/gpu/Makefile new file mode 100644 index 00000000000..b9bde147115 --- /dev/null +++ b/source/blender/gpu/Makefile @@ -0,0 +1,37 @@ +# +# $Id$ +# +# ***** BEGIN GPL/BL DUAL LICENSE BLOCK ***** +# +# This program is free software; you can redistribute it and/or +# modify it under the terms of the GNU General Public License +# as published by the Free Software Foundation; either version 2 +# of the License, or (at your option) any later version. The Blender +# Foundation also sells licenses for use in proprietary software under +# the Blender License. See http://www.blender.org/BL/ for information +# about this. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program; if not, write to the Free Software Foundation, +# Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +# +# The Original Code is Copyright (C) 2001-2002 by NaN Holding BV. +# All rights reserved. +# +# The Original Code is: all of this file. +# +# Contributor(s): none yet. +# +# ***** END GPL/BL DUAL LICENSE BLOCK ***** +# +# Makes module object directory and bounces make to subdirectories. + +SOURCEDIR = source/blender/gpu +DIRS = intern + +include nan_subdirs.mk diff --git a/source/blender/gpu/SConscript b/source/blender/gpu/SConscript new file mode 100644 index 00000000000..8ccd4b7b24c --- /dev/null +++ b/source/blender/gpu/SConscript @@ -0,0 +1,11 @@ +#!/usr/bin/python +Import ('env') + +sources = env.Glob('intern/*.c') + +incs = '../blenlib ../blenkernel ../makesdna ../include' +incs += ' #/extern/glew/include #intern/guardedalloc ../imbuf .' + +incs += ' ' + env['BF_OPENGL_INC'] + +env.BlenderLib ( 'bf_gpu', sources, Split(incs), [], libtype=['core', 'player'], priority=[65, 20] ) diff --git a/source/blender/gpu/intern/Makefile b/source/blender/gpu/intern/Makefile new file mode 100644 index 00000000000..733ee3f764c --- /dev/null +++ b/source/blender/gpu/intern/Makefile @@ -0,0 +1,53 @@ +# +# $Id$ +# +# ***** BEGIN GPL/BL DUAL LICENSE BLOCK ***** +# +# This program is free software; you can redistribute it and/or +# modify it under the terms of the GNU General Public License +# as published by the Free Software Foundation; either version 2 +# of the License, or (at your option) any later version. The Blender +# Foundation also sells licenses for use in proprietary software under +# the Blender License. See http://www.blender.org/BL/ for information +# about this. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program; if not, write to the Free Software Foundation, +# Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +# +# The Original Code is Copyright (C) 2001-2002 by NaN Holding BV. +# All rights reserved. +# +# The Original Code is: all of this file. +# +# Contributor(s): none yet. +# +# ***** END GPL/BL DUAL LICENSE BLOCK ***** +# + +LIBNAME = gpu +DIR = $(OCGDIR)/blender/$(LIBNAME) + +include nan_compile.mk + +ifeq ($(OS),$(findstring $(OS), "beos darwin freebsd linux openbsd solaris windows")) + CFLAGS += -funsigned-char +endif + +CFLAGS += $(LEVEL_1_C_WARNINGS) + +CPPFLAGS += -I$(OPENGL_HEADERS) + +CPPFLAGS += -I../../blenlib +CPPFLAGS += -I../../makesdna +CPPFLAGS += -I../../imbuf +CPPFLAGS += -I../../blenkernel +CPPFLAGS += -I$(NAN_GUARDEDALLOC)/include +CPPFLAGS += -I$(NAN_GLEW)/include +CPPFLAGS += -I../ + diff --git a/source/blender/gpu/intern/gpu_codegen.c b/source/blender/gpu/intern/gpu_codegen.c new file mode 100644 index 00000000000..b6285915484 --- /dev/null +++ b/source/blender/gpu/intern/gpu_codegen.c @@ -0,0 +1,1439 @@ +/** + * $Id$ + * + * ***** BEGIN GPL LICENSE BLOCK ***** + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. The Blender + * Foundation also sells licenses for use in proprietary software under + * the Blender License. See http://www.blender.org/BL/ for information + * about this. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software Foundation, + * Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. + * + * The Original Code is Copyright (C) 2005 Blender Foundation. + * All rights reserved. + * + * The Original Code is: all of this file. + * + * Contributor(s): Brecht Van Lommel. + * + * ***** END GPL LICENSE BLOCK ***** + */ + +#include "GL/glew.h" + +#include "MEM_guardedalloc.h" + +#include "DNA_customdata_types.h" +#include "DNA_image_types.h" +#include "DNA_listBase.h" +#include "DNA_material_types.h" + +#include "BLI_dynstr.h" +#include "BLI_blenlib.h" +#include "BLI_ghash.h" +#include "BLI_heap.h" + +#include "BKE_global.h" +#include "BKE_utildefines.h" + +#include "GPU_material.h" +#include "GPU_extensions.h" + +#include "gpu_codegen.h" + +#include +#include + +#ifdef _WIN32 +#ifndef vsnprintf +#define _vsnprintf vsnprintf +#endif +#ifndef snprintf +#define snprintf _snprintf +#endif +#endif + +extern char datatoc_gpu_shader_material_glsl[]; +extern char datatoc_gpu_shader_vertex_glsl[]; + +/* structs and defines */ + +typedef enum GPUDataSource { + GPU_SOURCE_VEC_UNIFORM, + GPU_SOURCE_BUILTIN, + GPU_SOURCE_TEX_PIXEL, + GPU_SOURCE_TEX, + GPU_SOURCE_ATTRIB +} GPUDataSource; + +static char* GPU_DATATYPE_STR[17] = {"", "float", "vec2", "vec3", "vec4", + 0, 0, 0, 0, "mat3", 0, 0, 0, 0, 0, 0, "mat4"}; + +struct GPUNode { + struct GPUNode *next, *prev; + + char *name; + int tag; + + ListBase inputs; + ListBase outputs; +}; + +struct GPUNodeLink { + GPUNodeStack *socket; + + int attribtype; + char *attribname; + + int image; + + int texture; + int texturesize; + + void *ptr1, *ptr2; + + int dynamic; + + int type; + int users; + + GPUTexture *dynamictex; + + GPUBuiltin builtin; + + struct GPUOutput *output; +}; + +typedef struct GPUOutput { + struct GPUOutput *next, *prev; + + GPUNode *node; + int type; /* data type = length of vector/matrix */ + GPUNodeLink *link; /* output link */ + int id; /* unique id as created by code generator */ +} GPUOutput; + +typedef struct GPUInput { + struct GPUInput *next, *prev; + + GPUNode *node; + + int type; /* datatype */ + int source; /* data source */ + + int id; /* unique id as created by code generator */ + int texid; /* number for multitexture */ + int attribid; /* id for vertex attributes */ + int bindtex; /* input is responsible for binding the texture? */ + int definetex; /* input is responsible for defining the pixel? */ + int textarget; /* GL_TEXTURE_* */ + int textype; /* datatype */ + + struct Image *ima; /* image */ + struct ImageUser *iuser;/* image user */ + float *dynamicvec; /* vector data in case it is dynamic */ + GPUTexture *tex; /* input texture, only set at runtime */ + int shaderloc; /* id from opengl */ + char shadername[32]; /* name in shader */ + + float vec[16]; /* vector data */ + GPUNodeLink *link; + int dynamictex; /* dynamic? */ + int attribtype; /* attribute type */ + char attribname[32]; /* attribute name */ + int attribfirst; /* this is the first one that is bound */ + GPUBuiltin builtin; /* builtin uniform */ +} GPUInput; + +struct GPUPass { + struct GPUPass *next, *prev; + + ListBase inputs; + struct GPUOutput *output; + struct GPUShader *shader; +}; + +/* Strings utility */ + +static void BLI_dynstr_printf(DynStr *dynstr, const char *format, ...) +{ + va_list args; + int retval; + char str[2048]; + + va_start(args, format); + retval = vsnprintf(str, sizeof(str), format, args); + va_end(args); + + if (retval >= sizeof(str)) + fprintf(stderr, "BLI_dynstr_printf: limit exceeded\n"); + else + BLI_dynstr_append(dynstr, str); +} + +/* GLSL code parsing for finding function definitions. + * These are stored in a hash for lookup when creating a material. */ + +static GHash *FUNCTION_HASH= NULL; +static char *FUNCTION_PROTOTYPES= NULL; +static GPUShader *FUNCTION_LIB= NULL; + +static int gpu_str_prefix(char *str, char *prefix) +{ + while(*str && *prefix) { + if(*str != *prefix) + return 0; + + str++; + prefix++; + } + + return (*prefix == '\0'); +} + +static char *gpu_str_skip_token(char *str, char *token, int max) +{ + int len = 0; + + /* skip a variable/function name */ + while(*str) { + if(ELEM6(*str, ' ', '(', ')', ',', '\t', '\n')) + break; + else { + if(token && len < max-1) { + *token= *str; + token++; + len++; + } + str++; + } + } + + if(token) + *token= '\0'; + + /* skip the next special characters: + * note the missing ')' */ + while(*str) { + if(ELEM5(*str, ' ', '(', ',', '\t', '\n')) + str++; + else + break; + } + + return str; +} + +static void gpu_parse_functions_string(GHash *hash, char *code) +{ + GPUFunction *function; + int i, type, qual; + + while((code = strstr(code, "void "))) { + function = MEM_callocN(sizeof(GPUFunction), "GPUFunction"); + + code = gpu_str_skip_token(code, NULL, 0); + code = gpu_str_skip_token(code, function->name, MAX_FUNCTION_NAME); + + /* get parameters */ + while(*code && *code != ')') { + /* test if it's an input or output */ + qual = FUNCTION_QUAL_IN; + if(gpu_str_prefix(code, "out ")) + qual = FUNCTION_QUAL_OUT; + if(gpu_str_prefix(code, "inout ")) + qual = FUNCTION_QUAL_INOUT; + if((qual != FUNCTION_QUAL_IN) || gpu_str_prefix(code, "in ")) + code = gpu_str_skip_token(code, NULL, 0); + + /* test for type */ + type= 0; + for(i=1; i<=16; i++) { + if(GPU_DATATYPE_STR[i] && gpu_str_prefix(code, GPU_DATATYPE_STR[i])) { + type= i; + break; + } + } + + if(!type && gpu_str_prefix(code, "sampler2DShadow")) + type= GPU_SHADOW2D; + if(!type && gpu_str_prefix(code, "sampler1D")) + type= GPU_TEX1D; + if(!type && gpu_str_prefix(code, "sampler2D")) + type= GPU_TEX2D; + + if(type) { + /* add paramater */ + code = gpu_str_skip_token(code, NULL, 0); + code = gpu_str_skip_token(code, NULL, 0); + function->paramqual[function->totparam]= qual; + function->paramtype[function->totparam]= type; + function->totparam++; + } + else { + fprintf(stderr, "GPU invalid function parameter in %s.\n", function->name); + break; + } + } + + if(strlen(function->name) == 0 || function->totparam == 0) { + fprintf(stderr, "GPU functions parse error.\n"); + MEM_freeN(function); + break; + } + + BLI_ghash_insert(hash, function->name, function); + } +} + +static char *gpu_generate_function_prototyps(GHash *hash) +{ + DynStr *ds = BLI_dynstr_new(); + GHashIterator *ghi; + GPUFunction *function; + char *name, *prototypes; + int a; + + /* automatically generate function prototypes to add to the top of the + * generated code, to avoid have to add the actual code & recompile all */ + ghi = BLI_ghashIterator_new(hash); + + for(; !BLI_ghashIterator_isDone(ghi); BLI_ghashIterator_step(ghi)) { + name = BLI_ghashIterator_getValue(ghi); + function = BLI_ghashIterator_getValue(ghi); + + BLI_dynstr_printf(ds, "void %s(", name); + for(a=0; atotparam; a++) { + if(function->paramqual[a] == FUNCTION_QUAL_OUT) + BLI_dynstr_append(ds, "out "); + else if(function->paramqual[a] == FUNCTION_QUAL_INOUT) + BLI_dynstr_append(ds, "inout "); + + if(function->paramtype[a] == GPU_TEX1D) + BLI_dynstr_append(ds, "sampler1D"); + else if(function->paramtype[a] == GPU_TEX2D) + BLI_dynstr_append(ds, "sampler2D"); + else if(function->paramtype[a] == GPU_SHADOW2D) + BLI_dynstr_append(ds, "sampler2DShadow"); + else + BLI_dynstr_append(ds, GPU_DATATYPE_STR[function->paramtype[a]]); + + BLI_dynstr_printf(ds, " param%d", a); + + if(a != function->totparam-1) + BLI_dynstr_append(ds, ", "); + } + BLI_dynstr_append(ds, ");\n"); + } + + BLI_dynstr_append(ds, "\n"); + + prototypes = BLI_dynstr_get_cstring(ds); + BLI_dynstr_free(ds); + + return prototypes; +} + +GPUFunction *GPU_lookup_function(char *name) +{ + if(!FUNCTION_HASH) { + FUNCTION_HASH = BLI_ghash_new(BLI_ghashutil_strhash, BLI_ghashutil_strcmp); + gpu_parse_functions_string(FUNCTION_HASH, datatoc_gpu_shader_material_glsl); + FUNCTION_PROTOTYPES = gpu_generate_function_prototyps(FUNCTION_HASH); + FUNCTION_LIB = GPU_shader_create_lib(datatoc_gpu_shader_material_glsl); + } + + return (GPUFunction*)BLI_ghash_lookup(FUNCTION_HASH, name); +} + +void GPU_extensions_exit(void) +{ + extern Material defmaterial; // render module abuse... + + if(defmaterial.gpumaterial.first) + GPU_material_free(&defmaterial); + + if(FUNCTION_HASH) { + BLI_ghash_free(FUNCTION_HASH, NULL, (GHashValFreeFP)MEM_freeN); + FUNCTION_HASH = NULL; + } + if(FUNCTION_PROTOTYPES) { + MEM_freeN(FUNCTION_PROTOTYPES); + FUNCTION_PROTOTYPES = NULL; + } + if(FUNCTION_LIB) { + GPU_shader_free(FUNCTION_LIB); + FUNCTION_LIB = NULL; + } +} + +/* GLSL code generation */ + +static void codegen_convert_datatype(DynStr *ds, int from, int to, char *tmp, int id) +{ + char name[1024]; + + snprintf(name, sizeof(name), "%s%d", tmp, id); + + if (from == to) { + BLI_dynstr_append(ds, name); + } + else if (to == GPU_FLOAT) { + if (from == GPU_VEC4) + BLI_dynstr_printf(ds, "dot(%s.rgb, vec3(0.35, 0.45, 0.2))", name); + else if (from == GPU_VEC3) + BLI_dynstr_printf(ds, "dot(%s, vec3(0.33))", name); + else if (from == GPU_VEC2) + BLI_dynstr_printf(ds, "%s.r", name); + } + else if (to == GPU_VEC2) { + if (from == GPU_VEC4) + BLI_dynstr_printf(ds, "vec2(dot(%s.rgb, vec3(0.35, 0.45, 0.2)), %s.a)", name, name); + else if (from == GPU_VEC3) + BLI_dynstr_printf(ds, "vec2(dot(%s.rgb, vec3(0.33)), 1.0)", name); + else if (from == GPU_FLOAT) + BLI_dynstr_printf(ds, "vec2(%s, 1.0)", name); + } + else if (to == GPU_VEC3) { + if (from == GPU_VEC4) + BLI_dynstr_printf(ds, "%s.rgb", name); + else if (from == GPU_VEC2) + BLI_dynstr_printf(ds, "vec3(%s.r, %s.r, %s.r)", name, name, name); + else if (from == GPU_FLOAT) + BLI_dynstr_printf(ds, "vec3(%s, %s, %s)", name, name, name); + } + else { + if (from == GPU_VEC3) + BLI_dynstr_printf(ds, "vec4(%s, 1.0)", name); + else if (from == GPU_VEC2) + BLI_dynstr_printf(ds, "vec4(%s.r, %s.r, %s.r, %s.g)", name, name, name, name); + else if (from == GPU_FLOAT) + BLI_dynstr_printf(ds, "vec4(%s, %s, %s, 1.0)", name, name, name); + } +} + +static void codegen_print_datatype(DynStr *ds, int type, float *data) +{ + int i; + + BLI_dynstr_printf(ds, "%s(", GPU_DATATYPE_STR[type]); + + for(i=0; ilink) + return 0; + else if(input->ima) + return 1; + else + return input->tex != 0; +} + +char *GPU_builtin_name(GPUBuiltin builtin) +{ + if(builtin == GPU_VIEW_MATRIX) + return "unfviewmat"; + else if(builtin == GPU_OBJECT_MATRIX) + return "unfobmat"; + else if(builtin == GPU_INVERSE_VIEW_MATRIX) + return "unfinvviewmat"; + else if(builtin == GPU_INVERSE_OBJECT_MATRIX) + return "unfinvobmat"; + else if(builtin == GPU_VIEW_POSITION) + return "varposition"; + else if(builtin == GPU_VIEW_NORMAL) + return "varnormal"; + else if(builtin == GPU_OBCOLOR) + return "unfobcolor"; + else + return ""; +} + +static void codegen_set_unique_ids(ListBase *nodes) +{ + GHash *bindhash, *definehash; + GPUNode *node; + GPUInput *input; + GPUOutput *output; + int id = 1, texid = 0; + + bindhash= BLI_ghash_new(BLI_ghashutil_ptrhash, BLI_ghashutil_ptrcmp); + definehash= BLI_ghash_new(BLI_ghashutil_ptrhash, BLI_ghashutil_ptrcmp); + + for (node=nodes->first; node; node=node->next) { + for (input=node->inputs.first; input; input=input->next) { + /* set id for unique names of uniform variables */ + input->id = id++; + input->bindtex = 0; + input->definetex = 0; + + /* set texid used for settings texture slot with multitexture */ + if (codegen_input_has_texture(input) && + ((input->source == GPU_SOURCE_TEX) || (input->source == GPU_SOURCE_TEX_PIXEL))) { + if (input->link) { + /* input is texture from buffer, assign only one texid per + buffer to avoid sampling the same texture twice */ + if (!BLI_ghash_haskey(bindhash, input->link)) { + input->texid = texid++; + input->bindtex = 1; + BLI_ghash_insert(bindhash, input->link, SET_INT_IN_POINTER(input->texid)); + } + else + input->texid = GET_INT_FROM_POINTER(BLI_ghash_lookup(bindhash, input->link)); + } + else if(input->ima) { + /* input is texture from image, assign only one texid per + buffer to avoid sampling the same texture twice */ + if (!BLI_ghash_haskey(bindhash, input->ima)) { + input->texid = texid++; + input->bindtex = 1; + BLI_ghash_insert(bindhash, input->ima, SET_INT_IN_POINTER(input->texid)); + } + else + input->texid = GET_INT_FROM_POINTER(BLI_ghash_lookup(bindhash, input->ima)); + } + else { + /* input is user created texture, we know there there is + only one, so assign new texid */ + input->bindtex = 1; + input->texid = texid++; + } + + /* make sure this pixel is defined exactly once */ + if (input->source == GPU_SOURCE_TEX_PIXEL) { + if(input->ima) { + if (!BLI_ghash_haskey(definehash, input->ima)) { + input->definetex = 1; + BLI_ghash_insert(definehash, input->ima, SET_INT_IN_POINTER(input->texid)); + } + } + else { + if (!BLI_ghash_haskey(definehash, input->link)) { + input->definetex = 1; + BLI_ghash_insert(definehash, input->link, SET_INT_IN_POINTER(input->texid)); + } + } + } + } + } + + for (output=node->outputs.first; output; output=output->next) + /* set id for unique names of tmp variables storing output */ + output->id = id++; + } + + BLI_ghash_free(bindhash, NULL, NULL); + BLI_ghash_free(definehash, NULL, NULL); +} + +static void codegen_print_uniforms_functions(DynStr *ds, ListBase *nodes) +{ + GPUNode *node; + GPUInput *input; + char *name; + int builtins = 0; + + /* print uniforms */ + for (node=nodes->first; node; node=node->next) { + for (input=node->inputs.first; input; input=input->next) { + if ((input->source == GPU_SOURCE_TEX) || (input->source == GPU_SOURCE_TEX_PIXEL)) { + /* create exactly one sampler for each texture */ + if (codegen_input_has_texture(input) && input->bindtex) + BLI_dynstr_printf(ds, "uniform %s samp%d;\n", + (input->textype == GPU_TEX1D)? "sampler1D": + (input->textype == GPU_TEX2D)? "sampler2D": "sampler2DShadow", + input->texid); + } + else if(input->source == GPU_SOURCE_BUILTIN) { + /* only define each builting uniform/varying once */ + if(!(builtins & input->builtin)) { + builtins |= input->builtin; + name = GPU_builtin_name(input->builtin); + + if(gpu_str_prefix(name, "unf")) { + BLI_dynstr_printf(ds, "uniform %s %s;\n", + GPU_DATATYPE_STR[input->type], name); + } + else { + BLI_dynstr_printf(ds, "varying %s %s;\n", + GPU_DATATYPE_STR[input->type], name); + } + } + } + else if (input->source == GPU_SOURCE_VEC_UNIFORM) { + if(input->dynamicvec) { + /* only create uniforms for dynamic vectors */ + BLI_dynstr_printf(ds, "uniform %s unf%d;\n", + GPU_DATATYPE_STR[input->type], input->id); + } + else { + /* for others use const so the compiler can do folding */ + BLI_dynstr_printf(ds, "const %s cons%d = ", + GPU_DATATYPE_STR[input->type], input->id); + codegen_print_datatype(ds, input->type, input->vec); + BLI_dynstr_append(ds, ";\n"); + } + } + else if (input->source == GPU_SOURCE_ATTRIB && input->attribfirst) { + BLI_dynstr_printf(ds, "varying %s var%d;\n", + GPU_DATATYPE_STR[input->type], input->attribid); + } + } + } + + BLI_dynstr_append(ds, "\n"); +} + +static void codegen_declare_tmps(DynStr *ds, ListBase *nodes) +{ + GPUNode *node; + GPUInput *input; + GPUOutput *output; + + for (node=nodes->first; node; node=node->next) { + /* load pixels from textures */ + for (input=node->inputs.first; input; input=input->next) { + if (input->source == GPU_SOURCE_TEX_PIXEL) { + if (codegen_input_has_texture(input) && input->definetex) { + BLI_dynstr_printf(ds, "\tvec4 tex%d = texture2D(", input->texid); + BLI_dynstr_printf(ds, "samp%d, gl_TexCoord[%d].st);\n", + input->texid, input->texid); + } + } + } + + /* declare temporary variables for node output storage */ + for (output=node->outputs.first; output; output=output->next) + BLI_dynstr_printf(ds, "\t%s tmp%d;\n", + GPU_DATATYPE_STR[output->type], output->id); + } + + BLI_dynstr_append(ds, "\n"); +} + +static void codegen_call_functions(DynStr *ds, ListBase *nodes, GPUOutput *finaloutput) +{ + GPUNode *node; + GPUInput *input; + GPUOutput *output; + + for (node=nodes->first; node; node=node->next) { + BLI_dynstr_printf(ds, "\t%s(", node->name); + + for (input=node->inputs.first; input; input=input->next) { + if (input->source == GPU_SOURCE_TEX) { + BLI_dynstr_printf(ds, "samp%d", input->texid); + if (input->link) + BLI_dynstr_printf(ds, ", gl_TexCoord[%d].st", input->texid); + } + else if (input->source == GPU_SOURCE_TEX_PIXEL) { + if (input->link && input->link->output) + codegen_convert_datatype(ds, input->link->output->type, input->type, + "tmp", input->link->output->id); + else + codegen_convert_datatype(ds, input->link->output->type, input->type, + "tex", input->texid); + } + else if(input->source == GPU_SOURCE_BUILTIN) + BLI_dynstr_printf(ds, "%s", GPU_builtin_name(input->builtin)); + else if(input->source == GPU_SOURCE_VEC_UNIFORM) { + if(input->dynamicvec) + BLI_dynstr_printf(ds, "unf%d", input->id); + else + BLI_dynstr_printf(ds, "cons%d", input->id); + } + else if (input->source == GPU_SOURCE_ATTRIB) + BLI_dynstr_printf(ds, "var%d", input->attribid); + + BLI_dynstr_append(ds, ", "); + } + + for (output=node->outputs.first; output; output=output->next) { + BLI_dynstr_printf(ds, "tmp%d", output->id); + if (output->next) + BLI_dynstr_append(ds, ", "); + } + + BLI_dynstr_append(ds, ");\n"); + } + + BLI_dynstr_append(ds, "\n\tgl_FragColor = "); + codegen_convert_datatype(ds, finaloutput->type, GPU_VEC4, "tmp", finaloutput->id); + BLI_dynstr_append(ds, ";\n"); +} + +static char *code_generate_fragment(ListBase *nodes, GPUOutput *output, const char *name) +{ + DynStr *ds = BLI_dynstr_new(); + char *code; + + BLI_dynstr_append(ds, FUNCTION_PROTOTYPES); + + codegen_set_unique_ids(nodes); + codegen_print_uniforms_functions(ds, nodes); + + //if(G.f & G_DEBUG) + // BLI_dynstr_printf(ds, "/* %s */\n", name); + + BLI_dynstr_append(ds, "void main(void)\n"); + BLI_dynstr_append(ds, "{\n"); + + codegen_declare_tmps(ds, nodes); + codegen_call_functions(ds, nodes, output); + + BLI_dynstr_append(ds, "}\n"); + + /* create shader */ + code = BLI_dynstr_get_cstring(ds); + BLI_dynstr_free(ds); + + //if(G.f & G_DEBUG) printf("%s\n", code); + + return code; +} + +static char *code_generate_vertex(ListBase *nodes) +{ + DynStr *ds = BLI_dynstr_new(); + GPUNode *node; + GPUInput *input; + char *code; + + for (node=nodes->first; node; node=node->next) { + for (input=node->inputs.first; input; input=input->next) { + if (input->source == GPU_SOURCE_ATTRIB && input->attribfirst) { + BLI_dynstr_printf(ds, "attribute %s att%d;\n", + GPU_DATATYPE_STR[input->type], input->attribid); + BLI_dynstr_printf(ds, "varying %s var%d;\n", + GPU_DATATYPE_STR[input->type], input->attribid); + } + } + } + + BLI_dynstr_append(ds, "\n"); + BLI_dynstr_append(ds, datatoc_gpu_shader_vertex_glsl); + + for (node=nodes->first; node; node=node->next) + for (input=node->inputs.first; input; input=input->next) + if (input->source == GPU_SOURCE_ATTRIB && input->attribfirst) { + if(input->attribtype == CD_TANGENT) /* silly exception */ + BLI_dynstr_printf(ds, "\tvar%d = gl_NormalMatrix * ", input->attribid); + else + BLI_dynstr_printf(ds, "\tvar%d = ", input->attribid); + + BLI_dynstr_printf(ds, "att%d;\n", input->attribid); + } + + BLI_dynstr_append(ds, "}\n\n"); + + code = BLI_dynstr_get_cstring(ds); + + BLI_dynstr_free(ds); + + //if(G.f & G_DEBUG) printf("%s\n", code); + + return code; +} + +/* GPU pass binding/unbinding */ + +GPUShader *GPU_pass_shader(GPUPass *pass) +{ + return pass->shader; +} + +void GPU_nodes_extract_dynamic_inputs(GPUPass *pass, ListBase *nodes) +{ + GPUShader *shader = pass->shader; + GPUNode *node; + GPUInput *next, *input; + ListBase *inputs = &pass->inputs; + int extract, z; + + memset(inputs, 0, sizeof(*inputs)); + + if(!shader) + return; + + GPU_shader_bind(shader); + + for (node=nodes->first; node; node=node->next) { + z = 0; + for (input=node->inputs.first; input; input=next, z++) { + next = input->next; + + /* attributes don't need to be bound, they already have + * an id that the drawing functions will use */ + if(input->source == GPU_SOURCE_ATTRIB || + input->source == GPU_SOURCE_BUILTIN) + continue; + + if (input->ima || input->tex) + snprintf(input->shadername, sizeof(input->shadername), "samp%d", input->texid); + else + snprintf(input->shadername, sizeof(input->shadername), "unf%d", input->id); + + /* pass non-dynamic uniforms to opengl */ + extract = 0; + + if(input->ima || input->tex) { + if (input->bindtex) + extract = 1; + } + else if(input->dynamicvec) + extract = 1; + + if(extract) + input->shaderloc = GPU_shader_get_uniform(shader, input->shadername); + + /* extract nodes */ + if(extract) { + BLI_remlink(&node->inputs, input); + BLI_addtail(inputs, input); + } + } + } + + GPU_shader_unbind(shader); +} + +void GPU_pass_bind(GPUPass *pass, double time) +{ + GPUInput *input; + GPUShader *shader = pass->shader; + ListBase *inputs = &pass->inputs; + + if (!shader) + return; + + GPU_shader_bind(shader); + + /* now bind the textures */ + for (input=inputs->first; input; input=input->next) { + if (input->ima) + input->tex = GPU_texture_from_blender(input->ima, input->iuser, time); + + if(input->ima || input->tex) { + if(input->tex) { + GPU_texture_bind(input->tex, input->texid); + GPU_shader_uniform_texture(shader, input->shaderloc, input->tex); + } + } + } +} + +void GPU_pass_update_uniforms(GPUPass *pass) +{ + GPUInput *input; + GPUShader *shader = pass->shader; + ListBase *inputs = &pass->inputs; + + if (!shader) + return; + + /* pass dynamic inputs to opengl, others were removed */ + for (input=inputs->first; input; input=input->next) + if(!(input->ima || input->tex)) + GPU_shader_uniform_vector(shader, input->shaderloc, input->type, 1, + input->dynamicvec); +} + +void GPU_pass_unbind(GPUPass *pass) +{ + GPUInput *input; + GPUShader *shader = pass->shader; + ListBase *inputs = &pass->inputs; + + if (!shader) + return; + + for (input=inputs->first; input; input=input->next) { + if (input->tex) + if(input->bindtex) + GPU_texture_unbind(input->tex); + if (input->ima) + input->tex = 0; + } + + GPU_shader_unbind(shader); +} + +/* Node Link Functions */ + +GPUNodeLink *GPU_node_link_create(int type) +{ + GPUNodeLink *link = MEM_callocN(sizeof(GPUNodeLink), "GPUNodeLink"); + link->type = type; + link->users++; + + return link; +} + +void GPU_node_link_free(GPUNodeLink *link) +{ + link->users--; + + if (link->users < 0) + fprintf(stderr, "GPU_node_link_free: negative refcount\n"); + + if (link->users == 0) { + if (link->output) + link->output->link = NULL; + MEM_freeN(link); + } +} + +/* Node Functions */ + +GPUNode *GPU_node_begin(char *name) +{ + GPUNode *node = MEM_callocN(sizeof(GPUNode), "GPUNode"); + + node->name = name; + + return node; +} + +void GPU_node_end(GPUNode *node) +{ + /* empty */ +} + +static void gpu_node_input_link(GPUNode *node, GPUNodeLink *link, int type) +{ + GPUInput *input; + GPUNode *outnode; + char *name; + + if(link->output) { + outnode = link->output->node; + name = outnode->name; + + if(strcmp(name, "set_value")==0 || strcmp(name, "set_rgb")==0) { + input = MEM_dupallocN(outnode->inputs.first); + input->type = type; + if(input->link) + input->link->users++; + BLI_addtail(&node->inputs, input); + return; + } + } + + input = MEM_callocN(sizeof(GPUInput), "GPUInput"); + input->node = node; + + if(link->builtin) { + /* builtin uniform */ + input->type = type; + input->source = GPU_SOURCE_BUILTIN; + input->builtin = link->builtin; + + MEM_freeN(link); + } + else if(link->output) { + /* link to a node output */ + input->type = type; + input->source = GPU_SOURCE_TEX_PIXEL; + input->link = link; + link->users++; + } + else if(link->dynamictex) { + /* dynamic texture, GPUTexture is updated/deleted externally */ + input->type = type; + input->source = GPU_SOURCE_TEX; + + input->tex = link->dynamictex; + input->textarget = GL_TEXTURE_2D; + input->textype = type; + input->dynamictex = 1; + MEM_freeN(link); + } + else if(link->texture) { + /* small texture created on the fly, like for colorbands */ + input->type = GPU_VEC4; + input->source = GPU_SOURCE_TEX; + input->textype = type; + + if (type == GPU_TEX1D) { + input->tex = GPU_texture_create_1D(link->texturesize, link->ptr1); + input->textarget = GL_TEXTURE_1D; + } + else { + input->tex = GPU_texture_create_2D(link->texturesize, link->texturesize, link->ptr2); + input->textarget = GL_TEXTURE_2D; + } + + MEM_freeN(link->ptr1); + MEM_freeN(link); + } + else if(link->image) { + /* blender image */ + input->type = GPU_VEC4; + input->source = GPU_SOURCE_TEX; + + input->ima = link->ptr1; + input->textarget = GL_TEXTURE_2D; + input->textype = GPU_TEX2D; + MEM_freeN(link); + } + else if(link->attribtype) { + /* vertex attribute */ + input->type = type; + input->source = GPU_SOURCE_ATTRIB; + + input->attribtype = link->attribtype; + BLI_strncpy(input->attribname, link->attribname, sizeof(input->attribname)); + MEM_freeN(link); + } + else { + /* uniform vector */ + input->type = type; + input->source = GPU_SOURCE_VEC_UNIFORM; + + memcpy(input->vec, link->ptr1, type*sizeof(float)); + if(link->dynamic) + input->dynamicvec= link->ptr1; + MEM_freeN(link); + } + + BLI_addtail(&node->inputs, input); +} + +static void gpu_node_input_socket(GPUNode *node, GPUNodeStack *sock) +{ + GPUNodeLink *link; + + if(sock->link) { + gpu_node_input_link(node, sock->link, sock->type); + } + else { + link = GPU_node_link_create(0); + link->ptr1 = sock->vec; + gpu_node_input_link(node, link, sock->type); + } +} + +void GPU_node_output(GPUNode *node, int type, char *name, GPUNodeLink **link) +{ + GPUOutput *output = MEM_callocN(sizeof(GPUOutput), "GPUOutput"); + + output->type = type; + output->node = node; + + if (link) { + *link = output->link = GPU_node_link_create(type); + output->link->output = output; + + /* note: the caller owns the reference to the linkfer, GPUOutput + merely points to it, and if the node is destroyed it will + set that pointer to NULL */ + } + + BLI_addtail(&node->outputs, output); +} + +void GPU_inputs_free(ListBase *inputs) +{ + GPUInput *input; + + for(input=inputs->first; input; input=input->next) { + if(input->link) + GPU_node_link_free(input->link); + else if(input->tex && !input->dynamictex) + GPU_texture_free(input->tex); + } + + BLI_freelistN(inputs); +} + +void GPU_node_free(GPUNode *node) +{ + GPUOutput *output; + + GPU_inputs_free(&node->inputs); + + for (output=node->outputs.first; output; output=output->next) + if (output->link) { + output->link->output = NULL; + GPU_node_link_free(output->link); + } + + BLI_freelistN(&node->outputs); + MEM_freeN(node); +} + +void GPU_nodes_free(ListBase *nodes) +{ + GPUNode *node; + + while (nodes->first) { + node = nodes->first; + BLI_remlink(nodes, node); + GPU_node_free(node); + } +} + +/* vertex attributes */ + +void gpu_nodes_get_vertex_attributes(ListBase *nodes, GPUVertexAttribs *attribs) +{ + GPUNode *node; + GPUInput *input; + int a; + + /* convert attributes requested by node inputs to an array of layers, + * checking for duplicates and assigning id's starting from zero. */ + + memset(attribs, 0, sizeof(*attribs)); + + for(node=nodes->first; node; node=node->next) { + for(input=node->inputs.first; input; input=input->next) { + if(input->source == GPU_SOURCE_ATTRIB) { + for(a=0; atotlayer; a++) { + if(attribs->layer[a].type == input->attribtype && + strcmp(attribs->layer[a].name, input->attribname) == 0) + break; + } + + if(a == attribs->totlayer && a < GPU_MAX_ATTRIB) { + input->attribid = attribs->totlayer++; + input->attribfirst = 1; + + attribs->layer[a].type = input->attribtype; + attribs->layer[a].glindex = input->attribid; + BLI_strncpy(attribs->layer[a].name, input->attribname, + sizeof(attribs->layer[a].name)); + } + else + input->attribid = attribs->layer[a].glindex; + } + } + } +} + +void gpu_nodes_get_builtin_flag(ListBase *nodes, int *builtin) +{ + GPUNode *node; + GPUInput *input; + + *builtin= 0; + + for(node=nodes->first; node; node=node->next) + for(input=node->inputs.first; input; input=input->next) + if(input->source == GPU_SOURCE_BUILTIN) + *builtin |= input->builtin; +} + +/* varargs linking */ + +GPUNodeLink *GPU_attribute(int type, char *name) +{ + GPUNodeLink *link = GPU_node_link_create(0); + + link->attribtype= type; + link->attribname= name; + + return link; +} + +GPUNodeLink *GPU_uniform(float *num) +{ + GPUNodeLink *link = GPU_node_link_create(0); + + link->ptr1= num; + link->ptr2= NULL; + + return link; +} + +GPUNodeLink *GPU_dynamic_uniform(float *num) +{ + GPUNodeLink *link = GPU_node_link_create(0); + + link->ptr1= num; + link->ptr2= NULL; + link->dynamic= 1; + + return link; +} + +GPUNodeLink *GPU_image(Image *ima, ImageUser *iuser) +{ + GPUNodeLink *link = GPU_node_link_create(0); + + link->image= 1; + link->ptr1= ima; + link->ptr2= iuser; + + return link; +} + +GPUNodeLink *GPU_texture(int size, float *pixels) +{ + GPUNodeLink *link = GPU_node_link_create(0); + + link->texture = 1; + link->texturesize = size; + link->ptr1= pixels; + + return link; +} + +GPUNodeLink *GPU_dynamic_texture(GPUTexture *tex) +{ + GPUNodeLink *link = GPU_node_link_create(0); + + link->dynamic = 1; + link->dynamictex = tex; + + return link; +} + +GPUNodeLink *GPU_socket(GPUNodeStack *sock) +{ + GPUNodeLink *link = GPU_node_link_create(0); + + link->socket= sock; + + return link; +} + +GPUNodeLink *GPU_builtin(GPUBuiltin builtin) +{ + GPUNodeLink *link = GPU_node_link_create(0); + + link->builtin= builtin; + + return link; +} + +int GPU_link(GPUMaterial *mat, char *name, ...) +{ + GPUNode *node; + GPUFunction *function; + GPUNodeLink *link, **linkptr; + va_list params; + int i; + + function = GPU_lookup_function(name); + if(!function) { + fprintf(stderr, "GPU failed to find function %s\n", name); + return 0; + } + + node = GPU_node_begin(name); + + va_start(params, name); + for(i=0; itotparam; i++) { + if(function->paramqual[i] != FUNCTION_QUAL_IN) { + linkptr= va_arg(params, GPUNodeLink**); + GPU_node_output(node, function->paramtype[i], "", linkptr); + } + else { + link= va_arg(params, GPUNodeLink*); + gpu_node_input_link(node, link, function->paramtype[i]); + } + } + va_end(params); + + GPU_node_end(node); + + gpu_material_add_node(mat, node); + + return 1; +} + +int GPU_stack_link(GPUMaterial *mat, char *name, GPUNodeStack *in, GPUNodeStack *out, ...) +{ + GPUNode *node; + GPUFunction *function; + GPUNodeLink *link, **linkptr; + va_list params; + int i, totin, totout; + + function = GPU_lookup_function(name); + if(!function) { + fprintf(stderr, "GPU failed to find function %s\n", name); + return 0; + } + + node = GPU_node_begin(name); + totin = 0; + totout = 0; + + if(in) { + for(i = 0; in[i].type != GPU_NONE; i++) { + gpu_node_input_socket(node, &in[i]); + totin++; + } + } + + if(out) { + for(i = 0; out[i].type != GPU_NONE; i++) { + GPU_node_output(node, out[i].type, out[i].name, &out[i].link); + totout++; + } + } + + va_start(params, out); + for(i=0; itotparam; i++) { + if(function->paramqual[i] != FUNCTION_QUAL_IN) { + if(totout == 0) { + linkptr= va_arg(params, GPUNodeLink**); + GPU_node_output(node, function->paramtype[i], "", linkptr); + } + else + totout--; + } + else { + if(totin == 0) { + link= va_arg(params, GPUNodeLink*); + if(link->socket) + gpu_node_input_socket(node, link->socket); + else + gpu_node_input_link(node, link, function->paramtype[i]); + } + else + totin--; + } + } + va_end(params); + + GPU_node_end(node); + + gpu_material_add_node(mat, node); + + return 1; +} + +int GPU_link_changed(GPUNodeLink *link) +{ + GPUNode *node; + GPUInput *input; + char *name; + + if(link->output) { + node = link->output->node; + name = node->name; + + if(strcmp(name, "set_value")==0 || strcmp(name, "set_rgb")==0) { + input = node->inputs.first; + return (input->link != NULL); + } + + return 1; + } + else + return 0; +} + +/* Pass create/free */ + +void gpu_nodes_tag(GPUNodeLink *link) +{ + GPUNode *node; + GPUInput *input; + + if(!link->output) + return; + + node = link->output->node; + if(node->tag) + return; + + node->tag= 1; + for(input=node->inputs.first; input; input=input->next) + if(input->link) + gpu_nodes_tag(input->link); +} + +void gpu_nodes_prune(ListBase *nodes, GPUNodeLink *outlink) +{ + GPUNode *node, *next; + + for(node=nodes->first; node; node=node->next) + node->tag= 0; + + gpu_nodes_tag(outlink); + + for(node=nodes->first; node; node=next) { + next = node->next; + + if(!node->tag) { + BLI_remlink(nodes, node); + GPU_node_free(node); + } + } +} + +GPUPass *GPU_generate_pass(ListBase *nodes, GPUNodeLink *outlink, GPUVertexAttribs *attribs, int *builtins, const char *name) +{ + GPUShader *shader; + GPUPass *pass; + char *vertexcode, *fragmentcode; + + if(!FUNCTION_LIB) { + GPU_nodes_free(nodes); + return NULL; + } + + /* prune unused nodes */ + gpu_nodes_prune(nodes, outlink); + + gpu_nodes_get_vertex_attributes(nodes, attribs); + gpu_nodes_get_builtin_flag(nodes, builtins); + + /* generate code and compile with opengl */ + fragmentcode = code_generate_fragment(nodes, outlink->output, name); + vertexcode = code_generate_vertex(nodes); + shader = GPU_shader_create(vertexcode, fragmentcode, FUNCTION_LIB); + MEM_freeN(fragmentcode); + MEM_freeN(vertexcode); + + /* failed? */ + if (!shader) { + memset(attribs, 0, sizeof(*attribs)); + memset(builtins, 0, sizeof(*builtins)); + GPU_nodes_free(nodes); + return NULL; + } + + /* create pass */ + pass = MEM_callocN(sizeof(GPUPass), "GPUPass"); + + pass->output = outlink->output; + pass->shader = shader; + + /* extract dynamic inputs and throw away nodes */ + GPU_nodes_extract_dynamic_inputs(pass, nodes); + GPU_nodes_free(nodes); + + return pass; +} + +void GPU_pass_free(GPUPass *pass) +{ + GPU_shader_free(pass->shader); + GPU_inputs_free(&pass->inputs); + MEM_freeN(pass); +} + diff --git a/source/blender/gpu/intern/gpu_codegen.h b/source/blender/gpu/intern/gpu_codegen.h new file mode 100644 index 00000000000..53b52f24f16 --- /dev/null +++ b/source/blender/gpu/intern/gpu_codegen.h @@ -0,0 +1,87 @@ +/** + * $Id$ + * + * ***** BEGIN GPL LICENSE BLOCK ***** + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. The Blender + * Foundation also sells licenses for use in proprietary software under + * the Blender License. See http://www.blender.org/BL/ for information + * about this. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software Foundation, + * Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. + * + * The Original Code is Copyright (C) 2005 Blender Foundation. + * All rights reserved. + * + * The Original Code is: all of this file. + * + * Contributor(s): Brecht Van Lommel. + * + * ***** END GPL LICENSE BLOCK ***** + */ + +#ifndef __GPU_CODEGEN_H__ +#define __GPU_CODEGEN_H__ + +#include "DNA_listBase.h" + +struct ListBase; +struct GPUShader; +struct GPUOutput; +struct GPUNode; +struct GPUVertexAttribs; + +#define MAX_FUNCTION_NAME 64 +#define MAX_PARAMETER 32 + +#define FUNCTION_QUAL_IN 0 +#define FUNCTION_QUAL_OUT 1 +#define FUNCTION_QUAL_INOUT 2 + +typedef struct GPUFunction { + char name[MAX_FUNCTION_NAME]; + int paramtype[MAX_PARAMETER]; + int paramqual[MAX_PARAMETER]; + int totparam; +} GPUFunction; + +GPUFunction *GPU_lookup_function(char *name); + +/* Pass Generation + - Takes a list of nodes and a desired output, and makes a pass. This + will take ownership of the nodes and free them early if unused or + at the end if used. +*/ + +struct GPUPass; +typedef struct GPUPass GPUPass; + +GPUPass *GPU_generate_pass(ListBase *nodes, struct GPUNodeLink *outlink, + struct GPUVertexAttribs *attribs, int *builtin, const char *name); + +struct GPUShader *GPU_pass_shader(GPUPass *pass); + +void GPU_pass_bind(GPUPass *pass, double time); +void GPU_pass_update_uniforms(GPUPass *pass); +void GPU_pass_unbind(GPUPass *pass); + +void GPU_pass_free(GPUPass *pass); + +/* Material calls */ + +char *GPU_builtin_name(GPUBuiltin builtin); +void gpu_material_add_node(struct GPUMaterial *material, struct GPUNode *node); +int GPU_link_changed(struct GPUNodeLink *link); + +#endif + diff --git a/source/blender/gpu/intern/gpu_draw.c b/source/blender/gpu/intern/gpu_draw.c new file mode 100644 index 00000000000..3ff8e7fa559 --- /dev/null +++ b/source/blender/gpu/intern/gpu_draw.c @@ -0,0 +1,1167 @@ +/** + * $Id$ + * + * ***** BEGIN GPL LICENSE BLOCK ***** + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. The Blender + * Foundation also sells licenses for use in proprietary software under + * the Blender License. See http://www.blender.org/BL/ for information + * about this. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software Foundation, + * Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. + * + * The Original Code is Copyright (C) 2005 Blender Foundation. + * All rights reserved. + * + * The Original Code is: all of this file. + * + * Contributor(s): Brecht Van Lommel. + * + * ***** END GPL LICENSE BLOCK ***** + */ + +#include + +#include "GL/glew.h" + +#include "DNA_image_types.h" +#include "DNA_lamp_types.h" +#include "DNA_material_types.h" +#include "DNA_meshdata_types.h" +#include "DNA_node_types.h" +#include "DNA_object_types.h" +#include "DNA_scene_types.h" +#include "DNA_userdef_types.h" +#include "DNA_view3d_types.h" + +#include "MEM_guardedalloc.h" + +#include "IMB_imbuf.h" +#include "IMB_imbuf_types.h" + +#include "BKE_bmfont.h" +#include "BKE_global.h" +#include "BKE_image.h" +#include "BKE_main.h" +#include "BKE_material.h" +#include "BKE_node.h" +#include "BKE_object.h" +#include "BKE_utildefines.h" + +#include "GPU_extensions.h" +#include "GPU_material.h" +#include "GPU_draw.h" + +/* These are some obscure rendering functions shared between the + * game engine and the blender, in this module to avoid duplicaten + * and abstract them away from the rest a bit */ + +/* Text Rendering */ + +static void gpu_mcol(unsigned int ucol) +{ + /* mcol order is swapped */ + char *cp= (char *)&ucol; + glColor3ub(cp[3], cp[2], cp[1]); +} + +void GPU_render_text(MTFace *tface, int mode, + const char *textstr, int textlen, unsigned int *col, + float *v1, float *v2, float *v3, float *v4, int glattrib) +{ + if (mode & TF_BMFONT) { + Image* ima; + int characters, index, character; + float centerx, centery, sizex, sizey, transx, transy, movex, movey, advance; + + characters = textlen; + + ima = (Image*)tface->tpage; + if (ima == NULL) + characters = 0; + + // color has been set + if (tface->mode & TF_OBCOL) + col= NULL; + else if (!col) + glColor3f(1.0f, 1.0f, 1.0f); + + glPushMatrix(); + for (index = 0; index < characters; index++) { + float uv[4][2]; + + // lets calculate offset stuff + character = textstr[index]; + + // space starts at offset 1 + // character = character - ' ' + 1; + matrixGlyph((ImBuf *)ima->ibufs.first, character, & centerx, ¢ery, + &sizex, &sizey, &transx, &transy, &movex, &movey, &advance); + + uv[0][0] = (tface->uv[0][0] - centerx) * sizex + transx; + uv[0][1] = (tface->uv[0][1] - centery) * sizey + transy; + uv[1][0] = (tface->uv[1][0] - centerx) * sizex + transx; + uv[1][1] = (tface->uv[1][1] - centery) * sizey + transy; + uv[2][0] = (tface->uv[2][0] - centerx) * sizex + transx; + uv[2][1] = (tface->uv[2][1] - centery) * sizey + transy; + + glBegin(GL_POLYGON); + if(glattrib >= 0) glVertexAttrib2fvARB(glattrib, uv[0]); + else glTexCoord2fv(uv[0]); + if(col) gpu_mcol(col[0]); + glVertex3f(sizex * v1[0] + movex, sizey * v1[1] + movey, v1[2]); + + if(glattrib >= 0) glVertexAttrib2fvARB(glattrib, uv[1]); + else glTexCoord2fv(uv[1]); + if(col) gpu_mcol(col[1]); + glVertex3f(sizex * v2[0] + movex, sizey * v2[1] + movey, v2[2]); + + if(glattrib >= 0) glVertexAttrib2fvARB(glattrib, uv[2]); + else glTexCoord2fv(uv[2]); + if(col) gpu_mcol(col[2]); + glVertex3f(sizex * v3[0] + movex, sizey * v3[1] + movey, v3[2]); + + if(v4) { + uv[3][0] = (tface->uv[3][0] - centerx) * sizex + transx; + uv[3][1] = (tface->uv[3][1] - centery) * sizey + transy; + + if(glattrib >= 0) glVertexAttrib2fvARB(glattrib, uv[3]); + else glTexCoord2fv(uv[3]); + if(col) gpu_mcol(col[3]); + glVertex3f(sizex * v4[0] + movex, sizey * v4[1] + movey, v4[2]); + } + glEnd(); + + glTranslatef(advance, 0.0, 0.0); + } + glPopMatrix(); + } +} + +/* Checking powers of two for images since opengl 1.x requires it */ + +static int is_pow2(int num) +{ + /* (n&(n-1)) zeros the least significant bit of n */ + return ((num)&(num-1))==0; +} + +static int smaller_pow2(int num) +{ + while (!is_pow2(num)) + num= num&(num-1); + + return num; +} + +static int is_pow2_limit(int num) +{ + /* take texture clamping into account */ + if (U.glreslimit != 0 && num > U.glreslimit) + return 0; + + return ((num)&(num-1))==0; +} + +static int smaller_pow2_limit(int num) +{ + /* take texture clamping into account */ + if (U.glreslimit != 0 && num > U.glreslimit) + return U.glreslimit; + + return smaller_pow2(num); +} + +/* Current OpenGL state caching for GPU_set_tpage */ + +static struct GPUTextureState { + int curtile, tile; + int curtilemode, tilemode; + int curtileXRep, tileXRep; + int curtileYRep, tileYRep; + Image *ima, *curima; + + int domipmap, linearmipmap; + + int alphamode; + MTFace *lasttface; +} GTS = {0, 0, 0, 0, 0, 0, 0, 0, NULL, NULL, 1, 0, -1, NULL}; + +/* Mipmap settings */ + +void GPU_set_mipmap(int mipmap) +{ + if (GTS.domipmap != (mipmap != 0)) { + GPU_free_images(); + GTS.domipmap = mipmap != 0; + } +} + +void GPU_set_linear_mipmap(int linear) +{ + if (GTS.linearmipmap != (linear != 0)) { + GPU_free_images(); + GTS.linearmipmap = linear != 0; + } +} + +static int gpu_get_mipmap(void) +{ + return GTS.domipmap && (!(G.f & G_TEXTUREPAINT)); +} + +static GLenum gpu_get_mipmap_filter() +{ + return GTS.linearmipmap? GL_LINEAR_MIPMAP_LINEAR: GL_LINEAR_MIPMAP_NEAREST; +} + +/* Set OpenGL state for an MTFace */ + +static void gpu_make_repbind(Image *ima) +{ + ImBuf *ibuf; + + ibuf = BKE_image_get_ibuf(ima, NULL); + if(ibuf==NULL) + return; + + if(ima->repbind) { + glDeleteTextures(ima->totbind, (GLuint *)ima->repbind); + MEM_freeN(ima->repbind); + ima->repbind= 0; + ima->tpageflag &= ~IMA_MIPMAP_COMPLETE; + } + + ima->totbind= ima->xrep*ima->yrep; + + if(ima->totbind>1) + ima->repbind= MEM_callocN(sizeof(int)*ima->totbind, "repbind"); +} + +static void gpu_clear_tpage() +{ + if(GTS.lasttface==0) + return; + + GTS.lasttface= 0; + GTS.curtile= 0; + GTS.curima= 0; + if(GTS.curtilemode!=0) { + glMatrixMode(GL_TEXTURE); + glLoadIdentity(); + glMatrixMode(GL_MODELVIEW); + } + GTS.curtilemode= 0; + GTS.curtileXRep=0; + GTS.curtileYRep=0; + GTS.alphamode= -1; + + glDisable(GL_BLEND); + glDisable(GL_TEXTURE_2D); + glDisable(GL_TEXTURE_GEN_S); + glDisable(GL_TEXTURE_GEN_T); + glDisable(GL_ALPHA_TEST); +} + +static void gpu_set_blend_mode(GPUBlendMode blendmode) +{ + if(blendmode == GPU_BLEND_SOLID) { + glDisable(GL_BLEND); + glDisable(GL_ALPHA_TEST); + glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); + } + else if(blendmode==GPU_BLEND_ADD) { + glEnable(GL_BLEND); + glBlendFunc(GL_ONE, GL_ONE); + glDisable(GL_ALPHA_TEST); + } + else if(blendmode==GPU_BLEND_ALPHA) { + glEnable(GL_BLEND); + glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); + + /* if U.glalphaclip == 1.0, some cards go bonkers... + * turn off alpha test in this case */ + + /* added after 2.45 to clip alpha */ + if(U.glalphaclip == 1.0) { + glDisable(GL_ALPHA_TEST); + } + else { + glEnable(GL_ALPHA_TEST); + glAlphaFunc(GL_GREATER, U.glalphaclip); + } + } + else if(blendmode==GPU_BLEND_CLIP) { + glDisable(GL_BLEND); + glEnable(GL_ALPHA_TEST); + glAlphaFunc(GL_GREATER, 0.5f); + } +} + +static void gpu_verify_alpha_mode(MTFace *tface) +{ + /* verify alpha blending modes */ + if(GTS.alphamode == tface->transp) + return; + + gpu_set_blend_mode(tface->transp); + GTS.alphamode= tface->transp; +} + +static void gpu_verify_reflection(Image *ima) +{ + if (ima && (ima->flag & IMA_REFLECT)) { + /* enable reflection mapping */ + glTexGeni(GL_S, GL_TEXTURE_GEN_MODE, GL_SPHERE_MAP); + glTexGeni(GL_T, GL_TEXTURE_GEN_MODE, GL_SPHERE_MAP); + + glEnable(GL_TEXTURE_GEN_S); + glEnable(GL_TEXTURE_GEN_T); + } + else { + /* disable reflection mapping */ + glDisable(GL_TEXTURE_GEN_S); + glDisable(GL_TEXTURE_GEN_T); + } +} + +int GPU_verify_image(Image *ima, int tftile, int tfmode, int compare) +{ + ImBuf *ibuf = NULL; + unsigned int *bind = NULL; + int rectw, recth, tpx=0, tpy=0, y; + unsigned int *rectrow, *tilerectrow; + unsigned int *tilerect= NULL, *scalerect= NULL, *rect= NULL; + short texwindx, texwindy, texwinsx, texwinsy; + + /* initialize tile mode and number of repeats */ + GTS.ima = ima; + GTS.tilemode= (tfmode & TF_TILES) || (ima && (ima->tpageflag & IMA_TWINANIM)); + GTS.tileXRep = 0; + GTS.tileYRep = 0; + + /* setting current tile according to frame */ + if(ima && (ima->tpageflag & IMA_TWINANIM)) + GTS.tile= ima->lastframe; + else + GTS.tile= tftile; + + if(ima) { + GTS.tileXRep = ima->xrep; + GTS.tileYRep = ima->yrep; + } + + /* if same image & tile, we're done */ + if(compare && ima == GTS.curima && GTS.curtile == GTS.tile && + GTS.tilemode == GTS.curtilemode && GTS.curtileXRep == GTS.tileXRep && + GTS.curtileYRep == GTS.tileYRep) + return (ima!=0); + + /* if tiling mode or repeat changed, change texture matrix to fit */ + if(GTS.tilemode!=GTS.curtilemode || GTS.curtileXRep!=GTS.tileXRep || + GTS.curtileYRep != GTS.tileYRep) { + + glMatrixMode(GL_TEXTURE); + glLoadIdentity(); + + if((tfmode & TF_TILES) && ima!=NULL) + glScalef(ima->xrep, ima->yrep, 1.0); + + glMatrixMode(GL_MODELVIEW); + } + + /* check if we have a valid image */ + if(ima==NULL || ima->ok==0) + return 0; + + /* check if we have a valid image buffer */ + ibuf= BKE_image_get_ibuf(ima, NULL); + + if(ibuf==NULL) + return 0; + + /* ensure we have a char buffer and not only float */ + if ((ibuf->rect==NULL) && ibuf->rect_float) + IMB_rect_from_float(ibuf); + + if(GTS.tilemode) { + /* tiled mode */ + if(ima->repbind==0) gpu_make_repbind(ima); + if(GTS.tile>=ima->totbind) GTS.tile= 0; + + /* this happens when you change repeat buttons */ + if(ima->repbind) bind= &ima->repbind[GTS.tile]; + else bind= &ima->bindcode; + + if(*bind==0) { + + texwindx= ibuf->x/ima->xrep; + texwindy= ibuf->y/ima->yrep; + + if(GTS.tile>=ima->xrep*ima->yrep) + GTS.tile= ima->xrep*ima->yrep-1; + + texwinsy= GTS.tile / ima->xrep; + texwinsx= GTS.tile - texwinsy*ima->xrep; + + texwinsx*= texwindx; + texwinsy*= texwindy; + + tpx= texwindx; + tpy= texwindy; + + rect= ibuf->rect + texwinsy*ibuf->x + texwinsx; + } + } + else { + /* regular image mode */ + bind= &ima->bindcode; + + if(*bind==0) { + tpx= ibuf->x; + tpy= ibuf->y; + rect= ibuf->rect; + } + } + + if(*bind != 0) { + /* enable opengl drawing with textures */ + glBindTexture(GL_TEXTURE_2D, *bind); + return *bind; + } + + rectw = tpx; + recth = tpy; + + /* for tiles, copy only part of image into buffer */ + if (GTS.tilemode) { + tilerect= MEM_mallocN(rectw*recth*sizeof(*tilerect), "tilerect"); + + for (y=0; yx]; + tilerectrow= &tilerect[y*rectw]; + + memcpy(tilerectrow, rectrow, tpx*sizeof(*rectrow)); + } + + rect= tilerect; + } + + /* scale if not a power of two */ + if (!is_pow2_limit(rectw) || !is_pow2_limit(recth)) { + rectw= smaller_pow2_limit(rectw); + recth= smaller_pow2_limit(recth); + + scalerect= MEM_mallocN(rectw*recth*sizeof(*scalerect), "scalerect"); + gluScaleImage(GL_RGBA, tpx, tpy, GL_UNSIGNED_BYTE, rect, rectw, recth, GL_UNSIGNED_BYTE, scalerect); + rect= scalerect; + } + + /* create image */ + glGenTextures(1, (GLuint *)bind); + glBindTexture( GL_TEXTURE_2D, *bind); + + if (!gpu_get_mipmap()) { + glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, rectw, recth, 0, GL_RGBA, GL_UNSIGNED_BYTE, rect); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); + } + else { + gluBuild2DMipmaps(GL_TEXTURE_2D, GL_RGBA, rectw, recth, GL_RGBA, GL_UNSIGNED_BYTE, rect); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, gpu_get_mipmap_filter()); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); + + ima->tpageflag |= IMA_MIPMAP_COMPLETE; + } + + /* set to modulate with vertex color */ + glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE); + + /* clean up */ + if (tilerect) + MEM_freeN(tilerect); + if (scalerect) + MEM_freeN(scalerect); + + return *bind; +} + +static void gpu_verify_repeat(Image *ima) +{ + /* set either clamp or repeat in X/Y */ + if (ima->tpageflag & IMA_CLAMP_U) + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); + else + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); + + if (ima->tpageflag & IMA_CLAMP_V) + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); + else + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); +} + +int GPU_set_tpage(MTFace *tface) +{ + Image *ima; + + /* check if we need to clear the state */ + if(tface==0) { + gpu_clear_tpage(); + return 0; + } + + ima= tface->tpage; + GTS.lasttface= tface; + + gpu_verify_alpha_mode(tface); + gpu_verify_reflection(ima); + + if(GPU_verify_image(ima, tface->tile, tface->mode, 1)) { + GTS.curtile= GTS.tile; + GTS.curima= GTS.ima; + GTS.curtilemode= GTS.tilemode; + GTS.curtileXRep = GTS.tileXRep; + GTS.curtileYRep = GTS.tileYRep; + + glEnable(GL_TEXTURE_2D); + } + else { + glDisable(GL_TEXTURE_2D); + + GTS.curtile= 0; + GTS.curima= 0; + GTS.curtilemode= 0; + GTS.curtileXRep = 0; + GTS.curtileYRep = 0; + + return 0; + } + + gpu_verify_repeat(ima); + + /* Did this get lost in the image recode? */ + /* tag_image_time(ima);*/ + + return 1; +} + +/* these two functions are called on entering and exiting texture paint mode, + temporary disabling/enabling mipmapping on all images for quick texture + updates with glTexSubImage2D. images that didn't change don't have to be + re-uploaded to OpenGL */ +void GPU_paint_set_mipmap(int mipmap) +{ + Image* ima; + + if(!GTS.domipmap) + return; + + if(mipmap) { + for(ima=G.main->image.first; ima; ima=ima->id.next) { + if(ima->bindcode) { + if(ima->tpageflag & IMA_MIPMAP_COMPLETE) { + glBindTexture(GL_TEXTURE_2D, ima->bindcode); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, gpu_get_mipmap_filter()); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); + } + else + GPU_free_image(ima); + } + } + + } + else { + for(ima=G.main->image.first; ima; ima=ima->id.next) { + if(ima->bindcode) { + glBindTexture(GL_TEXTURE_2D, ima->bindcode); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); + } + } + } +} + +void GPU_paint_update_image(Image *ima, int x, int y, int w, int h) +{ + ImBuf *ibuf; + + ibuf = BKE_image_get_ibuf(ima, NULL); + + if (ima->repbind || gpu_get_mipmap() || !ima->bindcode || !ibuf || + (!is_pow2(ibuf->x) || !is_pow2(ibuf->y)) || + (w == 0) || (h == 0)) { + /* these cases require full reload still */ + GPU_free_image(ima); + } + else { + /* for the special case, we can do a partial update + * which is much quicker for painting */ + GLint row_length, skip_pixels, skip_rows; + + glGetIntegerv(GL_UNPACK_ROW_LENGTH, &row_length); + glGetIntegerv(GL_UNPACK_SKIP_PIXELS, &skip_pixels); + glGetIntegerv(GL_UNPACK_SKIP_ROWS, &skip_rows); + + if ((ibuf->rect==NULL) && ibuf->rect_float) + IMB_rect_from_float(ibuf); + + glBindTexture(GL_TEXTURE_2D, ima->bindcode); + + glPixelStorei(GL_UNPACK_ROW_LENGTH, ibuf->x); + glPixelStorei(GL_UNPACK_SKIP_PIXELS, x); + glPixelStorei(GL_UNPACK_SKIP_ROWS, y); + + glTexSubImage2D(GL_TEXTURE_2D, 0, x, y, w, h, GL_RGBA, + GL_UNSIGNED_BYTE, ibuf->rect); + + glPixelStorei(GL_UNPACK_ROW_LENGTH, row_length); + glPixelStorei(GL_UNPACK_SKIP_PIXELS, skip_pixels); + glPixelStorei(GL_UNPACK_SKIP_ROWS, skip_rows); + + if(ima->tpageflag & IMA_MIPMAP_COMPLETE) + ima->tpageflag &= ~IMA_MIPMAP_COMPLETE; + } +} + +void GPU_update_images_framechange(void) +{ + Image *ima; + + for(ima=G.main->image.first; ima; ima=ima->id.next) { + if(ima->tpageflag & IMA_TWINANIM) { + if(ima->twend >= ima->xrep*ima->yrep) + ima->twend= ima->xrep*ima->yrep-1; + + /* check: is bindcode not in the array? free. (to do) */ + + ima->lastframe++; + if(ima->lastframe > ima->twend) + ima->lastframe= ima->twsta; + } + } +} + +int GPU_update_image_time(Image *ima, double time) +{ + int inc = 0; + float diff; + int newframe; + + if (!ima) + return 0; + + if (ima->lastupdate<0) + ima->lastupdate = 0; + + if (ima->lastupdate>time) + ima->lastupdate=(float)time; + + if(ima->tpageflag & IMA_TWINANIM) { + if(ima->twend >= ima->xrep*ima->yrep) ima->twend= ima->xrep*ima->yrep-1; + + /* check: is the bindcode not in the array? Then free. (still to do) */ + + diff = (float)(time-ima->lastupdate); + inc = (int)(diff*(float)ima->animspeed); + + ima->lastupdate+=((float)inc/(float)ima->animspeed); + + newframe = ima->lastframe+inc; + + if(newframe > (int)ima->twend) { + if(ima->twend-ima->twsta != 0) + newframe = (int)ima->twsta-1 + (newframe-ima->twend)%(ima->twend-ima->twsta); + else + newframe = ima->twsta; + } + + ima->lastframe = newframe; + } + + return inc; +} + +void GPU_free_image(Image *ima) +{ + /* free regular image binding */ + if(ima->bindcode) { + glDeleteTextures(1, (GLuint *)&ima->bindcode); + ima->bindcode= 0; + ima->tpageflag &= ~IMA_MIPMAP_COMPLETE; + } + + /* free glsl image binding */ + if(ima->gputexture) { + GPU_texture_free(ima->gputexture); + ima->gputexture= NULL; + } + + /* free repeated image binding */ + if(ima->repbind) { + glDeleteTextures(ima->totbind, (GLuint *)ima->repbind); + + MEM_freeN(ima->repbind); + ima->repbind= NULL; + ima->tpageflag &= ~IMA_MIPMAP_COMPLETE; + } +} + +void GPU_free_images(void) +{ + Image* ima; + + for(ima=G.main->image.first; ima; ima=ima->id.next) + GPU_free_image(ima); +} + +/* OpenGL Materials */ + +/* materials start counting at # one.... */ +#define MAXMATBUF (MAXMAT+1) + +/* OpenGL state caching for materials */ + +static struct GPUMaterialState { + float matbuf[MAXMATBUF][2][4]; + int totmat; + + Material *gmatbuf[MAXMATBUF]; + Material *gboundmat; + Object *gob; + Scene *gscene; + + GPUBlendMode blendmode[MAXMATBUF]; + int alphapass; + + int lastmatnr, lastretval; + GPUBlendMode lastblendmode; +} GMS; + +Material *gpu_active_node_material(Material *ma) +{ + if(ma && ma->use_nodes && ma->nodetree) { + bNode *node= nodeGetActiveID(ma->nodetree, ID_MA); + + if(node) + return (Material *)node->id; + else + return NULL; + } + + return ma; +} + +void GPU_set_object_materials(Scene *scene, Object *ob, int glsl, int *do_alpha_pass) +{ + extern Material defmaterial; /* from material.c */ + Material *ma; + GPUMaterial *gpumat; + GPUBlendMode blendmode; + int a; + + /* initialize state */ + memset(&GMS, 0, sizeof(GMS)); + GMS.lastmatnr = -1; + GMS.lastretval = -1; + GMS.lastblendmode = GPU_BLEND_SOLID; + + GMS.gob = ob; + GMS.gscene = scene; + GMS.totmat= ob->totcol; + + GMS.alphapass = (G.vd && G.vd->transp); + if(do_alpha_pass) + *do_alpha_pass = 0; + + /* no materials assigned? */ + if(ob->totcol==0) { + GMS.matbuf[0][0][0]= defmaterial.r; + GMS.matbuf[0][0][1]= defmaterial.g; + GMS.matbuf[0][0][2]= defmaterial.b; + GMS.matbuf[0][0][3]= 1.0; + + GMS.matbuf[0][1][0]= defmaterial.specr; + GMS.matbuf[0][1][1]= defmaterial.specg; + GMS.matbuf[0][1][2]= defmaterial.specb; + GMS.matbuf[0][1][3]= 1.0; + + /* do material 1 too, for displists! */ + QUATCOPY(GMS.matbuf[1][0], GMS.matbuf[0][0]); + QUATCOPY(GMS.matbuf[1][1], GMS.matbuf[0][1]); + + if(glsl) { + GMS.gmatbuf[0]= &defmaterial; + GPU_material_from_blender(GMS.gscene, &defmaterial); + } + + GMS.blendmode[0]= GPU_BLEND_SOLID; + } + + /* setup materials */ + for(a=1; a<=ob->totcol; a++) { + /* find a suitable material */ + ma= give_current_material(ob, a); + if(!glsl) ma= gpu_active_node_material(ma); + if(ma==NULL) ma= &defmaterial; + + /* this shouldn't happen .. */ + if(a>=MAXMATBUF) + continue; + + /* create glsl material if requested */ + gpumat = (glsl)? GPU_material_from_blender(GMS.gscene, ma): NULL; + + if(gpumat) { + /* do glsl only if creating it succeed, else fallback */ + GMS.gmatbuf[a]= ma; + blendmode = GPU_material_blend_mode(gpumat, ob->col); + } + else { + /* fixed function opengl materials */ + if (ma->mode & MA_SHLESS) { + GMS.matbuf[a][0][0]= ma->r; + GMS.matbuf[a][0][1]= ma->g; + GMS.matbuf[a][0][2]= ma->b; + } else { + GMS.matbuf[a][0][0]= (ma->ref+ma->emit)*ma->r; + GMS.matbuf[a][0][1]= (ma->ref+ma->emit)*ma->g; + GMS.matbuf[a][0][2]= (ma->ref+ma->emit)*ma->b; + + GMS.matbuf[a][1][0]= ma->spec*ma->specr; + GMS.matbuf[a][1][1]= ma->spec*ma->specg; + GMS.matbuf[a][1][2]= ma->spec*ma->specb; + GMS.matbuf[a][1][3]= 1.0; + } + + blendmode = (ma->alpha == 1.0f)? GPU_BLEND_SOLID: GPU_BLEND_ALPHA; + if(do_alpha_pass && GMS.alphapass) + GMS.matbuf[a][0][3]= ma->alpha; + else + GMS.matbuf[a][0][3]= 1.0f; + } + + /* setting do_alpha_pass = 1 indicates this object needs to be + * drawn in a second alpha pass for improved blending */ + if(do_alpha_pass) { + GMS.blendmode[a]= blendmode; + if(ELEM(blendmode, GPU_BLEND_ALPHA, GPU_BLEND_ADD) && !GMS.alphapass) + *do_alpha_pass= 1; + } + } + + /* let's start with a clean state */ + GPU_disable_material(); +} + +int GPU_enable_material(int nr, void *attribs) +{ + GPUVertexAttribs *gattribs = attribs; + GPUMaterial *gpumat; + GPUBlendMode blendmode; + + /* prevent index to use un-initialized array items */ + if(nr>GMS.totmat) + nr= GMS.totmat; + + if(gattribs) + memset(gattribs, 0, sizeof(*gattribs)); + + /* keep current material */ + if(nr>=MAXMATBUF || nr==GMS.lastmatnr) + return GMS.lastretval; + + /* unbind glsl material */ + if(GMS.gboundmat) { + if(GMS.alphapass) glDepthMask(0); + GPU_material_unbind(GPU_material_from_blender(GMS.gscene, GMS.gboundmat)); + GMS.gboundmat= NULL; + } + + /* draw materials with alpha in alpha pass */ + GMS.lastmatnr = nr; + GMS.lastretval = ELEM(GMS.blendmode[nr], GPU_BLEND_SOLID, GPU_BLEND_CLIP); + if(GMS.alphapass) + GMS.lastretval = !GMS.lastretval; + + if(GMS.lastretval) { + if(gattribs && GMS.gmatbuf[nr]) { + /* bind glsl material and get attributes */ + Material *mat = GMS.gmatbuf[nr]; + + gpumat = GPU_material_from_blender(GMS.gscene, mat); + GPU_material_vertex_attributes(gpumat, gattribs); + GPU_material_bind(gpumat, GMS.gob->lay, 1.0); + GPU_material_bind_uniforms(gpumat, GMS.gob->obmat, G.vd->viewmat, G.vd->viewinv, GMS.gob->col); + GMS.gboundmat= mat; + + if(GMS.alphapass) glDepthMask(1); + } + else { + /* or do fixed function opengl material */ + glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE, GMS.matbuf[nr][0]); + glMaterialfv(GL_FRONT_AND_BACK, GL_SPECULAR, GMS.matbuf[nr][1]); + } + + /* set (alpha) blending mode */ + blendmode = (GMS.alphapass)? GPU_BLEND_ALPHA: GPU_BLEND_SOLID; + GPU_set_material_blend_mode(blendmode); + } + + return GMS.lastretval; +} + +void GPU_set_material_blend_mode(int blendmode) +{ + if(GMS.lastblendmode == blendmode) + return; + + gpu_set_blend_mode(blendmode); + GMS.lastblendmode = blendmode; +} + +int GPU_get_material_blend_mode(void) +{ + return GMS.lastblendmode; +} + +void GPU_disable_material(void) +{ + GMS.lastmatnr= -1; + GMS.lastretval= 1; + + if(GMS.gboundmat) { + if(GMS.alphapass) glDepthMask(0); + GPU_material_unbind(GPU_material_from_blender(GMS.gscene, GMS.gboundmat)); + GMS.gboundmat= NULL; + } + + GPU_set_material_blend_mode(GPU_BLEND_SOLID); +} + +/* Lights */ + +int GPU_default_lights(void) +{ + int a, count = 0; + + /* initialize */ + if(U.light[0].flag==0 && U.light[1].flag==0 && U.light[2].flag==0) { + U.light[0].flag= 1; + U.light[0].vec[0]= -0.3; U.light[0].vec[1]= 0.3; U.light[0].vec[2]= 0.9; + U.light[0].col[0]= 0.8; U.light[0].col[1]= 0.8; U.light[0].col[2]= 0.8; + U.light[0].spec[0]= 0.5; U.light[0].spec[1]= 0.5; U.light[0].spec[2]= 0.5; + U.light[0].spec[3]= 1.0; + + U.light[1].flag= 0; + U.light[1].vec[0]= 0.5; U.light[1].vec[1]= 0.5; U.light[1].vec[2]= 0.1; + U.light[1].col[0]= 0.4; U.light[1].col[1]= 0.4; U.light[1].col[2]= 0.8; + U.light[1].spec[0]= 0.3; U.light[1].spec[1]= 0.3; U.light[1].spec[2]= 0.5; + U.light[1].spec[3]= 1.0; + + U.light[2].flag= 0; + U.light[2].vec[0]= 0.3; U.light[2].vec[1]= -0.3; U.light[2].vec[2]= -0.2; + U.light[2].col[0]= 0.8; U.light[2].col[1]= 0.5; U.light[2].col[2]= 0.4; + U.light[2].spec[0]= 0.5; U.light[2].spec[1]= 0.4; U.light[2].spec[2]= 0.3; + U.light[2].spec[3]= 1.0; + } + + glLightfv(GL_LIGHT0, GL_POSITION, U.light[0].vec); + glLightfv(GL_LIGHT0, GL_DIFFUSE, U.light[0].col); + glLightfv(GL_LIGHT0, GL_SPECULAR, U.light[0].spec); + + glLightfv(GL_LIGHT1, GL_POSITION, U.light[1].vec); + glLightfv(GL_LIGHT1, GL_DIFFUSE, U.light[1].col); + glLightfv(GL_LIGHT1, GL_SPECULAR, U.light[1].spec); + + glLightfv(GL_LIGHT2, GL_POSITION, U.light[2].vec); + glLightfv(GL_LIGHT2, GL_DIFFUSE, U.light[2].col); + glLightfv(GL_LIGHT2, GL_SPECULAR, U.light[2].spec); + + for(a=0; a<8; a++) { + if(a<3) { + if(U.light[a].flag) { + glEnable(GL_LIGHT0+a); + count++; + } + else + glDisable(GL_LIGHT0+a); + + // clear stuff from other opengl lamp usage + glLightf(GL_LIGHT0+a, GL_SPOT_CUTOFF, 180.0); + glLightf(GL_LIGHT0+a, GL_CONSTANT_ATTENUATION, 1.0); + glLightf(GL_LIGHT0+a, GL_LINEAR_ATTENUATION, 0.0); + } + else + glDisable(GL_LIGHT0+a); + } + + glDisable(GL_LIGHTING); + + glDisable(GL_COLOR_MATERIAL); + + return count; +} + +int GPU_scene_object_lights(Scene *scene, Object *ob, int lay, float viewmat[][4]) +{ + Base *base; + Lamp *la; + int count; + float position[4], direction[4], energy[4]; + + /* disable all lights */ + for(count=0; count<8; count++) + glDisable(GL_LIGHT0+count); + + count= 0; + + for(base=scene->base.first; base; base=base->next) { + if(base->object->type!=OB_LAMP) + continue; + + if(!(base->lay & lay) || !(base->lay & ob->lay)) + continue; + + la= base->object->data; + + /* setup lamp transform */ + glPushMatrix(); + glLoadMatrixf((float *)viewmat); + + where_is_object_simul(base->object); + + if(la->type==LA_SUN) { + /* sun lamp */ + VECCOPY(position, base->object->obmat[2]); + direction[3]= 0.0; + + glLightfv(GL_LIGHT0+count, GL_POSITION, direction); + } + else { + /* other lamps with attenuation */ + VECCOPY(position, base->object->obmat[3]); + position[3]= 1.0f; + + glLightfv(GL_LIGHT0+count, GL_POSITION, position); + glLightf(GL_LIGHT0+count, GL_CONSTANT_ATTENUATION, 1.0); + glLightf(GL_LIGHT0+count, GL_LINEAR_ATTENUATION, la->att1/la->dist); + glLightf(GL_LIGHT0+count, GL_QUADRATIC_ATTENUATION, la->att2/(la->dist*la->dist)); + + if(la->type==LA_SPOT) { + /* spot lamp */ + direction[0]= -base->object->obmat[2][0]; + direction[1]= -base->object->obmat[2][1]; + direction[2]= -base->object->obmat[2][2]; + glLightfv(GL_LIGHT0+count, GL_SPOT_DIRECTION, direction); + glLightf(GL_LIGHT0+count, GL_SPOT_CUTOFF, la->spotsize/2.0); + glLightf(GL_LIGHT0+count, GL_SPOT_EXPONENT, 128.0*la->spotblend); + } + else + glLightf(GL_LIGHT0+count, GL_SPOT_CUTOFF, 180.0); + } + + /* setup energy */ + energy[0]= la->energy*la->r; + energy[1]= la->energy*la->g; + energy[2]= la->energy*la->b; + energy[3]= 1.0; + + glLightfv(GL_LIGHT0+count, GL_DIFFUSE, energy); + glLightfv(GL_LIGHT0+count, GL_SPECULAR, energy); + glEnable(GL_LIGHT0+count); + + glPopMatrix(); + + count++; + if(count==8) + break; + } + + return count; +} + +/* Default OpenGL State */ + +void GPU_state_init(void) +{ + /* also called when doing opengl rendering and in the game engine */ + float mat_ambient[] = { 0.0, 0.0, 0.0, 0.0 }; + float mat_specular[] = { 0.5, 0.5, 0.5, 1.0 }; + float mat_shininess[] = { 35.0 }; + int a, x, y; + GLubyte pat[32*32]; + const GLubyte *patc= pat; + + glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT, mat_ambient); + glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE, mat_specular); + glMaterialfv(GL_FRONT_AND_BACK, GL_SPECULAR, mat_specular); + glMaterialfv(GL_FRONT_AND_BACK, GL_SHININESS, mat_shininess); + + GPU_default_lights(); + + /* no local viewer, looks ugly in ortho mode */ + /* glLightModelfv(GL_LIGHT_MODEL_LOCAL_VIEWER, &one); */ + + glDepthFunc(GL_LEQUAL); + /* scaling matrices */ + glEnable(GL_NORMALIZE); + + glShadeModel(GL_FLAT); + + glDisable(GL_ALPHA_TEST); + glDisable(GL_BLEND); + glDisable(GL_DEPTH_TEST); + glDisable(GL_FOG); + glDisable(GL_LIGHTING); + glDisable(GL_LOGIC_OP); + glDisable(GL_STENCIL_TEST); + glDisable(GL_TEXTURE_1D); + glDisable(GL_TEXTURE_2D); + + /* default on, disable/enable should be local per function */ + glEnableClientState(GL_VERTEX_ARRAY); + glEnableClientState(GL_NORMAL_ARRAY); + + glPixelTransferi(GL_MAP_COLOR, GL_FALSE); + glPixelTransferi(GL_RED_SCALE, 1); + glPixelTransferi(GL_RED_BIAS, 0); + glPixelTransferi(GL_GREEN_SCALE, 1); + glPixelTransferi(GL_GREEN_BIAS, 0); + glPixelTransferi(GL_BLUE_SCALE, 1); + glPixelTransferi(GL_BLUE_BIAS, 0); + glPixelTransferi(GL_ALPHA_SCALE, 1); + glPixelTransferi(GL_ALPHA_BIAS, 0); + + glPixelTransferi(GL_DEPTH_BIAS, 0); + glPixelTransferi(GL_DEPTH_SCALE, 1); + glDepthRange(0.0, 1.0); + + a= 0; + for(x=0; x<32; x++) { + for(y=0; y<4; y++) { + if( (x) & 1) pat[a++]= 0x88; + else pat[a++]= 0x22; + } + } + + glPolygonStipple(patc); + + glMatrixMode(GL_TEXTURE); + glLoadIdentity(); + glMatrixMode(GL_MODELVIEW); + + glFrontFace(GL_CCW); + glCullFace(GL_BACK); + glDisable(GL_CULL_FACE); +} + diff --git a/source/blender/gpu/intern/gpu_extensions.c b/source/blender/gpu/intern/gpu_extensions.c new file mode 100644 index 00000000000..d900f9c63f2 --- /dev/null +++ b/source/blender/gpu/intern/gpu_extensions.c @@ -0,0 +1,987 @@ +/** + * $Id$ + * + * ***** BEGIN GPL LICENSE BLOCK ***** + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. The Blender + * Foundation also sells licenses for use in proprietary software under + * the Blender License. See http://www.blender.org/BL/ for information + * about this. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software Foundation, + * Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. + * + * The Original Code is Copyright (C) 2005 Blender Foundation. + * All rights reserved. + * + * The Original Code is: all of this file. + * + * Contributor(s): Brecht Van Lommel. + * + * ***** END GPL LICENSE BLOCK ***** + */ + +#include "GL/glew.h" + +#include "DNA_listBase.h" +#include "DNA_image_types.h" +#include "DNA_userdef_types.h" + +#include "MEM_guardedalloc.h" + +#include "BKE_image.h" +#include "BKE_global.h" + +#include "IMB_imbuf.h" +#include "IMB_imbuf_types.h" + +#include "BLI_blenlib.h" + +#include "GPU_draw.h" +#include "GPU_extensions.h" + +#include +#include +#include + +/* Extensions support */ + +/* extensions used: + - texture border clamp: 1.3 core + - fragement shader: 2.0 core + - framebuffer object: ext specification + - multitexture 1.3 core + - arb non power of two: 2.0 core + - pixel buffer objects? 2.1 core + - arb draw buffers? 2.0 core +*/ + +struct GPUGlobal { + GLint maxtextures; + GLuint currentfb; + int minimumsupport; +} GG = {1, 0, 0}; + +void GPU_extensions_init() +{ + glewInit(); + + /* glewIsSupported("GL_VERSION_2_0") */ + + if (GLEW_ARB_multitexture) + glGetIntegerv(GL_MAX_TEXTURE_IMAGE_UNITS_ARB, &GG.maxtextures); + + GG.minimumsupport = 1; + if (!GLEW_ARB_multitexture) GG.minimumsupport = 0; + if (!GLEW_ARB_vertex_shader) GG.minimumsupport = 0; + if (!GLEW_ARB_fragment_shader) GG.minimumsupport = 0; +} + +int GPU_extensions_minimum_support() +{ + return GG.minimumsupport; +} + +int GPU_print_error(char *str) +{ + GLenum errCode; + + if (G.f & G_DEBUG) { + if ((errCode = glGetError()) != GL_NO_ERROR) { + fprintf(stderr, "%s opengl error: %s\n", str, gluErrorString(errCode)); + return 1; + } + } + + return 0; +} + +static void GPU_print_framebuffer_error(GLenum status) +{ + fprintf(stderr, "GPUFrameBuffer: framebuffer incomplete error %d\n", + (int)status); + + switch(status) { + case GL_FRAMEBUFFER_COMPLETE_EXT: + break; + case GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT_EXT: + fprintf(stderr, "Incomplete attachment.\n"); + break; + case GL_FRAMEBUFFER_UNSUPPORTED_EXT: + fprintf(stderr, "Unsupported framebuffer format.\n"); + break; + case GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT_EXT: + fprintf(stderr, "Missing attachment.\n"); + break; + case GL_FRAMEBUFFER_INCOMPLETE_DIMENSIONS_EXT: + fprintf(stderr, "Attached images must have same dimensions.\n"); + break; + case GL_FRAMEBUFFER_INCOMPLETE_FORMATS_EXT: + fprintf(stderr, "Attached images must have same format.\n"); + break; + case GL_FRAMEBUFFER_INCOMPLETE_DRAW_BUFFER_EXT: + fprintf(stderr, "Missing draw buffer.\n"); + break; + case GL_FRAMEBUFFER_INCOMPLETE_READ_BUFFER_EXT: + fprintf(stderr, "Missing read buffer.\n"); + break; + default: + fprintf(stderr, "Unknown.\n"); + break; + } +} + +/* GPUTexture */ + +struct GPUTexture { + int w, h; /* width/height */ + int number; /* number for multitexture binding */ + int refcount; /* reference count */ + GLenum target; /* GL_TEXTURE_* */ + GLuint bindcode; /* opengl identifier for texture */ + int fromblender; /* we got the texture from Blender */ + + GPUFrameBuffer *fb; /* GPUFramebuffer this texture is attached to */ + int depth; /* is a depth texture? */ +}; + +#define FTOCHAR(val) val<=0.0f?0: (val>=1.0f?255: (char)(255.0f*val)) +static unsigned char *GPU_texture_convert_pixels(int length, float *fpixels) +{ + unsigned char *pixels, *p; + float *fp; + int a, len; + + len = 4*length; + fp = fpixels; + p = pixels = MEM_callocN(sizeof(unsigned char)*len, "GPUTexturePixels"); + + for (a=0; aw = w; + tex->h = h; + tex->number = -1; + tex->refcount = 1; + tex->target = (n == 1)? GL_TEXTURE_1D: GL_TEXTURE_2D; + tex->depth = depth; + + glGenTextures(1, &tex->bindcode); + + if (!tex->bindcode) { + fprintf(stderr, "GPUTexture: texture create failed: %d\n", + (int)glGetError()); + GPU_texture_free(tex); + return NULL; + } + + if (!GLEW_ARB_texture_non_power_of_two) { + tex->w = larger_pow2(tex->w); + tex->h = larger_pow2(tex->h); + } + + tex->number = 0; + glBindTexture(tex->target, tex->bindcode); + + if(depth) { + type = GL_UNSIGNED_BYTE; + format = GL_DEPTH_COMPONENT; + internalformat = GL_DEPTH_COMPONENT; + } + else { + type = GL_UNSIGNED_BYTE; + format = GL_RGBA; + internalformat = GL_RGBA8; + + if (fpixels) + pixels = GPU_texture_convert_pixels(w*h, fpixels); + } + + if (tex->target == GL_TEXTURE_1D) { + glTexImage1D(tex->target, 0, internalformat, tex->w, 0, format, type, 0); + + if (fpixels) { + glTexSubImage1D(tex->target, 0, 0, w, format, type, + pixels? pixels: fpixels); + + if (tex->w > w) + GPU_glTexSubImageEmpty(tex->target, format, w, 0, + tex->w-w, 1); + } + } + else { + glTexImage2D(tex->target, 0, internalformat, tex->w, tex->h, 0, + format, type, 0); + + if (fpixels) { + glTexSubImage2D(tex->target, 0, 0, 0, w, h, + format, type, pixels? pixels: fpixels); + + if (tex->w > w) + GPU_glTexSubImageEmpty(tex->target, format, w, 0, tex->w-w, tex->h); + if (tex->h > h) + GPU_glTexSubImageEmpty(tex->target, format, 0, h, w, tex->h-h); + } + } + + if (pixels) + MEM_freeN(pixels); + + if(depth) { + glTexParameteri(tex->target, GL_TEXTURE_MIN_FILTER, GL_NEAREST); + glTexParameteri(tex->target, GL_TEXTURE_MAG_FILTER, GL_LINEAR); + glTexParameteri(tex->target, GL_TEXTURE_COMPARE_MODE_ARB, GL_COMPARE_R_TO_TEXTURE); + glTexParameteri(tex->target, GL_TEXTURE_COMPARE_FUNC_ARB, GL_LEQUAL); + glTexParameteri(tex->target, GL_DEPTH_TEXTURE_MODE_ARB, GL_INTENSITY); + } + else { + glTexParameteri(tex->target, GL_TEXTURE_MIN_FILTER, GL_LINEAR); + glTexParameteri(tex->target, GL_TEXTURE_MAG_FILTER, GL_LINEAR); + } + + if (tex->target != GL_TEXTURE_1D) { + /* CLAMP_TO_BORDER is an OpenGL 1.3 core feature */ + GLenum wrapmode = (depth)? GL_CLAMP_TO_EDGE: GL_CLAMP_TO_BORDER; + glTexParameteri(tex->target, GL_TEXTURE_WRAP_S, wrapmode); + glTexParameteri(tex->target, GL_TEXTURE_WRAP_T, wrapmode); + +#if 0 + float borderColor[] = { 1.0f, 1.0f, 1.0f, 1.0f }; + glTexParameterfv(GL_TEXTURE_2D, GL_TEXTURE_BORDER_COLOR, borderColor); +#endif + } + else + glTexParameteri(tex->target, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); + + return tex; +} + +GPUTexture *GPU_texture_from_blender(Image *ima, ImageUser *iuser, double time) +{ + GPUTexture *tex; + GLint w, h, border, lastbindcode, bindcode; + + glGetIntegerv(GL_TEXTURE_BINDING_2D, &lastbindcode); + + GPU_update_image_time(ima, time); + bindcode = GPU_verify_image(ima, 0, 0, 0); + + if(ima->gputexture) { + ima->gputexture->bindcode = bindcode; + glBindTexture(GL_TEXTURE_2D, lastbindcode); + return ima->gputexture; + } + + if(!bindcode) { + glBindTexture(GL_TEXTURE_2D, lastbindcode); + return NULL; + } + + tex = MEM_callocN(sizeof(GPUTexture), "GPUTexture"); + tex->bindcode = bindcode; + tex->number = -1; + tex->refcount = 1; + tex->target = GL_TEXTURE_2D; + tex->fromblender = 1; + + ima->gputexture= tex; + + if (!glIsTexture(tex->bindcode)) { + GPU_print_error("Blender Texture"); + } + else { + glBindTexture(GL_TEXTURE_2D, tex->bindcode); + glGetTexLevelParameteriv(GL_TEXTURE_2D, 0, GL_TEXTURE_WIDTH, &w); + glGetTexLevelParameteriv(GL_TEXTURE_2D, 0, GL_TEXTURE_HEIGHT, &h); + glGetTexLevelParameteriv(GL_TEXTURE_2D, 0, GL_TEXTURE_BORDER, &border); + + tex->w = w - border; + tex->h = h - border; + } + + glBindTexture(GL_TEXTURE_2D, lastbindcode); + + return tex; +} + +GPUTexture *GPU_texture_create_1D(int w, float *fpixels) +{ + GPUTexture *tex = GPU_texture_create_nD(w, 1, 1, fpixels, 0); + + if (tex) + GPU_texture_unbind(tex); + + return tex; +} + +GPUTexture *GPU_texture_create_2D(int w, int h, float *fpixels) +{ + GPUTexture *tex = GPU_texture_create_nD(w, h, 2, fpixels, 0); + + if (tex) + GPU_texture_unbind(tex); + + return tex; +} + +GPUTexture *GPU_texture_create_depth(int w, int h) +{ + GPUTexture *tex = GPU_texture_create_nD(w, h, 2, NULL, 1); + + if (tex) + GPU_texture_unbind(tex); + + return tex; +} + +void GPU_texture_bind(GPUTexture *tex, int number) +{ + GLenum arbnumber; + + if (number >= GG.maxtextures) { + GPU_print_error("Not enough texture slots."); + return; + } + + if(number == -1) + return; + + GPU_print_error("Pre Texture Bind"); + + arbnumber = (GLenum)((GLuint)GL_TEXTURE0_ARB + number); + if (number != 0) glActiveTextureARB(arbnumber); + glBindTexture(tex->target, tex->bindcode); + glEnable(tex->target); + if (number != 0) glActiveTextureARB(GL_TEXTURE0_ARB); + + tex->number = number; + + GPU_print_error("Post Texture Bind"); +} + +void GPU_texture_unbind(GPUTexture *tex) +{ + GLenum arbnumber; + + if (tex->number >= GG.maxtextures) { + GPU_print_error("Not enough texture slots."); + return; + } + + if(tex->number == -1) + return; + + GPU_print_error("Pre Texture Unbind"); + + arbnumber = (GLenum)((GLuint)GL_TEXTURE0_ARB + tex->number); + if (tex->number != 0) glActiveTextureARB(arbnumber); + glBindTexture(tex->target, 0); + glDisable(tex->target); + if (tex->number != 0) glActiveTextureARB(GL_TEXTURE0_ARB); + + tex->number = -1; + + GPU_print_error("Post Texture Unbind"); +} + +void GPU_texture_free(GPUTexture *tex) +{ + tex->refcount--; + + if (tex->refcount < 0) + fprintf(stderr, "GPUTexture: negative refcount\n"); + + if (tex->refcount == 0) { + if (tex->fb) + GPU_framebuffer_texture_detach(tex->fb, tex); + if (tex->bindcode && !tex->fromblender) + glDeleteTextures(1, &tex->bindcode); + + MEM_freeN(tex); + } +} + +void GPU_texture_ref(GPUTexture *tex) +{ + tex->refcount++; +} + +int GPU_texture_target(GPUTexture *tex) +{ + return tex->target; +} + +int GPU_texture_opengl_width(GPUTexture *tex) +{ + return tex->w; +} + +int GPU_texture_opengl_height(GPUTexture *tex) +{ + return tex->h; +} + +GPUFrameBuffer *GPU_texture_framebuffer(GPUTexture *tex) +{ + return tex->fb; +} + +/* GPUFrameBuffer */ + +struct GPUFrameBuffer { + GLuint object; + GPUTexture *colortex; + GPUTexture *depthtex; +}; + +GPUFrameBuffer *GPU_framebuffer_create() +{ + GPUFrameBuffer *fb; + + if (!GLEW_EXT_framebuffer_object) + return NULL; + + fb= MEM_callocN(sizeof(GPUFrameBuffer), "GPUFrameBuffer"); + glGenFramebuffersEXT(1, &fb->object); + + if (!fb->object) { + fprintf(stderr, "GPUFFrameBuffer: framebuffer gen failed. %d\n", + (int)glGetError()); + GPU_framebuffer_free(fb); + return NULL; + } + + return fb; +} + +int GPU_framebuffer_texture_attach(GPUFrameBuffer *fb, GPUTexture *tex) +{ + GLenum status; + GLenum attachment; + + if(tex->depth) + attachment = GL_DEPTH_ATTACHMENT_EXT; + else + attachment = GL_COLOR_ATTACHMENT0_EXT; + + glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, fb->object); + GG.currentfb = fb->object; + + glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, attachment, + tex->target, tex->bindcode, 0); + + if(tex->depth) { + glDrawBuffer(GL_NONE); + glReadBuffer(GL_NONE); + } + else { + glDrawBuffer(GL_COLOR_ATTACHMENT0_EXT); + glReadBuffer(GL_NONE); + } + + status = glCheckFramebufferStatusEXT(GL_FRAMEBUFFER_EXT); + + if (status != GL_FRAMEBUFFER_COMPLETE_EXT) { + GPU_framebuffer_restore(); + GPU_print_framebuffer_error(status); + return 0; + } + + if(tex->depth) + fb->depthtex = tex; + else + fb->colortex = tex; + + tex->fb= fb; + + return 1; +} + +void GPU_framebuffer_texture_detach(GPUFrameBuffer *fb, GPUTexture *tex) +{ + GLenum attachment; + + if(!tex->fb) + return; + + if(GG.currentfb != tex->fb->object) { + glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, tex->fb->object); + GG.currentfb = tex->fb->object; + } + + if(tex->depth) { + fb->depthtex = NULL; + attachment = GL_DEPTH_ATTACHMENT_EXT; + } + else { + fb->colortex = NULL; + attachment = GL_COLOR_ATTACHMENT0_EXT; + } + + glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, attachment, + tex->target, 0, 0); + + tex->fb = NULL; +} + +void GPU_framebuffer_texture_bind(GPUFrameBuffer *fb, GPUTexture *tex) +{ + /* push attributes */ + glPushAttrib(GL_ENABLE_BIT); + glPushAttrib(GL_VIEWPORT_BIT); + glDisable(GL_SCISSOR_TEST); + + /* bind framebuffer */ + glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, tex->fb->object); + + /* push matrices and set default viewport and matrix */ + glViewport(0, 0, tex->w, tex->h); + GG.currentfb = tex->fb->object; + + glMatrixMode(GL_PROJECTION); + glPushMatrix(); + glLoadIdentity(); + glMatrixMode(GL_MODELVIEW); + glPushMatrix(); + glLoadIdentity(); +} + +void GPU_framebuffer_texture_unbind(GPUFrameBuffer *fb, GPUTexture *tex) +{ + /* restore matrix */ + glMatrixMode(GL_PROJECTION); + glPopMatrix(); + glMatrixMode(GL_MODELVIEW); + glPopMatrix(); + + /* restore attributes */ + glPopAttrib(); + glPopAttrib(); + glEnable(GL_SCISSOR_TEST); +} + +void GPU_framebuffer_free(GPUFrameBuffer *fb) +{ + if(fb->depthtex) + GPU_framebuffer_texture_detach(fb, fb->depthtex); + if(fb->colortex) + GPU_framebuffer_texture_detach(fb, fb->colortex); + + if(fb->object) { + glDeleteFramebuffersEXT(1, &fb->object); + + if (GG.currentfb == fb->object) { + glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0); + GG.currentfb = 0; + } + } + + MEM_freeN(fb); +} + +void GPU_framebuffer_restore() +{ + if (GG.currentfb != 0) { + glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0); + GG.currentfb = 0; + } +} + +/* GPUShader */ + +struct GPUShader { + GLhandleARB object; /* handle for full shader */ + GLhandleARB vertex; /* handle for vertex shader */ + GLhandleARB fragment; /* handle for fragment shader */ + GLhandleARB lib; /* handle for libment shader */ + int totattrib; /* total number of attributes */ +}; + +static void shader_print_errors(char *task, char *log, const char *code) +{ + const char *c, *pos, *end = code + strlen(code); + int line = 1; + + fprintf(stderr, "GPUShader: %s error:\n", task); + + if(G.f & G_DEBUG) { + c = code; + while ((c < end) && (pos = strchr(c, '\n'))) { + fprintf(stderr, "%2d ", line); + fwrite(c, (pos+1)-c, 1, stderr); + c = pos+1; + line++; + } + + fprintf(stderr, "%s", c); + } + + fprintf(stderr, "%s\n", log); +} + +GPUShader *GPU_shader_create(const char *vertexcode, const char *fragcode, GPUShader *lib) +{ + GLint status; + GLcharARB log[5000]; + GLsizei length = 0; + GPUShader *shader; + + if (!GLEW_ARB_vertex_shader || !GLEW_ARB_fragment_shader) + return NULL; + + shader = MEM_callocN(sizeof(GPUShader), "GPUShader"); + + if(vertexcode) + shader->vertex = glCreateShaderObjectARB(GL_VERTEX_SHADER_ARB); + if(fragcode) + shader->fragment = glCreateShaderObjectARB(GL_FRAGMENT_SHADER_ARB); + shader->object = glCreateProgramObjectARB(); + + if (!shader->object || + (vertexcode && !shader->vertex) || + (fragcode && !shader->fragment)) { + fprintf(stderr, "GPUShader, object creation failed.\n"); + GPU_shader_free(shader); + return NULL; + } + + if(lib && lib->lib) + glAttachObjectARB(shader->object, lib->lib); + + if(vertexcode) { + glAttachObjectARB(shader->object, shader->vertex); + glShaderSourceARB(shader->vertex, 1, (const char**)&vertexcode, NULL); + + glCompileShaderARB(shader->vertex); + glGetObjectParameterivARB(shader->vertex, GL_OBJECT_COMPILE_STATUS_ARB, &status); + + if (!status) { + glValidateProgramARB(shader->vertex); + glGetInfoLogARB(shader->vertex, sizeof(log), &length, log); + shader_print_errors("compile", log, vertexcode); + + GPU_shader_free(shader); + return NULL; + } + } + + if(fragcode) { + glAttachObjectARB(shader->object, shader->fragment); + glShaderSourceARB(shader->fragment, 1, (const char**)&fragcode, NULL); + + glCompileShaderARB(shader->fragment); + glGetObjectParameterivARB(shader->fragment, GL_OBJECT_COMPILE_STATUS_ARB, &status); + + if (!status) { + glValidateProgramARB(shader->fragment); + glGetInfoLogARB(shader->fragment, sizeof(log), &length, log); + shader_print_errors("compile", log, fragcode); + + GPU_shader_free(shader); + return NULL; + } + } + + glLinkProgramARB(shader->object); + glGetObjectParameterivARB(shader->object, GL_OBJECT_LINK_STATUS_ARB, &status); + if (!status) { + glGetInfoLogARB(shader->object, sizeof(log), &length, log); + shader_print_errors("linking", log, fragcode); + + GPU_shader_free(shader); + return NULL; + } + + return shader; +} + +GPUShader *GPU_shader_create_lib(const char *code) +{ + GLint status; + GLcharARB log[5000]; + GLsizei length = 0; + GPUShader *shader; + + if (!GLEW_ARB_vertex_shader || !GLEW_ARB_fragment_shader) + return NULL; + + shader = MEM_callocN(sizeof(GPUShader), "GPUShader"); + + shader->lib = glCreateShaderObjectARB(GL_FRAGMENT_SHADER_ARB); + + if (!shader->lib) { + fprintf(stderr, "GPUShader, object creation failed.\n"); + GPU_shader_free(shader); + return NULL; + } + + glShaderSourceARB(shader->lib, 1, (const char**)&code, NULL); + + glCompileShaderARB(shader->lib); + glGetObjectParameterivARB(shader->lib, GL_OBJECT_COMPILE_STATUS_ARB, &status); + + if (!status) { + glValidateProgramARB(shader->lib); + glGetInfoLogARB(shader->lib, sizeof(log), &length, log); + shader_print_errors("compile", log, code); + + GPU_shader_free(shader); + return NULL; + } + + return shader; +} + +void GPU_shader_bind(GPUShader *shader) +{ + GPU_print_error("Pre Shader Bind"); + glUseProgramObjectARB(shader->object); + GPU_print_error("Post Shader Bind"); +} + +void GPU_shader_unbind() +{ + GPU_print_error("Pre Shader Unbind"); + glUseProgramObjectARB(0); + GPU_print_error("Post Shader Unbind"); +} + +void GPU_shader_free(GPUShader *shader) +{ + if (shader->lib) + glDeleteObjectARB(shader->lib); + if (shader->vertex) + glDeleteObjectARB(shader->vertex); + if (shader->fragment) + glDeleteObjectARB(shader->fragment); + if (shader->object) + glDeleteObjectARB(shader->object); + MEM_freeN(shader); +} + +int GPU_shader_get_uniform(GPUShader *shader, char *name) +{ + return glGetUniformLocationARB(shader->object, name); +} + +void GPU_shader_uniform_vector(GPUShader *shader, int location, int length, int arraysize, float *value) +{ + if(location == -1) + return; + + GPU_print_error("Pre Uniform Vector"); + + if (length == 1) glUniform1fvARB(location, arraysize, value); + else if (length == 2) glUniform2fvARB(location, arraysize, value); + else if (length == 3) glUniform3fvARB(location, arraysize, value); + else if (length == 4) glUniform4fvARB(location, arraysize, value); + else if (length == 9) glUniformMatrix3fvARB(location, arraysize, 0, value); + else if (length == 16) glUniformMatrix4fvARB(location, arraysize, 0, value); + + GPU_print_error("Post Uniform Vector"); +} + +void GPU_shader_uniform_texture(GPUShader *shader, int location, GPUTexture *tex) +{ + GLenum arbnumber; + + if (tex->number >= GG.maxtextures) { + GPU_print_error("Not enough texture slots."); + return; + } + + if(tex->number == -1) + return; + + if(location == -1) + return; + + GPU_print_error("Pre Uniform Texture"); + + arbnumber = (GLenum)((GLuint)GL_TEXTURE0_ARB + tex->number); + + if (tex->number != 0) glActiveTextureARB(arbnumber); + glBindTexture(tex->target, tex->bindcode); + glUniform1iARB(location, tex->number); + glEnable(tex->target); + if (tex->number != 0) glActiveTextureARB(GL_TEXTURE0_ARB); + + GPU_print_error("Post Uniform Texture"); +} + +int GPU_shader_get_attribute(GPUShader *shader, char *name) +{ + int index; + + GPU_print_error("Pre Get Attribute"); + + index = glGetAttribLocationARB(shader->object, name); + + GPU_print_error("Post Get Attribute"); + + return index; +} + +#if 0 +/* GPUPixelBuffer */ + +typedef struct GPUPixelBuffer { + GLuint bindcode[2]; + GLuint current; + int datasize; + int numbuffers; + int halffloat; +} GPUPixelBuffer; + +void GPU_pixelbuffer_free(GPUPixelBuffer *pb) +{ + if (pb->bindcode[0]) + glDeleteBuffersARB(pb->numbuffers, pb->bindcode); + MEM_freeN(pb); +} + +GPUPixelBuffer *gpu_pixelbuffer_create(int x, int y, int halffloat, int numbuffers) +{ + GPUPixelBuffer *pb; + + if (!GLEW_ARB_multitexture || !GLEW_EXT_pixel_buffer_object) + return NULL; + + pb = MEM_callocN(sizeof(GPUPixelBuffer), "GPUPBO"); + pb->datasize = x*y*4*((halffloat)? 16: 8); + pb->numbuffers = numbuffers; + pb->halffloat = halffloat; + + glGenBuffersARB(pb->numbuffers, pb->bindcode); + + if (!pb->bindcode[0]) { + fprintf(stderr, "GPUPixelBuffer allocation failed\n"); + GPU_pixelbuffer_free(pb); + return NULL; + } + + return pb; +} + +void GPU_pixelbuffer_texture(GPUTexture *tex, GPUPixelBuffer *pb) +{ + void *pixels; + int i; + + glBindTexture(GL_TEXTURE_RECTANGLE_EXT, tex->bindcode); + + for (i = 0; i < pb->numbuffers; i++) { + glBindBufferARB(GL_PIXEL_UNPACK_BUFFER_EXT, pb->bindcode[pb->current]); + glBufferDataARB(GL_PIXEL_UNPACK_BUFFER_EXT, pb->datasize, NULL, + GL_STREAM_DRAW_ARB); + + pixels = glMapBufferARB(GL_PIXEL_UNPACK_BUFFER_EXT, GL_WRITE_ONLY); + /*memcpy(pixels, _oImage.data(), pb->datasize);*/ + + if (!glUnmapBufferARB(GL_PIXEL_UNPACK_BUFFER_EXT)) { + fprintf(stderr, "Could not unmap opengl PBO\n"); + break; + } + } + + glBindTexture(GL_TEXTURE_RECTANGLE_EXT, 0); +} + +static int pixelbuffer_map_into_gpu(GLuint bindcode) +{ + void *pixels; + + glBindBufferARB(GL_PIXEL_UNPACK_BUFFER_EXT, bindcode); + pixels = glMapBufferARB(GL_PIXEL_UNPACK_BUFFER_EXT, GL_WRITE_ONLY); + + /* do stuff in pixels */ + + if (!glUnmapBufferARB(GL_PIXEL_UNPACK_BUFFER_EXT)) { + fprintf(stderr, "Could not unmap opengl PBO\n"); + return 0; + } + + return 1; +} + +static void pixelbuffer_copy_to_texture(GPUTexture *tex, GPUPixelBuffer *pb, GLuint bindcode) +{ + GLenum type = (pb->halffloat)? GL_HALF_FLOAT_NV: GL_UNSIGNED_BYTE; + glBindTexture(GL_TEXTURE_RECTANGLE_EXT, tex->bindcode); + glBindBufferARB(GL_PIXEL_UNPACK_BUFFER_EXT, bindcode); + + glTexSubImage2D(GL_TEXTURE_RECTANGLE_EXT, 0, 0, 0, tex->w, tex->h, + GL_RGBA, type, NULL); + + glBindBufferARB(GL_PIXEL_UNPACK_BUFFER_EXT, 0); + glBindTexture(GL_TEXTURE_RECTANGLE_EXT, 0); +} + +void GPU_pixelbuffer_async_to_gpu(GPUTexture *tex, GPUPixelBuffer *pb) +{ + int newbuffer; + + if (pb->numbuffers == 1) { + pixelbuffer_copy_to_texture(tex, pb, pb->bindcode[0]); + pixelbuffer_map_into_gpu(pb->bindcode[0]); + } + else { + pb->current = (pb->current+1)%pb->numbuffers; + newbuffer = (pb->current+1)%pb->numbuffers; + + pixelbuffer_map_into_gpu(pb->bindcode[newbuffer]); + pixelbuffer_copy_to_texture(tex, pb, pb->bindcode[pb->current]); + } +} +#endif + diff --git a/source/blender/gpu/intern/gpu_material.c b/source/blender/gpu/intern/gpu_material.c new file mode 100644 index 00000000000..47400f61c25 --- /dev/null +++ b/source/blender/gpu/intern/gpu_material.c @@ -0,0 +1,1460 @@ +/** + * $Id$ + * + * ***** BEGIN GPL LICENSE BLOCK ***** + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software Foundation, + * Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. + * + * The Original Code is Copyright (C) 2006 Blender Foundation. + * All rights reserved. + * + * The Original Code is: all of this file. + * + * Contributor(s): Brecht Van Lommel. + * + * ***** END GPL LICENSE BLOCK ***** + */ + +#include +#include + +#include "GL/glew.h" + +#include "MEM_guardedalloc.h" + +#include "DNA_image_types.h" +#include "DNA_lamp_types.h" +#include "DNA_listBase.h" +#include "DNA_material_types.h" +#include "DNA_object_types.h" +#include "DNA_scene_types.h" +#include "DNA_texture_types.h" +#include "DNA_view3d_types.h" +#include "DNA_world_types.h" + +#include "BKE_anim.h" +#include "BKE_colortools.h" +#include "BKE_DerivedMesh.h" +#include "BKE_global.h" +#include "BKE_main.h" +#include "BKE_node.h" +#include "BKE_scene.h" +#include "BKE_texture.h" +#include "BKE_utildefines.h" + +#include "BLI_arithb.h" +#include "BLI_blenlib.h" +#include "BLI_linklist.h" + +#include "GPU_extensions.h" +#include "GPU_material.h" + +#include "gpu_codegen.h" + +#include + +/* Structs */ + +typedef enum DynMatProperty { + DYN_LAMP_CO = 1, + DYN_LAMP_VEC = 2, + DYN_LAMP_IMAT = 4, + DYN_LAMP_PERSMAT = 8, +} DynMatProperty; + +struct GPUMaterial { + Scene *scene; + Material *ma; + + /* for creating the material */ + ListBase nodes; + GPUNodeLink *outlink; + + /* for binding the material */ + GPUPass *pass; + GPUVertexAttribs attribs; + int bound; + int builtins; + int alpha, obcolalpha; + int dynproperty; + + /* for passing uniforms */ + int viewmatloc, invviewmatloc; + int obmatloc, invobmatloc; + int obcolloc; + + LinkNode *lamps; +}; + +struct GPULamp { + Scene *scene; + Object *ob; + Object *par; + Lamp *la; + + int type, mode, lay; + + float dynenergy, dyncol[3]; + float energy, col[3]; + + float co[3], vec[3]; + float dynco[3], dynvec[3]; + float obmat[4][4]; + float imat[4][4]; + float dynimat[4][4]; + + float spotsi, spotbl, k; + float dist, att1, att2; + + float bias, d, clipend; + int size; + + int falloff_type; + struct CurveMapping *curfalloff; + + float winmat[4][4]; + float viewmat[4][4]; + float persmat[4][4]; + float dynpersmat[4][4]; + + GPUFrameBuffer *fb; + GPUTexture *tex; + + LinkNode *materials; +}; + +/* Functions */ + +static GPUMaterial *GPU_material_construct_begin(Material *ma) +{ + GPUMaterial *material = MEM_callocN(sizeof(GPUMaterial), "GPUMaterial"); + + material->ma= ma; + + return material; +} + +static void gpu_material_set_attrib_id(GPUMaterial *material) +{ + GPUVertexAttribs *attribs; + GPUShader *shader; + GPUPass *pass; + char name[32]; + int a, b; + + attribs= &material->attribs; + pass= material->pass; + if(!pass) { + attribs->totlayer = 0; + return; + } + + shader= GPU_pass_shader(pass); + if(!shader) { + attribs->totlayer = 0; + return; + } + + /* convert from attribute number to the actual id assigned by opengl, + * in case the attrib does not get a valid index back, it was probably + * removed by the glsl compiler by dead code elimination */ + + for(a=0, b=0; atotlayer; a++) { + sprintf(name, "att%d", attribs->layer[a].glindex); + attribs->layer[a].glindex = GPU_shader_get_attribute(shader, name); + + if(attribs->layer[a].glindex >= 0) { + attribs->layer[b] = attribs->layer[a]; + b++; + } + } + + attribs->totlayer = b; +} + +static int GPU_material_construct_end(GPUMaterial *material) +{ + if (material->outlink) { + GPUNodeLink *outlink; + GPUShader *shader; + + outlink = material->outlink; + material->pass = GPU_generate_pass(&material->nodes, outlink, + &material->attribs, &material->builtins, material->ma->id.name); + + if(!material->pass) + return 0; + + gpu_material_set_attrib_id(material); + + shader = GPU_pass_shader(material->pass); + + if(material->builtins & GPU_VIEW_MATRIX) + material->viewmatloc = GPU_shader_get_uniform(shader, GPU_builtin_name(GPU_VIEW_MATRIX)); + if(material->builtins & GPU_INVERSE_VIEW_MATRIX) + material->invviewmatloc = GPU_shader_get_uniform(shader, GPU_builtin_name(GPU_INVERSE_VIEW_MATRIX)); + if(material->builtins & GPU_OBJECT_MATRIX) + material->obmatloc = GPU_shader_get_uniform(shader, GPU_builtin_name(GPU_OBJECT_MATRIX)); + if(material->builtins & GPU_INVERSE_OBJECT_MATRIX) + material->invobmatloc = GPU_shader_get_uniform(shader, GPU_builtin_name(GPU_INVERSE_OBJECT_MATRIX)); + if(material->builtins & GPU_OBCOLOR) + material->obcolloc = GPU_shader_get_uniform(shader, GPU_builtin_name(GPU_OBCOLOR)); + + return 1; + } + + return 0; +} + +void GPU_material_free(Material *ma) +{ + LinkData *link; + + for(link=ma->gpumaterial.first; link; link=link->next) { + GPUMaterial *material = link->data; + + if(material->pass) + GPU_pass_free(material->pass); + + BLI_linklist_free(material->lamps, NULL); + + MEM_freeN(material); + } + + BLI_freelistN(&ma->gpumaterial); +} + +void GPU_material_bind(GPUMaterial *material, int lay, double time) +{ + if(material->pass) { + LinkNode *nlink; + GPULamp *lamp; + + /* handle layer lamps */ + for(nlink=material->lamps; nlink; nlink=nlink->next) { + lamp= nlink->link; + + if(!(lamp->mode & LA_LAYER) || (lamp->lay & lay)) { + lamp->dynenergy = lamp->energy; + VECCOPY(lamp->dyncol, lamp->col); + } + else { + lamp->dynenergy = 0.0f; + lamp->dyncol[0]= lamp->dyncol[1]= lamp->dyncol[2] = 0.0f; + } + } + + GPU_pass_bind(material->pass, time); + material->bound = 1; + } +} + +void GPU_material_bind_uniforms(GPUMaterial *material, float obmat[][4], float viewmat[][4], float viewinv[][4], float obcol[4]) +{ + if(material->pass) { + GPUShader *shader = GPU_pass_shader(material->pass); + LinkNode *nlink; + GPULamp *lamp; + float invmat[4][4], col[4]; + + /* handle builtins */ + if(material->builtins & GPU_VIEW_MATRIX) { + GPU_shader_uniform_vector(shader, material->viewmatloc, 16, 1, (float*)viewmat); + } + if(material->builtins & GPU_INVERSE_VIEW_MATRIX) { + GPU_shader_uniform_vector(shader, material->invviewmatloc, 16, 1, (float*)viewinv); + } + if(material->builtins & GPU_OBJECT_MATRIX) { + GPU_shader_uniform_vector(shader, material->obmatloc, 16, 1, (float*)obmat); + } + if(material->builtins & GPU_INVERSE_OBJECT_MATRIX) { + Mat4Invert(invmat, obmat); + GPU_shader_uniform_vector(shader, material->invobmatloc, 16, 1, (float*)invmat); + } + if(material->builtins & GPU_OBCOLOR) { + QUATCOPY(col, obcol); + CLAMP(col[3], 0.0f, 1.0f); + GPU_shader_uniform_vector(shader, material->obcolloc, 4, 1, col); + } + + /* update lamps */ + for(nlink=material->lamps; nlink; nlink=nlink->next) { + lamp= nlink->link; + + if(material->dynproperty & DYN_LAMP_VEC) { + VECCOPY(lamp->dynvec, lamp->vec); + Normalize(lamp->dynvec); + VecMulf(lamp->dynvec, -1.0f); + Mat4Mul3Vecfl(viewmat, lamp->dynvec); + } + + if(material->dynproperty & DYN_LAMP_CO) { + VECCOPY(lamp->dynco, lamp->co); + Mat4MulVecfl(viewmat, lamp->dynco); + } + + if(material->dynproperty & DYN_LAMP_IMAT) + Mat4MulMat4(lamp->dynimat, viewinv, lamp->imat); + if(material->dynproperty & DYN_LAMP_PERSMAT) + Mat4MulMat4(lamp->dynpersmat, viewinv, lamp->persmat); + } + + GPU_pass_update_uniforms(material->pass); + } +} + +void GPU_material_unbind(GPUMaterial *material) +{ + if (material->pass) { + material->bound = 0; + GPU_pass_unbind(material->pass); + } +} + +int GPU_material_bound(GPUMaterial *material) +{ + return material->bound; +} + +void GPU_material_vertex_attributes(GPUMaterial *material, GPUVertexAttribs *attribs) +{ + *attribs = material->attribs; +} + +void GPU_material_output_link(GPUMaterial *material, GPUNodeLink *link) +{ + if(!material->outlink) + material->outlink= link; +} + +void GPU_material_enable_alpha(GPUMaterial *material) +{ + material->alpha= 1; +} + +GPUBlendMode GPU_material_blend_mode(GPUMaterial *material, float obcol[3]) +{ + if(material->alpha || (material->obcolalpha && obcol[3] < 1.0f)) + return GPU_BLEND_ALPHA; + else + return GPU_BLEND_SOLID; +} + +void gpu_material_add_node(GPUMaterial *material, GPUNode *node) +{ + BLI_addtail(&material->nodes, node); +} + +/* Code generation */ + +static GPUNodeLink *lamp_get_visibility(GPUMaterial *mat, GPULamp *lamp, GPUNodeLink **lv, GPUNodeLink **dist) +{ + GPUNodeLink *visifac, *inpr; + + /* from get_lamp_visibility */ + if(lamp->type==LA_SUN || lamp->type==LA_HEMI) { + mat->dynproperty |= DYN_LAMP_VEC; + GPU_link(mat, "lamp_visibility_sun_hemi", GPU_dynamic_uniform(lamp->dynvec), lv, dist, &visifac); + return visifac; + } + else { + mat->dynproperty |= DYN_LAMP_CO; + GPU_link(mat, "lamp_visibility_other", GPU_builtin(GPU_VIEW_POSITION), GPU_dynamic_uniform(lamp->dynco), lv, dist, &visifac); + + if(lamp->type==LA_AREA) + return visifac; + + switch(lamp->falloff_type) + { + case LA_FALLOFF_CONSTANT: + break; + case LA_FALLOFF_INVLINEAR: + GPU_link(mat, "lamp_falloff_invlinear", GPU_uniform(&lamp->dist), *dist, &visifac); + break; + case LA_FALLOFF_INVSQUARE: + GPU_link(mat, "lamp_falloff_invsquare", GPU_uniform(&lamp->dist), *dist, &visifac); + break; + case LA_FALLOFF_SLIDERS: + GPU_link(mat, "lamp_falloff_sliders", GPU_uniform(&lamp->dist), GPU_uniform(&lamp->att1), GPU_uniform(&lamp->att2), *dist, &visifac); + break; + case LA_FALLOFF_CURVE: + { + float *array; + int size; + + curvemapping_table_RGBA(lamp->curfalloff, &array, &size); + GPU_link(mat, "lamp_falloff_curve", GPU_uniform(&lamp->dist), GPU_texture(size, array), *dist, &visifac); + } + break; + } + + if(lamp->mode & LA_SPHERE) + GPU_link(mat, "lamp_visibility_sphere", GPU_uniform(&lamp->dist), *dist, visifac, &visifac); + + if(lamp->type == LA_SPOT) { + if(lamp->mode & LA_SQUARE) { + mat->dynproperty |= DYN_LAMP_VEC|DYN_LAMP_IMAT; + GPU_link(mat, "lamp_visibility_spot_square", GPU_dynamic_uniform(lamp->dynvec), GPU_dynamic_uniform((float*)lamp->dynimat), *lv, &inpr); + } + else { + mat->dynproperty |= DYN_LAMP_VEC; + GPU_link(mat, "lamp_visibility_spot_circle", GPU_dynamic_uniform(lamp->dynvec), *lv, &inpr); + } + + GPU_link(mat, "lamp_visibility_spot", GPU_uniform(&lamp->spotsi), GPU_uniform(&lamp->spotbl), inpr, visifac, &visifac); + } + + GPU_link(mat, "lamp_visibility_clamp", visifac, &visifac); + + return visifac; + } +} + +#if 0 +static void area_lamp_vectors(LampRen *lar) +{ + float xsize= 0.5*lar->area_size, ysize= 0.5*lar->area_sizey, multifac; + + /* make it smaller, so area light can be multisampled */ + multifac= 1.0f/sqrt((float)lar->ray_totsamp); + xsize *= multifac; + ysize *= multifac; + + /* corner vectors */ + lar->area[0][0]= lar->co[0] - xsize*lar->mat[0][0] - ysize*lar->mat[1][0]; + lar->area[0][1]= lar->co[1] - xsize*lar->mat[0][1] - ysize*lar->mat[1][1]; + lar->area[0][2]= lar->co[2] - xsize*lar->mat[0][2] - ysize*lar->mat[1][2]; + + /* corner vectors */ + lar->area[1][0]= lar->co[0] - xsize*lar->mat[0][0] + ysize*lar->mat[1][0]; + lar->area[1][1]= lar->co[1] - xsize*lar->mat[0][1] + ysize*lar->mat[1][1]; + lar->area[1][2]= lar->co[2] - xsize*lar->mat[0][2] + ysize*lar->mat[1][2]; + + /* corner vectors */ + lar->area[2][0]= lar->co[0] + xsize*lar->mat[0][0] + ysize*lar->mat[1][0]; + lar->area[2][1]= lar->co[1] + xsize*lar->mat[0][1] + ysize*lar->mat[1][1]; + lar->area[2][2]= lar->co[2] + xsize*lar->mat[0][2] + ysize*lar->mat[1][2]; + + /* corner vectors */ + lar->area[3][0]= lar->co[0] + xsize*lar->mat[0][0] - ysize*lar->mat[1][0]; + lar->area[3][1]= lar->co[1] + xsize*lar->mat[0][1] - ysize*lar->mat[1][1]; + lar->area[3][2]= lar->co[2] + xsize*lar->mat[0][2] - ysize*lar->mat[1][2]; + /* only for correction button size, matrix size works on energy */ + lar->areasize= lar->dist*lar->dist/(4.0*xsize*ysize); +} +#endif + +static void ramp_blend(GPUMaterial *mat, GPUNodeLink *fac, GPUNodeLink *col1, GPUNodeLink *col2, int type, GPUNodeLink **outcol) +{ + static char *names[] = {"mix_blend", "mix_add", "mix_mult", "mix_sub", + "mix_screen", "mix_div", "mix_diff", "mix_dark", "mix_light", + "mix_overlay", "mix_dodge", "mix_burn", "mix_hue", "mix_sat", + "mix_val", "mix_color"}; + + GPU_link(mat, names[type], fac, col1, col2, outcol); +} + +static void do_colorband_blend(GPUMaterial *mat, ColorBand *coba, GPUNodeLink *fac, float rampfac, int type, GPUNodeLink *incol, GPUNodeLink **outcol) +{ + GPUNodeLink *tmp, *alpha, *col; + float *array; + int size; + + /* do colorband */ + colorband_table_RGBA(coba, &array, &size); + GPU_link(mat, "valtorgb", fac, GPU_texture(size, array), &col, &tmp); + + /* use alpha in fac */ + GPU_link(mat, "mtex_alpha_from_col", col, &alpha); + GPU_link(mat, "math_multiply", alpha, GPU_uniform(&rampfac), &fac); + + /* blending method */ + ramp_blend(mat, fac, incol, col, type, outcol); +} + +static void ramp_diffuse_result(GPUShadeInput *shi, GPUNodeLink **diff) +{ + Material *ma= shi->mat; + GPUMaterial *mat= shi->gpumat; + GPUNodeLink *fac; + + if(!(G.fileflags & G_FILE_GLSL_NO_RAMPS)) { + if(ma->ramp_col) { + if(ma->rampin_col==MA_RAMP_IN_RESULT) { + GPU_link(mat, "ramp_rgbtobw", *diff, &fac); + + /* colorband + blend */ + do_colorband_blend(mat, ma->ramp_col, fac, ma->rampfac_col, ma->rampblend_col, *diff, diff); + } + } + } +} + +static void add_to_diffuse(GPUMaterial *mat, Material *ma, GPUShadeInput *shi, GPUNodeLink *is, GPUNodeLink *rgb, GPUNodeLink **diff) +{ + GPUNodeLink *fac, *tmp, *addcol; + + if(!(G.fileflags & G_FILE_GLSL_NO_RAMPS) && + ma->ramp_col && (ma->mode & MA_RAMP_COL)) { + /* MA_RAMP_IN_RESULT is exceptional */ + if(ma->rampin_col==MA_RAMP_IN_RESULT) { + addcol = shi->rgb; + } + else { + /* input */ + switch(ma->rampin_col) { + case MA_RAMP_IN_ENERGY: + GPU_link(mat, "ramp_rgbtobw", rgb, &fac); + break; + case MA_RAMP_IN_SHADER: + fac= is; + break; + case MA_RAMP_IN_NOR: + GPU_link(mat, "vec_math_dot", shi->view, shi->vn, &tmp, &fac); + break; + default: + GPU_link(mat, "set_value_zero", &fac); + break; + } + + /* colorband + blend */ + do_colorband_blend(mat, ma->ramp_col, fac, ma->rampfac_col, ma->rampblend_col, shi->rgb, &addcol); + } + } + else + addcol = shi->rgb; + + /* output to */ + GPU_link(mat, "shade_madd", *diff, rgb, addcol, diff); +} + +static void ramp_spec_result(GPUShadeInput *shi, GPUNodeLink **spec) +{ + Material *ma= shi->mat; + GPUMaterial *mat= shi->gpumat; + GPUNodeLink *fac; + + if(!(G.fileflags & G_FILE_GLSL_NO_RAMPS) && + ma->ramp_spec && ma->rampin_spec==MA_RAMP_IN_RESULT) { + GPU_link(mat, "ramp_rgbtobw", *spec, &fac); + + /* colorband + blend */ + do_colorband_blend(mat, ma->ramp_spec, fac, ma->rampfac_spec, ma->rampblend_spec, *spec, spec); + } +} + +static void do_specular_ramp(GPUShadeInput *shi, GPUNodeLink *is, GPUNodeLink *t, GPUNodeLink **spec) +{ + Material *ma= shi->mat; + GPUMaterial *mat= shi->gpumat; + GPUNodeLink *fac, *tmp; + + *spec = shi->specrgb; + + /* MA_RAMP_IN_RESULT is exception */ + if(ma->ramp_spec && (ma->rampin_spec!=MA_RAMP_IN_RESULT)) { + + /* input */ + switch(ma->rampin_spec) { + case MA_RAMP_IN_ENERGY: + fac = t; + break; + case MA_RAMP_IN_SHADER: + fac = is; + break; + case MA_RAMP_IN_NOR: + GPU_link(mat, "vec_math_dot", shi->view, shi->vn, &tmp, &fac); + break; + default: + GPU_link(mat, "set_value_zero", &fac); + break; + } + + /* colorband + blend */ + do_colorband_blend(mat, ma->ramp_spec, fac, ma->rampfac_spec, ma->rampblend_spec, *spec, spec); + } +} + +static void shade_one_light(GPUShadeInput *shi, GPUShadeResult *shr, GPULamp *lamp) +{ + Material *ma= shi->mat; + GPUMaterial *mat= shi->gpumat; + GPUNodeLink *lv, *dist, *visifac, *is, *inp, *i, *vn, *view; + GPUNodeLink *outcol, *specfac, *t, *shadfac; + float one = 1.0f; + + if((lamp->mode & LA_ONLYSHADOW) && !(ma->mode & MA_SHADOW)) + return; + + vn= shi->vn; + view= shi->view; + + visifac= lamp_get_visibility(mat, lamp, &lv, &dist); + + /*if(ma->mode & MA_TANGENT_V) + GPU_link(mat, "shade_tangent_v", lv, GPU_attribute(CD_TANGENT, ""), &vn);*/ + + GPU_link(mat, "shade_inp", vn, lv, &inp); + + if(lamp->mode & LA_NO_DIFF) { + GPU_link(mat, "shade_is_no_diffuse", &is); + } + else if(lamp->type == LA_HEMI) { + GPU_link(mat, "shade_is_hemi", inp, &is); + } + else { + if(lamp->type == LA_AREA) { + float area[4][4], areasize; + + memset(&area, 0, sizeof(area)); + memset(&areasize, 0, sizeof(areasize)); + mat->dynproperty |= DYN_LAMP_VEC|DYN_LAMP_CO; + GPU_link(mat, "shade_inp_area", GPU_builtin(GPU_VIEW_POSITION), GPU_dynamic_uniform(lamp->dynco), GPU_dynamic_uniform(lamp->dynvec), vn, GPU_uniform((float*)area), + GPU_uniform(&areasize), GPU_uniform(&lamp->k), &inp); + } + + is= inp; /* Lambert */ + + if(!(G.fileflags & G_FILE_GLSL_NO_SHADERS)) { + if(ma->diff_shader==MA_DIFF_ORENNAYAR) + GPU_link(mat, "shade_diffuse_oren_nayer", inp, vn, lv, view, GPU_uniform(&ma->roughness), &is); + else if(ma->diff_shader==MA_DIFF_TOON) + GPU_link(mat, "shade_diffuse_toon", vn, lv, view, GPU_uniform(&ma->param[0]), GPU_uniform(&ma->param[1]), &is); + else if(ma->diff_shader==MA_DIFF_MINNAERT) + GPU_link(mat, "shade_diffuse_minnaert", inp, vn, view, GPU_uniform(&ma->darkness), &is); + else if(ma->diff_shader==MA_DIFF_FRESNEL) + GPU_link(mat, "shade_diffuse_fresnel", vn, lv, view, GPU_uniform(&ma->param[0]), GPU_uniform(&ma->param[1]), &is); + } + } + + if(!(G.fileflags & G_FILE_GLSL_NO_SHADERS)) + if(ma->shade_flag & MA_CUBIC) + GPU_link(mat, "shade_cubic", is, &is); + + i = is; + GPU_link(mat, "shade_visifac", i, visifac, shi->refl, &i); + + vn = shi->vn; + /*if(ma->mode & MA_TANGENT_VN) + GPU_link(mat, "shade_tangent_v_spec", GPU_attribute(CD_TANGENT, ""), &vn);*/ + + /* this replaces if(i > 0.0) conditional until that is supported */ + // done in shade_visifac now, GPU_link(mat, "mtex_value_clamp_positive", i, &i); + + if((ma->mode & MA_SHADOW) && GPU_lamp_has_shadow_buffer(lamp)) { + if(!(G.fileflags & G_FILE_GLSL_NO_SHADOWS)) { + mat->dynproperty |= DYN_LAMP_PERSMAT; + + GPU_link(mat, "test_shadowbuf", + GPU_builtin(GPU_VIEW_POSITION), + GPU_dynamic_texture(lamp->tex), + GPU_dynamic_uniform((float*)lamp->dynpersmat), + GPU_uniform(&lamp->bias), inp, &shadfac); + + if(lamp->mode & LA_ONLYSHADOW) { + GPU_link(mat, "shade_only_shadow", i, shadfac, + GPU_dynamic_uniform(&lamp->dynenergy), shi->rgb, shi->specrgb, + shr->diff, shr->spec, &shr->diff, &shr->spec); + + BLI_linklist_append(&mat->lamps, lamp); + BLI_linklist_append(&lamp->materials, ma); + return; + } + + GPU_link(mat, "math_multiply", i, shadfac, &i); + } + } + else if((G.fileflags & G_FILE_GLSL_NO_SHADOWS) && (lamp->mode & LA_ONLYSHADOW)) { + BLI_linklist_append(&mat->lamps, lamp); + BLI_linklist_append(&lamp->materials, ma); + return; + } + else + GPU_link(mat, "set_value", GPU_uniform(&one), &shadfac); + + if(GPU_link_changed(shi->refl) || ma->ref != 0.0f) { + if(!(lamp->mode & LA_NO_DIFF)) { + GPUNodeLink *rgb; + GPU_link(mat, "shade_mul_value", i, GPU_dynamic_uniform(lamp->dyncol), &rgb); + add_to_diffuse(mat, ma, shi, is, rgb, &shr->diff); + } + } + + if(G.fileflags & G_FILE_GLSL_NO_SHADERS); + else if(!(lamp->mode & LA_NO_SPEC) && !(lamp->mode & LA_ONLYSHADOW) && + (GPU_link_changed(shi->spec) || ma->spec != 0.0f)) { + if(lamp->type == LA_HEMI) { + GPU_link(mat, "shade_hemi_spec", vn, lv, view, GPU_uniform(&ma->spec), shi->har, visifac, &t); + GPU_link(mat, "shade_add_spec", t, GPU_dynamic_uniform(lamp->dyncol), shi->specrgb, &outcol); + GPU_link(mat, "shade_add", shr->spec, outcol, &shr->spec); + } + else { + if(ma->spec_shader==MA_SPEC_PHONG) + GPU_link(mat, "shade_phong_spec", vn, lv, view, shi->har, &specfac); + else if(ma->spec_shader==MA_SPEC_COOKTORR) + GPU_link(mat, "shade_cooktorr_spec", vn, lv, view, shi->har, &specfac); + else if(ma->spec_shader==MA_SPEC_BLINN) + GPU_link(mat, "shade_blinn_spec", vn, lv, view, GPU_uniform(&ma->refrac), shi->har, &specfac); + else if(ma->spec_shader==MA_SPEC_WARDISO) + GPU_link(mat, "shade_wardiso_spec", vn, lv, view, GPU_uniform(&ma->rms), &specfac); + else + GPU_link(mat, "shade_toon_spec", vn, lv, view, GPU_uniform(&ma->param[2]), GPU_uniform(&ma->param[3]), &specfac); + + if(lamp->type==LA_AREA) + GPU_link(mat, "shade_spec_area_inp", specfac, inp, &specfac); + + GPU_link(mat, "shade_spec_t", shadfac, shi->spec, visifac, specfac, &t); + + if(ma->mode & MA_RAMP_SPEC) { + GPUNodeLink *spec; + do_specular_ramp(shi, specfac, t, &spec); + GPU_link(mat, "shade_add_spec", t, GPU_dynamic_uniform(lamp->dyncol), spec, &outcol); + GPU_link(mat, "shade_add", shr->spec, outcol, &shr->spec); + } + else { + GPU_link(mat, "shade_add_spec", t, GPU_dynamic_uniform(lamp->dyncol), shi->specrgb, &outcol); + GPU_link(mat, "shade_add", shr->spec, outcol, &shr->spec); + } + } + } + + BLI_linklist_append(&mat->lamps, lamp); + BLI_linklist_append(&lamp->materials, ma); +} + +static void material_lights(GPUShadeInput *shi, GPUShadeResult *shr) +{ + Base *base; + Object *ob; + Scene *sce; + GPULamp *lamp; + + for(SETLOOPER(shi->gpumat->scene, base)) { + ob= base->object; + + if(ob->type==OB_LAMP) { + lamp = GPU_lamp_from_blender(shi->gpumat->scene, ob, NULL); + if(lamp) + shade_one_light(shi, shr, lamp); + } + + if (ob->transflag & OB_DUPLI) { + DupliObject *dob; + ListBase *lb = object_duplilist(shi->gpumat->scene, ob); + + for(dob=lb->first; dob; dob=dob->next) { + Object *ob = dob->ob; + + if(ob->type==OB_LAMP) { + Mat4CpyMat4(ob->obmat, dob->mat); + + lamp = GPU_lamp_from_blender(shi->gpumat->scene, ob, base->object); + if(lamp) + shade_one_light(shi, shr, lamp); + } + } + + free_object_duplilist(lb); + } + } +} + +static void texture_rgb_blend(GPUMaterial *mat, GPUNodeLink *tex, GPUNodeLink *out, GPUNodeLink *fact, GPUNodeLink *facg, int blendtype, GPUNodeLink **in) +{ + switch(blendtype) { + case MTEX_BLEND: + GPU_link(mat, "mtex_rgb_blend", out, tex, fact, facg, in); + break; + case MTEX_MUL: + GPU_link(mat, "mtex_rgb_mul", out, tex, fact, facg, in); + break; + case MTEX_SCREEN: + GPU_link(mat, "mtex_rgb_screen", out, tex, fact, facg, in); + break; + case MTEX_OVERLAY: + GPU_link(mat, "mtex_rgb_overlay", out, tex, fact, facg, in); + break; + case MTEX_SUB: + GPU_link(mat, "mtex_rgb_sub", out, tex, fact, facg, in); + break; + case MTEX_ADD: + GPU_link(mat, "mtex_rgb_add", out, tex, fact, facg, in); + break; + case MTEX_DIV: + GPU_link(mat, "mtex_rgb_div", out, tex, fact, facg, in); + break; + case MTEX_DIFF: + GPU_link(mat, "mtex_rgb_diff", out, tex, fact, facg, in); + break; + case MTEX_DARK: + GPU_link(mat, "mtex_rgb_dark", out, tex, fact, facg, in); + break; + case MTEX_LIGHT: + GPU_link(mat, "mtex_rgb_light", out, tex, fact, facg, in); + break; + case MTEX_BLEND_HUE: + GPU_link(mat, "mtex_rgb_hue", out, tex, fact, facg, in); + break; + case MTEX_BLEND_SAT: + GPU_link(mat, "mtex_rgb_sat", out, tex, fact, facg, in); + break; + case MTEX_BLEND_VAL: + GPU_link(mat, "mtex_rgb_val", out, tex, fact, facg, in); + break; + case MTEX_BLEND_COLOR: + GPU_link(mat, "mtex_rgb_color", out, tex, fact, facg, in); + break; + default: + GPU_link(mat, "set_rgb_zero", &in); + break; + } +} + +static void texture_value_blend(GPUMaterial *mat, GPUNodeLink *tex, GPUNodeLink *out, GPUNodeLink *fact, GPUNodeLink *facg, int blendtype, int flip, GPUNodeLink **in) +{ + float flipf = (flip)? 1.0f: 0.0; + + switch(blendtype) { + case MTEX_BLEND: + GPU_link(mat, "mtex_value_blend", out, tex, fact, facg, GPU_uniform(&flipf), in); + break; + case MTEX_MUL: + GPU_link(mat, "mtex_value_mul", out, tex, fact, facg, GPU_uniform(&flipf), in); + break; + case MTEX_SCREEN: + GPU_link(mat, "mtex_value_screen", out, tex, fact, facg, GPU_uniform(&flipf), in); + break; + case MTEX_SUB: + GPU_link(mat, "mtex_value_sub", out, tex, fact, facg, GPU_uniform(&flipf), in); + break; + case MTEX_ADD: + GPU_link(mat, "mtex_value_add", out, tex, fact, facg, GPU_uniform(&flipf), in); + break; + case MTEX_DIV: + GPU_link(mat, "mtex_value_div", out, tex, fact, facg, GPU_uniform(&flipf), in); + break; + case MTEX_DIFF: + GPU_link(mat, "mtex_value_diff", out, tex, fact, facg, GPU_uniform(&flipf), in); + break; + case MTEX_DARK: + GPU_link(mat, "mtex_value_dark", out, tex, fact, facg, GPU_uniform(&flipf), in); + break; + case MTEX_LIGHT: + GPU_link(mat, "mtex_value_light", out, tex, fact, facg, GPU_uniform(&flipf), in); + break; + default: + GPU_link(mat, "set_value_zero", &in); + break; + } +} + +static void do_material_tex(GPUShadeInput *shi) +{ + Material *ma= shi->mat; + GPUMaterial *mat= shi->gpumat; + MTex *mtex; + Tex *tex; + GPUNodeLink *texco, *tin, *trgb, *tnor, *tcol, *stencil, *tnorfac; + GPUNodeLink *texco_norm, *texco_orco, *texco_object, *texco_tangent; + GPUNodeLink *texco_global, *texco_uv = NULL; + GPUNodeLink *colfac, *newnor, *varfac, *orn; + char *lastuvname = NULL; + float one = 1.0f, norfac, ofs[3]; + int tex_nr, rgbnor, talpha; + + GPU_link(mat, "set_value", GPU_uniform(&one), &stencil); + + GPU_link(mat, "texco_norm", GPU_builtin(GPU_VIEW_NORMAL), &texco_norm); + GPU_link(mat, "texco_orco", GPU_attribute(CD_ORCO, ""), &texco_orco); + GPU_link(mat, "texco_object", GPU_builtin(GPU_INVERSE_VIEW_MATRIX), + GPU_builtin(GPU_INVERSE_OBJECT_MATRIX), + GPU_builtin(GPU_VIEW_POSITION), &texco_object); + GPU_link(mat, "texco_tangent", GPU_attribute(CD_TANGENT, ""), &texco_tangent); + GPU_link(mat, "texco_global", GPU_builtin(GPU_INVERSE_VIEW_MATRIX), + GPU_builtin(GPU_VIEW_POSITION), &texco_global); + + orn= texco_norm; + + /* go over texture slots */ + for(tex_nr=0; tex_nrseptex & (1<mtex[tex_nr]) { + mtex= ma->mtex[tex_nr]; + + tex= mtex->tex; + if(tex==0) continue; + + /* which coords */ + if(mtex->texco==TEXCO_ORCO) + texco= texco_orco; + else if(mtex->texco==TEXCO_OBJECT) + texco= texco_object; + else if(mtex->texco==TEXCO_NORM) + texco= texco_norm; + else if(mtex->texco==TEXCO_TANGENT) + texco= texco_object; + else if(mtex->texco==TEXCO_GLOB) + texco= texco_global; + else if(mtex->texco==TEXCO_REFL) + texco= shi->ref; + else if(mtex->texco==TEXCO_UV) { + if(1) { //!(texco_uv && strcmp(mtex->uvname, lastuvname) == 0)) { + GPU_link(mat, "texco_uv", GPU_attribute(CD_MTFACE, mtex->uvname), &texco_uv); + lastuvname = mtex->uvname; + } + texco= texco_uv; + } + else + continue; + + /* in case of uv, this would just undo a multiplication in texco_uv */ + if(mtex->texco != TEXCO_UV) + GPU_link(mat, "mtex_2d_mapping", texco, &texco); + + if(mtex->size[0] != 1.0f || mtex->size[1] != 1.0f || mtex->size[2] != 1.0f) + GPU_link(mat, "mtex_mapping_size", texco, GPU_uniform(mtex->size), &texco); + + ofs[0] = mtex->ofs[0] + 0.5f - 0.5f*mtex->size[0]; + ofs[1] = mtex->ofs[1] + 0.5f - 0.5f*mtex->size[1]; + ofs[2] = 0.0f; + if(ofs[0] != 0.0f || ofs[1] != 0.0f || ofs[2] != 0.0f) + GPU_link(mat, "mtex_mapping_ofs", texco, GPU_uniform(ofs), &texco); + + if(tex && tex->type == TEX_IMAGE && tex->ima) { + GPU_link(mat, "mtex_image", texco, GPU_image(tex->ima, NULL), &tin, &trgb, &tnor); + rgbnor= TEX_RGB; + talpha= 1; + } + else continue; + + /* texture output */ + if((rgbnor & TEX_RGB) && (mtex->texflag & MTEX_RGBTOINT)) { + GPU_link(mat, "mtex_rgbtoint", trgb, &tin); + rgbnor -= TEX_RGB; + } + + if(mtex->texflag & MTEX_NEGATIVE) { + if(rgbnor & TEX_RGB) + GPU_link(mat, "mtex_rgb_invert", trgb, &trgb); + else + GPU_link(mat, "mtex_value_invert", tin, &tin); + } + + if(mtex->texflag & MTEX_STENCIL) { + if(rgbnor & TEX_RGB) + GPU_link(mat, "mtex_rgb_stencil", stencil, trgb, &stencil, &trgb); + else + GPU_link(mat, "mtex_value_stencil", stencil, tin, &stencil, &tin); + } + + /* mapping */ + if(mtex->mapto & (MAP_COL+MAP_COLSPEC)) { + /* stencil maps on the texture control slider, not texture intensity value */ + if(mtex->colfac == 1.0f) + colfac = stencil; + else + GPU_link(mat, "math_multiply", GPU_uniform(&mtex->colfac), stencil, &colfac); + + if((rgbnor & TEX_RGB)==0) { + GPU_link(mat, "set_rgb", GPU_uniform(&mtex->r), &tcol); + } + else { + GPU_link(mat, "set_rgba", trgb, &tcol); + + if(mtex->mapto & MAP_ALPHA) + GPU_link(mat, "set_value", stencil, &tin); + else + GPU_link(mat, "mtex_alpha_from_col", trgb, &tin); + } + + if(mtex->mapto & MAP_COL) + texture_rgb_blend(mat, tcol, shi->rgb, tin, colfac, mtex->blendtype, &shi->rgb); + + if(!(G.fileflags & G_FILE_GLSL_NO_EXTRA_TEX) && (mtex->mapto & MAP_COLSPEC)) + texture_rgb_blend(mat, tcol, shi->specrgb, tin, colfac, mtex->blendtype, &shi->specrgb); + } + + if(!(G.fileflags & G_FILE_GLSL_NO_EXTRA_TEX) && (mtex->mapto & MAP_NORM)) { + if(mtex->maptoneg & MAP_NORM) tex->norfac= -mtex->norfac; + else tex->norfac= mtex->norfac; + + if((tex->type==TEX_IMAGE) && (tex->imaflag & TEX_NORMALMAP)) { + tex->norfac = mtex->norfac; + + if(mtex->maptoneg & MAP_NORM) + GPU_link(mat, "mtex_negate_texnormal", tnor, &tnor); + + if(mtex->normapspace == MTEX_NSPACE_TANGENT) + GPU_link(mat, "mtex_nspace_tangent", GPU_attribute(CD_TANGENT, ""), shi->vn, tnor, &newnor); + else + newnor = tnor; + + norfac = MIN2(mtex->norfac, 1.0); + if(norfac == 1.0f && !GPU_link_changed(stencil)) { + shi->vn = newnor; + } + else { + tnorfac = GPU_uniform(&norfac); + + if(GPU_link_changed(stencil)) + GPU_link(mat, "math_multiply", tnorfac, stencil, &tnorfac); + + GPU_link(mat, "mtex_blend_normal", tnorfac, shi->vn, newnor, &shi->vn); + } + } + + GPU_link(mat, "vec_math_negate", shi->vn, &orn); + GPU_link(mat, "texco_refl", shi->vn, shi->view, &shi->ref); + } + + if((mtex->mapto & MAP_VARS)) { + if(mtex->varfac == 1.0f) + varfac = stencil; + else + GPU_link(mat, "math_multiply", GPU_uniform(&mtex->varfac), stencil, &varfac); + + if(rgbnor & TEX_RGB) { + if(talpha) + GPU_link(mat, "mtex_alpha_from_col", trgb, &tin); + else + GPU_link(mat, "mtex_rgbtoint", trgb, &tin); + } + + if(!(G.fileflags & G_FILE_GLSL_NO_EXTRA_TEX) && mtex->mapto & MAP_REF) { + int flip= mtex->maptoneg & MAP_REF; + texture_value_blend(mat, GPU_uniform(&mtex->def_var), shi->refl, tin, varfac, mtex->blendtype, flip, &shi->refl); + GPU_link(mat, "mtex_value_clamp_positive", shi->refl, &shi->refl); + } + if(!(G.fileflags & G_FILE_GLSL_NO_EXTRA_TEX) && mtex->mapto & MAP_SPEC) { + int flip= mtex->maptoneg & MAP_SPEC; + texture_value_blend(mat, GPU_uniform(&mtex->def_var), shi->spec, tin, varfac, mtex->blendtype, flip, &shi->spec); + GPU_link(mat, "mtex_value_clamp_positive", shi->spec, &shi->spec); + } + if(!(G.fileflags & G_FILE_GLSL_NO_EXTRA_TEX) && mtex->mapto & MAP_EMIT) { + int flip= mtex->maptoneg & MAP_EMIT; + texture_value_blend(mat, GPU_uniform(&mtex->def_var), shi->emit, tin, varfac, mtex->blendtype, flip, &shi->emit); + GPU_link(mat, "mtex_value_clamp_positive", shi->emit, &shi->emit); + } + if(!(G.fileflags & G_FILE_GLSL_NO_EXTRA_TEX) && mtex->mapto & MAP_HAR) { + int flip= mtex->maptoneg & MAP_HAR; + GPU_link(mat, "mtex_har_divide", shi->har, &shi->har); + texture_value_blend(mat, GPU_uniform(&mtex->def_var), shi->har, tin, varfac, mtex->blendtype, flip, &shi->har); + GPU_link(mat, "mtex_har_multiply_clamp", shi->har, &shi->har); + } + if(mtex->mapto & MAP_ALPHA) { + int flip= mtex->maptoneg & MAP_ALPHA; + texture_value_blend(mat, GPU_uniform(&mtex->def_var), shi->alpha, tin, varfac, mtex->blendtype, flip, &shi->alpha); + GPU_link(mat, "mtex_value_clamp", shi->alpha, &shi->alpha); + } + if(!(G.fileflags & G_FILE_GLSL_NO_EXTRA_TEX) && mtex->mapto & MAP_AMB) { + int flip= mtex->maptoneg & MAP_AMB; + texture_value_blend(mat, GPU_uniform(&mtex->def_var), shi->amb, tin, varfac, mtex->blendtype, flip, &shi->amb); + GPU_link(mat, "mtex_value_clamp", shi->amb, &shi->amb); + } + } + } + } +} + +void GPU_shadeinput_set(GPUMaterial *mat, Material *ma, GPUShadeInput *shi) +{ + float hard = ma->har; + + memset(shi, 0, sizeof(*shi)); + + shi->gpumat = mat; + shi->mat = ma; + + GPU_link(mat, "set_rgb", GPU_uniform(&ma->r), &shi->rgb); + GPU_link(mat, "set_rgb", GPU_uniform(&ma->specr), &shi->specrgb); + GPU_link(mat, "shade_norm", GPU_builtin(GPU_VIEW_NORMAL), &shi->vn); + GPU_link(mat, "set_value", GPU_uniform(&ma->alpha), &shi->alpha); + GPU_link(mat, "set_value", GPU_uniform(&ma->ref), &shi->refl); + GPU_link(mat, "set_value", GPU_uniform(&ma->spec), &shi->spec); + GPU_link(mat, "set_value", GPU_uniform(&ma->emit), &shi->emit); + GPU_link(mat, "set_value", GPU_uniform(&hard), &shi->har); + GPU_link(mat, "set_value", GPU_uniform(&ma->amb), &shi->amb); + GPU_link(mat, "shade_view", GPU_builtin(GPU_VIEW_POSITION), &shi->view); + GPU_link(mat, "vcol_attribute", GPU_attribute(CD_MCOL, ""), &shi->vcol); + GPU_link(mat, "texco_refl", shi->vn, shi->view, &shi->ref); +} + +void GPU_shaderesult_set(GPUShadeInput *shi, GPUShadeResult *shr) +{ + GPUMaterial *mat= shi->gpumat; + GPUNodeLink *emit, *ulinfac, *ulogfac, *mistfac; + Material *ma= shi->mat; + World *world= mat->scene->world; + float linfac, logfac, misttype; + + memset(shr, 0, sizeof(*shr)); + + if(ma->mode & MA_VERTEXCOLP) + shi->rgb = shi->vcol; + + do_material_tex(shi); + + if(ma->mode & MA_ZTRA) + GPU_material_enable_alpha(mat); + + if((G.fileflags & G_FILE_GLSL_NO_LIGHTS) || (ma->mode & MA_SHLESS)) { + shr->combined = shi->rgb; + shr->alpha = shi->alpha; + } + else { + if(GPU_link_changed(shi->emit) || ma->emit != 0.0f) { + if((ma->mode & (MA_VERTEXCOL|MA_VERTEXCOLP))== MA_VERTEXCOL) { + GPU_link(mat, "shade_add", shi->emit, shi->vcol, &emit); + GPU_link(mat, "shade_mul", emit, shi->rgb, &shr->diff); + } + else + GPU_link(mat, "shade_mul_value", shi->emit, shi->rgb, &shr->diff); + } + else + GPU_link(mat, "set_rgb_zero", &shr->diff); + + GPU_link(mat, "set_rgb_zero", &shr->spec); + + material_lights(shi, shr); + + shr->combined = shr->diff; + shr->alpha = shi->alpha; + + if(world) { + /* exposure correction */ + if(world->exp!=0.0f || world->range!=1.0f) { + linfac= 1.0 + pow((2.0*world->exp + 0.5), -10); + logfac= log((linfac-1.0)/linfac)/world->range; + + GPU_link(mat, "set_value", GPU_uniform(&linfac), &ulinfac); + GPU_link(mat, "set_value", GPU_uniform(&logfac), &ulogfac); + + GPU_link(mat, "shade_exposure_correct", shr->combined, + ulinfac, ulogfac, &shr->combined); + GPU_link(mat, "shade_exposure_correct", shr->spec, + ulinfac, ulogfac, &shr->spec); + } + + /* ambient color */ + if(world->ambr!=0.0f || world->ambg!=0.0f || world->ambb!=0.0f) { + if(GPU_link_changed(shi->amb) || ma->amb != 0.0f) + GPU_link(mat, "shade_maddf", shr->combined, GPU_uniform(&ma->amb), + GPU_uniform(&world->ambr), &shr->combined); + } + } + + if(ma->mode & MA_RAMP_COL) ramp_diffuse_result(shi, &shr->combined); + if(ma->mode & MA_RAMP_SPEC) ramp_spec_result(shi, &shr->spec); + + if(GPU_link_changed(shi->spec) || ma->spec != 0.0f) + GPU_link(mat, "shade_add", shr->combined, shr->spec, &shr->combined); + } + + GPU_link(mat, "mtex_alpha_to_col", shr->combined, shr->alpha, &shr->combined); + + if(ma->shade_flag & MA_OBCOLOR) + GPU_link(mat, "shade_obcolor", shr->combined, GPU_builtin(GPU_OBCOLOR), &shr->combined); + + if(world && (world->mode & WO_MIST) && !(ma->mode & MA_NOMIST)) { + misttype = world->mistype; + + GPU_link(mat, "shade_mist_factor", GPU_builtin(GPU_VIEW_POSITION), + GPU_uniform(&world->miststa), GPU_uniform(&world->mistdist), + GPU_uniform(&misttype), GPU_uniform(&world->misi), &mistfac); + + GPU_link(mat, "mix_blend", mistfac, shr->combined, + GPU_uniform(&world->horr), &shr->combined); + } + + if(!(ma->mode & MA_ZTRA)) { + if(world && (GPU_link_changed(shr->alpha) || ma->alpha != 1.0f)) + GPU_link(mat, "shade_world_mix", GPU_uniform(&world->horr), + shr->combined, &shr->combined); + + GPU_link(mat, "shade_alpha_opaque", shr->combined, &shr->combined); + } + + if(ma->shade_flag & MA_OBCOLOR) { + mat->obcolalpha = 1; + GPU_link(mat, "shade_alpha_obcolor", shr->combined, GPU_builtin(GPU_OBCOLOR), &shr->combined); + } +} + +GPUNodeLink *GPU_blender_material(GPUMaterial *mat, Material *ma) +{ + GPUShadeInput shi; + GPUShadeResult shr; + + GPU_shadeinput_set(mat, ma, &shi); + GPU_shaderesult_set(&shi, &shr); + + return shr.combined; +} + +GPUMaterial *GPU_material_from_blender(Scene *scene, Material *ma) +{ + GPUMaterial *mat; + GPUNodeLink *outlink; + LinkData *link; + + for(link=ma->gpumaterial.first; link; link=link->next) + if(((GPUMaterial*)link->data)->scene == scene) + return link->data; + + mat = GPU_material_construct_begin(ma); + mat->scene = scene; + + if(!(G.fileflags & G_FILE_GLSL_NO_NODES) && ma->nodetree && ma->use_nodes) { + ntreeGPUMaterialNodes(ma->nodetree, mat); + } + else { + outlink = GPU_blender_material(mat, ma); + GPU_material_output_link(mat, outlink); + } + + /*if(!GPU_material_construct_end(mat)) { + GPU_material_free(mat); + mat= NULL; + return 0; + }*/ + + GPU_material_construct_end(mat); + + link = MEM_callocN(sizeof(LinkData), "GPUMaterialLink"); + link->data = mat; + BLI_addtail(&ma->gpumaterial, link); + + return mat; +} + +void GPU_materials_free() +{ + Object *ob; + Material *ma; + extern Material defmaterial; + + for(ma=G.main->mat.first; ma; ma=ma->id.next) + GPU_material_free(ma); + + GPU_material_free(&defmaterial); + + for(ob=G.main->object.first; ma; ma=ma->id.next) + GPU_lamp_free(ob); +} + +/* Lamps and shadow buffers */ + +void GPU_lamp_update(GPULamp *lamp, float obmat[][4]) +{ + float mat[4][4]; + + Mat4CpyMat4(mat, obmat); + Mat4Ortho(mat); + + VECCOPY(lamp->vec, mat[2]); + VECCOPY(lamp->co, mat[3]); + Mat4CpyMat4(lamp->obmat, mat); + Mat4Invert(lamp->imat, mat); +} + +static void gpu_lamp_from_blender(Scene *scene, Object *ob, Object *par, Lamp *la, GPULamp *lamp) +{ + float temp, angle, pixsize, wsize; + + lamp->scene = scene; + lamp->ob = ob; + lamp->par = par; + lamp->la = la; + lamp->lay = ob->lay; + + /* add_render_lamp */ + lamp->mode = la->mode; + lamp->type = la->type; + + lamp->energy = la->energy; + if(lamp->mode & LA_NEG) lamp->energy= -lamp->energy; + + lamp->col[0]= la->r*lamp->energy; + lamp->col[1]= la->g*lamp->energy; + lamp->col[2]= la->b*lamp->energy; + + GPU_lamp_update(lamp, ob->obmat); + + lamp->spotsi= la->spotsize; + if(lamp->mode & LA_HALO) + if(lamp->spotsi > 170.0) + lamp->spotsi = 170.0; + lamp->spotsi= cos(M_PI*lamp->spotsi/360.0); + lamp->spotbl= (1.0 - lamp->spotsi)*la->spotblend; + lamp->k= la->k; + + lamp->dist= la->dist; + lamp->falloff_type= la->falloff_type; + lamp->att1= la->att1; + lamp->att2= la->att2; + lamp->curfalloff= la->curfalloff; + + /* initshadowbuf */ + lamp->bias = 0.02f*la->bias; + lamp->size = la->bufsize; + lamp->d= la->clipsta; + lamp->clipend= la->clipend; + + /* arbitrary correction for the fact we do no soft transition */ + lamp->bias *= 0.25f; + + /* makeshadowbuf */ + angle= saacos(lamp->spotsi); + temp= 0.5f*lamp->size*cos(angle)/sin(angle); + pixsize= (lamp->d)/temp; + wsize= pixsize*0.5f*lamp->size; + + i_window(-wsize, wsize, -wsize, wsize, lamp->d, lamp->clipend, lamp->winmat); +} + +static void gpu_lamp_shadow_free(GPULamp *lamp) +{ + if(lamp->tex) + GPU_texture_free(lamp->tex); + if(lamp->fb) + GPU_framebuffer_free(lamp->fb); +} + +GPULamp *GPU_lamp_from_blender(Scene *scene, Object *ob, Object *par) +{ + Lamp *la; + GPULamp *lamp; + LinkData *link; + + for(link=ob->gpulamp.first; link; link=link->next) + if(((GPULamp*)link->data)->par == par && + ((GPULamp*)link->data)->scene == scene) + return link->data; + + lamp = MEM_callocN(sizeof(GPULamp), "GPULamp"); + + link = MEM_callocN(sizeof(LinkData), "GPULampLink"); + link->data = lamp; + BLI_addtail(&ob->gpulamp, link); + + la = ob->data; + gpu_lamp_from_blender(scene, ob, par, la, lamp); + + if(la->type==LA_SPOT && (la->mode & LA_SHAD_BUF)) { + /* opengl */ + lamp->fb = GPU_framebuffer_create(); + if(!lamp->fb) { + gpu_lamp_shadow_free(lamp); + return lamp; + } + + lamp->tex = GPU_texture_create_depth(lamp->size, lamp->size); + if(!lamp->tex) { + gpu_lamp_shadow_free(lamp); + return lamp; + } + + if(!GPU_framebuffer_texture_attach(lamp->fb, lamp->tex)) { + gpu_lamp_shadow_free(lamp); + return lamp; + } + + GPU_framebuffer_restore(); + } + + return lamp; +} + +void GPU_lamp_free(Object *ob) +{ + GPULamp *lamp; + LinkData *link; + LinkNode *nlink; + Material *ma; + + for(link=ob->gpulamp.first; link; link=link->next) { + lamp = link->data; + + for(nlink=lamp->materials; nlink; nlink=nlink->next) { + ma= nlink->link; + if(ma->gpumaterial.first) + GPU_material_free(ma); + } + BLI_linklist_free(lamp->materials, NULL); + + gpu_lamp_shadow_free(lamp); + + MEM_freeN(lamp); + } + + BLI_freelistN(&ob->gpulamp); +} + +int GPU_lamp_has_shadow_buffer(GPULamp *lamp) +{ + return (!(G.fileflags & G_FILE_GLSL_NO_SHADOWS) && + !(G.fileflags & G_FILE_GLSL_NO_LIGHTS) && + lamp->tex && lamp->fb); +} + +void GPU_lamp_shadow_buffer_bind(GPULamp *lamp, float viewmat[][4], int *winsize, float winmat[][4]) +{ + float rangemat[4][4], persmat[4][4]; + + /* initshadowbuf */ + Mat4Invert(lamp->viewmat, lamp->obmat); + Normalize(lamp->viewmat[0]); + Normalize(lamp->viewmat[1]); + Normalize(lamp->viewmat[2]); + + /* makeshadowbuf */ + Mat4MulMat4(persmat, lamp->viewmat, lamp->winmat); + + /* opengl depth buffer is range 0.0..1.0 instead of -1.0..1.0 in blender */ + Mat4One(rangemat); + rangemat[0][0] = 0.5f; + rangemat[1][1] = 0.5f; + rangemat[2][2] = 0.5f; + rangemat[3][0] = 0.5f; + rangemat[3][1] = 0.5f; + rangemat[3][2] = 0.5f; + + Mat4MulMat4(lamp->persmat, persmat, rangemat); + + /* opengl */ + GPU_framebuffer_texture_bind(lamp->fb, lamp->tex); + + /* set matrices */ + Mat4CpyMat4(viewmat, lamp->viewmat); + Mat4CpyMat4(winmat, lamp->winmat); + *winsize = lamp->size; +} + +void GPU_lamp_shadow_buffer_unbind(GPULamp *lamp) +{ + GPU_framebuffer_texture_unbind(lamp->fb, lamp->tex); + GPU_framebuffer_restore(); +} + +int GPU_lamp_shadow_layer(GPULamp *lamp) +{ + if(lamp->fb && lamp->tex && (lamp->mode & (LA_LAYER|LA_LAYER_SHADOW))) + return lamp->lay; + else + return -1; +} + diff --git a/source/blender/gpu/intern/gpu_shader_material.glsl b/source/blender/gpu/intern/gpu_shader_material.glsl new file mode 100644 index 00000000000..309cb738454 --- /dev/null +++ b/source/blender/gpu/intern/gpu_shader_material.glsl @@ -0,0 +1,1543 @@ + +float exp_blender(float f) +{ + return pow(2.71828182846, f); +} + +void rgb_to_hsv(vec4 rgb, out vec4 outcol) +{ + float cmax, cmin, h, s, v, cdelta; + vec3 c; + + cmax = max(rgb[0], max(rgb[1], rgb[2])); + cmin = min(rgb[0], min(rgb[1], rgb[2])); + cdelta = cmax-cmin; + + v = cmax; + if (cmax!=0.0) + s = cdelta/cmax; + else { + s = 0.0; + h = 0.0; + } + + if (s == 0.0) { + h = 0.0; + } + else { + c = (vec3(cmax, cmax, cmax) - rgb.xyz)/cdelta; + + if (rgb.x==cmax) h = c[2] - c[1]; + else if (rgb.y==cmax) h = 2.0 + c[0] - c[2]; + else h = 4.0 + c[1] - c[0]; + + h /= 6.0; + + if (h<0.0) + h += 1.0; + } + + outcol = vec4(h, s, v, rgb.w); +} + +void hsv_to_rgb(vec4 hsv, out vec4 outcol) +{ + float i, f, p, q, t, h, s, v; + vec3 rgb; + + h = hsv[0]; + s = hsv[1]; + v = hsv[2]; + + if(s==0.0) { + rgb = vec3(v, v, v); + } + else { + if(h==1.0) + h = 0.0; + + h *= 6.0; + i = floor(h); + f = h - i; + rgb = vec3(f, f, f); + p = v*(1.0-s); + q = v*(1.0-(s*f)); + t = v*(1.0-(s*(1.0-f))); + + if (i == 0.0) rgb = vec3(v, t, p); + else if (i == 1.0) rgb = vec3(q, v, p); + else if (i == 2.0) rgb = vec3(p, v, t); + else if (i == 3.0) rgb = vec3(p, q, v); + else if (i == 4.0) rgb = vec3(t, p, v); + else rgb = vec3(v, p, q); + } + + outcol = vec4(rgb, hsv.w); +} + +#define M_PI 3.14159265358979323846 + +/*********** SHADER NODES ***************/ + +void vcol_attribute(vec4 attvcol, out vec4 vcol) +{ + vcol = vec4(attvcol.x/255.0, attvcol.y/255.0, attvcol.z/255.0, 1.0); +} + +void uv_attribute(vec2 attuv, out vec3 uv) +{ + uv = vec3(attuv*2.0 - vec2(1.0, 1.0), 0.0); +} + +void geom(vec3 co, vec3 nor, mat4 viewinvmat, vec3 attorco, vec2 attuv, vec4 attvcol, out vec3 global, out vec3 local, out vec3 view, out vec3 orco, out vec3 uv, out vec3 normal, out vec4 vcol, out float frontback) +{ + local = co; + view = normalize(local); + global = (viewinvmat*vec4(local, 1.0)).xyz; + orco = attorco; + uv_attribute(attuv, uv); + normal = -normalize(nor); /* blender render normal is negated */ + vcol_attribute(attvcol, vcol); + frontback = 1.0; +} + +void mapping(vec3 vec, mat4 mat, vec3 minvec, vec3 maxvec, float domin, float domax, out vec3 outvec) +{ + outvec = (mat * vec4(vec, 1.0)).xyz; + if(domin == 1.0) + outvec = max(outvec, minvec); + if(domax == 1.0) + outvec = min(outvec, maxvec); +} + +void camera(vec3 co, out vec3 outview, out float outdepth, out float outdist) +{ + outdepth = abs(co.z); + outdist = length(co); + outview = normalize(co); +} + +void math_add(float val1, float val2, out float outval) +{ + outval = val1 + val2; +} + +void math_subtract(float val1, float val2, out float outval) +{ + outval = val1 - val2; +} + +void math_multiply(float val1, float val2, out float outval) +{ + outval = val1 * val2; +} + +void math_divide(float val1, float val2, out float outval) +{ + if (val2 == 0.0) + outval = 0.0; + else + outval = val1 / val2; +} + +void math_sine(float val, out float outval) +{ + outval = sin(val); +} + +void math_cosine(float val, out float outval) +{ + outval = cos(val); +} + +void math_tangent(float val, out float outval) +{ + outval = tan(val); +} + +void math_asin(float val, out float outval) +{ + if (val <= 1.0 && val >= -1.0) + outval = asin(val); + else + outval = 0.0; +} + +void math_acos(float val, out float outval) +{ + if (val <= 1.0 && val >= -1.0) + outval = acos(val); + else + outval = 0.0; +} + +void math_atan(float val, out float outval) +{ + outval = atan(val); +} + +void math_pow(float val1, float val2, out float outval) +{ + if (val1 >= 0.0) + outval = pow(val1, val2); + else + outval = 0.0; +} + +void math_log(float val1, float val2, out float outval) +{ + if(val1 > 0.0 && val2 > 0.0) + outval= log2(val1) / log2(val2); + else + outval= 0.0; +} + +void math_max(float val1, float val2, out float outval) +{ + outval = max(val1, val2); +} + +void math_min(float val1, float val2, out float outval) +{ + outval = min(val1, val2); +} + +void math_round(float val, out float outval) +{ + outval= floor(val + 0.5); +} + +void math_less_than(float val1, float val2, out float outval) +{ + if(val1 < val2) + outval = 1.0; + else + outval = 0.0; +} + +void math_greater_than(float val1, float val2, out float outval) +{ + if(val1 > val2) + outval = 1.0; + else + outval = 0.0; +} + +void squeeze(float val, float width, float center, out float outval) +{ + outval = 1.0/(1.0 + pow(2.71828183, -((val-center)*width))); +} + +void vec_math_add(vec3 v1, vec3 v2, out vec3 outvec, out float outval) +{ + outvec = v1 + v2; + outval = (abs(outvec[0]) + abs(outvec[1]) + abs(outvec[2]))/3.0; +} + +void vec_math_sub(vec3 v1, vec3 v2, out vec3 outvec, out float outval) +{ + outvec = v1 - v2; + outval = (abs(outvec[0]) + abs(outvec[1]) + abs(outvec[2]))/3.0; +} + +void vec_math_average(vec3 v1, vec3 v2, out vec3 outvec, out float outval) +{ + outvec = v1 + v2; + outval = length(outvec); + outvec = normalize(outvec); +} + +void vec_math_dot(vec3 v1, vec3 v2, out vec3 outvec, out float outval) +{ + outvec = vec3(0, 0, 0); + outval = dot(v1, v2); +} + +void vec_math_cross(vec3 v1, vec3 v2, out vec3 outvec, out float outval) +{ + outvec = cross(v1, v2); + outval = length(outvec); +} + +void vec_math_normalize(vec3 v, out vec3 outvec, out float outval) +{ + outval = length(v); + outvec = normalize(v); +} + +void vec_math_negate(vec3 v, out vec3 outv) +{ + outv = -v; +} + +void normal(vec3 dir, vec3 nor, out vec3 outnor, out float outdot) +{ + outnor = dir; + outdot = -dot(dir, nor); +} + +void curves_vec(vec3 vec, sampler1D curvemap, out vec3 outvec) +{ + outvec.x = texture1D(curvemap, (vec.x + 1.0)*0.5).x; + outvec.y = texture1D(curvemap, (vec.y + 1.0)*0.5).y; + outvec.z = texture1D(curvemap, (vec.z + 1.0)*0.5).z; +} + +void curves_rgb(vec4 col, sampler1D curvemap, out vec4 outcol) +{ + outcol.r = texture1D(curvemap, texture1D(curvemap, col.r).a).r; + outcol.g = texture1D(curvemap, texture1D(curvemap, col.g).a).g; + outcol.b = texture1D(curvemap, texture1D(curvemap, col.b).a).b; + outcol.a = col.a; +} + +void set_value(float val, out float outval) +{ + outval = val; +} + +void set_rgb(vec3 col, out vec3 outcol) +{ + outcol = col; +} + +void set_rgba(vec4 col, out vec4 outcol) +{ + outcol = col; +} + +void set_value_zero(out float outval) +{ + outval = 0.0; +} + +void set_rgb_zero(out vec3 outval) +{ + outval = vec3(0.0); +} + +void set_rgba_zero(out vec4 outval) +{ + outval = vec4(0.0); +} + +void mix_blend(float fac, vec4 col1, vec4 col2, out vec4 outcol) +{ + fac = clamp(fac, 0.0, 1.0); + outcol = mix(col1, col2, fac); + outcol.a = col1.a; +} + +void mix_add(float fac, vec4 col1, vec4 col2, out vec4 outcol) +{ + fac = clamp(fac, 0.0, 1.0); + outcol = mix(col1, col1 + col2, fac); + outcol.a = col1.a; +} + +void mix_mult(float fac, vec4 col1, vec4 col2, out vec4 outcol) +{ + fac = clamp(fac, 0.0, 1.0); + outcol = mix(col1, col1 * col2, fac); + outcol.a = col1.a; +} + +void mix_screen(float fac, vec4 col1, vec4 col2, out vec4 outcol) +{ + fac = clamp(fac, 0.0, 1.0); + float facm = 1.0 - fac; + + outcol = vec4(1.0) - (vec4(facm) + fac*(vec4(1.0) - col2))*(vec4(1.0) - col1); + outcol.a = col1.a; +} + +void mix_overlay(float fac, vec4 col1, vec4 col2, out vec4 outcol) +{ + fac = clamp(fac, 0.0, 1.0); + float facm = 1.0 - fac; + + outcol = col1; + + if(outcol.r < 0.5) + outcol.r *= facm + 2.0*fac*col2.r; + else + outcol.r = 1.0 - (facm + 2.0*fac*(1.0 - col2.r))*(1.0 - outcol.r); + + if(outcol.g < 0.5) + outcol.g *= facm + 2.0*fac*col2.g; + else + outcol.g = 1.0 - (facm + 2.0*fac*(1.0 - col2.g))*(1.0 - outcol.g); + + if(outcol.b < 0.5) + outcol.b *= facm + 2.0*fac*col2.b; + else + outcol.b = 1.0 - (facm + 2.0*fac*(1.0 - col2.b))*(1.0 - outcol.b); +} + +void mix_sub(float fac, vec4 col1, vec4 col2, out vec4 outcol) +{ + fac = clamp(fac, 0.0, 1.0); + outcol = mix(col1, col1 - col2, fac); + outcol.a = col1.a; +} + +void mix_div(float fac, vec4 col1, vec4 col2, out vec4 outcol) +{ + fac = clamp(fac, 0.0, 1.0); + float facm = 1.0 - fac; + + outcol = col1; + + if(col2.r != 0.0) outcol.r = facm*outcol.r + fac*outcol.r/col2.r; + if(col2.g != 0.0) outcol.g = facm*outcol.g + fac*outcol.g/col2.g; + if(col2.b != 0.0) outcol.b = facm*outcol.b + fac*outcol.b/col2.b; +} + +void mix_diff(float fac, vec4 col1, vec4 col2, out vec4 outcol) +{ + fac = clamp(fac, 0.0, 1.0); + outcol = mix(col1, abs(col1 - col2), fac); + outcol.a = col1.a; +} + +void mix_dark(float fac, vec4 col1, vec4 col2, out vec4 outcol) +{ + fac = clamp(fac, 0.0, 1.0); + outcol.rgb = min(col1.rgb, col2.rgb*fac); + outcol.a = col1.a; +} + +void mix_light(float fac, vec4 col1, vec4 col2, out vec4 outcol) +{ + fac = clamp(fac, 0.0, 1.0); + outcol.rgb = max(col1.rgb, col2.rgb*fac); + outcol.a = col1.a; +} + +void mix_dodge(float fac, vec4 col1, vec4 col2, out vec4 outcol) +{ + fac = clamp(fac, 0.0, 1.0); + outcol = col1; + + if(outcol.r != 0.0) { + float tmp = 1.0 - fac*col2.r; + if(tmp <= 0.0) + outcol.r = 1.0; + else if((tmp = outcol.r/tmp) > 1.0) + outcol.r = 1.0; + else + outcol.r = tmp; + } + if(outcol.g != 0.0) { + float tmp = 1.0 - fac*col2.g; + if(tmp <= 0.0) + outcol.g = 1.0; + else if((tmp = outcol.g/tmp) > 1.0) + outcol.g = 1.0; + else + outcol.g = tmp; + } + if(outcol.b != 0.0) { + float tmp = 1.0 - fac*col2.b; + if(tmp <= 0.0) + outcol.b = 1.0; + else if((tmp = outcol.b/tmp) > 1.0) + outcol.b = 1.0; + else + outcol.b = tmp; + } +} + +void mix_burn(float fac, vec4 col1, vec4 col2, out vec4 outcol) +{ + fac = clamp(fac, 0.0, 1.0); + float tmp, facm = 1.0 - fac; + + outcol = col1; + + tmp = facm + fac*col2.r; + if(tmp <= 0.0) + outcol.r = 0.0; + else if((tmp = (1.0 - (1.0 - outcol.r)/tmp)) < 0.0) + outcol.r = 0.0; + else if(tmp > 1.0) + outcol.r = 1.0; + else + outcol.r = tmp; + + tmp = facm + fac*col2.g; + if(tmp <= 0.0) + outcol.g = 0.0; + else if((tmp = (1.0 - (1.0 - outcol.g)/tmp)) < 0.0) + outcol.g = 0.0; + else if(tmp > 1.0) + outcol.g = 1.0; + else + outcol.g = tmp; + + tmp = facm + fac*col2.b; + if(tmp <= 0.0) + outcol.b = 0.0; + else if((tmp = (1.0 - (1.0 - outcol.b)/tmp)) < 0.0) + outcol.b = 0.0; + else if(tmp > 1.0) + outcol.b = 1.0; + else + outcol.b = tmp; +} + +void mix_hue(float fac, vec4 col1, vec4 col2, out vec4 outcol) +{ + fac = clamp(fac, 0.0, 1.0); + float facm = 1.0 - fac; + + outcol = col1; + + vec4 hsv, hsv2, tmp; + rgb_to_hsv(col2, hsv2); + + if(hsv2.y != 0.0) { + rgb_to_hsv(outcol, hsv); + hsv.x = hsv2.x; + hsv_to_rgb(hsv, tmp); + + outcol = mix(outcol, tmp, fac); + outcol.a = col1.a; + } +} + +void mix_sat(float fac, vec4 col1, vec4 col2, out vec4 outcol) +{ + fac = clamp(fac, 0.0, 1.0); + float facm = 1.0 - fac; + + outcol = col1; + + vec4 hsv, hsv2; + rgb_to_hsv(outcol, hsv); + + if(hsv.y != 0.0) { + rgb_to_hsv(col2, hsv2); + + hsv.y = facm*hsv.y + fac*hsv2.y; + hsv_to_rgb(hsv, outcol); + } +} + +void mix_val(float fac, vec4 col1, vec4 col2, out vec4 outcol) +{ + fac = clamp(fac, 0.0, 1.0); + float facm = 1.0 - fac; + + vec4 hsv, hsv2; + rgb_to_hsv(col1, hsv); + rgb_to_hsv(col2, hsv2); + + hsv.z = facm*hsv.z + fac*hsv2.z; + hsv_to_rgb(hsv, outcol); +} + +void mix_color(float fac, vec4 col1, vec4 col2, out vec4 outcol) +{ + fac = clamp(fac, 0.0, 1.0); + float facm = 1.0 - fac; + + outcol = col1; + + vec4 hsv, hsv2, tmp; + rgb_to_hsv(col2, hsv2); + + if(hsv2.y != 0.0) { + rgb_to_hsv(outcol, hsv); + hsv.x = hsv2.x; + hsv.y = hsv2.y; + hsv_to_rgb(hsv, tmp); + + outcol = mix(outcol, tmp, fac); + outcol.a = col1.a; + } +} + +void valtorgb(float fac, sampler1D colormap, out vec4 outcol, out float outalpha) +{ + outcol = texture1D(colormap, fac); + outalpha = outcol.a; +} + +void rgbtobw(vec4 color, out float outval) +{ + outval = color.r*0.35 + color.g*0.45 + color.b*0.2; +} + +void invert(float fac, vec4 col, out vec4 outcol) +{ + outcol.xyz = mix(col.xyz, vec3(1.0, 1.0, 1.0) - col.xyz, fac); + outcol.w = col.w; +} + +void hue_sat(float hue, float sat, float value, float fac, vec4 col, out vec4 outcol) +{ + vec4 hsv; + + rgb_to_hsv(col, hsv); + + hsv[0] += (hue - 0.5); + if(hsv[0]>1.0) hsv[0]-=1.0; else if(hsv[0]<0.0) hsv[0]+= 1.0; + hsv[1] *= sat; + if(hsv[1]>1.0) hsv[1]= 1.0; else if(hsv[1]<0.0) hsv[1]= 0.0; + hsv[2] *= value; + if(hsv[2]>1.0) hsv[2]= 1.0; else if(hsv[2]<0.0) hsv[2]= 0.0; + + hsv_to_rgb(hsv, outcol); + + outcol = mix(col, outcol, fac); +} + +void separate_rgb(vec4 col, out float r, out float g, out float b) +{ + r = col.r; + g = col.g; + b = col.b; +} + +void combine_rgb(float r, float g, float b, out vec4 col) +{ + col = vec4(r, g, b, 1.0); +} + +void output_node(vec4 rgb, float alpha, out vec4 outrgb) +{ + outrgb = vec4(rgb.rgb, alpha); +} + +/*********** TEXTURES ***************/ + +void texture_flip_blend(vec3 vec, out vec3 outvec) +{ + outvec = vec.yxz; +} + +void texture_blend_lin(vec3 vec, out float outval) +{ + outval = (1.0+vec.x)/2.0; +} + +void texture_blend_quad(vec3 vec, out float outval) +{ + outval = max((1.0+vec.x)/2.0, 0.0); + outval *= outval; +} + +void texture_wood_sin(vec3 vec, out float value, out vec4 color, out vec3 normal) +{ + float a = sqrt(vec.x*vec.x + vec.y*vec.y + vec.z*vec.z)*20.0; + float wi = 0.5 + 0.5*sin(a); + + value = wi; + color = vec4(wi, wi, wi, 1.0); + normal = vec3(0.0, 0.0, 0.0); +} + +void texture_image(vec3 vec, sampler2D ima, out float value, out vec4 color, out vec3 normal) +{ + color = texture2D(ima, (vec.xy + vec2(1.0, 1.0))*0.5); + value = 1.0; + + normal.x = 2.0*(color.r - 0.5); + normal.y = 2.0*(0.5 - color.g); + normal.z = 2.0*(color.b - 0.5); +} + +/************* MTEX *****************/ + +void texco_orco(vec3 attorco, out vec3 orco) +{ + orco = attorco; +} + +void texco_uv(vec2 attuv, out vec3 uv) +{ + /* disabled for now, works together with leaving out mtex_2d_mapping + uv = vec3(attuv*2.0 - vec2(1.0, 1.0), 0.0); */ + uv = vec3(attuv, 0.0); +} + +void texco_norm(vec3 normal, out vec3 outnormal) +{ + /* corresponds to shi->orn, which is negated so cancels + out blender normal negation */ + outnormal = normalize(normal); +} + +void texco_tangent(vec3 tangent, out vec3 outtangent) +{ + outtangent = normalize(tangent); +} + +void texco_global(mat4 viewinvmat, vec3 co, out vec3 global) +{ + global = (viewinvmat*vec4(co, 1.0)).xyz; +} + +void texco_object(mat4 viewinvmat, mat4 obinvmat, vec3 co, out vec3 object) +{ + object = (obinvmat*(viewinvmat*vec4(co, 1.0))).xyz; +} + +void texco_refl(vec3 vn, vec3 view, out vec3 ref) +{ + ref = view - 2.0*dot(vn, view)*vn; +} + +void shade_norm(vec3 normal, out vec3 outnormal) +{ + /* blender render normal is negated */ + outnormal = -normalize(normal); +} + +void mtex_rgb_blend(vec3 outcol, vec3 texcol, float fact, float facg, out vec3 incol) +{ + float facm; + + fact *= facg; + facm = 1.0-fact; + + incol = fact*texcol + facm*outcol; +} + +void mtex_rgb_mul(vec3 outcol, vec3 texcol, float fact, float facg, out vec3 incol) +{ + float facm; + + fact *= facg; + facm = 1.0-facg; + + incol = (facm + fact*texcol)*outcol; +} + +void mtex_rgb_screen(vec3 outcol, vec3 texcol, float fact, float facg, out vec3 incol) +{ + float facm; + + fact *= facg; + facm = 1.0-facg; + + incol = vec3(1.0) - (vec3(facm) + fact*(vec3(1.0) - texcol))*(vec3(1.0) - outcol); +} + +void mtex_rgb_overlay(vec3 outcol, vec3 texcol, float fact, float facg, out vec3 incol) +{ + float facm; + + fact *= facg; + facm = 1.0-facg; + + if(outcol.r < 0.5) + incol.r = outcol.r*(facm + 2.0*fact*texcol.r); + else + incol.r = 1.0 - (facm + 2.0*fact*(1.0 - texcol.r))*(1.0 - outcol.r); + + if(outcol.g < 0.5) + incol.g = outcol.g*(facm + 2.0*fact*texcol.g); + else + incol.g = 1.0 - (facm + 2.0*fact*(1.0 - texcol.g))*(1.0 - outcol.g); + + if(outcol.b < 0.5) + incol.b = outcol.b*(facm + 2.0*fact*texcol.b); + else + incol.b = 1.0 - (facm + 2.0*fact*(1.0 - texcol.b))*(1.0 - outcol.b); +} + +void mtex_rgb_sub(vec3 outcol, vec3 texcol, float fact, float facg, out vec3 incol) +{ + incol = -fact*facg*texcol + outcol; +} + +void mtex_rgb_add(vec3 outcol, vec3 texcol, float fact, float facg, out vec3 incol) +{ + incol = fact*facg*texcol + outcol; +} + +void mtex_rgb_div(vec3 outcol, vec3 texcol, float fact, float facg, out vec3 incol) +{ + float facm; + + fact *= facg; + facm = 1.0-fact; + + if(texcol.r != 0.0) incol.r = facm*outcol.r + fact*outcol.r/texcol.r; + if(texcol.g != 0.0) incol.g = facm*outcol.g + fact*outcol.g/texcol.g; + if(texcol.b != 0.0) incol.b = facm*outcol.b + fact*outcol.b/texcol.b; +} + +void mtex_rgb_diff(vec3 outcol, vec3 texcol, float fact, float facg, out vec3 incol) +{ + float facm; + + fact *= facg; + facm = 1.0-fact; + + incol = facm*outcol + fact*abs(texcol - outcol); +} + +void mtex_rgb_dark(vec3 outcol, vec3 texcol, float fact, float facg, out vec3 incol) +{ + float facm, col; + + fact *= facg; + facm = 1.0-fact; + + col = fact*texcol.r; + if(col < outcol.r) incol.r = col; else incol.r = outcol.r; + col = fact*texcol.g; + if(col < outcol.g) incol.g = col; else incol.g = outcol.g; + col = fact*texcol.b; + if(col < outcol.b) incol.b = col; else incol.b = outcol.b; +} + +void mtex_rgb_light(vec3 outcol, vec3 texcol, float fact, float facg, out vec3 incol) +{ + float facm, col; + + fact *= facg; + facm = 1.0-fact; + + col = fact*texcol.r; + if(col > outcol.r) incol.r = col; else incol.r = outcol.r; + col = fact*texcol.g; + if(col > outcol.g) incol.g = col; else incol.g = outcol.g; + col = fact*texcol.b; + if(col > outcol.b) incol.b = col; else incol.b = outcol.b; +} + +void mtex_rgb_hue(vec3 outcol, vec3 texcol, float fact, float facg, out vec3 incol) +{ + vec4 col; + + mix_hue(fact*facg, vec4(outcol, 1.0), vec4(texcol, 1.0), col); + incol.rgb = col.rgb; +} + +void mtex_rgb_sat(vec3 outcol, vec3 texcol, float fact, float facg, out vec3 incol) +{ + vec4 col; + + mix_sat(fact*facg, vec4(outcol, 1.0), vec4(texcol, 1.0), col); + incol.rgb = col.rgb; +} + +void mtex_rgb_val(vec3 outcol, vec3 texcol, float fact, float facg, out vec3 incol) +{ + vec4 col; + + mix_val(fact*facg, vec4(outcol, 1.0), vec4(texcol, 1.0), col); + incol.rgb = col.rgb; +} + +void mtex_rgb_color(vec3 outcol, vec3 texcol, float fact, float facg, out vec3 incol) +{ + vec4 col; + + mix_color(fact*facg, vec4(outcol, 1.0), vec4(texcol, 1.0), col); + incol.rgb = col.rgb; +} + +void mtex_value_vars(inout float fact, float facg, out float facm, float flip) +{ + fact *= facg; + facm = 1.0-fact; + + if(flip != 0.0) { + float tmp = fact; + fact = facm; + facm = tmp; + } +} + +void mtex_value_blend(float outcol, float texcol, float fact, float facg, float flip, out float incol) +{ + float facm; + mtex_value_vars(fact, facg, facm, flip); + + incol = fact*texcol + facm*outcol; +} + +void mtex_value_mul(float outcol, float texcol, float fact, float facg, float flip, out float incol) +{ + float facm; + mtex_value_vars(fact, facg, facm, flip); + + facm = 1.0 - facg; + incol = (facm + fact*texcol)*outcol; +} + +void mtex_value_screen(float outcol, float texcol, float fact, float facg, float flip, out float incol) +{ + float facm; + mtex_value_vars(fact, facg, facm, flip); + + facm = 1.0 - facg; + incol = 1.0 - (facm + fact*(1.0 - texcol))*(1.0 - outcol); +} + +void mtex_value_sub(float outcol, float texcol, float fact, float facg, float flip, out float incol) +{ + float facm; + mtex_value_vars(fact, facg, facm, flip); + + fact = -fact; + incol = fact*texcol + outcol; +} + +void mtex_value_add(float outcol, float texcol, float fact, float facg, float flip, out float incol) +{ + float facm; + mtex_value_vars(fact, facg, facm, flip); + + fact = fact; + incol = fact*texcol + outcol; +} + +void mtex_value_div(float outcol, float texcol, float fact, float facg, float flip, out float incol) +{ + float facm; + mtex_value_vars(fact, facg, facm, flip); + + if(texcol != 0.0) + incol = facm*outcol + fact*outcol/texcol; + else + incol = 0.0; +} + +void mtex_value_diff(float outcol, float texcol, float fact, float facg, float flip, out float incol) +{ + float facm; + mtex_value_vars(fact, facg, facm, flip); + + incol = facm*outcol + fact*abs(texcol - outcol); +} + +void mtex_value_dark(float outcol, float texcol, float fact, float facg, float flip, out float incol) +{ + float facm; + mtex_value_vars(fact, facg, facm, flip); + + float col = fact*texcol; + if(col < outcol) incol = col; else incol = outcol; +} + +void mtex_value_light(float outcol, float texcol, float fact, float facg, float flip, out float incol) +{ + float facm; + mtex_value_vars(fact, facg, facm, flip); + + float col = fact*texcol; + if(col > outcol) incol = col; else incol = outcol; +} + +void mtex_value_clamp_positive(float fac, out float outfac) +{ + outfac = max(fac, 0.0); +} + +void mtex_value_clamp(float fac, out float outfac) +{ + outfac = clamp(fac, 0.0, 1.0); +} + +void mtex_har_divide(float har, out float outhar) +{ + outhar = har/128.0; +} + +void mtex_har_multiply_clamp(float har, out float outhar) +{ + har *= 128.0; + + if(har < 1.0) outhar = 1.0; + else if(har > 511.0) outhar = 511.0; + else outhar = har; +} + +void mtex_alpha_from_col(vec4 col, out float alpha) +{ + alpha = col.a; +} + +void mtex_alpha_to_col(vec4 col, float alpha, out vec4 outcol) +{ + outcol = vec4(col.rgb, alpha); +} + +void mtex_rgbtoint(vec4 rgb, out float intensity) +{ + intensity = dot(vec3(0.35, 0.45, 0.2), rgb.rgb); +} + +void mtex_value_invert(float invalue, out float outvalue) +{ + outvalue = 1.0 - invalue; +} + +void mtex_rgb_invert(vec4 inrgb, out vec4 outrgb) +{ + outrgb = vec4(vec3(1.0) - inrgb.rgb, inrgb.a); +} + +void mtex_value_stencil(float stencil, float intensity, out float outstencil, out float outintensity) +{ + float fact = intensity; + outintensity = intensity*stencil; + outstencil = stencil*fact; +} + +void mtex_rgb_stencil(float stencil, vec4 rgb, out float outstencil, out vec4 outrgb) +{ + float fact = rgb.a; + outrgb = vec4(rgb.rgb, rgb.a*stencil); + outstencil = stencil*fact; +} + +void mtex_mapping_ofs(vec3 texco, vec3 ofs, out vec3 outtexco) +{ + outtexco = texco + ofs; +} + +void mtex_mapping_size(vec3 texco, vec3 size, out vec3 outtexco) +{ + outtexco = size*texco; +} + +void mtex_2d_mapping(vec3 vec, out vec3 outvec) +{ + outvec = vec3(vec.xy*0.5 + vec2(0.5, 0.5), vec.z); +} + +void mtex_image(vec3 vec, sampler2D ima, out float value, out vec4 color, out vec3 normal) +{ + color = texture2D(ima, vec.xy); + value = 1.0; + + normal = 2.0*(vec3(color.r, -color.g, color.b) - vec3(0.5, -0.5, 0.5)); +} + +void mtex_negate_texnormal(vec3 normal, out vec3 outnormal) +{ + outnormal = vec3(-normal.x, -normal.y, normal.z); +} + +void mtex_nspace_tangent(vec3 tangent, vec3 normal, vec3 texnormal, out vec3 outnormal) +{ + tangent = normalize(tangent); + vec3 B = cross(normal, tangent); + + outnormal = texnormal.x*tangent + texnormal.y*B + texnormal.z*normal; + outnormal = normalize(outnormal); +} + +void mtex_blend_normal(float norfac, vec3 normal, vec3 newnormal, out vec3 outnormal) +{ + outnormal = (1.0 - norfac)*normal + norfac*newnormal; + outnormal = normalize(outnormal); +} + +/******* MATERIAL *********/ + +void lamp_visibility_sun_hemi(vec3 lampvec, out vec3 lv, out float dist, out float visifac) +{ + lv = lampvec; + dist = 1.0; + visifac = 1.0; +} + +void lamp_visibility_other(vec3 co, vec3 lampco, out vec3 lv, out float dist, out float visifac) +{ + lv = co - lampco; + dist = length(lv); + lv = normalize(lv); + visifac = 1.0; +} + +void lamp_falloff_invlinear(float lampdist, float dist, out float visifac) +{ + visifac = lampdist/(lampdist + dist); +} + +void lamp_falloff_invsquare(float lampdist, float dist, out float visifac) +{ + visifac = lampdist/(lampdist + dist*dist); +} + +void lamp_falloff_sliders(float lampdist, float ld1, float ld2, float dist, out float visifac) +{ + float lampdistkw = lampdist*lampdist; + + visifac = lampdist/(lampdist + ld1*dist); + visifac *= lampdistkw/(lampdistkw + ld2*dist*dist); +} + +void lamp_falloff_curve(float lampdist, sampler1D curvemap, float dist, out float visifac) +{ + visifac = texture1D(curvemap, dist/lampdist).x; +} + +void lamp_visibility_sphere(float lampdist, float dist, float visifac, out float outvisifac) +{ + float t= lampdist - dist; + + outvisifac= visifac*max(t, 0.0)/lampdist; +} + +void lamp_visibility_spot_square(vec3 lampvec, mat4 lampimat, vec3 lv, out float inpr) +{ + if(dot(lv, lampvec) > 0.0) { + vec3 lvrot = (lampimat*vec4(lv, 0.0)).xyz; + float x = max(abs(lvrot.x/lvrot.z), abs(lvrot.y/lvrot.z)); + + inpr = 1.0/sqrt(1.0 + x*x); + } + else + inpr = 0.0; +} + +void lamp_visibility_spot_circle(vec3 lampvec, vec3 lv, out float inpr) +{ + inpr = dot(lv, lampvec); +} + +void lamp_visibility_spot(float spotsi, float spotbl, float inpr, float visifac, out float outvisifac) +{ + float t = spotsi; + + if(inpr <= t) { + outvisifac = 0.0; + } + else { + t = inpr - t; + + /* soft area */ + if(spotbl != 0.0) + inpr *= smoothstep(0.0, 1.0, t/spotbl); + + outvisifac = visifac*inpr; + } +} + +void lamp_visibility_clamp(float visifac, out float outvisifac) +{ + outvisifac = (visifac < 0.001)? 0.0: visifac; +} + +void shade_view(vec3 co, out vec3 view) +{ + /* handle perspective/orthographic */ + view = (gl_ProjectionMatrix[3][3] == 0.0)? normalize(co): vec3(0.0, 0.0, -1.0); +} + +void shade_tangent_v(vec3 lv, vec3 tang, out vec3 vn) +{ + vec3 c = cross(lv, tang); + vec3 vnor = cross(c, tang); + + vn = -normalize(vnor); +} + +void shade_inp(vec3 vn, vec3 lv, out float inp) +{ + inp = dot(vn, lv); +} + +void shade_is_no_diffuse(out float is) +{ + is = 0.0; +} + +void shade_is_hemi(float inp, out float is) +{ + is = 0.5*inp + 0.5; +} + +float area_lamp_energy(mat4 area, vec3 co, vec3 vn) +{ + vec3 vec[4], c[4]; + float rad[4], fac; + + vec[0] = normalize(co - area[0].xyz); + vec[1] = normalize(co - area[1].xyz); + vec[2] = normalize(co - area[2].xyz); + vec[3] = normalize(co - area[3].xyz); + + c[0] = normalize(cross(vec[0], vec[1])); + c[1] = normalize(cross(vec[1], vec[2])); + c[2] = normalize(cross(vec[2], vec[3])); + c[3] = normalize(cross(vec[3], vec[0])); + + rad[0] = acos(dot(vec[0], vec[1])); + rad[1] = acos(dot(vec[1], vec[2])); + rad[2] = acos(dot(vec[2], vec[3])); + rad[3] = acos(dot(vec[3], vec[0])); + + fac= rad[0]*dot(vn, c[0]); + fac+= rad[1]*dot(vn, c[1]); + fac+= rad[2]*dot(vn, c[2]); + fac+= rad[3]*dot(vn, c[3]); + + return max(fac, 0.0); +} + +void shade_inp_area(vec3 position, vec3 lampco, vec3 lampvec, vec3 vn, mat4 area, float areasize, float k, out float inp) +{ + vec3 co = position; + vec3 vec = co - lampco; + + if(dot(vec, lampvec) < 0.0) { + inp = 0.0; + } + else { + float intens = area_lamp_energy(area, co, vn); + + inp = pow(intens*areasize, k); + } +} + +void shade_diffuse_oren_nayer(float nl, vec3 n, vec3 l, vec3 v, float rough, out float is) +{ + vec3 h = normalize(v + l); + float nh = max(dot(n, h), 0.0); + float nv = max(dot(n, v), 0.0); + float realnl = dot(n, l); + + if(realnl < 0.0) { + is = 0.0; + } + else if(nl < 0.0) { + is = 0.0; + } + else { + float vh = max(dot(v, h), 0.0); + float Lit_A = acos(realnl); + float View_A = acos(nv); + + vec3 Lit_B = normalize(l - realnl*n); + vec3 View_B = normalize(v - nv*n); + + float t = max(dot(Lit_B, View_B), 0.0); + + float a, b; + + if(Lit_A > View_A) { + a = Lit_A; + b = View_A; + } + else { + a = View_A; + b = Lit_A; + } + + float A = 1.0 - (0.5*((rough*rough)/((rough*rough) + 0.33))); + float B = 0.45*((rough*rough)/((rough*rough) + 0.09)); + + b *= 0.95; + is = nl*(A + (B * t * sin(a) * tan(b))); + } +} + +void shade_diffuse_toon(vec3 n, vec3 l, vec3 v, float size, float tsmooth, out float is) +{ + float rslt = dot(n, l); + float ang = acos(rslt); + + if(ang < size) is = 1.0; + else if(ang > (size + tsmooth) || tsmooth == 0.0) is = 0.0; + else is = 1.0 - ((ang - size)/tsmooth); +} + +void shade_diffuse_minnaert(float nl, vec3 n, vec3 v, float darkness, out float is) +{ + if(nl <= 0.0) { + is = 0.0; + } + else { + float nv = max(dot(n, v), 0.0); + + if(darkness <= 1.0) + is = nl*pow(max(nv*nl, 0.1), darkness - 1.0); + else + is = nl*pow(1.0001 - nv, darkness - 1.0); + } +} + +float fresnel_fac(vec3 view, vec3 vn, float grad, float fac) +{ + float t1, t2; + float ffac; + + if(fac==0.0) { + ffac = 1.0; + } + else { + t1= dot(view, vn); + if(t1>0.0) t2= 1.0+t1; + else t2= 1.0-t1; + + t2= grad + (1.0-grad)*pow(t2, fac); + + if(t2<0.0) ffac = 0.0; + else if(t2>1.0) ffac = 1.0; + else ffac = t2; + } + + return ffac; +} + +void shade_diffuse_fresnel(vec3 vn, vec3 lv, vec3 view, float fac_i, float fac, out float is) +{ + is = fresnel_fac(lv, vn, fac_i, fac); +} + +void shade_cubic(float is, out float outis) +{ + if(is>0.0 && is<1.0) + outis= smoothstep(0.0, 1.0, is); + else + outis= is; +} + +void shade_visifac(float i, float visifac, float refl, out float outi) +{ + /*if(i > 0.0)*/ + outi = max(i*visifac*refl, 0.0); + /*else + outi = i;*/ +} + +void shade_tangent_v_spec(vec3 tang, out vec3 vn) +{ + vn = tang; +} + +void shade_add_to_diffuse(float i, vec3 lampcol, vec3 col, out vec3 outcol) +{ + if(i > 0.0) + outcol = i*lampcol*col; + else + outcol = vec3(0.0, 0.0, 0.0); +} + +void shade_hemi_spec(vec3 vn, vec3 lv, vec3 view, float spec, float hard, float visifac, out float t) +{ + lv += view; + lv = normalize(lv); + + t = dot(vn, lv); + t = 0.5*t + 0.5; + + t = visifac*spec*pow(t, hard); +} + +void shade_phong_spec(vec3 n, vec3 l, vec3 v, float hard, out float specfac) +{ + vec3 h = normalize(l + v); + float rslt = max(dot(h, n), 0.0); + + specfac = pow(rslt, hard); +} + +void shade_cooktorr_spec(vec3 n, vec3 l, vec3 v, float hard, out float specfac) +{ + vec3 h = normalize(v + l); + float nh = dot(n, h); + + if(nh < 0.0) { + specfac = 0.0; + } + else { + float nv = max(dot(n, v), 0.0); + float i = pow(nh, hard); + + i = i/(0.1+nv); + specfac = i; + } +} + +void shade_blinn_spec(vec3 n, vec3 l, vec3 v, float refrac, float spec_power, out float specfac) +{ + if(refrac < 1.0) { + specfac = 0.0; + } + else if(spec_power == 0.0) { + specfac = 0.0; + } + else { + if(spec_power<100.0) + spec_power= sqrt(1.0/spec_power); + else + spec_power= 10.0/spec_power; + + vec3 h = normalize(v + l); + float nh = dot(n, h); + if(nh < 0.0) { + specfac = 0.0; + } + else { + float nv = max(dot(n, v), 0.01); + float nl = dot(n, l); + if(nl <= 0.01) { + specfac = 0.0; + } + else { + float vh = max(dot(v, h), 0.01); + + float a = 1.0; + float b = (2.0*nh*nv)/vh; + float c = (2.0*nh*nl)/vh; + + float g; + + if(a < b && a < c) g = a; + else if(b < a && b < c) g = b; + else if(c < a && c < b) g = c; + + float p = sqrt(((refrac * refrac)+(vh*vh)-1.0)); + float f = (((p-vh)*(p-vh))/((p+vh)*(p+vh)))*(1.0+((((vh*(p+vh))-1.0)*((vh*(p+vh))-1.0))/(((vh*(p-vh))+1.0)*((vh*(p-vh))+1.0)))); + float ang = acos(nh); + + specfac = max(f*g*exp_blender((-(ang*ang)/(2.0*spec_power*spec_power))), 0.0); + } + } + } +} + +void shade_wardiso_spec(vec3 n, vec3 l, vec3 v, float rms, out float specfac) +{ + vec3 h = normalize(l + v); + float nh = max(dot(n, h), 0.001); + float nv = max(dot(n, v), 0.001); + float nl = max(dot(n, l), 0.001); + float angle = tan(acos(nh)); + float alpha = max(rms, 0.001); + + specfac= nl * (1.0/(4.0*M_PI*alpha*alpha))*(exp_blender(-(angle*angle)/(alpha*alpha))/(sqrt(nv*nl))); +} + +void shade_toon_spec(vec3 n, vec3 l, vec3 v, float size, float tsmooth, out float specfac) +{ + vec3 h = normalize(l + v); + float rslt = dot(h, n); + float ang = acos(rslt); + + if(ang < size) rslt = 1.0; + else if(ang >= (size + tsmooth) || tsmooth == 0.0) rslt = 0.0; + else rslt = 1.0 - ((ang - size)/tsmooth); + + specfac = rslt; +} + +void shade_spec_area_inp(float specfac, float inp, out float outspecfac) +{ + outspecfac = specfac*inp; +} + +void shade_spec_t(float shadfac, float spec, float visifac, float specfac, out float t) +{ + t = shadfac*spec*visifac*specfac; +} + +void shade_add_spec(float t, vec3 lampcol, vec3 speccol, out vec3 outcol) +{ + outcol = t*lampcol*speccol; +} + +void shade_add(vec4 col1, vec4 col2, out vec4 outcol) +{ + outcol = col1 + col2; +} + +void shade_madd(vec4 col, vec4 col1, vec4 col2, out vec4 outcol) +{ + outcol = col + col1*col2; +} + +void shade_maddf(vec4 col, float f, vec4 col1, out vec4 outcol) +{ + outcol = col + f*col1; +} + +void shade_mul(vec4 col1, vec4 col2, out vec4 outcol) +{ + outcol = col1*col2; +} + +void shade_mul_value(float fac, vec4 col, out vec4 outcol) +{ + outcol = col*fac; +} + +void shade_obcolor(vec4 col, vec4 obcol, out vec4 outcol) +{ + outcol = vec4(col.rgb*obcol.rgb, col.a); +} + +void ramp_rgbtobw(vec3 color, out float outval) +{ + outval = color.r*0.3 + color.g*0.58 + color.b*0.12; +} + +void shade_only_shadow(float i, float shadfac, float energy, vec3 rgb, vec3 specrgb, vec4 diff, vec4 spec, out vec4 outdiff, out vec4 outspec) +{ + shadfac = i*energy*(1.0 - shadfac); + + outdiff = diff - vec4(rgb*shadfac, 0.0); + outspec = spec - vec4(specrgb*shadfac, 0.0); +} + +void test_shadowbuf(vec3 rco, sampler2DShadow shadowmap, mat4 shadowpersmat, float shadowbias, float inp, out float result) +{ + if(inp <= 0.0) { + result = 0.0; + } + else { + vec4 co = shadowpersmat*vec4(rco, 1.0); + + //float bias = (1.5 - inp*inp)*shadowbias; + co.z -= shadowbias*co.w; + + result = shadow2DProj(shadowmap, co).x; + } +} + +void shade_exposure_correct(vec3 col, float linfac, float logfac, out vec3 outcol) +{ + outcol = linfac*(1.0 - exp(col*logfac)); +} + +void shade_mist_factor(vec3 co, float miststa, float mistdist, float misttype, float misi, out float outfac) +{ + float fac, zcor; + + zcor = (gl_ProjectionMatrix[3][3] == 0.0)? length(co): -co[2]; + + fac = clamp((zcor-miststa)/mistdist, 0.0, 1.0); + if(misttype == 0.0) fac *= fac; + else if(misttype == 1.0); + else fac = sqrt(fac); + + outfac = 1.0 - (1.0-fac)*(1.0-misi); +} + +void shade_world_mix(vec3 hor, vec4 col, out vec4 outcol) +{ + float fac = clamp(col.a, 0.0, 1.0); + outcol = vec4(mix(hor, col.rgb, fac), col.a); +} + +void shade_alpha_opaque(vec4 col, out vec4 outcol) +{ + outcol = vec4(col.rgb, 1.0); +} + +void shade_alpha_obcolor(vec4 col, vec4 obcol, out vec4 outcol) +{ + outcol = vec4(col.rgb, col.a*obcol.a); +} + diff --git a/source/blender/gpu/intern/gpu_shader_material.glsl.c b/source/blender/gpu/intern/gpu_shader_material.glsl.c new file mode 100644 index 00000000000..38263efd864 --- /dev/null +++ b/source/blender/gpu/intern/gpu_shader_material.glsl.c @@ -0,0 +1,1026 @@ +/* DataToC output of file */ + +int datatoc_gpu_shader_material_glsl_size= 32638; +char datatoc_gpu_shader_material_glsl[]= { + 10,102,108,111, 97,116, 32,101,120,112, 95, 98,108,101,110,100,101,114, 40,102,108,111, 97,116, 32,102, 41, 10,123, 10, + 9,114,101,116,117,114,110, 32,112,111,119, 40, 50, 46, 55, 49, 56, 50, 56, 49, 56, 50, 56, 52, 54, 44, 32,102, 41, 59, 10,125, + 10, 10,118,111,105,100, 32,114,103, 98, 95,116,111, 95,104,115,118, 40,118,101, 99, 52, 32,114,103, 98, 44, 32,111,117,116, 32, +118,101, 99, 52, 32,111,117,116, 99,111,108, 41, 10,123, 10, 9,102,108,111, 97,116, 32, 99,109, 97,120, 44, 32, 99,109,105,110, + 44, 32,104, 44, 32,115, 44, 32,118, 44, 32, 99,100,101,108,116, 97, 59, 10, 9,118,101, 99, 51, 32, 99, 59, 10, 10, 9, 99,109, + 97,120, 32, 61, 32,109, 97,120, 40,114,103, 98, 91, 48, 93, 44, 32,109, 97,120, 40,114,103, 98, 91, 49, 93, 44, 32,114,103, 98, + 91, 50, 93, 41, 41, 59, 10, 9, 99,109,105,110, 32, 61, 32,109,105,110, 40,114,103, 98, 91, 48, 93, 44, 32,109,105,110, 40,114, +103, 98, 91, 49, 93, 44, 32,114,103, 98, 91, 50, 93, 41, 41, 59, 10, 9, 99,100,101,108,116, 97, 32, 61, 32, 99,109, 97,120, 45, + 99,109,105,110, 59, 10, 10, 9,118, 32, 61, 32, 99,109, 97,120, 59, 10, 9,105,102, 32, 40, 99,109, 97,120, 33, 61, 48, 46, 48, + 41, 10, 9, 9,115, 32, 61, 32, 99,100,101,108,116, 97, 47, 99,109, 97,120, 59, 10, 9,101,108,115,101, 32,123, 10, 9, 9,115, + 32, 61, 32, 48, 46, 48, 59, 10, 9, 9,104, 32, 61, 32, 48, 46, 48, 59, 10, 9,125, 10, 10, 9,105,102, 32, 40,115, 32, 61, 61, + 32, 48, 46, 48, 41, 32,123, 10, 9, 9,104, 32, 61, 32, 48, 46, 48, 59, 10, 9,125, 10, 9,101,108,115,101, 32,123, 10, 9, 9, + 99, 32, 61, 32, 40,118,101, 99, 51, 40, 99,109, 97,120, 44, 32, 99,109, 97,120, 44, 32, 99,109, 97,120, 41, 32, 45, 32,114,103, + 98, 46,120,121,122, 41, 47, 99,100,101,108,116, 97, 59, 10, 10, 9, 9,105,102, 32, 40,114,103, 98, 46,120, 61, 61, 99,109, 97, +120, 41, 32,104, 32, 61, 32, 99, 91, 50, 93, 32, 45, 32, 99, 91, 49, 93, 59, 10, 9, 9,101,108,115,101, 32,105,102, 32, 40,114, +103, 98, 46,121, 61, 61, 99,109, 97,120, 41, 32,104, 32, 61, 32, 50, 46, 48, 32, 43, 32, 99, 91, 48, 93, 32, 45, 32, 32, 99, 91, + 50, 93, 59, 10, 9, 9,101,108,115,101, 32,104, 32, 61, 32, 52, 46, 48, 32, 43, 32, 99, 91, 49, 93, 32, 45, 32, 99, 91, 48, 93, + 59, 10, 10, 9, 9,104, 32, 47, 61, 32, 54, 46, 48, 59, 10, 10, 9, 9,105,102, 32, 40,104, 60, 48, 46, 48, 41, 10, 9, 9, 9, +104, 32, 43, 61, 32, 49, 46, 48, 59, 10, 9,125, 10, 10, 9,111,117,116, 99,111,108, 32, 61, 32,118,101, 99, 52, 40,104, 44, 32, +115, 44, 32,118, 44, 32,114,103, 98, 46,119, 41, 59, 10,125, 10, 10,118,111,105,100, 32,104,115,118, 95,116,111, 95,114,103, 98, + 40,118,101, 99, 52, 32,104,115,118, 44, 32,111,117,116, 32,118,101, 99, 52, 32,111,117,116, 99,111,108, 41, 10,123, 10, 9,102, +108,111, 97,116, 32,105, 44, 32,102, 44, 32,112, 44, 32,113, 44, 32,116, 44, 32,104, 44, 32,115, 44, 32,118, 59, 10, 9,118,101, + 99, 51, 32,114,103, 98, 59, 10, 10, 9,104, 32, 61, 32,104,115,118, 91, 48, 93, 59, 10, 9,115, 32, 61, 32,104,115,118, 91, 49, + 93, 59, 10, 9,118, 32, 61, 32,104,115,118, 91, 50, 93, 59, 10, 10, 9,105,102, 40,115, 61, 61, 48, 46, 48, 41, 32,123, 10, 9, + 9,114,103, 98, 32, 61, 32,118,101, 99, 51, 40,118, 44, 32,118, 44, 32,118, 41, 59, 10, 9,125, 10, 9,101,108,115,101, 32,123, + 10, 9, 9,105,102, 40,104, 61, 61, 49, 46, 48, 41, 10, 9, 9, 9,104, 32, 61, 32, 48, 46, 48, 59, 10, 9, 9, 10, 9, 9,104, + 32, 42, 61, 32, 54, 46, 48, 59, 10, 9, 9,105, 32, 61, 32,102,108,111,111,114, 40,104, 41, 59, 10, 9, 9,102, 32, 61, 32,104, + 32, 45, 32,105, 59, 10, 9, 9,114,103, 98, 32, 61, 32,118,101, 99, 51, 40,102, 44, 32,102, 44, 32,102, 41, 59, 10, 9, 9,112, + 32, 61, 32,118, 42, 40, 49, 46, 48, 45,115, 41, 59, 10, 9, 9,113, 32, 61, 32,118, 42, 40, 49, 46, 48, 45, 40,115, 42,102, 41, + 41, 59, 10, 9, 9,116, 32, 61, 32,118, 42, 40, 49, 46, 48, 45, 40,115, 42, 40, 49, 46, 48, 45,102, 41, 41, 41, 59, 10, 9, 9, + 10, 9, 9,105,102, 32, 40,105, 32, 61, 61, 32, 48, 46, 48, 41, 32,114,103, 98, 32, 61, 32,118,101, 99, 51, 40,118, 44, 32,116, + 44, 32,112, 41, 59, 10, 9, 9,101,108,115,101, 32,105,102, 32, 40,105, 32, 61, 61, 32, 49, 46, 48, 41, 32,114,103, 98, 32, 61, + 32,118,101, 99, 51, 40,113, 44, 32,118, 44, 32,112, 41, 59, 10, 9, 9,101,108,115,101, 32,105,102, 32, 40,105, 32, 61, 61, 32, + 50, 46, 48, 41, 32,114,103, 98, 32, 61, 32,118,101, 99, 51, 40,112, 44, 32,118, 44, 32,116, 41, 59, 10, 9, 9,101,108,115,101, + 32,105,102, 32, 40,105, 32, 61, 61, 32, 51, 46, 48, 41, 32,114,103, 98, 32, 61, 32,118,101, 99, 51, 40,112, 44, 32,113, 44, 32, +118, 41, 59, 10, 9, 9,101,108,115,101, 32,105,102, 32, 40,105, 32, 61, 61, 32, 52, 46, 48, 41, 32,114,103, 98, 32, 61, 32,118, +101, 99, 51, 40,116, 44, 32,112, 44, 32,118, 41, 59, 10, 9, 9,101,108,115,101, 32,114,103, 98, 32, 61, 32,118,101, 99, 51, 40, +118, 44, 32,112, 44, 32,113, 41, 59, 10, 9,125, 10, 10, 9,111,117,116, 99,111,108, 32, 61, 32,118,101, 99, 52, 40,114,103, 98, + 44, 32,104,115,118, 46,119, 41, 59, 10,125, 10, 10, 35,100,101,102,105,110,101, 32, 77, 95, 80, 73, 32, 51, 46, 49, 52, 49, 53, + 57, 50, 54, 53, 51, 53, 56, 57, 55, 57, 51, 50, 51, 56, 52, 54, 10, 10, 47, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 32, 83, + 72, 65, 68, 69, 82, 32, 78, 79, 68, 69, 83, 32, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 47, 10, 10,118,111, +105,100, 32,118, 99,111,108, 95, 97,116,116,114,105, 98,117,116,101, 40,118,101, 99, 52, 32, 97,116,116,118, 99,111,108, 44, 32, +111,117,116, 32,118,101, 99, 52, 32,118, 99,111,108, 41, 10,123, 10, 9,118, 99,111,108, 32, 61, 32,118,101, 99, 52, 40, 97,116, +116,118, 99,111,108, 46,120, 47, 50, 53, 53, 46, 48, 44, 32, 97,116,116,118, 99,111,108, 46,121, 47, 50, 53, 53, 46, 48, 44, 32, + 97,116,116,118, 99,111,108, 46,122, 47, 50, 53, 53, 46, 48, 44, 32, 49, 46, 48, 41, 59, 10,125, 10, 10,118,111,105,100, 32,117, +118, 95, 97,116,116,114,105, 98,117,116,101, 40,118,101, 99, 50, 32, 97,116,116,117,118, 44, 32,111,117,116, 32,118,101, 99, 51, + 32,117,118, 41, 10,123, 10, 9,117,118, 32, 61, 32,118,101, 99, 51, 40, 97,116,116,117,118, 42, 50, 46, 48, 32, 45, 32,118,101, + 99, 50, 40, 49, 46, 48, 44, 32, 49, 46, 48, 41, 44, 32, 48, 46, 48, 41, 59, 10,125, 10, 10,118,111,105,100, 32,103,101,111,109, + 40,118,101, 99, 51, 32, 99,111, 44, 32,118,101, 99, 51, 32,110,111,114, 44, 32,109, 97,116, 52, 32,118,105,101,119,105,110,118, +109, 97,116, 44, 32,118,101, 99, 51, 32, 97,116,116,111,114, 99,111, 44, 32,118,101, 99, 50, 32, 97,116,116,117,118, 44, 32,118, +101, 99, 52, 32, 97,116,116,118, 99,111,108, 44, 32,111,117,116, 32,118,101, 99, 51, 32,103,108,111, 98, 97,108, 44, 32,111,117, +116, 32,118,101, 99, 51, 32,108,111, 99, 97,108, 44, 32,111,117,116, 32,118,101, 99, 51, 32,118,105,101,119, 44, 32,111,117,116, + 32,118,101, 99, 51, 32,111,114, 99,111, 44, 32,111,117,116, 32,118,101, 99, 51, 32,117,118, 44, 32,111,117,116, 32,118,101, 99, + 51, 32,110,111,114,109, 97,108, 44, 32,111,117,116, 32,118,101, 99, 52, 32,118, 99,111,108, 44, 32,111,117,116, 32,102,108,111, + 97,116, 32,102,114,111,110,116, 98, 97, 99,107, 41, 10,123, 10, 9,108,111, 99, 97,108, 32, 61, 32, 99,111, 59, 10, 9,118,105, +101,119, 32, 61, 32,110,111,114,109, 97,108,105,122,101, 40,108,111, 99, 97,108, 41, 59, 10, 9,103,108,111, 98, 97,108, 32, 61, + 32, 40,118,105,101,119,105,110,118,109, 97,116, 42,118,101, 99, 52, 40,108,111, 99, 97,108, 44, 32, 49, 46, 48, 41, 41, 46,120, +121,122, 59, 10, 9,111,114, 99,111, 32, 61, 32, 97,116,116,111,114, 99,111, 59, 10, 9,117,118, 95, 97,116,116,114,105, 98,117, +116,101, 40, 97,116,116,117,118, 44, 32,117,118, 41, 59, 10, 9,110,111,114,109, 97,108, 32, 61, 32, 45,110,111,114,109, 97,108, +105,122,101, 40,110,111,114, 41, 59, 9, 47, 42, 32, 98,108,101,110,100,101,114, 32,114,101,110,100,101,114, 32,110,111,114,109, + 97,108, 32,105,115, 32,110,101,103, 97,116,101,100, 32, 42, 47, 10, 9,118, 99,111,108, 95, 97,116,116,114,105, 98,117,116,101, + 40, 97,116,116,118, 99,111,108, 44, 32,118, 99,111,108, 41, 59, 10, 9,102,114,111,110,116, 98, 97, 99,107, 32, 61, 32, 49, 46, + 48, 59, 10,125, 10, 10,118,111,105,100, 32,109, 97,112,112,105,110,103, 40,118,101, 99, 51, 32,118,101, 99, 44, 32,109, 97,116, + 52, 32,109, 97,116, 44, 32,118,101, 99, 51, 32,109,105,110,118,101, 99, 44, 32,118,101, 99, 51, 32,109, 97,120,118,101, 99, 44, + 32,102,108,111, 97,116, 32,100,111,109,105,110, 44, 32,102,108,111, 97,116, 32,100,111,109, 97,120, 44, 32,111,117,116, 32,118, +101, 99, 51, 32,111,117,116,118,101, 99, 41, 10,123, 10, 9,111,117,116,118,101, 99, 32, 61, 32, 40,109, 97,116, 32, 42, 32,118, +101, 99, 52, 40,118,101, 99, 44, 32, 49, 46, 48, 41, 41, 46,120,121,122, 59, 10, 9,105,102, 40,100,111,109,105,110, 32, 61, 61, + 32, 49, 46, 48, 41, 10, 9, 9,111,117,116,118,101, 99, 32, 61, 32,109, 97,120, 40,111,117,116,118,101, 99, 44, 32,109,105,110, +118,101, 99, 41, 59, 10, 9,105,102, 40,100,111,109, 97,120, 32, 61, 61, 32, 49, 46, 48, 41, 10, 9, 9,111,117,116,118,101, 99, + 32, 61, 32,109,105,110, 40,111,117,116,118,101, 99, 44, 32,109, 97,120,118,101, 99, 41, 59, 10,125, 10, 10,118,111,105,100, 32, + 99, 97,109,101,114, 97, 40,118,101, 99, 51, 32, 99,111, 44, 32,111,117,116, 32,118,101, 99, 51, 32,111,117,116,118,105,101,119, + 44, 32,111,117,116, 32,102,108,111, 97,116, 32,111,117,116,100,101,112,116,104, 44, 32,111,117,116, 32,102,108,111, 97,116, 32, +111,117,116,100,105,115,116, 41, 10,123, 10, 9,111,117,116,100,101,112,116,104, 32, 61, 32, 97, 98,115, 40, 99,111, 46,122, 41, + 59, 10, 9,111,117,116,100,105,115,116, 32, 61, 32,108,101,110,103,116,104, 40, 99,111, 41, 59, 10, 9,111,117,116,118,105,101, +119, 32, 61, 32,110,111,114,109, 97,108,105,122,101, 40, 99,111, 41, 59, 10,125, 10, 10,118,111,105,100, 32,109, 97,116,104, 95, + 97,100,100, 40,102,108,111, 97,116, 32,118, 97,108, 49, 44, 32,102,108,111, 97,116, 32,118, 97,108, 50, 44, 32,111,117,116, 32, +102,108,111, 97,116, 32,111,117,116,118, 97,108, 41, 10,123, 10, 9,111,117,116,118, 97,108, 32, 61, 32,118, 97,108, 49, 32, 43, + 32,118, 97,108, 50, 59, 10,125, 10, 10,118,111,105,100, 32,109, 97,116,104, 95,115,117, 98,116,114, 97, 99,116, 40,102,108,111, + 97,116, 32,118, 97,108, 49, 44, 32,102,108,111, 97,116, 32,118, 97,108, 50, 44, 32,111,117,116, 32,102,108,111, 97,116, 32,111, +117,116,118, 97,108, 41, 10,123, 10, 9,111,117,116,118, 97,108, 32, 61, 32,118, 97,108, 49, 32, 45, 32,118, 97,108, 50, 59, 10, +125, 10, 10,118,111,105,100, 32,109, 97,116,104, 95,109,117,108,116,105,112,108,121, 40,102,108,111, 97,116, 32,118, 97,108, 49, + 44, 32,102,108,111, 97,116, 32,118, 97,108, 50, 44, 32,111,117,116, 32,102,108,111, 97,116, 32,111,117,116,118, 97,108, 41, 10, +123, 10, 9,111,117,116,118, 97,108, 32, 61, 32,118, 97,108, 49, 32, 42, 32,118, 97,108, 50, 59, 10,125, 10, 10,118,111,105,100, + 32,109, 97,116,104, 95,100,105,118,105,100,101, 40,102,108,111, 97,116, 32,118, 97,108, 49, 44, 32,102,108,111, 97,116, 32,118, + 97,108, 50, 44, 32,111,117,116, 32,102,108,111, 97,116, 32,111,117,116,118, 97,108, 41, 10,123, 10, 9,105,102, 32, 40,118, 97, +108, 50, 32, 61, 61, 32, 48, 46, 48, 41, 10, 9, 9,111,117,116,118, 97,108, 32, 61, 32, 48, 46, 48, 59, 10, 9,101,108,115,101, + 10, 9, 9,111,117,116,118, 97,108, 32, 61, 32,118, 97,108, 49, 32, 47, 32,118, 97,108, 50, 59, 10,125, 10, 10,118,111,105,100, + 32,109, 97,116,104, 95,115,105,110,101, 40,102,108,111, 97,116, 32,118, 97,108, 44, 32,111,117,116, 32,102,108,111, 97,116, 32, +111,117,116,118, 97,108, 41, 10,123, 10, 9,111,117,116,118, 97,108, 32, 61, 32,115,105,110, 40,118, 97,108, 41, 59, 10,125, 10, + 10,118,111,105,100, 32,109, 97,116,104, 95, 99,111,115,105,110,101, 40,102,108,111, 97,116, 32,118, 97,108, 44, 32,111,117,116, + 32,102,108,111, 97,116, 32,111,117,116,118, 97,108, 41, 10,123, 10, 9,111,117,116,118, 97,108, 32, 61, 32, 99,111,115, 40,118, + 97,108, 41, 59, 10,125, 10, 10,118,111,105,100, 32,109, 97,116,104, 95,116, 97,110,103,101,110,116, 40,102,108,111, 97,116, 32, +118, 97,108, 44, 32,111,117,116, 32,102,108,111, 97,116, 32,111,117,116,118, 97,108, 41, 10,123, 10, 9,111,117,116,118, 97,108, + 32, 61, 32,116, 97,110, 40,118, 97,108, 41, 59, 10,125, 10, 10,118,111,105,100, 32,109, 97,116,104, 95, 97,115,105,110, 40,102, +108,111, 97,116, 32,118, 97,108, 44, 32,111,117,116, 32,102,108,111, 97,116, 32,111,117,116,118, 97,108, 41, 10,123, 10, 9,105, +102, 32, 40,118, 97,108, 32, 60, 61, 32, 49, 46, 48, 32, 38, 38, 32,118, 97,108, 32, 62, 61, 32, 45, 49, 46, 48, 41, 10, 9, 9, +111,117,116,118, 97,108, 32, 61, 32, 97,115,105,110, 40,118, 97,108, 41, 59, 10, 9,101,108,115,101, 10, 9, 9,111,117,116,118, + 97,108, 32, 61, 32, 48, 46, 48, 59, 10,125, 10, 10,118,111,105,100, 32,109, 97,116,104, 95, 97, 99,111,115, 40,102,108,111, 97, +116, 32,118, 97,108, 44, 32,111,117,116, 32,102,108,111, 97,116, 32,111,117,116,118, 97,108, 41, 10,123, 10, 9,105,102, 32, 40, +118, 97,108, 32, 60, 61, 32, 49, 46, 48, 32, 38, 38, 32,118, 97,108, 32, 62, 61, 32, 45, 49, 46, 48, 41, 10, 9, 9,111,117,116, +118, 97,108, 32, 61, 32, 97, 99,111,115, 40,118, 97,108, 41, 59, 10, 9,101,108,115,101, 10, 9, 9,111,117,116,118, 97,108, 32, + 61, 32, 48, 46, 48, 59, 10,125, 10, 10,118,111,105,100, 32,109, 97,116,104, 95, 97,116, 97,110, 40,102,108,111, 97,116, 32,118, + 97,108, 44, 32,111,117,116, 32,102,108,111, 97,116, 32,111,117,116,118, 97,108, 41, 10,123, 10, 9,111,117,116,118, 97,108, 32, + 61, 32, 97,116, 97,110, 40,118, 97,108, 41, 59, 10,125, 10, 10,118,111,105,100, 32,109, 97,116,104, 95,112,111,119, 40,102,108, +111, 97,116, 32,118, 97,108, 49, 44, 32,102,108,111, 97,116, 32,118, 97,108, 50, 44, 32,111,117,116, 32,102,108,111, 97,116, 32, +111,117,116,118, 97,108, 41, 10,123, 10, 9,105,102, 32, 40,118, 97,108, 49, 32, 62, 61, 32, 48, 46, 48, 41, 10, 9, 9,111,117, +116,118, 97,108, 32, 61, 32,112,111,119, 40,118, 97,108, 49, 44, 32,118, 97,108, 50, 41, 59, 10, 9,101,108,115,101, 10, 9, 9, +111,117,116,118, 97,108, 32, 61, 32, 48, 46, 48, 59, 10,125, 10, 10,118,111,105,100, 32,109, 97,116,104, 95,108,111,103, 40,102, +108,111, 97,116, 32,118, 97,108, 49, 44, 32,102,108,111, 97,116, 32,118, 97,108, 50, 44, 32,111,117,116, 32,102,108,111, 97,116, + 32,111,117,116,118, 97,108, 41, 10,123, 10, 9,105,102, 40,118, 97,108, 49, 32, 62, 32, 48, 46, 48, 32, 32, 38, 38, 32,118, 97, +108, 50, 32, 62, 32, 48, 46, 48, 41, 10, 9, 9,111,117,116,118, 97,108, 61, 32,108,111,103, 50, 40,118, 97,108, 49, 41, 32, 47, + 32,108,111,103, 50, 40,118, 97,108, 50, 41, 59, 10, 9,101,108,115,101, 10, 9, 9,111,117,116,118, 97,108, 61, 32, 48, 46, 48, + 59, 10,125, 10, 10,118,111,105,100, 32,109, 97,116,104, 95,109, 97,120, 40,102,108,111, 97,116, 32,118, 97,108, 49, 44, 32,102, +108,111, 97,116, 32,118, 97,108, 50, 44, 32,111,117,116, 32,102,108,111, 97,116, 32,111,117,116,118, 97,108, 41, 10,123, 10, 9, +111,117,116,118, 97,108, 32, 61, 32,109, 97,120, 40,118, 97,108, 49, 44, 32,118, 97,108, 50, 41, 59, 10,125, 10, 10,118,111,105, +100, 32,109, 97,116,104, 95,109,105,110, 40,102,108,111, 97,116, 32,118, 97,108, 49, 44, 32,102,108,111, 97,116, 32,118, 97,108, + 50, 44, 32,111,117,116, 32,102,108,111, 97,116, 32,111,117,116,118, 97,108, 41, 10,123, 10, 9,111,117,116,118, 97,108, 32, 61, + 32,109,105,110, 40,118, 97,108, 49, 44, 32,118, 97,108, 50, 41, 59, 10,125, 10, 10,118,111,105,100, 32,109, 97,116,104, 95,114, +111,117,110,100, 40,102,108,111, 97,116, 32,118, 97,108, 44, 32,111,117,116, 32,102,108,111, 97,116, 32,111,117,116,118, 97,108, + 41, 10,123, 10, 9,111,117,116,118, 97,108, 61, 32,102,108,111,111,114, 40,118, 97,108, 32, 43, 32, 48, 46, 53, 41, 59, 10,125, + 10, 10,118,111,105,100, 32,109, 97,116,104, 95,108,101,115,115, 95,116,104, 97,110, 40,102,108,111, 97,116, 32,118, 97,108, 49, + 44, 32,102,108,111, 97,116, 32,118, 97,108, 50, 44, 32,111,117,116, 32,102,108,111, 97,116, 32,111,117,116,118, 97,108, 41, 10, +123, 10, 9,105,102, 40,118, 97,108, 49, 32, 60, 32,118, 97,108, 50, 41, 10, 9, 9,111,117,116,118, 97,108, 32, 61, 32, 49, 46, + 48, 59, 10, 9,101,108,115,101, 10, 9, 9,111,117,116,118, 97,108, 32, 61, 32, 48, 46, 48, 59, 10,125, 10, 10,118,111,105,100, + 32,109, 97,116,104, 95,103,114,101, 97,116,101,114, 95,116,104, 97,110, 40,102,108,111, 97,116, 32,118, 97,108, 49, 44, 32,102, +108,111, 97,116, 32,118, 97,108, 50, 44, 32,111,117,116, 32,102,108,111, 97,116, 32,111,117,116,118, 97,108, 41, 10,123, 10, 9, +105,102, 40,118, 97,108, 49, 32, 62, 32,118, 97,108, 50, 41, 10, 9, 9,111,117,116,118, 97,108, 32, 61, 32, 49, 46, 48, 59, 10, + 9,101,108,115,101, 10, 9, 9,111,117,116,118, 97,108, 32, 61, 32, 48, 46, 48, 59, 10,125, 10, 10,118,111,105,100, 32,115,113, +117,101,101,122,101, 40,102,108,111, 97,116, 32,118, 97,108, 44, 32,102,108,111, 97,116, 32,119,105,100,116,104, 44, 32,102,108, +111, 97,116, 32, 99,101,110,116,101,114, 44, 32,111,117,116, 32,102,108,111, 97,116, 32,111,117,116,118, 97,108, 41, 10,123, 10, + 9,111,117,116,118, 97,108, 32, 61, 32, 49, 46, 48, 47, 40, 49, 46, 48, 32, 43, 32,112,111,119, 40, 50, 46, 55, 49, 56, 50, 56, + 49, 56, 51, 44, 32, 45, 40, 40,118, 97,108, 45, 99,101,110,116,101,114, 41, 42,119,105,100,116,104, 41, 41, 41, 59, 10,125, 10, + 10,118,111,105,100, 32,118,101, 99, 95,109, 97,116,104, 95, 97,100,100, 40,118,101, 99, 51, 32,118, 49, 44, 32,118,101, 99, 51, + 32,118, 50, 44, 32,111,117,116, 32,118,101, 99, 51, 32,111,117,116,118,101, 99, 44, 32,111,117,116, 32,102,108,111, 97,116, 32, +111,117,116,118, 97,108, 41, 10,123, 10, 9,111,117,116,118,101, 99, 32, 61, 32,118, 49, 32, 43, 32,118, 50, 59, 10, 9,111,117, +116,118, 97,108, 32, 61, 32, 40, 97, 98,115, 40,111,117,116,118,101, 99, 91, 48, 93, 41, 32, 43, 32, 97, 98,115, 40,111,117,116, +118,101, 99, 91, 49, 93, 41, 32, 43, 32, 97, 98,115, 40,111,117,116,118,101, 99, 91, 50, 93, 41, 41, 47, 51, 46, 48, 59, 10,125, + 10, 10,118,111,105,100, 32,118,101, 99, 95,109, 97,116,104, 95,115,117, 98, 40,118,101, 99, 51, 32,118, 49, 44, 32,118,101, 99, + 51, 32,118, 50, 44, 32,111,117,116, 32,118,101, 99, 51, 32,111,117,116,118,101, 99, 44, 32,111,117,116, 32,102,108,111, 97,116, + 32,111,117,116,118, 97,108, 41, 10,123, 10, 9,111,117,116,118,101, 99, 32, 61, 32,118, 49, 32, 45, 32,118, 50, 59, 10, 9,111, +117,116,118, 97,108, 32, 61, 32, 40, 97, 98,115, 40,111,117,116,118,101, 99, 91, 48, 93, 41, 32, 43, 32, 97, 98,115, 40,111,117, +116,118,101, 99, 91, 49, 93, 41, 32, 43, 32, 97, 98,115, 40,111,117,116,118,101, 99, 91, 50, 93, 41, 41, 47, 51, 46, 48, 59, 10, +125, 10, 10,118,111,105,100, 32,118,101, 99, 95,109, 97,116,104, 95, 97,118,101,114, 97,103,101, 40,118,101, 99, 51, 32,118, 49, + 44, 32,118,101, 99, 51, 32,118, 50, 44, 32,111,117,116, 32,118,101, 99, 51, 32,111,117,116,118,101, 99, 44, 32,111,117,116, 32, +102,108,111, 97,116, 32,111,117,116,118, 97,108, 41, 10,123, 10, 9,111,117,116,118,101, 99, 32, 61, 32,118, 49, 32, 43, 32,118, + 50, 59, 10, 9,111,117,116,118, 97,108, 32, 61, 32,108,101,110,103,116,104, 40,111,117,116,118,101, 99, 41, 59, 10, 9,111,117, +116,118,101, 99, 32, 61, 32,110,111,114,109, 97,108,105,122,101, 40,111,117,116,118,101, 99, 41, 59, 10,125, 10, 10,118,111,105, +100, 32,118,101, 99, 95,109, 97,116,104, 95,100,111,116, 40,118,101, 99, 51, 32,118, 49, 44, 32,118,101, 99, 51, 32,118, 50, 44, + 32,111,117,116, 32,118,101, 99, 51, 32,111,117,116,118,101, 99, 44, 32,111,117,116, 32,102,108,111, 97,116, 32,111,117,116,118, + 97,108, 41, 10,123, 10, 9,111,117,116,118,101, 99, 32, 61, 32,118,101, 99, 51, 40, 48, 44, 32, 48, 44, 32, 48, 41, 59, 10, 9, +111,117,116,118, 97,108, 32, 61, 32,100,111,116, 40,118, 49, 44, 32,118, 50, 41, 59, 10,125, 10, 10,118,111,105,100, 32,118,101, + 99, 95,109, 97,116,104, 95, 99,114,111,115,115, 40,118,101, 99, 51, 32,118, 49, 44, 32,118,101, 99, 51, 32,118, 50, 44, 32,111, +117,116, 32,118,101, 99, 51, 32,111,117,116,118,101, 99, 44, 32,111,117,116, 32,102,108,111, 97,116, 32,111,117,116,118, 97,108, + 41, 10,123, 10, 9,111,117,116,118,101, 99, 32, 61, 32, 99,114,111,115,115, 40,118, 49, 44, 32,118, 50, 41, 59, 10, 9,111,117, +116,118, 97,108, 32, 61, 32,108,101,110,103,116,104, 40,111,117,116,118,101, 99, 41, 59, 10,125, 10, 10,118,111,105,100, 32,118, +101, 99, 95,109, 97,116,104, 95,110,111,114,109, 97,108,105,122,101, 40,118,101, 99, 51, 32,118, 44, 32,111,117,116, 32,118,101, + 99, 51, 32,111,117,116,118,101, 99, 44, 32,111,117,116, 32,102,108,111, 97,116, 32,111,117,116,118, 97,108, 41, 10,123, 10, 9, +111,117,116,118, 97,108, 32, 61, 32,108,101,110,103,116,104, 40,118, 41, 59, 10, 9,111,117,116,118,101, 99, 32, 61, 32,110,111, +114,109, 97,108,105,122,101, 40,118, 41, 59, 10,125, 10, 10,118,111,105,100, 32,118,101, 99, 95,109, 97,116,104, 95,110,101,103, + 97,116,101, 40,118,101, 99, 51, 32,118, 44, 32,111,117,116, 32,118,101, 99, 51, 32,111,117,116,118, 41, 10,123, 10, 9,111,117, +116,118, 32, 61, 32, 45,118, 59, 10,125, 10, 10,118,111,105,100, 32,110,111,114,109, 97,108, 40,118,101, 99, 51, 32,100,105,114, + 44, 32,118,101, 99, 51, 32,110,111,114, 44, 32,111,117,116, 32,118,101, 99, 51, 32,111,117,116,110,111,114, 44, 32,111,117,116, + 32,102,108,111, 97,116, 32,111,117,116,100,111,116, 41, 10,123, 10, 9,111,117,116,110,111,114, 32, 61, 32,100,105,114, 59, 10, + 9,111,117,116,100,111,116, 32, 61, 32, 45,100,111,116, 40,100,105,114, 44, 32,110,111,114, 41, 59, 10,125, 10, 10,118,111,105, +100, 32, 99,117,114,118,101,115, 95,118,101, 99, 40,118,101, 99, 51, 32,118,101, 99, 44, 32,115, 97,109,112,108,101,114, 49, 68, + 32, 99,117,114,118,101,109, 97,112, 44, 32,111,117,116, 32,118,101, 99, 51, 32,111,117,116,118,101, 99, 41, 10,123, 10, 9,111, +117,116,118,101, 99, 46,120, 32, 61, 32,116,101,120,116,117,114,101, 49, 68, 40, 99,117,114,118,101,109, 97,112, 44, 32, 40,118, +101, 99, 46,120, 32, 43, 32, 49, 46, 48, 41, 42, 48, 46, 53, 41, 46,120, 59, 10, 9,111,117,116,118,101, 99, 46,121, 32, 61, 32, +116,101,120,116,117,114,101, 49, 68, 40, 99,117,114,118,101,109, 97,112, 44, 32, 40,118,101, 99, 46,121, 32, 43, 32, 49, 46, 48, + 41, 42, 48, 46, 53, 41, 46,121, 59, 10, 9,111,117,116,118,101, 99, 46,122, 32, 61, 32,116,101,120,116,117,114,101, 49, 68, 40, + 99,117,114,118,101,109, 97,112, 44, 32, 40,118,101, 99, 46,122, 32, 43, 32, 49, 46, 48, 41, 42, 48, 46, 53, 41, 46,122, 59, 10, +125, 10, 10,118,111,105,100, 32, 99,117,114,118,101,115, 95,114,103, 98, 40,118,101, 99, 52, 32, 99,111,108, 44, 32,115, 97,109, +112,108,101,114, 49, 68, 32, 99,117,114,118,101,109, 97,112, 44, 32,111,117,116, 32,118,101, 99, 52, 32,111,117,116, 99,111,108, + 41, 10,123, 10, 9,111,117,116, 99,111,108, 46,114, 32, 61, 32,116,101,120,116,117,114,101, 49, 68, 40, 99,117,114,118,101,109, + 97,112, 44, 32,116,101,120,116,117,114,101, 49, 68, 40, 99,117,114,118,101,109, 97,112, 44, 32, 99,111,108, 46,114, 41, 46, 97, + 41, 46,114, 59, 10, 9,111,117,116, 99,111,108, 46,103, 32, 61, 32,116,101,120,116,117,114,101, 49, 68, 40, 99,117,114,118,101, +109, 97,112, 44, 32,116,101,120,116,117,114,101, 49, 68, 40, 99,117,114,118,101,109, 97,112, 44, 32, 99,111,108, 46,103, 41, 46, + 97, 41, 46,103, 59, 10, 9,111,117,116, 99,111,108, 46, 98, 32, 61, 32,116,101,120,116,117,114,101, 49, 68, 40, 99,117,114,118, +101,109, 97,112, 44, 32,116,101,120,116,117,114,101, 49, 68, 40, 99,117,114,118,101,109, 97,112, 44, 32, 99,111,108, 46, 98, 41, + 46, 97, 41, 46, 98, 59, 10, 9,111,117,116, 99,111,108, 46, 97, 32, 61, 32, 99,111,108, 46, 97, 59, 10,125, 10, 10,118,111,105, +100, 32,115,101,116, 95,118, 97,108,117,101, 40,102,108,111, 97,116, 32,118, 97,108, 44, 32,111,117,116, 32,102,108,111, 97,116, + 32,111,117,116,118, 97,108, 41, 10,123, 10, 9,111,117,116,118, 97,108, 32, 61, 32,118, 97,108, 59, 10,125, 10, 10,118,111,105, +100, 32,115,101,116, 95,114,103, 98, 40,118,101, 99, 51, 32, 99,111,108, 44, 32,111,117,116, 32,118,101, 99, 51, 32,111,117,116, + 99,111,108, 41, 10,123, 10, 9,111,117,116, 99,111,108, 32, 61, 32, 99,111,108, 59, 10,125, 10, 10,118,111,105,100, 32,115,101, +116, 95,114,103, 98, 97, 40,118,101, 99, 52, 32, 99,111,108, 44, 32,111,117,116, 32,118,101, 99, 52, 32,111,117,116, 99,111,108, + 41, 10,123, 10, 9,111,117,116, 99,111,108, 32, 61, 32, 99,111,108, 59, 10,125, 10, 10,118,111,105,100, 32,115,101,116, 95,118, + 97,108,117,101, 95,122,101,114,111, 40,111,117,116, 32,102,108,111, 97,116, 32,111,117,116,118, 97,108, 41, 10,123, 10, 9,111, +117,116,118, 97,108, 32, 61, 32, 48, 46, 48, 59, 10,125, 10, 10,118,111,105,100, 32,115,101,116, 95,114,103, 98, 95,122,101,114, +111, 40,111,117,116, 32,118,101, 99, 51, 32,111,117,116,118, 97,108, 41, 10,123, 10, 9,111,117,116,118, 97,108, 32, 61, 32,118, +101, 99, 51, 40, 48, 46, 48, 41, 59, 10,125, 10, 10,118,111,105,100, 32,115,101,116, 95,114,103, 98, 97, 95,122,101,114,111, 40, +111,117,116, 32,118,101, 99, 52, 32,111,117,116,118, 97,108, 41, 10,123, 10, 9,111,117,116,118, 97,108, 32, 61, 32,118,101, 99, + 52, 40, 48, 46, 48, 41, 59, 10,125, 10, 10,118,111,105,100, 32,109,105,120, 95, 98,108,101,110,100, 40,102,108,111, 97,116, 32, +102, 97, 99, 44, 32,118,101, 99, 52, 32, 99,111,108, 49, 44, 32,118,101, 99, 52, 32, 99,111,108, 50, 44, 32,111,117,116, 32,118, +101, 99, 52, 32,111,117,116, 99,111,108, 41, 10,123, 10, 9,102, 97, 99, 32, 61, 32, 99,108, 97,109,112, 40,102, 97, 99, 44, 32, + 48, 46, 48, 44, 32, 49, 46, 48, 41, 59, 10, 9,111,117,116, 99,111,108, 32, 61, 32,109,105,120, 40, 99,111,108, 49, 44, 32, 99, +111,108, 50, 44, 32,102, 97, 99, 41, 59, 10, 9,111,117,116, 99,111,108, 46, 97, 32, 61, 32, 99,111,108, 49, 46, 97, 59, 10,125, + 10, 10,118,111,105,100, 32,109,105,120, 95, 97,100,100, 40,102,108,111, 97,116, 32,102, 97, 99, 44, 32,118,101, 99, 52, 32, 99, +111,108, 49, 44, 32,118,101, 99, 52, 32, 99,111,108, 50, 44, 32,111,117,116, 32,118,101, 99, 52, 32,111,117,116, 99,111,108, 41, + 10,123, 10, 9,102, 97, 99, 32, 61, 32, 99,108, 97,109,112, 40,102, 97, 99, 44, 32, 48, 46, 48, 44, 32, 49, 46, 48, 41, 59, 10, + 9,111,117,116, 99,111,108, 32, 61, 32,109,105,120, 40, 99,111,108, 49, 44, 32, 99,111,108, 49, 32, 43, 32, 99,111,108, 50, 44, + 32,102, 97, 99, 41, 59, 10, 9,111,117,116, 99,111,108, 46, 97, 32, 61, 32, 99,111,108, 49, 46, 97, 59, 10,125, 10, 10,118,111, +105,100, 32,109,105,120, 95,109,117,108,116, 40,102,108,111, 97,116, 32,102, 97, 99, 44, 32,118,101, 99, 52, 32, 99,111,108, 49, + 44, 32,118,101, 99, 52, 32, 99,111,108, 50, 44, 32,111,117,116, 32,118,101, 99, 52, 32,111,117,116, 99,111,108, 41, 10,123, 10, + 9,102, 97, 99, 32, 61, 32, 99,108, 97,109,112, 40,102, 97, 99, 44, 32, 48, 46, 48, 44, 32, 49, 46, 48, 41, 59, 10, 9,111,117, +116, 99,111,108, 32, 61, 32,109,105,120, 40, 99,111,108, 49, 44, 32, 99,111,108, 49, 32, 42, 32, 99,111,108, 50, 44, 32,102, 97, + 99, 41, 59, 10, 9,111,117,116, 99,111,108, 46, 97, 32, 61, 32, 99,111,108, 49, 46, 97, 59, 10,125, 10, 10,118,111,105,100, 32, +109,105,120, 95,115, 99,114,101,101,110, 40,102,108,111, 97,116, 32,102, 97, 99, 44, 32,118,101, 99, 52, 32, 99,111,108, 49, 44, + 32,118,101, 99, 52, 32, 99,111,108, 50, 44, 32,111,117,116, 32,118,101, 99, 52, 32,111,117,116, 99,111,108, 41, 10,123, 10, 9, +102, 97, 99, 32, 61, 32, 99,108, 97,109,112, 40,102, 97, 99, 44, 32, 48, 46, 48, 44, 32, 49, 46, 48, 41, 59, 10, 9,102,108,111, + 97,116, 32,102, 97, 99,109, 32, 61, 32, 49, 46, 48, 32, 45, 32,102, 97, 99, 59, 10, 10, 9,111,117,116, 99,111,108, 32, 61, 32, +118,101, 99, 52, 40, 49, 46, 48, 41, 32, 45, 32, 40,118,101, 99, 52, 40,102, 97, 99,109, 41, 32, 43, 32,102, 97, 99, 42, 40,118, +101, 99, 52, 40, 49, 46, 48, 41, 32, 45, 32, 99,111,108, 50, 41, 41, 42, 40,118,101, 99, 52, 40, 49, 46, 48, 41, 32, 45, 32, 99, +111,108, 49, 41, 59, 10, 9,111,117,116, 99,111,108, 46, 97, 32, 61, 32, 99,111,108, 49, 46, 97, 59, 10,125, 10, 10,118,111,105, +100, 32,109,105,120, 95,111,118,101,114,108, 97,121, 40,102,108,111, 97,116, 32,102, 97, 99, 44, 32,118,101, 99, 52, 32, 99,111, +108, 49, 44, 32,118,101, 99, 52, 32, 99,111,108, 50, 44, 32,111,117,116, 32,118,101, 99, 52, 32,111,117,116, 99,111,108, 41, 10, +123, 10, 9,102, 97, 99, 32, 61, 32, 99,108, 97,109,112, 40,102, 97, 99, 44, 32, 48, 46, 48, 44, 32, 49, 46, 48, 41, 59, 10, 9, +102,108,111, 97,116, 32,102, 97, 99,109, 32, 61, 32, 49, 46, 48, 32, 45, 32,102, 97, 99, 59, 10, 10, 9,111,117,116, 99,111,108, + 32, 61, 32, 99,111,108, 49, 59, 10, 10, 9,105,102, 40,111,117,116, 99,111,108, 46,114, 32, 60, 32, 48, 46, 53, 41, 10, 9, 9, +111,117,116, 99,111,108, 46,114, 32, 42, 61, 32,102, 97, 99,109, 32, 43, 32, 50, 46, 48, 42,102, 97, 99, 42, 99,111,108, 50, 46, +114, 59, 10, 9,101,108,115,101, 10, 9, 9,111,117,116, 99,111,108, 46,114, 32, 61, 32, 49, 46, 48, 32, 45, 32, 40,102, 97, 99, +109, 32, 43, 32, 50, 46, 48, 42,102, 97, 99, 42, 40, 49, 46, 48, 32, 45, 32, 99,111,108, 50, 46,114, 41, 41, 42, 40, 49, 46, 48, + 32, 45, 32,111,117,116, 99,111,108, 46,114, 41, 59, 10, 10, 9,105,102, 40,111,117,116, 99,111,108, 46,103, 32, 60, 32, 48, 46, + 53, 41, 10, 9, 9,111,117,116, 99,111,108, 46,103, 32, 42, 61, 32,102, 97, 99,109, 32, 43, 32, 50, 46, 48, 42,102, 97, 99, 42, + 99,111,108, 50, 46,103, 59, 10, 9,101,108,115,101, 10, 9, 9,111,117,116, 99,111,108, 46,103, 32, 61, 32, 49, 46, 48, 32, 45, + 32, 40,102, 97, 99,109, 32, 43, 32, 50, 46, 48, 42,102, 97, 99, 42, 40, 49, 46, 48, 32, 45, 32, 99,111,108, 50, 46,103, 41, 41, + 42, 40, 49, 46, 48, 32, 45, 32,111,117,116, 99,111,108, 46,103, 41, 59, 10, 10, 9,105,102, 40,111,117,116, 99,111,108, 46, 98, + 32, 60, 32, 48, 46, 53, 41, 10, 9, 9,111,117,116, 99,111,108, 46, 98, 32, 42, 61, 32,102, 97, 99,109, 32, 43, 32, 50, 46, 48, + 42,102, 97, 99, 42, 99,111,108, 50, 46, 98, 59, 10, 9,101,108,115,101, 10, 9, 9,111,117,116, 99,111,108, 46, 98, 32, 61, 32, + 49, 46, 48, 32, 45, 32, 40,102, 97, 99,109, 32, 43, 32, 50, 46, 48, 42,102, 97, 99, 42, 40, 49, 46, 48, 32, 45, 32, 99,111,108, + 50, 46, 98, 41, 41, 42, 40, 49, 46, 48, 32, 45, 32,111,117,116, 99,111,108, 46, 98, 41, 59, 10,125, 10, 10,118,111,105,100, 32, +109,105,120, 95,115,117, 98, 40,102,108,111, 97,116, 32,102, 97, 99, 44, 32,118,101, 99, 52, 32, 99,111,108, 49, 44, 32,118,101, + 99, 52, 32, 99,111,108, 50, 44, 32,111,117,116, 32,118,101, 99, 52, 32,111,117,116, 99,111,108, 41, 10,123, 10, 9,102, 97, 99, + 32, 61, 32, 99,108, 97,109,112, 40,102, 97, 99, 44, 32, 48, 46, 48, 44, 32, 49, 46, 48, 41, 59, 10, 9,111,117,116, 99,111,108, + 32, 61, 32,109,105,120, 40, 99,111,108, 49, 44, 32, 99,111,108, 49, 32, 45, 32, 99,111,108, 50, 44, 32,102, 97, 99, 41, 59, 10, + 9,111,117,116, 99,111,108, 46, 97, 32, 61, 32, 99,111,108, 49, 46, 97, 59, 10,125, 10, 10,118,111,105,100, 32,109,105,120, 95, +100,105,118, 40,102,108,111, 97,116, 32,102, 97, 99, 44, 32,118,101, 99, 52, 32, 99,111,108, 49, 44, 32,118,101, 99, 52, 32, 99, +111,108, 50, 44, 32,111,117,116, 32,118,101, 99, 52, 32,111,117,116, 99,111,108, 41, 10,123, 10, 9,102, 97, 99, 32, 61, 32, 99, +108, 97,109,112, 40,102, 97, 99, 44, 32, 48, 46, 48, 44, 32, 49, 46, 48, 41, 59, 10, 9,102,108,111, 97,116, 32,102, 97, 99,109, + 32, 61, 32, 49, 46, 48, 32, 45, 32,102, 97, 99, 59, 10, 10, 9,111,117,116, 99,111,108, 32, 61, 32, 99,111,108, 49, 59, 10, 10, + 9,105,102, 40, 99,111,108, 50, 46,114, 32, 33, 61, 32, 48, 46, 48, 41, 32,111,117,116, 99,111,108, 46,114, 32, 61, 32,102, 97, + 99,109, 42,111,117,116, 99,111,108, 46,114, 32, 43, 32,102, 97, 99, 42,111,117,116, 99,111,108, 46,114, 47, 99,111,108, 50, 46, +114, 59, 10, 9,105,102, 40, 99,111,108, 50, 46,103, 32, 33, 61, 32, 48, 46, 48, 41, 32,111,117,116, 99,111,108, 46,103, 32, 61, + 32,102, 97, 99,109, 42,111,117,116, 99,111,108, 46,103, 32, 43, 32,102, 97, 99, 42,111,117,116, 99,111,108, 46,103, 47, 99,111, +108, 50, 46,103, 59, 10, 9,105,102, 40, 99,111,108, 50, 46, 98, 32, 33, 61, 32, 48, 46, 48, 41, 32,111,117,116, 99,111,108, 46, + 98, 32, 61, 32,102, 97, 99,109, 42,111,117,116, 99,111,108, 46, 98, 32, 43, 32,102, 97, 99, 42,111,117,116, 99,111,108, 46, 98, + 47, 99,111,108, 50, 46, 98, 59, 10,125, 10, 10,118,111,105,100, 32,109,105,120, 95,100,105,102,102, 40,102,108,111, 97,116, 32, +102, 97, 99, 44, 32,118,101, 99, 52, 32, 99,111,108, 49, 44, 32,118,101, 99, 52, 32, 99,111,108, 50, 44, 32,111,117,116, 32,118, +101, 99, 52, 32,111,117,116, 99,111,108, 41, 10,123, 10, 9,102, 97, 99, 32, 61, 32, 99,108, 97,109,112, 40,102, 97, 99, 44, 32, + 48, 46, 48, 44, 32, 49, 46, 48, 41, 59, 10, 9,111,117,116, 99,111,108, 32, 61, 32,109,105,120, 40, 99,111,108, 49, 44, 32, 97, + 98,115, 40, 99,111,108, 49, 32, 45, 32, 99,111,108, 50, 41, 44, 32,102, 97, 99, 41, 59, 10, 9,111,117,116, 99,111,108, 46, 97, + 32, 61, 32, 99,111,108, 49, 46, 97, 59, 10,125, 10, 10,118,111,105,100, 32,109,105,120, 95,100, 97,114,107, 40,102,108,111, 97, +116, 32,102, 97, 99, 44, 32,118,101, 99, 52, 32, 99,111,108, 49, 44, 32,118,101, 99, 52, 32, 99,111,108, 50, 44, 32,111,117,116, + 32,118,101, 99, 52, 32,111,117,116, 99,111,108, 41, 10,123, 10, 9,102, 97, 99, 32, 61, 32, 99,108, 97,109,112, 40,102, 97, 99, + 44, 32, 48, 46, 48, 44, 32, 49, 46, 48, 41, 59, 10, 9,111,117,116, 99,111,108, 46,114,103, 98, 32, 61, 32,109,105,110, 40, 99, +111,108, 49, 46,114,103, 98, 44, 32, 99,111,108, 50, 46,114,103, 98, 42,102, 97, 99, 41, 59, 10, 9,111,117,116, 99,111,108, 46, + 97, 32, 61, 32, 99,111,108, 49, 46, 97, 59, 10,125, 10, 10,118,111,105,100, 32,109,105,120, 95,108,105,103,104,116, 40,102,108, +111, 97,116, 32,102, 97, 99, 44, 32,118,101, 99, 52, 32, 99,111,108, 49, 44, 32,118,101, 99, 52, 32, 99,111,108, 50, 44, 32,111, +117,116, 32,118,101, 99, 52, 32,111,117,116, 99,111,108, 41, 10,123, 10, 9,102, 97, 99, 32, 61, 32, 99,108, 97,109,112, 40,102, + 97, 99, 44, 32, 48, 46, 48, 44, 32, 49, 46, 48, 41, 59, 10, 9,111,117,116, 99,111,108, 46,114,103, 98, 32, 61, 32,109, 97,120, + 40, 99,111,108, 49, 46,114,103, 98, 44, 32, 99,111,108, 50, 46,114,103, 98, 42,102, 97, 99, 41, 59, 10, 9,111,117,116, 99,111, +108, 46, 97, 32, 61, 32, 99,111,108, 49, 46, 97, 59, 10,125, 10, 10,118,111,105,100, 32,109,105,120, 95,100,111,100,103,101, 40, +102,108,111, 97,116, 32,102, 97, 99, 44, 32,118,101, 99, 52, 32, 99,111,108, 49, 44, 32,118,101, 99, 52, 32, 99,111,108, 50, 44, + 32,111,117,116, 32,118,101, 99, 52, 32,111,117,116, 99,111,108, 41, 10,123, 10, 9,102, 97, 99, 32, 61, 32, 99,108, 97,109,112, + 40,102, 97, 99, 44, 32, 48, 46, 48, 44, 32, 49, 46, 48, 41, 59, 10, 9,111,117,116, 99,111,108, 32, 61, 32, 99,111,108, 49, 59, + 10, 10, 9,105,102, 40,111,117,116, 99,111,108, 46,114, 32, 33, 61, 32, 48, 46, 48, 41, 32,123, 10, 9, 9,102,108,111, 97,116, + 32,116,109,112, 32, 61, 32, 49, 46, 48, 32, 45, 32,102, 97, 99, 42, 99,111,108, 50, 46,114, 59, 10, 9, 9,105,102, 40,116,109, +112, 32, 60, 61, 32, 48, 46, 48, 41, 10, 9, 9, 9,111,117,116, 99,111,108, 46,114, 32, 61, 32, 49, 46, 48, 59, 10, 9, 9,101, +108,115,101, 32,105,102, 40, 40,116,109,112, 32, 61, 32,111,117,116, 99,111,108, 46,114, 47,116,109,112, 41, 32, 62, 32, 49, 46, + 48, 41, 10, 9, 9, 9,111,117,116, 99,111,108, 46,114, 32, 61, 32, 49, 46, 48, 59, 10, 9, 9,101,108,115,101, 10, 9, 9, 9, +111,117,116, 99,111,108, 46,114, 32, 61, 32,116,109,112, 59, 10, 9,125, 10, 9,105,102, 40,111,117,116, 99,111,108, 46,103, 32, + 33, 61, 32, 48, 46, 48, 41, 32,123, 10, 9, 9,102,108,111, 97,116, 32,116,109,112, 32, 61, 32, 49, 46, 48, 32, 45, 32,102, 97, + 99, 42, 99,111,108, 50, 46,103, 59, 10, 9, 9,105,102, 40,116,109,112, 32, 60, 61, 32, 48, 46, 48, 41, 10, 9, 9, 9,111,117, +116, 99,111,108, 46,103, 32, 61, 32, 49, 46, 48, 59, 10, 9, 9,101,108,115,101, 32,105,102, 40, 40,116,109,112, 32, 61, 32,111, +117,116, 99,111,108, 46,103, 47,116,109,112, 41, 32, 62, 32, 49, 46, 48, 41, 10, 9, 9, 9,111,117,116, 99,111,108, 46,103, 32, + 61, 32, 49, 46, 48, 59, 10, 9, 9,101,108,115,101, 10, 9, 9, 9,111,117,116, 99,111,108, 46,103, 32, 61, 32,116,109,112, 59, + 10, 9,125, 10, 9,105,102, 40,111,117,116, 99,111,108, 46, 98, 32, 33, 61, 32, 48, 46, 48, 41, 32,123, 10, 9, 9,102,108,111, + 97,116, 32,116,109,112, 32, 61, 32, 49, 46, 48, 32, 45, 32,102, 97, 99, 42, 99,111,108, 50, 46, 98, 59, 10, 9, 9,105,102, 40, +116,109,112, 32, 60, 61, 32, 48, 46, 48, 41, 10, 9, 9, 9,111,117,116, 99,111,108, 46, 98, 32, 61, 32, 49, 46, 48, 59, 10, 9, + 9,101,108,115,101, 32,105,102, 40, 40,116,109,112, 32, 61, 32,111,117,116, 99,111,108, 46, 98, 47,116,109,112, 41, 32, 62, 32, + 49, 46, 48, 41, 10, 9, 9, 9,111,117,116, 99,111,108, 46, 98, 32, 61, 32, 49, 46, 48, 59, 10, 9, 9,101,108,115,101, 10, 9, + 9, 9,111,117,116, 99,111,108, 46, 98, 32, 61, 32,116,109,112, 59, 10, 9,125, 10,125, 10, 10,118,111,105,100, 32,109,105,120, + 95, 98,117,114,110, 40,102,108,111, 97,116, 32,102, 97, 99, 44, 32,118,101, 99, 52, 32, 99,111,108, 49, 44, 32,118,101, 99, 52, + 32, 99,111,108, 50, 44, 32,111,117,116, 32,118,101, 99, 52, 32,111,117,116, 99,111,108, 41, 10,123, 10, 9,102, 97, 99, 32, 61, + 32, 99,108, 97,109,112, 40,102, 97, 99, 44, 32, 48, 46, 48, 44, 32, 49, 46, 48, 41, 59, 10, 9,102,108,111, 97,116, 32,116,109, +112, 44, 32,102, 97, 99,109, 32, 61, 32, 49, 46, 48, 32, 45, 32,102, 97, 99, 59, 10, 10, 9,111,117,116, 99,111,108, 32, 61, 32, + 99,111,108, 49, 59, 10, 10, 9,116,109,112, 32, 61, 32,102, 97, 99,109, 32, 43, 32,102, 97, 99, 42, 99,111,108, 50, 46,114, 59, + 10, 9,105,102, 40,116,109,112, 32, 60, 61, 32, 48, 46, 48, 41, 10, 9, 9,111,117,116, 99,111,108, 46,114, 32, 61, 32, 48, 46, + 48, 59, 10, 9,101,108,115,101, 32,105,102, 40, 40,116,109,112, 32, 61, 32, 40, 49, 46, 48, 32, 45, 32, 40, 49, 46, 48, 32, 45, + 32,111,117,116, 99,111,108, 46,114, 41, 47,116,109,112, 41, 41, 32, 60, 32, 48, 46, 48, 41, 10, 9, 9,111,117,116, 99,111,108, + 46,114, 32, 61, 32, 48, 46, 48, 59, 10, 9,101,108,115,101, 32,105,102, 40,116,109,112, 32, 62, 32, 49, 46, 48, 41, 10, 9, 9, +111,117,116, 99,111,108, 46,114, 32, 61, 32, 49, 46, 48, 59, 10, 9,101,108,115,101, 10, 9, 9,111,117,116, 99,111,108, 46,114, + 32, 61, 32,116,109,112, 59, 10, 10, 9,116,109,112, 32, 61, 32,102, 97, 99,109, 32, 43, 32,102, 97, 99, 42, 99,111,108, 50, 46, +103, 59, 10, 9,105,102, 40,116,109,112, 32, 60, 61, 32, 48, 46, 48, 41, 10, 9, 9,111,117,116, 99,111,108, 46,103, 32, 61, 32, + 48, 46, 48, 59, 10, 9,101,108,115,101, 32,105,102, 40, 40,116,109,112, 32, 61, 32, 40, 49, 46, 48, 32, 45, 32, 40, 49, 46, 48, + 32, 45, 32,111,117,116, 99,111,108, 46,103, 41, 47,116,109,112, 41, 41, 32, 60, 32, 48, 46, 48, 41, 10, 9, 9,111,117,116, 99, +111,108, 46,103, 32, 61, 32, 48, 46, 48, 59, 10, 9,101,108,115,101, 32,105,102, 40,116,109,112, 32, 62, 32, 49, 46, 48, 41, 10, + 9, 9,111,117,116, 99,111,108, 46,103, 32, 61, 32, 49, 46, 48, 59, 10, 9,101,108,115,101, 10, 9, 9,111,117,116, 99,111,108, + 46,103, 32, 61, 32,116,109,112, 59, 10, 10, 9,116,109,112, 32, 61, 32,102, 97, 99,109, 32, 43, 32,102, 97, 99, 42, 99,111,108, + 50, 46, 98, 59, 10, 9,105,102, 40,116,109,112, 32, 60, 61, 32, 48, 46, 48, 41, 10, 9, 9,111,117,116, 99,111,108, 46, 98, 32, + 61, 32, 48, 46, 48, 59, 10, 9,101,108,115,101, 32,105,102, 40, 40,116,109,112, 32, 61, 32, 40, 49, 46, 48, 32, 45, 32, 40, 49, + 46, 48, 32, 45, 32,111,117,116, 99,111,108, 46, 98, 41, 47,116,109,112, 41, 41, 32, 60, 32, 48, 46, 48, 41, 10, 9, 9,111,117, +116, 99,111,108, 46, 98, 32, 61, 32, 48, 46, 48, 59, 10, 9,101,108,115,101, 32,105,102, 40,116,109,112, 32, 62, 32, 49, 46, 48, + 41, 10, 9, 9,111,117,116, 99,111,108, 46, 98, 32, 61, 32, 49, 46, 48, 59, 10, 9,101,108,115,101, 10, 9, 9,111,117,116, 99, +111,108, 46, 98, 32, 61, 32,116,109,112, 59, 10,125, 10, 10,118,111,105,100, 32,109,105,120, 95,104,117,101, 40,102,108,111, 97, +116, 32,102, 97, 99, 44, 32,118,101, 99, 52, 32, 99,111,108, 49, 44, 32,118,101, 99, 52, 32, 99,111,108, 50, 44, 32,111,117,116, + 32,118,101, 99, 52, 32,111,117,116, 99,111,108, 41, 10,123, 10, 9,102, 97, 99, 32, 61, 32, 99,108, 97,109,112, 40,102, 97, 99, + 44, 32, 48, 46, 48, 44, 32, 49, 46, 48, 41, 59, 10, 9,102,108,111, 97,116, 32,102, 97, 99,109, 32, 61, 32, 49, 46, 48, 32, 45, + 32,102, 97, 99, 59, 10, 10, 9,111,117,116, 99,111,108, 32, 61, 32, 99,111,108, 49, 59, 10, 10, 9,118,101, 99, 52, 32,104,115, +118, 44, 32,104,115,118, 50, 44, 32,116,109,112, 59, 10, 9,114,103, 98, 95,116,111, 95,104,115,118, 40, 99,111,108, 50, 44, 32, +104,115,118, 50, 41, 59, 10, 10, 9,105,102, 40,104,115,118, 50, 46,121, 32, 33, 61, 32, 48, 46, 48, 41, 32,123, 10, 9, 9,114, +103, 98, 95,116,111, 95,104,115,118, 40,111,117,116, 99,111,108, 44, 32,104,115,118, 41, 59, 10, 9, 9,104,115,118, 46,120, 32, + 61, 32,104,115,118, 50, 46,120, 59, 10, 9, 9,104,115,118, 95,116,111, 95,114,103, 98, 40,104,115,118, 44, 32,116,109,112, 41, + 59, 32, 10, 10, 9, 9,111,117,116, 99,111,108, 32, 61, 32,109,105,120, 40,111,117,116, 99,111,108, 44, 32,116,109,112, 44, 32, +102, 97, 99, 41, 59, 10, 9, 9,111,117,116, 99,111,108, 46, 97, 32, 61, 32, 99,111,108, 49, 46, 97, 59, 10, 9,125, 10,125, 10, + 10,118,111,105,100, 32,109,105,120, 95,115, 97,116, 40,102,108,111, 97,116, 32,102, 97, 99, 44, 32,118,101, 99, 52, 32, 99,111, +108, 49, 44, 32,118,101, 99, 52, 32, 99,111,108, 50, 44, 32,111,117,116, 32,118,101, 99, 52, 32,111,117,116, 99,111,108, 41, 10, +123, 10, 9,102, 97, 99, 32, 61, 32, 99,108, 97,109,112, 40,102, 97, 99, 44, 32, 48, 46, 48, 44, 32, 49, 46, 48, 41, 59, 10, 9, +102,108,111, 97,116, 32,102, 97, 99,109, 32, 61, 32, 49, 46, 48, 32, 45, 32,102, 97, 99, 59, 10, 10, 9,111,117,116, 99,111,108, + 32, 61, 32, 99,111,108, 49, 59, 10, 10, 9,118,101, 99, 52, 32,104,115,118, 44, 32,104,115,118, 50, 59, 10, 9,114,103, 98, 95, +116,111, 95,104,115,118, 40,111,117,116, 99,111,108, 44, 32,104,115,118, 41, 59, 10, 10, 9,105,102, 40,104,115,118, 46,121, 32, + 33, 61, 32, 48, 46, 48, 41, 32,123, 10, 9, 9,114,103, 98, 95,116,111, 95,104,115,118, 40, 99,111,108, 50, 44, 32,104,115,118, + 50, 41, 59, 10, 10, 9, 9,104,115,118, 46,121, 32, 61, 32,102, 97, 99,109, 42,104,115,118, 46,121, 32, 43, 32,102, 97, 99, 42, +104,115,118, 50, 46,121, 59, 10, 9, 9,104,115,118, 95,116,111, 95,114,103, 98, 40,104,115,118, 44, 32,111,117,116, 99,111,108, + 41, 59, 10, 9,125, 10,125, 10, 10,118,111,105,100, 32,109,105,120, 95,118, 97,108, 40,102,108,111, 97,116, 32,102, 97, 99, 44, + 32,118,101, 99, 52, 32, 99,111,108, 49, 44, 32,118,101, 99, 52, 32, 99,111,108, 50, 44, 32,111,117,116, 32,118,101, 99, 52, 32, +111,117,116, 99,111,108, 41, 10,123, 10, 9,102, 97, 99, 32, 61, 32, 99,108, 97,109,112, 40,102, 97, 99, 44, 32, 48, 46, 48, 44, + 32, 49, 46, 48, 41, 59, 10, 9,102,108,111, 97,116, 32,102, 97, 99,109, 32, 61, 32, 49, 46, 48, 32, 45, 32,102, 97, 99, 59, 10, + 10, 9,118,101, 99, 52, 32,104,115,118, 44, 32,104,115,118, 50, 59, 10, 9,114,103, 98, 95,116,111, 95,104,115,118, 40, 99,111, +108, 49, 44, 32,104,115,118, 41, 59, 10, 9,114,103, 98, 95,116,111, 95,104,115,118, 40, 99,111,108, 50, 44, 32,104,115,118, 50, + 41, 59, 10, 10, 9,104,115,118, 46,122, 32, 61, 32,102, 97, 99,109, 42,104,115,118, 46,122, 32, 43, 32,102, 97, 99, 42,104,115, +118, 50, 46,122, 59, 10, 9,104,115,118, 95,116,111, 95,114,103, 98, 40,104,115,118, 44, 32,111,117,116, 99,111,108, 41, 59, 10, +125, 10, 10,118,111,105,100, 32,109,105,120, 95, 99,111,108,111,114, 40,102,108,111, 97,116, 32,102, 97, 99, 44, 32,118,101, 99, + 52, 32, 99,111,108, 49, 44, 32,118,101, 99, 52, 32, 99,111,108, 50, 44, 32,111,117,116, 32,118,101, 99, 52, 32,111,117,116, 99, +111,108, 41, 10,123, 10, 9,102, 97, 99, 32, 61, 32, 99,108, 97,109,112, 40,102, 97, 99, 44, 32, 48, 46, 48, 44, 32, 49, 46, 48, + 41, 59, 10, 9,102,108,111, 97,116, 32,102, 97, 99,109, 32, 61, 32, 49, 46, 48, 32, 45, 32,102, 97, 99, 59, 10, 10, 9,111,117, +116, 99,111,108, 32, 61, 32, 99,111,108, 49, 59, 10, 10, 9,118,101, 99, 52, 32,104,115,118, 44, 32,104,115,118, 50, 44, 32,116, +109,112, 59, 10, 9,114,103, 98, 95,116,111, 95,104,115,118, 40, 99,111,108, 50, 44, 32,104,115,118, 50, 41, 59, 10, 10, 9,105, +102, 40,104,115,118, 50, 46,121, 32, 33, 61, 32, 48, 46, 48, 41, 32,123, 10, 9, 9,114,103, 98, 95,116,111, 95,104,115,118, 40, +111,117,116, 99,111,108, 44, 32,104,115,118, 41, 59, 10, 9, 9,104,115,118, 46,120, 32, 61, 32,104,115,118, 50, 46,120, 59, 10, + 9, 9,104,115,118, 46,121, 32, 61, 32,104,115,118, 50, 46,121, 59, 10, 9, 9,104,115,118, 95,116,111, 95,114,103, 98, 40,104, +115,118, 44, 32,116,109,112, 41, 59, 32, 10, 10, 9, 9,111,117,116, 99,111,108, 32, 61, 32,109,105,120, 40,111,117,116, 99,111, +108, 44, 32,116,109,112, 44, 32,102, 97, 99, 41, 59, 10, 9, 9,111,117,116, 99,111,108, 46, 97, 32, 61, 32, 99,111,108, 49, 46, + 97, 59, 10, 9,125, 10,125, 10, 10,118,111,105,100, 32,118, 97,108,116,111,114,103, 98, 40,102,108,111, 97,116, 32,102, 97, 99, + 44, 32,115, 97,109,112,108,101,114, 49, 68, 32, 99,111,108,111,114,109, 97,112, 44, 32,111,117,116, 32,118,101, 99, 52, 32,111, +117,116, 99,111,108, 44, 32,111,117,116, 32,102,108,111, 97,116, 32,111,117,116, 97,108,112,104, 97, 41, 10,123, 10, 9,111,117, +116, 99,111,108, 32, 61, 32,116,101,120,116,117,114,101, 49, 68, 40, 99,111,108,111,114,109, 97,112, 44, 32,102, 97, 99, 41, 59, + 10, 9,111,117,116, 97,108,112,104, 97, 32, 61, 32,111,117,116, 99,111,108, 46, 97, 59, 10,125, 10, 10,118,111,105,100, 32,114, +103, 98,116,111, 98,119, 40,118,101, 99, 52, 32, 99,111,108,111,114, 44, 32,111,117,116, 32,102,108,111, 97,116, 32,111,117,116, +118, 97,108, 41, 10,123, 10, 9,111,117,116,118, 97,108, 32, 61, 32, 99,111,108,111,114, 46,114, 42, 48, 46, 51, 53, 32, 43, 32, + 99,111,108,111,114, 46,103, 42, 48, 46, 52, 53, 32, 43, 32, 99,111,108,111,114, 46, 98, 42, 48, 46, 50, 59, 10,125, 10, 10,118, +111,105,100, 32,105,110,118,101,114,116, 40,102,108,111, 97,116, 32,102, 97, 99, 44, 32,118,101, 99, 52, 32, 99,111,108, 44, 32, +111,117,116, 32,118,101, 99, 52, 32,111,117,116, 99,111,108, 41, 10,123, 10, 9,111,117,116, 99,111,108, 46,120,121,122, 32, 61, + 32,109,105,120, 40, 99,111,108, 46,120,121,122, 44, 32,118,101, 99, 51, 40, 49, 46, 48, 44, 32, 49, 46, 48, 44, 32, 49, 46, 48, + 41, 32, 45, 32, 99,111,108, 46,120,121,122, 44, 32,102, 97, 99, 41, 59, 10, 9,111,117,116, 99,111,108, 46,119, 32, 61, 32, 99, +111,108, 46,119, 59, 10,125, 10, 10,118,111,105,100, 32,104,117,101, 95,115, 97,116, 40,102,108,111, 97,116, 32,104,117,101, 44, + 32,102,108,111, 97,116, 32,115, 97,116, 44, 32,102,108,111, 97,116, 32,118, 97,108,117,101, 44, 32,102,108,111, 97,116, 32,102, + 97, 99, 44, 32,118,101, 99, 52, 32, 99,111,108, 44, 32,111,117,116, 32,118,101, 99, 52, 32,111,117,116, 99,111,108, 41, 10,123, + 10, 9,118,101, 99, 52, 32,104,115,118, 59, 10, 10, 9,114,103, 98, 95,116,111, 95,104,115,118, 40, 99,111,108, 44, 32,104,115, +118, 41, 59, 10, 10, 9,104,115,118, 91, 48, 93, 32, 43, 61, 32, 40,104,117,101, 32, 45, 32, 48, 46, 53, 41, 59, 10, 9,105,102, + 40,104,115,118, 91, 48, 93, 62, 49, 46, 48, 41, 32,104,115,118, 91, 48, 93, 45, 61, 49, 46, 48, 59, 32,101,108,115,101, 32,105, +102, 40,104,115,118, 91, 48, 93, 60, 48, 46, 48, 41, 32,104,115,118, 91, 48, 93, 43, 61, 32, 49, 46, 48, 59, 10, 9,104,115,118, + 91, 49, 93, 32, 42, 61, 32,115, 97,116, 59, 10, 9,105,102, 40,104,115,118, 91, 49, 93, 62, 49, 46, 48, 41, 32,104,115,118, 91, + 49, 93, 61, 32, 49, 46, 48, 59, 32,101,108,115,101, 32,105,102, 40,104,115,118, 91, 49, 93, 60, 48, 46, 48, 41, 32,104,115,118, + 91, 49, 93, 61, 32, 48, 46, 48, 59, 10, 9,104,115,118, 91, 50, 93, 32, 42, 61, 32,118, 97,108,117,101, 59, 10, 9,105,102, 40, +104,115,118, 91, 50, 93, 62, 49, 46, 48, 41, 32,104,115,118, 91, 50, 93, 61, 32, 49, 46, 48, 59, 32,101,108,115,101, 32,105,102, + 40,104,115,118, 91, 50, 93, 60, 48, 46, 48, 41, 32,104,115,118, 91, 50, 93, 61, 32, 48, 46, 48, 59, 10, 10, 9,104,115,118, 95, +116,111, 95,114,103, 98, 40,104,115,118, 44, 32,111,117,116, 99,111,108, 41, 59, 10, 10, 9,111,117,116, 99,111,108, 32, 61, 32, +109,105,120, 40, 99,111,108, 44, 32,111,117,116, 99,111,108, 44, 32,102, 97, 99, 41, 59, 10,125, 10, 10,118,111,105,100, 32,115, +101,112, 97,114, 97,116,101, 95,114,103, 98, 40,118,101, 99, 52, 32, 99,111,108, 44, 32,111,117,116, 32,102,108,111, 97,116, 32, +114, 44, 32,111,117,116, 32,102,108,111, 97,116, 32,103, 44, 32,111,117,116, 32,102,108,111, 97,116, 32, 98, 41, 10,123, 10, 9, +114, 32, 61, 32, 99,111,108, 46,114, 59, 10, 9,103, 32, 61, 32, 99,111,108, 46,103, 59, 10, 9, 98, 32, 61, 32, 99,111,108, 46, + 98, 59, 10,125, 10, 10,118,111,105,100, 32, 99,111,109, 98,105,110,101, 95,114,103, 98, 40,102,108,111, 97,116, 32,114, 44, 32, +102,108,111, 97,116, 32,103, 44, 32,102,108,111, 97,116, 32, 98, 44, 32,111,117,116, 32,118,101, 99, 52, 32, 99,111,108, 41, 10, +123, 10, 9, 99,111,108, 32, 61, 32,118,101, 99, 52, 40,114, 44, 32,103, 44, 32, 98, 44, 32, 49, 46, 48, 41, 59, 10,125, 10, 10, +118,111,105,100, 32,111,117,116,112,117,116, 95,110,111,100,101, 40,118,101, 99, 52, 32,114,103, 98, 44, 32,102,108,111, 97,116, + 32, 97,108,112,104, 97, 44, 32,111,117,116, 32,118,101, 99, 52, 32,111,117,116,114,103, 98, 41, 10,123, 10, 9,111,117,116,114, +103, 98, 32, 61, 32,118,101, 99, 52, 40,114,103, 98, 46,114,103, 98, 44, 32, 97,108,112,104, 97, 41, 59, 10,125, 10, 10, 47, 42, + 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 32, 84, 69, 88, 84, 85, 82, 69, 83, 32, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, + 42, 42, 42, 47, 10, 10,118,111,105,100, 32,116,101,120,116,117,114,101, 95,102,108,105,112, 95, 98,108,101,110,100, 40,118,101, + 99, 51, 32,118,101, 99, 44, 32,111,117,116, 32,118,101, 99, 51, 32,111,117,116,118,101, 99, 41, 10,123, 10, 9,111,117,116,118, +101, 99, 32, 61, 32,118,101, 99, 46,121,120,122, 59, 10,125, 10, 10,118,111,105,100, 32,116,101,120,116,117,114,101, 95, 98,108, +101,110,100, 95,108,105,110, 40,118,101, 99, 51, 32,118,101, 99, 44, 32,111,117,116, 32,102,108,111, 97,116, 32,111,117,116,118, + 97,108, 41, 10,123, 10, 9,111,117,116,118, 97,108, 32, 61, 32, 40, 49, 46, 48, 43,118,101, 99, 46,120, 41, 47, 50, 46, 48, 59, + 10,125, 10, 10,118,111,105,100, 32,116,101,120,116,117,114,101, 95, 98,108,101,110,100, 95,113,117, 97,100, 40,118,101, 99, 51, + 32,118,101, 99, 44, 32,111,117,116, 32,102,108,111, 97,116, 32,111,117,116,118, 97,108, 41, 10,123, 10, 9,111,117,116,118, 97, +108, 32, 61, 32,109, 97,120, 40, 40, 49, 46, 48, 43,118,101, 99, 46,120, 41, 47, 50, 46, 48, 44, 32, 48, 46, 48, 41, 59, 10, 9, +111,117,116,118, 97,108, 32, 42, 61, 32,111,117,116,118, 97,108, 59, 10,125, 10, 10,118,111,105,100, 32,116,101,120,116,117,114, +101, 95,119,111,111,100, 95,115,105,110, 40,118,101, 99, 51, 32,118,101, 99, 44, 32,111,117,116, 32,102,108,111, 97,116, 32,118, + 97,108,117,101, 44, 32,111,117,116, 32,118,101, 99, 52, 32, 99,111,108,111,114, 44, 32,111,117,116, 32,118,101, 99, 51, 32,110, +111,114,109, 97,108, 41, 10,123, 10, 9,102,108,111, 97,116, 32, 97, 32, 61, 32,115,113,114,116, 40,118,101, 99, 46,120, 42,118, +101, 99, 46,120, 32, 43, 32,118,101, 99, 46,121, 42,118,101, 99, 46,121, 32, 43, 32,118,101, 99, 46,122, 42,118,101, 99, 46,122, + 41, 42, 50, 48, 46, 48, 59, 10, 9,102,108,111, 97,116, 32,119,105, 32, 61, 32, 48, 46, 53, 32, 43, 32, 48, 46, 53, 42,115,105, +110, 40, 97, 41, 59, 10, 10, 9,118, 97,108,117,101, 32, 61, 32,119,105, 59, 10, 9, 99,111,108,111,114, 32, 61, 32,118,101, 99, + 52, 40,119,105, 44, 32,119,105, 44, 32,119,105, 44, 32, 49, 46, 48, 41, 59, 10, 9,110,111,114,109, 97,108, 32, 61, 32,118,101, + 99, 51, 40, 48, 46, 48, 44, 32, 48, 46, 48, 44, 32, 48, 46, 48, 41, 59, 10,125, 10, 10,118,111,105,100, 32,116,101,120,116,117, +114,101, 95,105,109, 97,103,101, 40,118,101, 99, 51, 32,118,101, 99, 44, 32,115, 97,109,112,108,101,114, 50, 68, 32,105,109, 97, + 44, 32,111,117,116, 32,102,108,111, 97,116, 32,118, 97,108,117,101, 44, 32,111,117,116, 32,118,101, 99, 52, 32, 99,111,108,111, +114, 44, 32,111,117,116, 32,118,101, 99, 51, 32,110,111,114,109, 97,108, 41, 10,123, 10, 9, 99,111,108,111,114, 32, 61, 32,116, +101,120,116,117,114,101, 50, 68, 40,105,109, 97, 44, 32, 40,118,101, 99, 46,120,121, 32, 43, 32,118,101, 99, 50, 40, 49, 46, 48, + 44, 32, 49, 46, 48, 41, 41, 42, 48, 46, 53, 41, 59, 10, 9,118, 97,108,117,101, 32, 61, 32, 49, 46, 48, 59, 10, 10, 9,110,111, +114,109, 97,108, 46,120, 32, 61, 32, 50, 46, 48, 42, 40, 99,111,108,111,114, 46,114, 32, 45, 32, 48, 46, 53, 41, 59, 10, 9,110, +111,114,109, 97,108, 46,121, 32, 61, 32, 50, 46, 48, 42, 40, 48, 46, 53, 32, 45, 32, 99,111,108,111,114, 46,103, 41, 59, 10, 9, +110,111,114,109, 97,108, 46,122, 32, 61, 32, 50, 46, 48, 42, 40, 99,111,108,111,114, 46, 98, 32, 45, 32, 48, 46, 53, 41, 59, 10, +125, 10, 10, 47, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 32, 77, 84, 69, 88, 32, 42, 42, 42, 42, 42, 42, 42, 42, 42, + 42, 42, 42, 42, 42, 42, 42, 42, 47, 10, 10,118,111,105,100, 32,116,101,120, 99,111, 95,111,114, 99,111, 40,118,101, 99, 51, 32, + 97,116,116,111,114, 99,111, 44, 32,111,117,116, 32,118,101, 99, 51, 32,111,114, 99,111, 41, 10,123, 10, 9,111,114, 99,111, 32, + 61, 32, 97,116,116,111,114, 99,111, 59, 10,125, 10, 10,118,111,105,100, 32,116,101,120, 99,111, 95,117,118, 40,118,101, 99, 50, + 32, 97,116,116,117,118, 44, 32,111,117,116, 32,118,101, 99, 51, 32,117,118, 41, 10,123, 10, 9, 47, 42, 32,100,105,115, 97, 98, +108,101,100, 32,102,111,114, 32,110,111,119, 44, 32,119,111,114,107,115, 32,116,111,103,101,116,104,101,114, 32,119,105,116,104, + 32,108,101, 97,118,105,110,103, 32,111,117,116, 32,109,116,101,120, 95, 50,100, 95,109, 97,112,112,105,110,103, 10, 9, 32, 32, + 32,117,118, 32, 61, 32,118,101, 99, 51, 40, 97,116,116,117,118, 42, 50, 46, 48, 32, 45, 32,118,101, 99, 50, 40, 49, 46, 48, 44, + 32, 49, 46, 48, 41, 44, 32, 48, 46, 48, 41, 59, 32, 42, 47, 10, 9,117,118, 32, 61, 32,118,101, 99, 51, 40, 97,116,116,117,118, + 44, 32, 48, 46, 48, 41, 59, 10,125, 10, 10,118,111,105,100, 32,116,101,120, 99,111, 95,110,111,114,109, 40,118,101, 99, 51, 32, +110,111,114,109, 97,108, 44, 32,111,117,116, 32,118,101, 99, 51, 32,111,117,116,110,111,114,109, 97,108, 41, 10,123, 10, 9, 47, + 42, 32, 99,111,114,114,101,115,112,111,110,100,115, 32,116,111, 32,115,104,105, 45, 62,111,114,110, 44, 32,119,104,105, 99,104, + 32,105,115, 32,110,101,103, 97,116,101,100, 32,115,111, 32, 99, 97,110, 99,101,108,115, 10, 9, 32, 32, 32,111,117,116, 32, 98, +108,101,110,100,101,114, 32,110,111,114,109, 97,108, 32,110,101,103, 97,116,105,111,110, 32, 42, 47, 10, 9,111,117,116,110,111, +114,109, 97,108, 32, 61, 32,110,111,114,109, 97,108,105,122,101, 40,110,111,114,109, 97,108, 41, 59, 10,125, 10, 10,118,111,105, +100, 32,116,101,120, 99,111, 95,116, 97,110,103,101,110,116, 40,118,101, 99, 51, 32,116, 97,110,103,101,110,116, 44, 32,111,117, +116, 32,118,101, 99, 51, 32,111,117,116,116, 97,110,103,101,110,116, 41, 10,123, 10, 9,111,117,116,116, 97,110,103,101,110,116, + 32, 61, 32,110,111,114,109, 97,108,105,122,101, 40,116, 97,110,103,101,110,116, 41, 59, 10,125, 10, 10,118,111,105,100, 32,116, +101,120, 99,111, 95,103,108,111, 98, 97,108, 40,109, 97,116, 52, 32,118,105,101,119,105,110,118,109, 97,116, 44, 32,118,101, 99, + 51, 32, 99,111, 44, 32,111,117,116, 32,118,101, 99, 51, 32,103,108,111, 98, 97,108, 41, 10,123, 10, 9,103,108,111, 98, 97,108, + 32, 61, 32, 40,118,105,101,119,105,110,118,109, 97,116, 42,118,101, 99, 52, 40, 99,111, 44, 32, 49, 46, 48, 41, 41, 46,120,121, +122, 59, 10,125, 10, 10,118,111,105,100, 32,116,101,120, 99,111, 95,111, 98,106,101, 99,116, 40,109, 97,116, 52, 32,118,105,101, +119,105,110,118,109, 97,116, 44, 32,109, 97,116, 52, 32,111, 98,105,110,118,109, 97,116, 44, 32,118,101, 99, 51, 32, 99,111, 44, + 32,111,117,116, 32,118,101, 99, 51, 32,111, 98,106,101, 99,116, 41, 10,123, 10, 9,111, 98,106,101, 99,116, 32, 61, 32, 40,111, + 98,105,110,118,109, 97,116, 42, 40,118,105,101,119,105,110,118,109, 97,116, 42,118,101, 99, 52, 40, 99,111, 44, 32, 49, 46, 48, + 41, 41, 41, 46,120,121,122, 59, 10,125, 10, 10,118,111,105,100, 32,116,101,120, 99,111, 95,114,101,102,108, 40,118,101, 99, 51, + 32,118,110, 44, 32,118,101, 99, 51, 32,118,105,101,119, 44, 32,111,117,116, 32,118,101, 99, 51, 32,114,101,102, 41, 10,123, 10, + 9,114,101,102, 32, 61, 32,118,105,101,119, 32, 45, 32, 50, 46, 48, 42,100,111,116, 40,118,110, 44, 32,118,105,101,119, 41, 42, +118,110, 59, 10,125, 10, 10,118,111,105,100, 32,115,104, 97,100,101, 95,110,111,114,109, 40,118,101, 99, 51, 32,110,111,114,109, + 97,108, 44, 32,111,117,116, 32,118,101, 99, 51, 32,111,117,116,110,111,114,109, 97,108, 41, 10,123, 10, 9, 47, 42, 32, 98,108, +101,110,100,101,114, 32,114,101,110,100,101,114, 32,110,111,114,109, 97,108, 32,105,115, 32,110,101,103, 97,116,101,100, 32, 42, + 47, 10, 9,111,117,116,110,111,114,109, 97,108, 32, 61, 32, 45,110,111,114,109, 97,108,105,122,101, 40,110,111,114,109, 97,108, + 41, 59, 10,125, 10, 10,118,111,105,100, 32,109,116,101,120, 95,114,103, 98, 95, 98,108,101,110,100, 40,118,101, 99, 51, 32,111, +117,116, 99,111,108, 44, 32,118,101, 99, 51, 32,116,101,120, 99,111,108, 44, 32,102,108,111, 97,116, 32,102, 97, 99,116, 44, 32, +102,108,111, 97,116, 32,102, 97, 99,103, 44, 32,111,117,116, 32,118,101, 99, 51, 32,105,110, 99,111,108, 41, 10,123, 10, 9,102, +108,111, 97,116, 32,102, 97, 99,109, 59, 10, 10, 9,102, 97, 99,116, 32, 42, 61, 32,102, 97, 99,103, 59, 10, 9,102, 97, 99,109, + 32, 61, 32, 49, 46, 48, 45,102, 97, 99,116, 59, 10, 10, 9,105,110, 99,111,108, 32, 61, 32,102, 97, 99,116, 42,116,101,120, 99, +111,108, 32, 43, 32,102, 97, 99,109, 42,111,117,116, 99,111,108, 59, 10,125, 10, 10,118,111,105,100, 32,109,116,101,120, 95,114, +103, 98, 95,109,117,108, 40,118,101, 99, 51, 32,111,117,116, 99,111,108, 44, 32,118,101, 99, 51, 32,116,101,120, 99,111,108, 44, + 32,102,108,111, 97,116, 32,102, 97, 99,116, 44, 32,102,108,111, 97,116, 32,102, 97, 99,103, 44, 32,111,117,116, 32,118,101, 99, + 51, 32,105,110, 99,111,108, 41, 10,123, 10, 9,102,108,111, 97,116, 32,102, 97, 99,109, 59, 10, 10, 9,102, 97, 99,116, 32, 42, + 61, 32,102, 97, 99,103, 59, 10, 9,102, 97, 99,109, 32, 61, 32, 49, 46, 48, 45,102, 97, 99,103, 59, 10, 10, 9,105,110, 99,111, +108, 32, 61, 32, 40,102, 97, 99,109, 32, 43, 32,102, 97, 99,116, 42,116,101,120, 99,111,108, 41, 42,111,117,116, 99,111,108, 59, + 10,125, 10, 10,118,111,105,100, 32,109,116,101,120, 95,114,103, 98, 95,115, 99,114,101,101,110, 40,118,101, 99, 51, 32,111,117, +116, 99,111,108, 44, 32,118,101, 99, 51, 32,116,101,120, 99,111,108, 44, 32,102,108,111, 97,116, 32,102, 97, 99,116, 44, 32,102, +108,111, 97,116, 32,102, 97, 99,103, 44, 32,111,117,116, 32,118,101, 99, 51, 32,105,110, 99,111,108, 41, 10,123, 10, 9,102,108, +111, 97,116, 32,102, 97, 99,109, 59, 10, 10, 9,102, 97, 99,116, 32, 42, 61, 32,102, 97, 99,103, 59, 10, 9,102, 97, 99,109, 32, + 61, 32, 49, 46, 48, 45,102, 97, 99,103, 59, 10, 10, 9,105,110, 99,111,108, 32, 61, 32,118,101, 99, 51, 40, 49, 46, 48, 41, 32, + 45, 32, 40,118,101, 99, 51, 40,102, 97, 99,109, 41, 32, 43, 32,102, 97, 99,116, 42, 40,118,101, 99, 51, 40, 49, 46, 48, 41, 32, + 45, 32,116,101,120, 99,111,108, 41, 41, 42, 40,118,101, 99, 51, 40, 49, 46, 48, 41, 32, 45, 32,111,117,116, 99,111,108, 41, 59, + 10,125, 10, 10,118,111,105,100, 32,109,116,101,120, 95,114,103, 98, 95,111,118,101,114,108, 97,121, 40,118,101, 99, 51, 32,111, +117,116, 99,111,108, 44, 32,118,101, 99, 51, 32,116,101,120, 99,111,108, 44, 32,102,108,111, 97,116, 32,102, 97, 99,116, 44, 32, +102,108,111, 97,116, 32,102, 97, 99,103, 44, 32,111,117,116, 32,118,101, 99, 51, 32,105,110, 99,111,108, 41, 10,123, 10, 9,102, +108,111, 97,116, 32,102, 97, 99,109, 59, 10, 10, 9,102, 97, 99,116, 32, 42, 61, 32,102, 97, 99,103, 59, 10, 9,102, 97, 99,109, + 32, 61, 32, 49, 46, 48, 45,102, 97, 99,103, 59, 10, 10, 9,105,102, 40,111,117,116, 99,111,108, 46,114, 32, 60, 32, 48, 46, 53, + 41, 10, 9, 9,105,110, 99,111,108, 46,114, 32, 61, 32,111,117,116, 99,111,108, 46,114, 42, 40,102, 97, 99,109, 32, 43, 32, 50, + 46, 48, 42,102, 97, 99,116, 42,116,101,120, 99,111,108, 46,114, 41, 59, 10, 9,101,108,115,101, 10, 9, 9,105,110, 99,111,108, + 46,114, 32, 61, 32, 49, 46, 48, 32, 45, 32, 40,102, 97, 99,109, 32, 43, 32, 50, 46, 48, 42,102, 97, 99,116, 42, 40, 49, 46, 48, + 32, 45, 32,116,101,120, 99,111,108, 46,114, 41, 41, 42, 40, 49, 46, 48, 32, 45, 32,111,117,116, 99,111,108, 46,114, 41, 59, 10, + 10, 9,105,102, 40,111,117,116, 99,111,108, 46,103, 32, 60, 32, 48, 46, 53, 41, 10, 9, 9,105,110, 99,111,108, 46,103, 32, 61, + 32,111,117,116, 99,111,108, 46,103, 42, 40,102, 97, 99,109, 32, 43, 32, 50, 46, 48, 42,102, 97, 99,116, 42,116,101,120, 99,111, +108, 46,103, 41, 59, 10, 9,101,108,115,101, 10, 9, 9,105,110, 99,111,108, 46,103, 32, 61, 32, 49, 46, 48, 32, 45, 32, 40,102, + 97, 99,109, 32, 43, 32, 50, 46, 48, 42,102, 97, 99,116, 42, 40, 49, 46, 48, 32, 45, 32,116,101,120, 99,111,108, 46,103, 41, 41, + 42, 40, 49, 46, 48, 32, 45, 32,111,117,116, 99,111,108, 46,103, 41, 59, 10, 10, 9,105,102, 40,111,117,116, 99,111,108, 46, 98, + 32, 60, 32, 48, 46, 53, 41, 10, 9, 9,105,110, 99,111,108, 46, 98, 32, 61, 32,111,117,116, 99,111,108, 46, 98, 42, 40,102, 97, + 99,109, 32, 43, 32, 50, 46, 48, 42,102, 97, 99,116, 42,116,101,120, 99,111,108, 46, 98, 41, 59, 10, 9,101,108,115,101, 10, 9, + 9,105,110, 99,111,108, 46, 98, 32, 61, 32, 49, 46, 48, 32, 45, 32, 40,102, 97, 99,109, 32, 43, 32, 50, 46, 48, 42,102, 97, 99, +116, 42, 40, 49, 46, 48, 32, 45, 32,116,101,120, 99,111,108, 46, 98, 41, 41, 42, 40, 49, 46, 48, 32, 45, 32,111,117,116, 99,111, +108, 46, 98, 41, 59, 10,125, 10, 10,118,111,105,100, 32,109,116,101,120, 95,114,103, 98, 95,115,117, 98, 40,118,101, 99, 51, 32, +111,117,116, 99,111,108, 44, 32,118,101, 99, 51, 32,116,101,120, 99,111,108, 44, 32,102,108,111, 97,116, 32,102, 97, 99,116, 44, + 32,102,108,111, 97,116, 32,102, 97, 99,103, 44, 32,111,117,116, 32,118,101, 99, 51, 32,105,110, 99,111,108, 41, 10,123, 10, 9, +105,110, 99,111,108, 32, 61, 32, 45,102, 97, 99,116, 42,102, 97, 99,103, 42,116,101,120, 99,111,108, 32, 43, 32,111,117,116, 99, +111,108, 59, 10,125, 10, 10,118,111,105,100, 32,109,116,101,120, 95,114,103, 98, 95, 97,100,100, 40,118,101, 99, 51, 32,111,117, +116, 99,111,108, 44, 32,118,101, 99, 51, 32,116,101,120, 99,111,108, 44, 32,102,108,111, 97,116, 32,102, 97, 99,116, 44, 32,102, +108,111, 97,116, 32,102, 97, 99,103, 44, 32,111,117,116, 32,118,101, 99, 51, 32,105,110, 99,111,108, 41, 10,123, 10, 9,105,110, + 99,111,108, 32, 61, 32,102, 97, 99,116, 42,102, 97, 99,103, 42,116,101,120, 99,111,108, 32, 43, 32,111,117,116, 99,111,108, 59, + 10,125, 10, 10,118,111,105,100, 32,109,116,101,120, 95,114,103, 98, 95,100,105,118, 40,118,101, 99, 51, 32,111,117,116, 99,111, +108, 44, 32,118,101, 99, 51, 32,116,101,120, 99,111,108, 44, 32,102,108,111, 97,116, 32,102, 97, 99,116, 44, 32,102,108,111, 97, +116, 32,102, 97, 99,103, 44, 32,111,117,116, 32,118,101, 99, 51, 32,105,110, 99,111,108, 41, 10,123, 10, 9,102,108,111, 97,116, + 32,102, 97, 99,109, 59, 10, 10, 9,102, 97, 99,116, 32, 42, 61, 32,102, 97, 99,103, 59, 10, 9,102, 97, 99,109, 32, 61, 32, 49, + 46, 48, 45,102, 97, 99,116, 59, 10, 10, 9,105,102, 40,116,101,120, 99,111,108, 46,114, 32, 33, 61, 32, 48, 46, 48, 41, 32,105, +110, 99,111,108, 46,114, 32, 61, 32,102, 97, 99,109, 42,111,117,116, 99,111,108, 46,114, 32, 43, 32,102, 97, 99,116, 42,111,117, +116, 99,111,108, 46,114, 47,116,101,120, 99,111,108, 46,114, 59, 10, 9,105,102, 40,116,101,120, 99,111,108, 46,103, 32, 33, 61, + 32, 48, 46, 48, 41, 32,105,110, 99,111,108, 46,103, 32, 61, 32,102, 97, 99,109, 42,111,117,116, 99,111,108, 46,103, 32, 43, 32, +102, 97, 99,116, 42,111,117,116, 99,111,108, 46,103, 47,116,101,120, 99,111,108, 46,103, 59, 10, 9,105,102, 40,116,101,120, 99, +111,108, 46, 98, 32, 33, 61, 32, 48, 46, 48, 41, 32,105,110, 99,111,108, 46, 98, 32, 61, 32,102, 97, 99,109, 42,111,117,116, 99, +111,108, 46, 98, 32, 43, 32,102, 97, 99,116, 42,111,117,116, 99,111,108, 46, 98, 47,116,101,120, 99,111,108, 46, 98, 59, 10,125, + 10, 10,118,111,105,100, 32,109,116,101,120, 95,114,103, 98, 95,100,105,102,102, 40,118,101, 99, 51, 32,111,117,116, 99,111,108, + 44, 32,118,101, 99, 51, 32,116,101,120, 99,111,108, 44, 32,102,108,111, 97,116, 32,102, 97, 99,116, 44, 32,102,108,111, 97,116, + 32,102, 97, 99,103, 44, 32,111,117,116, 32,118,101, 99, 51, 32,105,110, 99,111,108, 41, 10,123, 10, 9,102,108,111, 97,116, 32, +102, 97, 99,109, 59, 10, 10, 9,102, 97, 99,116, 32, 42, 61, 32,102, 97, 99,103, 59, 10, 9,102, 97, 99,109, 32, 61, 32, 49, 46, + 48, 45,102, 97, 99,116, 59, 10, 10, 9,105,110, 99,111,108, 32, 61, 32,102, 97, 99,109, 42,111,117,116, 99,111,108, 32, 43, 32, +102, 97, 99,116, 42, 97, 98,115, 40,116,101,120, 99,111,108, 32, 45, 32,111,117,116, 99,111,108, 41, 59, 10,125, 10, 10,118,111, +105,100, 32,109,116,101,120, 95,114,103, 98, 95,100, 97,114,107, 40,118,101, 99, 51, 32,111,117,116, 99,111,108, 44, 32,118,101, + 99, 51, 32,116,101,120, 99,111,108, 44, 32,102,108,111, 97,116, 32,102, 97, 99,116, 44, 32,102,108,111, 97,116, 32,102, 97, 99, +103, 44, 32,111,117,116, 32,118,101, 99, 51, 32,105,110, 99,111,108, 41, 10,123, 10, 9,102,108,111, 97,116, 32,102, 97, 99,109, + 44, 32, 99,111,108, 59, 10, 10, 9,102, 97, 99,116, 32, 42, 61, 32,102, 97, 99,103, 59, 10, 9,102, 97, 99,109, 32, 61, 32, 49, + 46, 48, 45,102, 97, 99,116, 59, 10, 10, 9, 99,111,108, 32, 61, 32,102, 97, 99,116, 42,116,101,120, 99,111,108, 46,114, 59, 10, + 9,105,102, 40, 99,111,108, 32, 60, 32,111,117,116, 99,111,108, 46,114, 41, 32,105,110, 99,111,108, 46,114, 32, 61, 32, 99,111, +108, 59, 32,101,108,115,101, 32,105,110, 99,111,108, 46,114, 32, 61, 32,111,117,116, 99,111,108, 46,114, 59, 10, 9, 99,111,108, + 32, 61, 32,102, 97, 99,116, 42,116,101,120, 99,111,108, 46,103, 59, 10, 9,105,102, 40, 99,111,108, 32, 60, 32,111,117,116, 99, +111,108, 46,103, 41, 32,105,110, 99,111,108, 46,103, 32, 61, 32, 99,111,108, 59, 32,101,108,115,101, 32,105,110, 99,111,108, 46, +103, 32, 61, 32,111,117,116, 99,111,108, 46,103, 59, 10, 9, 99,111,108, 32, 61, 32,102, 97, 99,116, 42,116,101,120, 99,111,108, + 46, 98, 59, 10, 9,105,102, 40, 99,111,108, 32, 60, 32,111,117,116, 99,111,108, 46, 98, 41, 32,105,110, 99,111,108, 46, 98, 32, + 61, 32, 99,111,108, 59, 32,101,108,115,101, 32,105,110, 99,111,108, 46, 98, 32, 61, 32,111,117,116, 99,111,108, 46, 98, 59, 10, +125, 10, 10,118,111,105,100, 32,109,116,101,120, 95,114,103, 98, 95,108,105,103,104,116, 40,118,101, 99, 51, 32,111,117,116, 99, +111,108, 44, 32,118,101, 99, 51, 32,116,101,120, 99,111,108, 44, 32,102,108,111, 97,116, 32,102, 97, 99,116, 44, 32,102,108,111, + 97,116, 32,102, 97, 99,103, 44, 32,111,117,116, 32,118,101, 99, 51, 32,105,110, 99,111,108, 41, 10,123, 10, 9,102,108,111, 97, +116, 32,102, 97, 99,109, 44, 32, 99,111,108, 59, 10, 10, 9,102, 97, 99,116, 32, 42, 61, 32,102, 97, 99,103, 59, 10, 9,102, 97, + 99,109, 32, 61, 32, 49, 46, 48, 45,102, 97, 99,116, 59, 10, 10, 9, 99,111,108, 32, 61, 32,102, 97, 99,116, 42,116,101,120, 99, +111,108, 46,114, 59, 10, 9,105,102, 40, 99,111,108, 32, 62, 32,111,117,116, 99,111,108, 46,114, 41, 32,105,110, 99,111,108, 46, +114, 32, 61, 32, 99,111,108, 59, 32,101,108,115,101, 32,105,110, 99,111,108, 46,114, 32, 61, 32,111,117,116, 99,111,108, 46,114, + 59, 10, 9, 99,111,108, 32, 61, 32,102, 97, 99,116, 42,116,101,120, 99,111,108, 46,103, 59, 10, 9,105,102, 40, 99,111,108, 32, + 62, 32,111,117,116, 99,111,108, 46,103, 41, 32,105,110, 99,111,108, 46,103, 32, 61, 32, 99,111,108, 59, 32,101,108,115,101, 32, +105,110, 99,111,108, 46,103, 32, 61, 32,111,117,116, 99,111,108, 46,103, 59, 10, 9, 99,111,108, 32, 61, 32,102, 97, 99,116, 42, +116,101,120, 99,111,108, 46, 98, 59, 10, 9,105,102, 40, 99,111,108, 32, 62, 32,111,117,116, 99,111,108, 46, 98, 41, 32,105,110, + 99,111,108, 46, 98, 32, 61, 32, 99,111,108, 59, 32,101,108,115,101, 32,105,110, 99,111,108, 46, 98, 32, 61, 32,111,117,116, 99, +111,108, 46, 98, 59, 10,125, 10, 10,118,111,105,100, 32,109,116,101,120, 95,114,103, 98, 95,104,117,101, 40,118,101, 99, 51, 32, +111,117,116, 99,111,108, 44, 32,118,101, 99, 51, 32,116,101,120, 99,111,108, 44, 32,102,108,111, 97,116, 32,102, 97, 99,116, 44, + 32,102,108,111, 97,116, 32,102, 97, 99,103, 44, 32,111,117,116, 32,118,101, 99, 51, 32,105,110, 99,111,108, 41, 10,123, 10, 9, +118,101, 99, 52, 32, 99,111,108, 59, 10, 10, 9,109,105,120, 95,104,117,101, 40,102, 97, 99,116, 42,102, 97, 99,103, 44, 32,118, +101, 99, 52, 40,111,117,116, 99,111,108, 44, 32, 49, 46, 48, 41, 44, 32,118,101, 99, 52, 40,116,101,120, 99,111,108, 44, 32, 49, + 46, 48, 41, 44, 32, 99,111,108, 41, 59, 10, 9,105,110, 99,111,108, 46,114,103, 98, 32, 61, 32, 99,111,108, 46,114,103, 98, 59, + 10,125, 10, 10,118,111,105,100, 32,109,116,101,120, 95,114,103, 98, 95,115, 97,116, 40,118,101, 99, 51, 32,111,117,116, 99,111, +108, 44, 32,118,101, 99, 51, 32,116,101,120, 99,111,108, 44, 32,102,108,111, 97,116, 32,102, 97, 99,116, 44, 32,102,108,111, 97, +116, 32,102, 97, 99,103, 44, 32,111,117,116, 32,118,101, 99, 51, 32,105,110, 99,111,108, 41, 10,123, 10, 9,118,101, 99, 52, 32, + 99,111,108, 59, 10, 10, 9,109,105,120, 95,115, 97,116, 40,102, 97, 99,116, 42,102, 97, 99,103, 44, 32,118,101, 99, 52, 40,111, +117,116, 99,111,108, 44, 32, 49, 46, 48, 41, 44, 32,118,101, 99, 52, 40,116,101,120, 99,111,108, 44, 32, 49, 46, 48, 41, 44, 32, + 99,111,108, 41, 59, 10, 9,105,110, 99,111,108, 46,114,103, 98, 32, 61, 32, 99,111,108, 46,114,103, 98, 59, 10,125, 10, 10,118, +111,105,100, 32,109,116,101,120, 95,114,103, 98, 95,118, 97,108, 40,118,101, 99, 51, 32,111,117,116, 99,111,108, 44, 32,118,101, + 99, 51, 32,116,101,120, 99,111,108, 44, 32,102,108,111, 97,116, 32,102, 97, 99,116, 44, 32,102,108,111, 97,116, 32,102, 97, 99, +103, 44, 32,111,117,116, 32,118,101, 99, 51, 32,105,110, 99,111,108, 41, 10,123, 10, 9,118,101, 99, 52, 32, 99,111,108, 59, 10, + 10, 9,109,105,120, 95,118, 97,108, 40,102, 97, 99,116, 42,102, 97, 99,103, 44, 32,118,101, 99, 52, 40,111,117,116, 99,111,108, + 44, 32, 49, 46, 48, 41, 44, 32,118,101, 99, 52, 40,116,101,120, 99,111,108, 44, 32, 49, 46, 48, 41, 44, 32, 99,111,108, 41, 59, + 10, 9,105,110, 99,111,108, 46,114,103, 98, 32, 61, 32, 99,111,108, 46,114,103, 98, 59, 10,125, 10, 10,118,111,105,100, 32,109, +116,101,120, 95,114,103, 98, 95, 99,111,108,111,114, 40,118,101, 99, 51, 32,111,117,116, 99,111,108, 44, 32,118,101, 99, 51, 32, +116,101,120, 99,111,108, 44, 32,102,108,111, 97,116, 32,102, 97, 99,116, 44, 32,102,108,111, 97,116, 32,102, 97, 99,103, 44, 32, +111,117,116, 32,118,101, 99, 51, 32,105,110, 99,111,108, 41, 10,123, 10, 9,118,101, 99, 52, 32, 99,111,108, 59, 10, 10, 9,109, +105,120, 95, 99,111,108,111,114, 40,102, 97, 99,116, 42,102, 97, 99,103, 44, 32,118,101, 99, 52, 40,111,117,116, 99,111,108, 44, + 32, 49, 46, 48, 41, 44, 32,118,101, 99, 52, 40,116,101,120, 99,111,108, 44, 32, 49, 46, 48, 41, 44, 32, 99,111,108, 41, 59, 10, + 9,105,110, 99,111,108, 46,114,103, 98, 32, 61, 32, 99,111,108, 46,114,103, 98, 59, 10,125, 10, 10,118,111,105,100, 32,109,116, +101,120, 95,118, 97,108,117,101, 95,118, 97,114,115, 40,105,110,111,117,116, 32,102,108,111, 97,116, 32,102, 97, 99,116, 44, 32, +102,108,111, 97,116, 32,102, 97, 99,103, 44, 32,111,117,116, 32,102,108,111, 97,116, 32,102, 97, 99,109, 44, 32,102,108,111, 97, +116, 32,102,108,105,112, 41, 10,123, 10, 9,102, 97, 99,116, 32, 42, 61, 32,102, 97, 99,103, 59, 10, 9,102, 97, 99,109, 32, 61, + 32, 49, 46, 48, 45,102, 97, 99,116, 59, 10, 10, 9,105,102, 40,102,108,105,112, 32, 33, 61, 32, 48, 46, 48, 41, 32,123, 10, 9, + 9,102,108,111, 97,116, 32,116,109,112, 32, 61, 32,102, 97, 99,116, 59, 10, 9, 9,102, 97, 99,116, 32, 61, 32,102, 97, 99,109, + 59, 10, 9, 9,102, 97, 99,109, 32, 61, 32,116,109,112, 59, 10, 9,125, 10,125, 10, 10,118,111,105,100, 32,109,116,101,120, 95, +118, 97,108,117,101, 95, 98,108,101,110,100, 40,102,108,111, 97,116, 32,111,117,116, 99,111,108, 44, 32,102,108,111, 97,116, 32, +116,101,120, 99,111,108, 44, 32,102,108,111, 97,116, 32,102, 97, 99,116, 44, 32,102,108,111, 97,116, 32,102, 97, 99,103, 44, 32, +102,108,111, 97,116, 32,102,108,105,112, 44, 32,111,117,116, 32,102,108,111, 97,116, 32,105,110, 99,111,108, 41, 10,123, 10, 9, +102,108,111, 97,116, 32,102, 97, 99,109, 59, 10, 9,109,116,101,120, 95,118, 97,108,117,101, 95,118, 97,114,115, 40,102, 97, 99, +116, 44, 32,102, 97, 99,103, 44, 32,102, 97, 99,109, 44, 32,102,108,105,112, 41, 59, 10, 10, 9,105,110, 99,111,108, 32, 61, 32, +102, 97, 99,116, 42,116,101,120, 99,111,108, 32, 43, 32,102, 97, 99,109, 42,111,117,116, 99,111,108, 59, 10,125, 10, 10,118,111, +105,100, 32,109,116,101,120, 95,118, 97,108,117,101, 95,109,117,108, 40,102,108,111, 97,116, 32,111,117,116, 99,111,108, 44, 32, +102,108,111, 97,116, 32,116,101,120, 99,111,108, 44, 32,102,108,111, 97,116, 32,102, 97, 99,116, 44, 32,102,108,111, 97,116, 32, +102, 97, 99,103, 44, 32,102,108,111, 97,116, 32,102,108,105,112, 44, 32,111,117,116, 32,102,108,111, 97,116, 32,105,110, 99,111, +108, 41, 10,123, 10, 9,102,108,111, 97,116, 32,102, 97, 99,109, 59, 10, 9,109,116,101,120, 95,118, 97,108,117,101, 95,118, 97, +114,115, 40,102, 97, 99,116, 44, 32,102, 97, 99,103, 44, 32,102, 97, 99,109, 44, 32,102,108,105,112, 41, 59, 10, 10, 9,102, 97, + 99,109, 32, 61, 32, 49, 46, 48, 32, 45, 32,102, 97, 99,103, 59, 10, 9,105,110, 99,111,108, 32, 61, 32, 40,102, 97, 99,109, 32, + 43, 32,102, 97, 99,116, 42,116,101,120, 99,111,108, 41, 42,111,117,116, 99,111,108, 59, 10,125, 10, 10,118,111,105,100, 32,109, +116,101,120, 95,118, 97,108,117,101, 95,115, 99,114,101,101,110, 40,102,108,111, 97,116, 32,111,117,116, 99,111,108, 44, 32,102, +108,111, 97,116, 32,116,101,120, 99,111,108, 44, 32,102,108,111, 97,116, 32,102, 97, 99,116, 44, 32,102,108,111, 97,116, 32,102, + 97, 99,103, 44, 32,102,108,111, 97,116, 32,102,108,105,112, 44, 32,111,117,116, 32,102,108,111, 97,116, 32,105,110, 99,111,108, + 41, 10,123, 10, 9,102,108,111, 97,116, 32,102, 97, 99,109, 59, 10, 9,109,116,101,120, 95,118, 97,108,117,101, 95,118, 97,114, +115, 40,102, 97, 99,116, 44, 32,102, 97, 99,103, 44, 32,102, 97, 99,109, 44, 32,102,108,105,112, 41, 59, 10, 10, 9,102, 97, 99, +109, 32, 61, 32, 49, 46, 48, 32, 45, 32,102, 97, 99,103, 59, 10, 9,105,110, 99,111,108, 32, 61, 32, 49, 46, 48, 32, 45, 32, 40, +102, 97, 99,109, 32, 43, 32,102, 97, 99,116, 42, 40, 49, 46, 48, 32, 45, 32,116,101,120, 99,111,108, 41, 41, 42, 40, 49, 46, 48, + 32, 45, 32,111,117,116, 99,111,108, 41, 59, 10,125, 10, 10,118,111,105,100, 32,109,116,101,120, 95,118, 97,108,117,101, 95,115, +117, 98, 40,102,108,111, 97,116, 32,111,117,116, 99,111,108, 44, 32,102,108,111, 97,116, 32,116,101,120, 99,111,108, 44, 32,102, +108,111, 97,116, 32,102, 97, 99,116, 44, 32,102,108,111, 97,116, 32,102, 97, 99,103, 44, 32,102,108,111, 97,116, 32,102,108,105, +112, 44, 32,111,117,116, 32,102,108,111, 97,116, 32,105,110, 99,111,108, 41, 10,123, 10, 9,102,108,111, 97,116, 32,102, 97, 99, +109, 59, 10, 9,109,116,101,120, 95,118, 97,108,117,101, 95,118, 97,114,115, 40,102, 97, 99,116, 44, 32,102, 97, 99,103, 44, 32, +102, 97, 99,109, 44, 32,102,108,105,112, 41, 59, 10, 10, 9,102, 97, 99,116, 32, 61, 32, 45,102, 97, 99,116, 59, 10, 9,105,110, + 99,111,108, 32, 61, 32,102, 97, 99,116, 42,116,101,120, 99,111,108, 32, 43, 32,111,117,116, 99,111,108, 59, 10,125, 10, 10,118, +111,105,100, 32,109,116,101,120, 95,118, 97,108,117,101, 95, 97,100,100, 40,102,108,111, 97,116, 32,111,117,116, 99,111,108, 44, + 32,102,108,111, 97,116, 32,116,101,120, 99,111,108, 44, 32,102,108,111, 97,116, 32,102, 97, 99,116, 44, 32,102,108,111, 97,116, + 32,102, 97, 99,103, 44, 32,102,108,111, 97,116, 32,102,108,105,112, 44, 32,111,117,116, 32,102,108,111, 97,116, 32,105,110, 99, +111,108, 41, 10,123, 10, 9,102,108,111, 97,116, 32,102, 97, 99,109, 59, 10, 9,109,116,101,120, 95,118, 97,108,117,101, 95,118, + 97,114,115, 40,102, 97, 99,116, 44, 32,102, 97, 99,103, 44, 32,102, 97, 99,109, 44, 32,102,108,105,112, 41, 59, 10, 10, 9,102, + 97, 99,116, 32, 61, 32,102, 97, 99,116, 59, 10, 9,105,110, 99,111,108, 32, 61, 32,102, 97, 99,116, 42,116,101,120, 99,111,108, + 32, 43, 32,111,117,116, 99,111,108, 59, 10,125, 10, 10,118,111,105,100, 32,109,116,101,120, 95,118, 97,108,117,101, 95,100,105, +118, 40,102,108,111, 97,116, 32,111,117,116, 99,111,108, 44, 32,102,108,111, 97,116, 32,116,101,120, 99,111,108, 44, 32,102,108, +111, 97,116, 32,102, 97, 99,116, 44, 32,102,108,111, 97,116, 32,102, 97, 99,103, 44, 32,102,108,111, 97,116, 32,102,108,105,112, + 44, 32,111,117,116, 32,102,108,111, 97,116, 32,105,110, 99,111,108, 41, 10,123, 10, 9,102,108,111, 97,116, 32,102, 97, 99,109, + 59, 10, 9,109,116,101,120, 95,118, 97,108,117,101, 95,118, 97,114,115, 40,102, 97, 99,116, 44, 32,102, 97, 99,103, 44, 32,102, + 97, 99,109, 44, 32,102,108,105,112, 41, 59, 10, 10, 9,105,102, 40,116,101,120, 99,111,108, 32, 33, 61, 32, 48, 46, 48, 41, 10, + 9, 9,105,110, 99,111,108, 32, 61, 32,102, 97, 99,109, 42,111,117,116, 99,111,108, 32, 43, 32,102, 97, 99,116, 42,111,117,116, + 99,111,108, 47,116,101,120, 99,111,108, 59, 10, 9,101,108,115,101, 10, 9, 9,105,110, 99,111,108, 32, 61, 32, 48, 46, 48, 59, + 10,125, 10, 10,118,111,105,100, 32,109,116,101,120, 95,118, 97,108,117,101, 95,100,105,102,102, 40,102,108,111, 97,116, 32,111, +117,116, 99,111,108, 44, 32,102,108,111, 97,116, 32,116,101,120, 99,111,108, 44, 32,102,108,111, 97,116, 32,102, 97, 99,116, 44, + 32,102,108,111, 97,116, 32,102, 97, 99,103, 44, 32,102,108,111, 97,116, 32,102,108,105,112, 44, 32,111,117,116, 32,102,108,111, + 97,116, 32,105,110, 99,111,108, 41, 10,123, 10, 9,102,108,111, 97,116, 32,102, 97, 99,109, 59, 10, 9,109,116,101,120, 95,118, + 97,108,117,101, 95,118, 97,114,115, 40,102, 97, 99,116, 44, 32,102, 97, 99,103, 44, 32,102, 97, 99,109, 44, 32,102,108,105,112, + 41, 59, 10, 10, 9,105,110, 99,111,108, 32, 61, 32,102, 97, 99,109, 42,111,117,116, 99,111,108, 32, 43, 32,102, 97, 99,116, 42, + 97, 98,115, 40,116,101,120, 99,111,108, 32, 45, 32,111,117,116, 99,111,108, 41, 59, 10,125, 10, 10,118,111,105,100, 32,109,116, +101,120, 95,118, 97,108,117,101, 95,100, 97,114,107, 40,102,108,111, 97,116, 32,111,117,116, 99,111,108, 44, 32,102,108,111, 97, +116, 32,116,101,120, 99,111,108, 44, 32,102,108,111, 97,116, 32,102, 97, 99,116, 44, 32,102,108,111, 97,116, 32,102, 97, 99,103, + 44, 32,102,108,111, 97,116, 32,102,108,105,112, 44, 32,111,117,116, 32,102,108,111, 97,116, 32,105,110, 99,111,108, 41, 10,123, + 10, 9,102,108,111, 97,116, 32,102, 97, 99,109, 59, 10, 9,109,116,101,120, 95,118, 97,108,117,101, 95,118, 97,114,115, 40,102, + 97, 99,116, 44, 32,102, 97, 99,103, 44, 32,102, 97, 99,109, 44, 32,102,108,105,112, 41, 59, 10, 10, 9,102,108,111, 97,116, 32, + 99,111,108, 32, 61, 32,102, 97, 99,116, 42,116,101,120, 99,111,108, 59, 10, 9,105,102, 40, 99,111,108, 32, 60, 32,111,117,116, + 99,111,108, 41, 32,105,110, 99,111,108, 32, 61, 32, 99,111,108, 59, 32,101,108,115,101, 32,105,110, 99,111,108, 32, 61, 32,111, +117,116, 99,111,108, 59, 10,125, 10, 10,118,111,105,100, 32,109,116,101,120, 95,118, 97,108,117,101, 95,108,105,103,104,116, 40, +102,108,111, 97,116, 32,111,117,116, 99,111,108, 44, 32,102,108,111, 97,116, 32,116,101,120, 99,111,108, 44, 32,102,108,111, 97, +116, 32,102, 97, 99,116, 44, 32,102,108,111, 97,116, 32,102, 97, 99,103, 44, 32,102,108,111, 97,116, 32,102,108,105,112, 44, 32, +111,117,116, 32,102,108,111, 97,116, 32,105,110, 99,111,108, 41, 10,123, 10, 9,102,108,111, 97,116, 32,102, 97, 99,109, 59, 10, + 9,109,116,101,120, 95,118, 97,108,117,101, 95,118, 97,114,115, 40,102, 97, 99,116, 44, 32,102, 97, 99,103, 44, 32,102, 97, 99, +109, 44, 32,102,108,105,112, 41, 59, 10, 10, 9,102,108,111, 97,116, 32, 99,111,108, 32, 61, 32,102, 97, 99,116, 42,116,101,120, + 99,111,108, 59, 10, 9,105,102, 40, 99,111,108, 32, 62, 32,111,117,116, 99,111,108, 41, 32,105,110, 99,111,108, 32, 61, 32, 99, +111,108, 59, 32,101,108,115,101, 32,105,110, 99,111,108, 32, 61, 32,111,117,116, 99,111,108, 59, 10,125, 10, 10,118,111,105,100, + 32,109,116,101,120, 95,118, 97,108,117,101, 95, 99,108, 97,109,112, 95,112,111,115,105,116,105,118,101, 40,102,108,111, 97,116, + 32,102, 97, 99, 44, 32,111,117,116, 32,102,108,111, 97,116, 32,111,117,116,102, 97, 99, 41, 10,123, 10, 9,111,117,116,102, 97, + 99, 32, 61, 32,109, 97,120, 40,102, 97, 99, 44, 32, 48, 46, 48, 41, 59, 10,125, 10, 10,118,111,105,100, 32,109,116,101,120, 95, +118, 97,108,117,101, 95, 99,108, 97,109,112, 40,102,108,111, 97,116, 32,102, 97, 99, 44, 32,111,117,116, 32,102,108,111, 97,116, + 32,111,117,116,102, 97, 99, 41, 10,123, 10, 9,111,117,116,102, 97, 99, 32, 61, 32, 99,108, 97,109,112, 40,102, 97, 99, 44, 32, + 48, 46, 48, 44, 32, 49, 46, 48, 41, 59, 10,125, 10, 10,118,111,105,100, 32,109,116,101,120, 95,104, 97,114, 95,100,105,118,105, +100,101, 40,102,108,111, 97,116, 32,104, 97,114, 44, 32,111,117,116, 32,102,108,111, 97,116, 32,111,117,116,104, 97,114, 41, 10, +123, 10, 9,111,117,116,104, 97,114, 32, 61, 32,104, 97,114, 47, 49, 50, 56, 46, 48, 59, 10,125, 10, 10,118,111,105,100, 32,109, +116,101,120, 95,104, 97,114, 95,109,117,108,116,105,112,108,121, 95, 99,108, 97,109,112, 40,102,108,111, 97,116, 32,104, 97,114, + 44, 32,111,117,116, 32,102,108,111, 97,116, 32,111,117,116,104, 97,114, 41, 10,123, 10, 9,104, 97,114, 32, 42, 61, 32, 49, 50, + 56, 46, 48, 59, 10, 10, 9,105,102, 40,104, 97,114, 32, 60, 32, 49, 46, 48, 41, 32,111,117,116,104, 97,114, 32, 61, 32, 49, 46, + 48, 59, 10, 9,101,108,115,101, 32,105,102, 40,104, 97,114, 32, 62, 32, 53, 49, 49, 46, 48, 41, 32,111,117,116,104, 97,114, 32, + 61, 32, 53, 49, 49, 46, 48, 59, 10, 9,101,108,115,101, 32,111,117,116,104, 97,114, 32, 61, 32,104, 97,114, 59, 10,125, 10, 10, +118,111,105,100, 32,109,116,101,120, 95, 97,108,112,104, 97, 95,102,114,111,109, 95, 99,111,108, 40,118,101, 99, 52, 32, 99,111, +108, 44, 32,111,117,116, 32,102,108,111, 97,116, 32, 97,108,112,104, 97, 41, 10,123, 10, 9, 97,108,112,104, 97, 32, 61, 32, 99, +111,108, 46, 97, 59, 10,125, 10, 10,118,111,105,100, 32,109,116,101,120, 95, 97,108,112,104, 97, 95,116,111, 95, 99,111,108, 40, +118,101, 99, 52, 32, 99,111,108, 44, 32,102,108,111, 97,116, 32, 97,108,112,104, 97, 44, 32,111,117,116, 32,118,101, 99, 52, 32, +111,117,116, 99,111,108, 41, 10,123, 10, 9,111,117,116, 99,111,108, 32, 61, 32,118,101, 99, 52, 40, 99,111,108, 46,114,103, 98, + 44, 32, 97,108,112,104, 97, 41, 59, 10,125, 10, 10,118,111,105,100, 32,109,116,101,120, 95,114,103, 98,116,111,105,110,116, 40, +118,101, 99, 52, 32,114,103, 98, 44, 32,111,117,116, 32,102,108,111, 97,116, 32,105,110,116,101,110,115,105,116,121, 41, 10,123, + 10, 9,105,110,116,101,110,115,105,116,121, 32, 61, 32,100,111,116, 40,118,101, 99, 51, 40, 48, 46, 51, 53, 44, 32, 48, 46, 52, + 53, 44, 32, 48, 46, 50, 41, 44, 32,114,103, 98, 46,114,103, 98, 41, 59, 10,125, 10, 10,118,111,105,100, 32,109,116,101,120, 95, +118, 97,108,117,101, 95,105,110,118,101,114,116, 40,102,108,111, 97,116, 32,105,110,118, 97,108,117,101, 44, 32,111,117,116, 32, +102,108,111, 97,116, 32,111,117,116,118, 97,108,117,101, 41, 10,123, 10, 9,111,117,116,118, 97,108,117,101, 32, 61, 32, 49, 46, + 48, 32, 45, 32,105,110,118, 97,108,117,101, 59, 10,125, 10, 10,118,111,105,100, 32,109,116,101,120, 95,114,103, 98, 95,105,110, +118,101,114,116, 40,118,101, 99, 52, 32,105,110,114,103, 98, 44, 32,111,117,116, 32,118,101, 99, 52, 32,111,117,116,114,103, 98, + 41, 10,123, 10, 9,111,117,116,114,103, 98, 32, 61, 32,118,101, 99, 52, 40,118,101, 99, 51, 40, 49, 46, 48, 41, 32, 45, 32,105, +110,114,103, 98, 46,114,103, 98, 44, 32,105,110,114,103, 98, 46, 97, 41, 59, 10,125, 10, 10,118,111,105,100, 32,109,116,101,120, + 95,118, 97,108,117,101, 95,115,116,101,110, 99,105,108, 40,102,108,111, 97,116, 32,115,116,101,110, 99,105,108, 44, 32,102,108, +111, 97,116, 32,105,110,116,101,110,115,105,116,121, 44, 32,111,117,116, 32,102,108,111, 97,116, 32,111,117,116,115,116,101,110, + 99,105,108, 44, 32,111,117,116, 32,102,108,111, 97,116, 32,111,117,116,105,110,116,101,110,115,105,116,121, 41, 10,123, 10, 9, +102,108,111, 97,116, 32,102, 97, 99,116, 32, 61, 32,105,110,116,101,110,115,105,116,121, 59, 10, 9,111,117,116,105,110,116,101, +110,115,105,116,121, 32, 61, 32,105,110,116,101,110,115,105,116,121, 42,115,116,101,110, 99,105,108, 59, 10, 9,111,117,116,115, +116,101,110, 99,105,108, 32, 61, 32,115,116,101,110, 99,105,108, 42,102, 97, 99,116, 59, 10,125, 10, 10,118,111,105,100, 32,109, +116,101,120, 95,114,103, 98, 95,115,116,101,110, 99,105,108, 40,102,108,111, 97,116, 32,115,116,101,110, 99,105,108, 44, 32,118, +101, 99, 52, 32,114,103, 98, 44, 32,111,117,116, 32,102,108,111, 97,116, 32,111,117,116,115,116,101,110, 99,105,108, 44, 32,111, +117,116, 32,118,101, 99, 52, 32,111,117,116,114,103, 98, 41, 10,123, 10, 9,102,108,111, 97,116, 32,102, 97, 99,116, 32, 61, 32, +114,103, 98, 46, 97, 59, 10, 9,111,117,116,114,103, 98, 32, 61, 32,118,101, 99, 52, 40,114,103, 98, 46,114,103, 98, 44, 32,114, +103, 98, 46, 97, 42,115,116,101,110, 99,105,108, 41, 59, 10, 9,111,117,116,115,116,101,110, 99,105,108, 32, 61, 32,115,116,101, +110, 99,105,108, 42,102, 97, 99,116, 59, 10,125, 10, 10,118,111,105,100, 32,109,116,101,120, 95,109, 97,112,112,105,110,103, 95, +111,102,115, 40,118,101, 99, 51, 32,116,101,120, 99,111, 44, 32,118,101, 99, 51, 32,111,102,115, 44, 32,111,117,116, 32,118,101, + 99, 51, 32,111,117,116,116,101,120, 99,111, 41, 10,123, 10, 9,111,117,116,116,101,120, 99,111, 32, 61, 32,116,101,120, 99,111, + 32, 43, 32,111,102,115, 59, 10,125, 10, 10,118,111,105,100, 32,109,116,101,120, 95,109, 97,112,112,105,110,103, 95,115,105,122, +101, 40,118,101, 99, 51, 32,116,101,120, 99,111, 44, 32,118,101, 99, 51, 32,115,105,122,101, 44, 32,111,117,116, 32,118,101, 99, + 51, 32,111,117,116,116,101,120, 99,111, 41, 10,123, 10, 9,111,117,116,116,101,120, 99,111, 32, 61, 32,115,105,122,101, 42,116, +101,120, 99,111, 59, 10,125, 10, 10,118,111,105,100, 32,109,116,101,120, 95, 50,100, 95,109, 97,112,112,105,110,103, 40,118,101, + 99, 51, 32,118,101, 99, 44, 32,111,117,116, 32,118,101, 99, 51, 32,111,117,116,118,101, 99, 41, 10,123, 10, 9,111,117,116,118, +101, 99, 32, 61, 32,118,101, 99, 51, 40,118,101, 99, 46,120,121, 42, 48, 46, 53, 32, 43, 32,118,101, 99, 50, 40, 48, 46, 53, 44, + 32, 48, 46, 53, 41, 44, 32,118,101, 99, 46,122, 41, 59, 10,125, 10, 10,118,111,105,100, 32,109,116,101,120, 95,105,109, 97,103, +101, 40,118,101, 99, 51, 32,118,101, 99, 44, 32,115, 97,109,112,108,101,114, 50, 68, 32,105,109, 97, 44, 32,111,117,116, 32,102, +108,111, 97,116, 32,118, 97,108,117,101, 44, 32,111,117,116, 32,118,101, 99, 52, 32, 99,111,108,111,114, 44, 32,111,117,116, 32, +118,101, 99, 51, 32,110,111,114,109, 97,108, 41, 10,123, 10, 9, 99,111,108,111,114, 32, 61, 32,116,101,120,116,117,114,101, 50, + 68, 40,105,109, 97, 44, 32,118,101, 99, 46,120,121, 41, 59, 10, 9,118, 97,108,117,101, 32, 61, 32, 49, 46, 48, 59, 10, 9, 10, + 9,110,111,114,109, 97,108, 32, 61, 32, 50, 46, 48, 42, 40,118,101, 99, 51, 40, 99,111,108,111,114, 46,114, 44, 32, 45, 99,111, +108,111,114, 46,103, 44, 32, 99,111,108,111,114, 46, 98, 41, 32, 45, 32,118,101, 99, 51, 40, 48, 46, 53, 44, 32, 45, 48, 46, 53, + 44, 32, 48, 46, 53, 41, 41, 59, 10,125, 10, 10,118,111,105,100, 32,109,116,101,120, 95,110,101,103, 97,116,101, 95,116,101,120, +110,111,114,109, 97,108, 40,118,101, 99, 51, 32,110,111,114,109, 97,108, 44, 32,111,117,116, 32,118,101, 99, 51, 32,111,117,116, +110,111,114,109, 97,108, 41, 10,123, 10, 9,111,117,116,110,111,114,109, 97,108, 32, 61, 32,118,101, 99, 51, 40, 45,110,111,114, +109, 97,108, 46,120, 44, 32, 45,110,111,114,109, 97,108, 46,121, 44, 32,110,111,114,109, 97,108, 46,122, 41, 59, 10,125, 10, 10, +118,111,105,100, 32,109,116,101,120, 95,110,115,112, 97, 99,101, 95,116, 97,110,103,101,110,116, 40,118,101, 99, 51, 32,116, 97, +110,103,101,110,116, 44, 32,118,101, 99, 51, 32,110,111,114,109, 97,108, 44, 32,118,101, 99, 51, 32,116,101,120,110,111,114,109, + 97,108, 44, 32,111,117,116, 32,118,101, 99, 51, 32,111,117,116,110,111,114,109, 97,108, 41, 10,123, 10, 9,116, 97,110,103,101, +110,116, 32, 61, 32,110,111,114,109, 97,108,105,122,101, 40,116, 97,110,103,101,110,116, 41, 59, 10, 9,118,101, 99, 51, 32, 66, + 32, 61, 32, 99,114,111,115,115, 40,110,111,114,109, 97,108, 44, 32,116, 97,110,103,101,110,116, 41, 59, 10, 10, 9,111,117,116, +110,111,114,109, 97,108, 32, 61, 32,116,101,120,110,111,114,109, 97,108, 46,120, 42,116, 97,110,103,101,110,116, 32, 43, 32,116, +101,120,110,111,114,109, 97,108, 46,121, 42, 66, 32, 43, 32,116,101,120,110,111,114,109, 97,108, 46,122, 42,110,111,114,109, 97, +108, 59, 10, 9,111,117,116,110,111,114,109, 97,108, 32, 61, 32,110,111,114,109, 97,108,105,122,101, 40,111,117,116,110,111,114, +109, 97,108, 41, 59, 10,125, 10, 10,118,111,105,100, 32,109,116,101,120, 95, 98,108,101,110,100, 95,110,111,114,109, 97,108, 40, +102,108,111, 97,116, 32,110,111,114,102, 97, 99, 44, 32,118,101, 99, 51, 32,110,111,114,109, 97,108, 44, 32,118,101, 99, 51, 32, +110,101,119,110,111,114,109, 97,108, 44, 32,111,117,116, 32,118,101, 99, 51, 32,111,117,116,110,111,114,109, 97,108, 41, 10,123, + 10, 9,111,117,116,110,111,114,109, 97,108, 32, 61, 32, 40, 49, 46, 48, 32, 45, 32,110,111,114,102, 97, 99, 41, 42,110,111,114, +109, 97,108, 32, 43, 32,110,111,114,102, 97, 99, 42,110,101,119,110,111,114,109, 97,108, 59, 10, 9,111,117,116,110,111,114,109, + 97,108, 32, 61, 32,110,111,114,109, 97,108,105,122,101, 40,111,117,116,110,111,114,109, 97,108, 41, 59, 10,125, 10, 10, 47, 42, + 42, 42, 42, 42, 42, 42, 32, 77, 65, 84, 69, 82, 73, 65, 76, 32, 42, 42, 42, 42, 42, 42, 42, 42, 42, 47, 10, 10,118,111,105,100, + 32,108, 97,109,112, 95,118,105,115,105, 98,105,108,105,116,121, 95,115,117,110, 95,104,101,109,105, 40,118,101, 99, 51, 32,108, + 97,109,112,118,101, 99, 44, 32,111,117,116, 32,118,101, 99, 51, 32,108,118, 44, 32,111,117,116, 32,102,108,111, 97,116, 32,100, +105,115,116, 44, 32,111,117,116, 32,102,108,111, 97,116, 32,118,105,115,105,102, 97, 99, 41, 10,123, 10, 9,108,118, 32, 61, 32, +108, 97,109,112,118,101, 99, 59, 10, 9,100,105,115,116, 32, 61, 32, 49, 46, 48, 59, 10, 9,118,105,115,105,102, 97, 99, 32, 61, + 32, 49, 46, 48, 59, 10,125, 10, 10,118,111,105,100, 32,108, 97,109,112, 95,118,105,115,105, 98,105,108,105,116,121, 95,111,116, +104,101,114, 40,118,101, 99, 51, 32, 99,111, 44, 32,118,101, 99, 51, 32,108, 97,109,112, 99,111, 44, 32,111,117,116, 32,118,101, + 99, 51, 32,108,118, 44, 32,111,117,116, 32,102,108,111, 97,116, 32,100,105,115,116, 44, 32,111,117,116, 32,102,108,111, 97,116, + 32,118,105,115,105,102, 97, 99, 41, 10,123, 10, 9,108,118, 32, 61, 32, 99,111, 32, 45, 32,108, 97,109,112, 99,111, 59, 10, 9, +100,105,115,116, 32, 61, 32,108,101,110,103,116,104, 40,108,118, 41, 59, 10, 9,108,118, 32, 61, 32,110,111,114,109, 97,108,105, +122,101, 40,108,118, 41, 59, 10, 9,118,105,115,105,102, 97, 99, 32, 61, 32, 49, 46, 48, 59, 10,125, 10, 10,118,111,105,100, 32, +108, 97,109,112, 95,102, 97,108,108,111,102,102, 95,105,110,118,108,105,110,101, 97,114, 40,102,108,111, 97,116, 32,108, 97,109, +112,100,105,115,116, 44, 32,102,108,111, 97,116, 32,100,105,115,116, 44, 32,111,117,116, 32,102,108,111, 97,116, 32,118,105,115, +105,102, 97, 99, 41, 10,123, 10, 9,118,105,115,105,102, 97, 99, 32, 61, 32,108, 97,109,112,100,105,115,116, 47, 40,108, 97,109, +112,100,105,115,116, 32, 43, 32,100,105,115,116, 41, 59, 10,125, 10, 10,118,111,105,100, 32,108, 97,109,112, 95,102, 97,108,108, +111,102,102, 95,105,110,118,115,113,117, 97,114,101, 40,102,108,111, 97,116, 32,108, 97,109,112,100,105,115,116, 44, 32,102,108, +111, 97,116, 32,100,105,115,116, 44, 32,111,117,116, 32,102,108,111, 97,116, 32,118,105,115,105,102, 97, 99, 41, 10,123, 10, 9, +118,105,115,105,102, 97, 99, 32, 61, 32,108, 97,109,112,100,105,115,116, 47, 40,108, 97,109,112,100,105,115,116, 32, 43, 32,100, +105,115,116, 42,100,105,115,116, 41, 59, 10,125, 10, 10,118,111,105,100, 32,108, 97,109,112, 95,102, 97,108,108,111,102,102, 95, +115,108,105,100,101,114,115, 40,102,108,111, 97,116, 32,108, 97,109,112,100,105,115,116, 44, 32,102,108,111, 97,116, 32,108,100, + 49, 44, 32,102,108,111, 97,116, 32,108,100, 50, 44, 32,102,108,111, 97,116, 32,100,105,115,116, 44, 32,111,117,116, 32,102,108, +111, 97,116, 32,118,105,115,105,102, 97, 99, 41, 10,123, 10, 9,102,108,111, 97,116, 32,108, 97,109,112,100,105,115,116,107,119, + 32, 61, 32,108, 97,109,112,100,105,115,116, 42,108, 97,109,112,100,105,115,116, 59, 10, 10, 9,118,105,115,105,102, 97, 99, 32, + 61, 32,108, 97,109,112,100,105,115,116, 47, 40,108, 97,109,112,100,105,115,116, 32, 43, 32,108,100, 49, 42,100,105,115,116, 41, + 59, 10, 9,118,105,115,105,102, 97, 99, 32, 42, 61, 32,108, 97,109,112,100,105,115,116,107,119, 47, 40,108, 97,109,112,100,105, +115,116,107,119, 32, 43, 32,108,100, 50, 42,100,105,115,116, 42,100,105,115,116, 41, 59, 10,125, 10, 10,118,111,105,100, 32,108, + 97,109,112, 95,102, 97,108,108,111,102,102, 95, 99,117,114,118,101, 40,102,108,111, 97,116, 32,108, 97,109,112,100,105,115,116, + 44, 32,115, 97,109,112,108,101,114, 49, 68, 32, 99,117,114,118,101,109, 97,112, 44, 32,102,108,111, 97,116, 32,100,105,115,116, + 44, 32,111,117,116, 32,102,108,111, 97,116, 32,118,105,115,105,102, 97, 99, 41, 10,123, 10, 9,118,105,115,105,102, 97, 99, 32, + 61, 32,116,101,120,116,117,114,101, 49, 68, 40, 99,117,114,118,101,109, 97,112, 44, 32,100,105,115,116, 47,108, 97,109,112,100, +105,115,116, 41, 46,120, 59, 10,125, 10, 10,118,111,105,100, 32,108, 97,109,112, 95,118,105,115,105, 98,105,108,105,116,121, 95, +115,112,104,101,114,101, 40,102,108,111, 97,116, 32,108, 97,109,112,100,105,115,116, 44, 32,102,108,111, 97,116, 32,100,105,115, +116, 44, 32,102,108,111, 97,116, 32,118,105,115,105,102, 97, 99, 44, 32,111,117,116, 32,102,108,111, 97,116, 32,111,117,116,118, +105,115,105,102, 97, 99, 41, 10,123, 10, 9,102,108,111, 97,116, 32,116, 61, 32,108, 97,109,112,100,105,115,116, 32, 45, 32,100, +105,115,116, 59, 10, 10, 9,111,117,116,118,105,115,105,102, 97, 99, 61, 32,118,105,115,105,102, 97, 99, 42,109, 97,120, 40,116, + 44, 32, 48, 46, 48, 41, 47,108, 97,109,112,100,105,115,116, 59, 10,125, 10, 10,118,111,105,100, 32,108, 97,109,112, 95,118,105, +115,105, 98,105,108,105,116,121, 95,115,112,111,116, 95,115,113,117, 97,114,101, 40,118,101, 99, 51, 32,108, 97,109,112,118,101, + 99, 44, 32,109, 97,116, 52, 32,108, 97,109,112,105,109, 97,116, 44, 32,118,101, 99, 51, 32,108,118, 44, 32,111,117,116, 32,102, +108,111, 97,116, 32,105,110,112,114, 41, 10,123, 10, 9,105,102, 40,100,111,116, 40,108,118, 44, 32,108, 97,109,112,118,101, 99, + 41, 32, 62, 32, 48, 46, 48, 41, 32,123, 10, 9, 9,118,101, 99, 51, 32,108,118,114,111,116, 32, 61, 32, 40,108, 97,109,112,105, +109, 97,116, 42,118,101, 99, 52, 40,108,118, 44, 32, 48, 46, 48, 41, 41, 46,120,121,122, 59, 10, 9, 9,102,108,111, 97,116, 32, +120, 32, 61, 32,109, 97,120, 40, 97, 98,115, 40,108,118,114,111,116, 46,120, 47,108,118,114,111,116, 46,122, 41, 44, 32, 97, 98, +115, 40,108,118,114,111,116, 46,121, 47,108,118,114,111,116, 46,122, 41, 41, 59, 10, 10, 9, 9,105,110,112,114, 32, 61, 32, 49, + 46, 48, 47,115,113,114,116, 40, 49, 46, 48, 32, 43, 32,120, 42,120, 41, 59, 10, 9,125, 10, 9,101,108,115,101, 10, 9, 9,105, +110,112,114, 32, 61, 32, 48, 46, 48, 59, 10,125, 10, 10,118,111,105,100, 32,108, 97,109,112, 95,118,105,115,105, 98,105,108,105, +116,121, 95,115,112,111,116, 95, 99,105,114, 99,108,101, 40,118,101, 99, 51, 32,108, 97,109,112,118,101, 99, 44, 32,118,101, 99, + 51, 32,108,118, 44, 32,111,117,116, 32,102,108,111, 97,116, 32,105,110,112,114, 41, 10,123, 10, 9,105,110,112,114, 32, 61, 32, +100,111,116, 40,108,118, 44, 32,108, 97,109,112,118,101, 99, 41, 59, 10,125, 10, 10,118,111,105,100, 32,108, 97,109,112, 95,118, +105,115,105, 98,105,108,105,116,121, 95,115,112,111,116, 40,102,108,111, 97,116, 32,115,112,111,116,115,105, 44, 32,102,108,111, + 97,116, 32,115,112,111,116, 98,108, 44, 32,102,108,111, 97,116, 32,105,110,112,114, 44, 32,102,108,111, 97,116, 32,118,105,115, +105,102, 97, 99, 44, 32,111,117,116, 32,102,108,111, 97,116, 32,111,117,116,118,105,115,105,102, 97, 99, 41, 10,123, 10, 9,102, +108,111, 97,116, 32,116, 32, 61, 32,115,112,111,116,115,105, 59, 10, 10, 9,105,102, 40,105,110,112,114, 32, 60, 61, 32,116, 41, + 32,123, 10, 9, 9,111,117,116,118,105,115,105,102, 97, 99, 32, 61, 32, 48, 46, 48, 59, 10, 9,125, 10, 9,101,108,115,101, 32, +123, 10, 9, 9,116, 32, 61, 32,105,110,112,114, 32, 45, 32,116, 59, 10, 10, 9, 9, 47, 42, 32,115,111,102,116, 32, 97,114,101, + 97, 32, 42, 47, 10, 9, 9,105,102, 40,115,112,111,116, 98,108, 32, 33, 61, 32, 48, 46, 48, 41, 10, 9, 9, 9,105,110,112,114, + 32, 42, 61, 32,115,109,111,111,116,104,115,116,101,112, 40, 48, 46, 48, 44, 32, 49, 46, 48, 44, 32,116, 47,115,112,111,116, 98, +108, 41, 59, 10, 10, 9, 9,111,117,116,118,105,115,105,102, 97, 99, 32, 61, 32,118,105,115,105,102, 97, 99, 42,105,110,112,114, + 59, 10, 9,125, 10,125, 10, 10,118,111,105,100, 32,108, 97,109,112, 95,118,105,115,105, 98,105,108,105,116,121, 95, 99,108, 97, +109,112, 40,102,108,111, 97,116, 32,118,105,115,105,102, 97, 99, 44, 32,111,117,116, 32,102,108,111, 97,116, 32,111,117,116,118, +105,115,105,102, 97, 99, 41, 10,123, 10, 9,111,117,116,118,105,115,105,102, 97, 99, 32, 61, 32, 40,118,105,115,105,102, 97, 99, + 32, 60, 32, 48, 46, 48, 48, 49, 41, 63, 32, 48, 46, 48, 58, 32,118,105,115,105,102, 97, 99, 59, 10,125, 10, 10,118,111,105,100, + 32,115,104, 97,100,101, 95,118,105,101,119, 40,118,101, 99, 51, 32, 99,111, 44, 32,111,117,116, 32,118,101, 99, 51, 32,118,105, +101,119, 41, 10,123, 10, 9, 47, 42, 32,104, 97,110,100,108,101, 32,112,101,114,115,112,101, 99,116,105,118,101, 47,111,114,116, +104,111,103,114, 97,112,104,105, 99, 32, 42, 47, 10, 9,118,105,101,119, 32, 61, 32, 40,103,108, 95, 80,114,111,106,101, 99,116, +105,111,110, 77, 97,116,114,105,120, 91, 51, 93, 91, 51, 93, 32, 61, 61, 32, 48, 46, 48, 41, 63, 32,110,111,114,109, 97,108,105, +122,101, 40, 99,111, 41, 58, 32,118,101, 99, 51, 40, 48, 46, 48, 44, 32, 48, 46, 48, 44, 32, 45, 49, 46, 48, 41, 59, 10,125, 10, + 10,118,111,105,100, 32,115,104, 97,100,101, 95,116, 97,110,103,101,110,116, 95,118, 40,118,101, 99, 51, 32,108,118, 44, 32,118, +101, 99, 51, 32,116, 97,110,103, 44, 32,111,117,116, 32,118,101, 99, 51, 32,118,110, 41, 10,123, 10, 9,118,101, 99, 51, 32, 99, + 32, 61, 32, 99,114,111,115,115, 40,108,118, 44, 32,116, 97,110,103, 41, 59, 10, 9,118,101, 99, 51, 32,118,110,111,114, 32, 61, + 32, 99,114,111,115,115, 40, 99, 44, 32,116, 97,110,103, 41, 59, 10, 10, 9,118,110, 32, 61, 32, 45,110,111,114,109, 97,108,105, +122,101, 40,118,110,111,114, 41, 59, 10,125, 10, 10,118,111,105,100, 32,115,104, 97,100,101, 95,105,110,112, 40,118,101, 99, 51, + 32,118,110, 44, 32,118,101, 99, 51, 32,108,118, 44, 32,111,117,116, 32,102,108,111, 97,116, 32,105,110,112, 41, 10,123, 10, 9, +105,110,112, 32, 61, 32,100,111,116, 40,118,110, 44, 32,108,118, 41, 59, 10,125, 10, 10,118,111,105,100, 32,115,104, 97,100,101, + 95,105,115, 95,110,111, 95,100,105,102,102,117,115,101, 40,111,117,116, 32,102,108,111, 97,116, 32,105,115, 41, 10,123, 10, 9, +105,115, 32, 61, 32, 48, 46, 48, 59, 10,125, 10, 10,118,111,105,100, 32,115,104, 97,100,101, 95,105,115, 95,104,101,109,105, 40, +102,108,111, 97,116, 32,105,110,112, 44, 32,111,117,116, 32,102,108,111, 97,116, 32,105,115, 41, 10,123, 10, 9,105,115, 32, 61, + 32, 48, 46, 53, 42,105,110,112, 32, 43, 32, 48, 46, 53, 59, 10,125, 10, 10,102,108,111, 97,116, 32, 97,114,101, 97, 95,108, 97, +109,112, 95,101,110,101,114,103,121, 40,109, 97,116, 52, 32, 97,114,101, 97, 44, 32,118,101, 99, 51, 32, 99,111, 44, 32,118,101, + 99, 51, 32,118,110, 41, 10,123, 10, 9,118,101, 99, 51, 32,118,101, 99, 91, 52, 93, 44, 32, 99, 91, 52, 93, 59, 10, 9,102,108, +111, 97,116, 32,114, 97,100, 91, 52, 93, 44, 32,102, 97, 99, 59, 10, 9, 10, 9,118,101, 99, 91, 48, 93, 32, 61, 32,110,111,114, +109, 97,108,105,122,101, 40, 99,111, 32, 45, 32, 97,114,101, 97, 91, 48, 93, 46,120,121,122, 41, 59, 10, 9,118,101, 99, 91, 49, + 93, 32, 61, 32,110,111,114,109, 97,108,105,122,101, 40, 99,111, 32, 45, 32, 97,114,101, 97, 91, 49, 93, 46,120,121,122, 41, 59, + 10, 9,118,101, 99, 91, 50, 93, 32, 61, 32,110,111,114,109, 97,108,105,122,101, 40, 99,111, 32, 45, 32, 97,114,101, 97, 91, 50, + 93, 46,120,121,122, 41, 59, 10, 9,118,101, 99, 91, 51, 93, 32, 61, 32,110,111,114,109, 97,108,105,122,101, 40, 99,111, 32, 45, + 32, 97,114,101, 97, 91, 51, 93, 46,120,121,122, 41, 59, 10, 10, 9, 99, 91, 48, 93, 32, 61, 32,110,111,114,109, 97,108,105,122, +101, 40, 99,114,111,115,115, 40,118,101, 99, 91, 48, 93, 44, 32,118,101, 99, 91, 49, 93, 41, 41, 59, 10, 9, 99, 91, 49, 93, 32, + 61, 32,110,111,114,109, 97,108,105,122,101, 40, 99,114,111,115,115, 40,118,101, 99, 91, 49, 93, 44, 32,118,101, 99, 91, 50, 93, + 41, 41, 59, 10, 9, 99, 91, 50, 93, 32, 61, 32,110,111,114,109, 97,108,105,122,101, 40, 99,114,111,115,115, 40,118,101, 99, 91, + 50, 93, 44, 32,118,101, 99, 91, 51, 93, 41, 41, 59, 10, 9, 99, 91, 51, 93, 32, 61, 32,110,111,114,109, 97,108,105,122,101, 40, + 99,114,111,115,115, 40,118,101, 99, 91, 51, 93, 44, 32,118,101, 99, 91, 48, 93, 41, 41, 59, 10, 10, 9,114, 97,100, 91, 48, 93, + 32, 61, 32, 97, 99,111,115, 40,100,111,116, 40,118,101, 99, 91, 48, 93, 44, 32,118,101, 99, 91, 49, 93, 41, 41, 59, 10, 9,114, + 97,100, 91, 49, 93, 32, 61, 32, 97, 99,111,115, 40,100,111,116, 40,118,101, 99, 91, 49, 93, 44, 32,118,101, 99, 91, 50, 93, 41, + 41, 59, 10, 9,114, 97,100, 91, 50, 93, 32, 61, 32, 97, 99,111,115, 40,100,111,116, 40,118,101, 99, 91, 50, 93, 44, 32,118,101, + 99, 91, 51, 93, 41, 41, 59, 10, 9,114, 97,100, 91, 51, 93, 32, 61, 32, 97, 99,111,115, 40,100,111,116, 40,118,101, 99, 91, 51, + 93, 44, 32,118,101, 99, 91, 48, 93, 41, 41, 59, 10, 10, 9,102, 97, 99, 61, 32, 32,114, 97,100, 91, 48, 93, 42,100,111,116, 40, +118,110, 44, 32, 99, 91, 48, 93, 41, 59, 10, 9,102, 97, 99, 43, 61, 32,114, 97,100, 91, 49, 93, 42,100,111,116, 40,118,110, 44, + 32, 99, 91, 49, 93, 41, 59, 10, 9,102, 97, 99, 43, 61, 32,114, 97,100, 91, 50, 93, 42,100,111,116, 40,118,110, 44, 32, 99, 91, + 50, 93, 41, 59, 10, 9,102, 97, 99, 43, 61, 32,114, 97,100, 91, 51, 93, 42,100,111,116, 40,118,110, 44, 32, 99, 91, 51, 93, 41, + 59, 10, 10, 9,114,101,116,117,114,110, 32,109, 97,120, 40,102, 97, 99, 44, 32, 48, 46, 48, 41, 59, 10,125, 10, 10,118,111,105, +100, 32,115,104, 97,100,101, 95,105,110,112, 95, 97,114,101, 97, 40,118,101, 99, 51, 32,112,111,115,105,116,105,111,110, 44, 32, +118,101, 99, 51, 32,108, 97,109,112, 99,111, 44, 32,118,101, 99, 51, 32,108, 97,109,112,118,101, 99, 44, 32,118,101, 99, 51, 32, +118,110, 44, 32,109, 97,116, 52, 32, 97,114,101, 97, 44, 32,102,108,111, 97,116, 32, 97,114,101, 97,115,105,122,101, 44, 32,102, +108,111, 97,116, 32,107, 44, 32,111,117,116, 32,102,108,111, 97,116, 32,105,110,112, 41, 10,123, 10, 9,118,101, 99, 51, 32, 99, +111, 32, 61, 32,112,111,115,105,116,105,111,110, 59, 10, 9,118,101, 99, 51, 32,118,101, 99, 32, 61, 32, 99,111, 32, 45, 32,108, + 97,109,112, 99,111, 59, 10, 10, 9,105,102, 40,100,111,116, 40,118,101, 99, 44, 32,108, 97,109,112,118,101, 99, 41, 32, 60, 32, + 48, 46, 48, 41, 32,123, 10, 9, 9,105,110,112, 32, 61, 32, 48, 46, 48, 59, 10, 9,125, 10, 9,101,108,115,101, 32,123, 10, 9, + 9,102,108,111, 97,116, 32,105,110,116,101,110,115, 32, 61, 32, 97,114,101, 97, 95,108, 97,109,112, 95,101,110,101,114,103,121, + 40, 97,114,101, 97, 44, 32, 99,111, 44, 32,118,110, 41, 59, 10, 10, 9, 9,105,110,112, 32, 61, 32,112,111,119, 40,105,110,116, +101,110,115, 42, 97,114,101, 97,115,105,122,101, 44, 32,107, 41, 59, 10, 9,125, 10,125, 10, 10,118,111,105,100, 32,115,104, 97, +100,101, 95,100,105,102,102,117,115,101, 95,111,114,101,110, 95,110, 97,121,101,114, 40,102,108,111, 97,116, 32,110,108, 44, 32, +118,101, 99, 51, 32,110, 44, 32,118,101, 99, 51, 32,108, 44, 32,118,101, 99, 51, 32,118, 44, 32,102,108,111, 97,116, 32,114,111, +117,103,104, 44, 32,111,117,116, 32,102,108,111, 97,116, 32,105,115, 41, 10,123, 10, 9,118,101, 99, 51, 32,104, 32, 61, 32,110, +111,114,109, 97,108,105,122,101, 40,118, 32, 43, 32,108, 41, 59, 10, 9,102,108,111, 97,116, 32,110,104, 32, 61, 32,109, 97,120, + 40,100,111,116, 40,110, 44, 32,104, 41, 44, 32, 48, 46, 48, 41, 59, 10, 9,102,108,111, 97,116, 32,110,118, 32, 61, 32,109, 97, +120, 40,100,111,116, 40,110, 44, 32,118, 41, 44, 32, 48, 46, 48, 41, 59, 10, 9,102,108,111, 97,116, 32,114,101, 97,108,110,108, + 32, 61, 32,100,111,116, 40,110, 44, 32,108, 41, 59, 10, 10, 9,105,102, 40,114,101, 97,108,110,108, 32, 60, 32, 48, 46, 48, 41, + 32,123, 10, 9, 9,105,115, 32, 61, 32, 48, 46, 48, 59, 10, 9,125, 10, 9,101,108,115,101, 32,105,102, 40,110,108, 32, 60, 32, + 48, 46, 48, 41, 32,123, 10, 9, 9,105,115, 32, 61, 32, 48, 46, 48, 59, 10, 9,125, 10, 9,101,108,115,101, 32,123, 10, 9, 9, +102,108,111, 97,116, 32,118,104, 32, 61, 32,109, 97,120, 40,100,111,116, 40,118, 44, 32,104, 41, 44, 32, 48, 46, 48, 41, 59, 10, + 9, 9,102,108,111, 97,116, 32, 76,105,116, 95, 65, 32, 61, 32, 97, 99,111,115, 40,114,101, 97,108,110,108, 41, 59, 10, 9, 9, +102,108,111, 97,116, 32, 86,105,101,119, 95, 65, 32, 61, 32, 97, 99,111,115, 40,110,118, 41, 59, 10, 10, 9, 9,118,101, 99, 51, + 32, 76,105,116, 95, 66, 32, 61, 32,110,111,114,109, 97,108,105,122,101, 40,108, 32, 45, 32,114,101, 97,108,110,108, 42,110, 41, + 59, 10, 9, 9,118,101, 99, 51, 32, 86,105,101,119, 95, 66, 32, 61, 32,110,111,114,109, 97,108,105,122,101, 40,118, 32, 45, 32, +110,118, 42,110, 41, 59, 10, 10, 9, 9,102,108,111, 97,116, 32,116, 32, 61, 32,109, 97,120, 40,100,111,116, 40, 76,105,116, 95, + 66, 44, 32, 86,105,101,119, 95, 66, 41, 44, 32, 48, 46, 48, 41, 59, 10, 10, 9, 9,102,108,111, 97,116, 32, 97, 44, 32, 98, 59, + 10, 10, 9, 9,105,102, 40, 76,105,116, 95, 65, 32, 62, 32, 86,105,101,119, 95, 65, 41, 32,123, 10, 9, 9, 9, 97, 32, 61, 32, + 76,105,116, 95, 65, 59, 10, 9, 9, 9, 98, 32, 61, 32, 86,105,101,119, 95, 65, 59, 10, 9, 9,125, 10, 9, 9,101,108,115,101, + 32,123, 10, 9, 9, 9, 97, 32, 61, 32, 86,105,101,119, 95, 65, 59, 10, 9, 9, 9, 98, 32, 61, 32, 76,105,116, 95, 65, 59, 10, + 9, 9,125, 10, 10, 9, 9,102,108,111, 97,116, 32, 65, 32, 61, 32, 49, 46, 48, 32, 45, 32, 40, 48, 46, 53, 42, 40, 40,114,111, +117,103,104, 42,114,111,117,103,104, 41, 47, 40, 40,114,111,117,103,104, 42,114,111,117,103,104, 41, 32, 43, 32, 48, 46, 51, 51, + 41, 41, 41, 59, 10, 9, 9,102,108,111, 97,116, 32, 66, 32, 61, 32, 48, 46, 52, 53, 42, 40, 40,114,111,117,103,104, 42,114,111, +117,103,104, 41, 47, 40, 40,114,111,117,103,104, 42,114,111,117,103,104, 41, 32, 43, 32, 48, 46, 48, 57, 41, 41, 59, 10, 10, 9, + 9, 98, 32, 42, 61, 32, 48, 46, 57, 53, 59, 10, 9, 9,105,115, 32, 61, 32,110,108, 42, 40, 65, 32, 43, 32, 40, 66, 32, 42, 32, +116, 32, 42, 32,115,105,110, 40, 97, 41, 32, 42, 32,116, 97,110, 40, 98, 41, 41, 41, 59, 10, 9,125, 10,125, 10, 10,118,111,105, +100, 32,115,104, 97,100,101, 95,100,105,102,102,117,115,101, 95,116,111,111,110, 40,118,101, 99, 51, 32,110, 44, 32,118,101, 99, + 51, 32,108, 44, 32,118,101, 99, 51, 32,118, 44, 32,102,108,111, 97,116, 32,115,105,122,101, 44, 32,102,108,111, 97,116, 32,116, +115,109,111,111,116,104, 44, 32,111,117,116, 32,102,108,111, 97,116, 32,105,115, 41, 10,123, 10, 9,102,108,111, 97,116, 32,114, +115,108,116, 32, 61, 32,100,111,116, 40,110, 44, 32,108, 41, 59, 10, 9,102,108,111, 97,116, 32, 97,110,103, 32, 61, 32, 97, 99, +111,115, 40,114,115,108,116, 41, 59, 10, 10, 9,105,102, 40, 97,110,103, 32, 60, 32,115,105,122,101, 41, 32,105,115, 32, 61, 32, + 49, 46, 48, 59, 10, 9,101,108,115,101, 32,105,102, 40, 97,110,103, 32, 62, 32, 40,115,105,122,101, 32, 43, 32,116,115,109,111, +111,116,104, 41, 32,124,124, 32,116,115,109,111,111,116,104, 32, 61, 61, 32, 48, 46, 48, 41, 32,105,115, 32, 61, 32, 48, 46, 48, + 59, 10, 9,101,108,115,101, 32,105,115, 32, 61, 32, 49, 46, 48, 32, 45, 32, 40, 40, 97,110,103, 32, 45, 32,115,105,122,101, 41, + 47,116,115,109,111,111,116,104, 41, 59, 10,125, 10, 10,118,111,105,100, 32,115,104, 97,100,101, 95,100,105,102,102,117,115,101, + 95,109,105,110,110, 97,101,114,116, 40,102,108,111, 97,116, 32,110,108, 44, 32,118,101, 99, 51, 32,110, 44, 32,118,101, 99, 51, + 32,118, 44, 32,102,108,111, 97,116, 32,100, 97,114,107,110,101,115,115, 44, 32,111,117,116, 32,102,108,111, 97,116, 32,105,115, + 41, 10,123, 10, 9,105,102, 40,110,108, 32, 60, 61, 32, 48, 46, 48, 41, 32,123, 10, 9, 9,105,115, 32, 61, 32, 48, 46, 48, 59, + 10, 9,125, 10, 9,101,108,115,101, 32,123, 10, 9, 9,102,108,111, 97,116, 32,110,118, 32, 61, 32,109, 97,120, 40,100,111,116, + 40,110, 44, 32,118, 41, 44, 32, 48, 46, 48, 41, 59, 10, 10, 9, 9,105,102, 40,100, 97,114,107,110,101,115,115, 32, 60, 61, 32, + 49, 46, 48, 41, 10, 9, 9, 9,105,115, 32, 61, 32,110,108, 42,112,111,119, 40,109, 97,120, 40,110,118, 42,110,108, 44, 32, 48, + 46, 49, 41, 44, 32,100, 97,114,107,110,101,115,115, 32, 45, 32, 49, 46, 48, 41, 59, 10, 9, 9,101,108,115,101, 10, 9, 9, 9, +105,115, 32, 61, 32,110,108, 42,112,111,119, 40, 49, 46, 48, 48, 48, 49, 32, 45, 32,110,118, 44, 32,100, 97,114,107,110,101,115, +115, 32, 45, 32, 49, 46, 48, 41, 59, 10, 9,125, 10,125, 10, 10,102,108,111, 97,116, 32,102,114,101,115,110,101,108, 95,102, 97, + 99, 40,118,101, 99, 51, 32,118,105,101,119, 44, 32,118,101, 99, 51, 32,118,110, 44, 32,102,108,111, 97,116, 32,103,114, 97,100, + 44, 32,102,108,111, 97,116, 32,102, 97, 99, 41, 10,123, 10, 9,102,108,111, 97,116, 32,116, 49, 44, 32,116, 50, 59, 10, 9,102, +108,111, 97,116, 32,102,102, 97, 99, 59, 10, 10, 9,105,102, 40,102, 97, 99, 61, 61, 48, 46, 48, 41, 32,123, 10, 9, 9,102,102, + 97, 99, 32, 61, 32, 49, 46, 48, 59, 10, 9,125, 10, 9,101,108,115,101, 32,123, 10, 9, 9,116, 49, 61, 32,100,111,116, 40,118, +105,101,119, 44, 32,118,110, 41, 59, 10, 9, 9,105,102, 40,116, 49, 62, 48, 46, 48, 41, 32, 32,116, 50, 61, 32, 49, 46, 48, 43, +116, 49, 59, 10, 9, 9,101,108,115,101, 32,116, 50, 61, 32, 49, 46, 48, 45,116, 49, 59, 10, 10, 9, 9,116, 50, 61, 32,103,114, + 97,100, 32, 43, 32, 40, 49, 46, 48, 45,103,114, 97,100, 41, 42,112,111,119, 40,116, 50, 44, 32,102, 97, 99, 41, 59, 10, 10, 9, + 9,105,102, 40,116, 50, 60, 48, 46, 48, 41, 32,102,102, 97, 99, 32, 61, 32, 48, 46, 48, 59, 10, 9, 9,101,108,115,101, 32,105, +102, 40,116, 50, 62, 49, 46, 48, 41, 32,102,102, 97, 99, 32, 61, 32, 49, 46, 48, 59, 10, 9, 9,101,108,115,101, 32,102,102, 97, + 99, 32, 61, 32,116, 50, 59, 10, 9,125, 10, 10, 9,114,101,116,117,114,110, 32,102,102, 97, 99, 59, 10,125, 10, 10,118,111,105, +100, 32,115,104, 97,100,101, 95,100,105,102,102,117,115,101, 95,102,114,101,115,110,101,108, 40,118,101, 99, 51, 32,118,110, 44, + 32,118,101, 99, 51, 32,108,118, 44, 32,118,101, 99, 51, 32,118,105,101,119, 44, 32,102,108,111, 97,116, 32,102, 97, 99, 95,105, + 44, 32,102,108,111, 97,116, 32,102, 97, 99, 44, 32,111,117,116, 32,102,108,111, 97,116, 32,105,115, 41, 10,123, 10, 9,105,115, + 32, 61, 32,102,114,101,115,110,101,108, 95,102, 97, 99, 40,108,118, 44, 32,118,110, 44, 32,102, 97, 99, 95,105, 44, 32,102, 97, + 99, 41, 59, 10,125, 10, 10,118,111,105,100, 32,115,104, 97,100,101, 95, 99,117, 98,105, 99, 40,102,108,111, 97,116, 32,105,115, + 44, 32,111,117,116, 32,102,108,111, 97,116, 32,111,117,116,105,115, 41, 10,123, 10, 9,105,102, 40,105,115, 62, 48, 46, 48, 32, + 38, 38, 32,105,115, 60, 49, 46, 48, 41, 10, 9, 9,111,117,116,105,115, 61, 32,115,109,111,111,116,104,115,116,101,112, 40, 48, + 46, 48, 44, 32, 49, 46, 48, 44, 32,105,115, 41, 59, 10, 9,101,108,115,101, 10, 9, 9,111,117,116,105,115, 61, 32,105,115, 59, + 10,125, 10, 10,118,111,105,100, 32,115,104, 97,100,101, 95,118,105,115,105,102, 97, 99, 40,102,108,111, 97,116, 32,105, 44, 32, +102,108,111, 97,116, 32,118,105,115,105,102, 97, 99, 44, 32,102,108,111, 97,116, 32,114,101,102,108, 44, 32,111,117,116, 32,102, +108,111, 97,116, 32,111,117,116,105, 41, 10,123, 10, 9, 47, 42,105,102, 40,105, 32, 62, 32, 48, 46, 48, 41, 42, 47, 10, 9, 9, +111,117,116,105, 32, 61, 32,109, 97,120, 40,105, 42,118,105,115,105,102, 97, 99, 42,114,101,102,108, 44, 32, 48, 46, 48, 41, 59, + 10, 9, 47, 42,101,108,115,101, 10, 9, 9,111,117,116,105, 32, 61, 32,105, 59, 42, 47, 10,125, 10, 10,118,111,105,100, 32,115, +104, 97,100,101, 95,116, 97,110,103,101,110,116, 95,118, 95,115,112,101, 99, 40,118,101, 99, 51, 32,116, 97,110,103, 44, 32,111, +117,116, 32,118,101, 99, 51, 32,118,110, 41, 10,123, 10, 9,118,110, 32, 61, 32,116, 97,110,103, 59, 10,125, 10, 10,118,111,105, +100, 32,115,104, 97,100,101, 95, 97,100,100, 95,116,111, 95,100,105,102,102,117,115,101, 40,102,108,111, 97,116, 32,105, 44, 32, +118,101, 99, 51, 32,108, 97,109,112, 99,111,108, 44, 32,118,101, 99, 51, 32, 99,111,108, 44, 32,111,117,116, 32,118,101, 99, 51, + 32,111,117,116, 99,111,108, 41, 10,123, 10, 9,105,102, 40,105, 32, 62, 32, 48, 46, 48, 41, 10, 9, 9,111,117,116, 99,111,108, + 32, 61, 32,105, 42,108, 97,109,112, 99,111,108, 42, 99,111,108, 59, 10, 9,101,108,115,101, 10, 9, 9,111,117,116, 99,111,108, + 32, 61, 32,118,101, 99, 51, 40, 48, 46, 48, 44, 32, 48, 46, 48, 44, 32, 48, 46, 48, 41, 59, 10,125, 10, 10,118,111,105,100, 32, +115,104, 97,100,101, 95,104,101,109,105, 95,115,112,101, 99, 40,118,101, 99, 51, 32,118,110, 44, 32,118,101, 99, 51, 32,108,118, + 44, 32,118,101, 99, 51, 32,118,105,101,119, 44, 32,102,108,111, 97,116, 32,115,112,101, 99, 44, 32,102,108,111, 97,116, 32,104, + 97,114,100, 44, 32,102,108,111, 97,116, 32,118,105,115,105,102, 97, 99, 44, 32,111,117,116, 32,102,108,111, 97,116, 32,116, 41, + 10,123, 10, 9,108,118, 32, 43, 61, 32,118,105,101,119, 59, 10, 9,108,118, 32, 61, 32,110,111,114,109, 97,108,105,122,101, 40, +108,118, 41, 59, 10, 10, 9,116, 32, 61, 32,100,111,116, 40,118,110, 44, 32,108,118, 41, 59, 10, 9,116, 32, 61, 32, 48, 46, 53, + 42,116, 32, 43, 32, 48, 46, 53, 59, 10, 10, 9,116, 32, 61, 32,118,105,115,105,102, 97, 99, 42,115,112,101, 99, 42,112,111,119, + 40,116, 44, 32,104, 97,114,100, 41, 59, 10,125, 10, 10,118,111,105,100, 32,115,104, 97,100,101, 95,112,104,111,110,103, 95,115, +112,101, 99, 40,118,101, 99, 51, 32,110, 44, 32,118,101, 99, 51, 32,108, 44, 32,118,101, 99, 51, 32,118, 44, 32,102,108,111, 97, +116, 32,104, 97,114,100, 44, 32,111,117,116, 32,102,108,111, 97,116, 32,115,112,101, 99,102, 97, 99, 41, 10,123, 10, 9,118,101, + 99, 51, 32,104, 32, 61, 32,110,111,114,109, 97,108,105,122,101, 40,108, 32, 43, 32,118, 41, 59, 10, 9,102,108,111, 97,116, 32, +114,115,108,116, 32, 61, 32,109, 97,120, 40,100,111,116, 40,104, 44, 32,110, 41, 44, 32, 48, 46, 48, 41, 59, 10, 10, 9,115,112, +101, 99,102, 97, 99, 32, 61, 32,112,111,119, 40,114,115,108,116, 44, 32,104, 97,114,100, 41, 59, 10,125, 10, 10,118,111,105,100, + 32,115,104, 97,100,101, 95, 99,111,111,107,116,111,114,114, 95,115,112,101, 99, 40,118,101, 99, 51, 32,110, 44, 32,118,101, 99, + 51, 32,108, 44, 32,118,101, 99, 51, 32,118, 44, 32,102,108,111, 97,116, 32,104, 97,114,100, 44, 32,111,117,116, 32,102,108,111, + 97,116, 32,115,112,101, 99,102, 97, 99, 41, 10,123, 10, 9,118,101, 99, 51, 32,104, 32, 61, 32,110,111,114,109, 97,108,105,122, +101, 40,118, 32, 43, 32,108, 41, 59, 10, 9,102,108,111, 97,116, 32,110,104, 32, 61, 32,100,111,116, 40,110, 44, 32,104, 41, 59, + 10, 10, 9,105,102, 40,110,104, 32, 60, 32, 48, 46, 48, 41, 32,123, 10, 9, 9,115,112,101, 99,102, 97, 99, 32, 61, 32, 48, 46, + 48, 59, 10, 9,125, 10, 9,101,108,115,101, 32,123, 10, 9, 9,102,108,111, 97,116, 32,110,118, 32, 61, 32,109, 97,120, 40,100, +111,116, 40,110, 44, 32,118, 41, 44, 32, 48, 46, 48, 41, 59, 10, 9, 9,102,108,111, 97,116, 32,105, 32, 61, 32,112,111,119, 40, +110,104, 44, 32,104, 97,114,100, 41, 59, 10, 10, 9, 9,105, 32, 61, 32,105, 47, 40, 48, 46, 49, 43,110,118, 41, 59, 10, 9, 9, +115,112,101, 99,102, 97, 99, 32, 61, 32,105, 59, 10, 9,125, 10,125, 10, 10,118,111,105,100, 32,115,104, 97,100,101, 95, 98,108, +105,110,110, 95,115,112,101, 99, 40,118,101, 99, 51, 32,110, 44, 32,118,101, 99, 51, 32,108, 44, 32,118,101, 99, 51, 32,118, 44, + 32,102,108,111, 97,116, 32,114,101,102,114, 97, 99, 44, 32,102,108,111, 97,116, 32,115,112,101, 99, 95,112,111,119,101,114, 44, + 32,111,117,116, 32,102,108,111, 97,116, 32,115,112,101, 99,102, 97, 99, 41, 10,123, 10, 9,105,102, 40,114,101,102,114, 97, 99, + 32, 60, 32, 49, 46, 48, 41, 32,123, 10, 9, 9,115,112,101, 99,102, 97, 99, 32, 61, 32, 48, 46, 48, 59, 10, 9,125, 10, 9,101, +108,115,101, 32,105,102, 40,115,112,101, 99, 95,112,111,119,101,114, 32, 61, 61, 32, 48, 46, 48, 41, 32,123, 10, 9, 9,115,112, +101, 99,102, 97, 99, 32, 61, 32, 48, 46, 48, 59, 10, 9,125, 10, 9,101,108,115,101, 32,123, 10, 9, 9,105,102, 40,115,112,101, + 99, 95,112,111,119,101,114, 60, 49, 48, 48, 46, 48, 41, 10, 9, 9, 9,115,112,101, 99, 95,112,111,119,101,114, 61, 32,115,113, +114,116, 40, 49, 46, 48, 47,115,112,101, 99, 95,112,111,119,101,114, 41, 59, 10, 9, 9,101,108,115,101, 10, 9, 9, 9,115,112, +101, 99, 95,112,111,119,101,114, 61, 32, 49, 48, 46, 48, 47,115,112,101, 99, 95,112,111,119,101,114, 59, 10, 10, 9, 9,118,101, + 99, 51, 32,104, 32, 61, 32,110,111,114,109, 97,108,105,122,101, 40,118, 32, 43, 32,108, 41, 59, 10, 9, 9,102,108,111, 97,116, + 32,110,104, 32, 61, 32,100,111,116, 40,110, 44, 32,104, 41, 59, 10, 9, 9,105,102, 40,110,104, 32, 60, 32, 48, 46, 48, 41, 32, +123, 10, 9, 9, 9,115,112,101, 99,102, 97, 99, 32, 61, 32, 48, 46, 48, 59, 10, 9, 9,125, 10, 9, 9,101,108,115,101, 32,123, + 10, 9, 9, 9,102,108,111, 97,116, 32,110,118, 32, 61, 32,109, 97,120, 40,100,111,116, 40,110, 44, 32,118, 41, 44, 32, 48, 46, + 48, 49, 41, 59, 10, 9, 9, 9,102,108,111, 97,116, 32,110,108, 32, 61, 32,100,111,116, 40,110, 44, 32,108, 41, 59, 10, 9, 9, + 9,105,102, 40,110,108, 32, 60, 61, 32, 48, 46, 48, 49, 41, 32,123, 10, 9, 9, 9, 9,115,112,101, 99,102, 97, 99, 32, 61, 32, + 48, 46, 48, 59, 10, 9, 9, 9,125, 10, 9, 9, 9,101,108,115,101, 32,123, 10, 9, 9, 9, 9,102,108,111, 97,116, 32,118,104, + 32, 61, 32,109, 97,120, 40,100,111,116, 40,118, 44, 32,104, 41, 44, 32, 48, 46, 48, 49, 41, 59, 10, 10, 9, 9, 9, 9,102,108, +111, 97,116, 32, 97, 32, 61, 32, 49, 46, 48, 59, 10, 9, 9, 9, 9,102,108,111, 97,116, 32, 98, 32, 61, 32, 40, 50, 46, 48, 42, +110,104, 42,110,118, 41, 47,118,104, 59, 10, 9, 9, 9, 9,102,108,111, 97,116, 32, 99, 32, 61, 32, 40, 50, 46, 48, 42,110,104, + 42,110,108, 41, 47,118,104, 59, 10, 10, 9, 9, 9, 9,102,108,111, 97,116, 32,103, 59, 10, 10, 9, 9, 9, 9,105,102, 40, 97, + 32, 60, 32, 98, 32, 38, 38, 32, 97, 32, 60, 32, 99, 41, 32,103, 32, 61, 32, 97, 59, 10, 9, 9, 9, 9,101,108,115,101, 32,105, +102, 40, 98, 32, 60, 32, 97, 32, 38, 38, 32, 98, 32, 60, 32, 99, 41, 32,103, 32, 61, 32, 98, 59, 10, 9, 9, 9, 9,101,108,115, +101, 32,105,102, 40, 99, 32, 60, 32, 97, 32, 38, 38, 32, 99, 32, 60, 32, 98, 41, 32,103, 32, 61, 32, 99, 59, 10, 10, 9, 9, 9, + 9,102,108,111, 97,116, 32,112, 32, 61, 32,115,113,114,116, 40, 40, 40,114,101,102,114, 97, 99, 32, 42, 32,114,101,102,114, 97, + 99, 41, 43, 40,118,104, 42,118,104, 41, 45, 49, 46, 48, 41, 41, 59, 10, 9, 9, 9, 9,102,108,111, 97,116, 32,102, 32, 61, 32, + 40, 40, 40,112, 45,118,104, 41, 42, 40,112, 45,118,104, 41, 41, 47, 40, 40,112, 43,118,104, 41, 42, 40,112, 43,118,104, 41, 41, + 41, 42, 40, 49, 46, 48, 43, 40, 40, 40, 40,118,104, 42, 40,112, 43,118,104, 41, 41, 45, 49, 46, 48, 41, 42, 40, 40,118,104, 42, + 40,112, 43,118,104, 41, 41, 45, 49, 46, 48, 41, 41, 47, 40, 40, 40,118,104, 42, 40,112, 45,118,104, 41, 41, 43, 49, 46, 48, 41, + 42, 40, 40,118,104, 42, 40,112, 45,118,104, 41, 41, 43, 49, 46, 48, 41, 41, 41, 41, 59, 10, 9, 9, 9, 9,102,108,111, 97,116, + 32, 97,110,103, 32, 61, 32, 97, 99,111,115, 40,110,104, 41, 59, 10, 10, 9, 9, 9, 9,115,112,101, 99,102, 97, 99, 32, 61, 32, +109, 97,120, 40,102, 42,103, 42,101,120,112, 95, 98,108,101,110,100,101,114, 40, 40, 45, 40, 97,110,103, 42, 97,110,103, 41, 47, + 40, 50, 46, 48, 42,115,112,101, 99, 95,112,111,119,101,114, 42,115,112,101, 99, 95,112,111,119,101,114, 41, 41, 41, 44, 32, 48, + 46, 48, 41, 59, 10, 9, 9, 9,125, 10, 9, 9,125, 10, 9,125, 10,125, 10, 10,118,111,105,100, 32,115,104, 97,100,101, 95,119, + 97,114,100,105,115,111, 95,115,112,101, 99, 40,118,101, 99, 51, 32,110, 44, 32,118,101, 99, 51, 32,108, 44, 32,118,101, 99, 51, + 32,118, 44, 32,102,108,111, 97,116, 32,114,109,115, 44, 32,111,117,116, 32,102,108,111, 97,116, 32,115,112,101, 99,102, 97, 99, + 41, 10,123, 10, 9,118,101, 99, 51, 32,104, 32, 61, 32,110,111,114,109, 97,108,105,122,101, 40,108, 32, 43, 32,118, 41, 59, 10, + 9,102,108,111, 97,116, 32,110,104, 32, 61, 32,109, 97,120, 40,100,111,116, 40,110, 44, 32,104, 41, 44, 32, 48, 46, 48, 48, 49, + 41, 59, 10, 9,102,108,111, 97,116, 32,110,118, 32, 61, 32,109, 97,120, 40,100,111,116, 40,110, 44, 32,118, 41, 44, 32, 48, 46, + 48, 48, 49, 41, 59, 10, 9,102,108,111, 97,116, 32,110,108, 32, 61, 32,109, 97,120, 40,100,111,116, 40,110, 44, 32,108, 41, 44, + 32, 48, 46, 48, 48, 49, 41, 59, 10, 9,102,108,111, 97,116, 32, 97,110,103,108,101, 32, 61, 32,116, 97,110, 40, 97, 99,111,115, + 40,110,104, 41, 41, 59, 10, 9,102,108,111, 97,116, 32, 97,108,112,104, 97, 32, 61, 32,109, 97,120, 40,114,109,115, 44, 32, 48, + 46, 48, 48, 49, 41, 59, 10, 10, 9,115,112,101, 99,102, 97, 99, 61, 32,110,108, 32, 42, 32, 40, 49, 46, 48, 47, 40, 52, 46, 48, + 42, 77, 95, 80, 73, 42, 97,108,112,104, 97, 42, 97,108,112,104, 97, 41, 41, 42, 40,101,120,112, 95, 98,108,101,110,100,101,114, + 40, 45, 40, 97,110,103,108,101, 42, 97,110,103,108,101, 41, 47, 40, 97,108,112,104, 97, 42, 97,108,112,104, 97, 41, 41, 47, 40, +115,113,114,116, 40,110,118, 42,110,108, 41, 41, 41, 59, 10,125, 10, 10,118,111,105,100, 32,115,104, 97,100,101, 95,116,111,111, +110, 95,115,112,101, 99, 40,118,101, 99, 51, 32,110, 44, 32,118,101, 99, 51, 32,108, 44, 32,118,101, 99, 51, 32,118, 44, 32,102, +108,111, 97,116, 32,115,105,122,101, 44, 32,102,108,111, 97,116, 32,116,115,109,111,111,116,104, 44, 32,111,117,116, 32,102,108, +111, 97,116, 32,115,112,101, 99,102, 97, 99, 41, 10,123, 10, 9,118,101, 99, 51, 32,104, 32, 61, 32,110,111,114,109, 97,108,105, +122,101, 40,108, 32, 43, 32,118, 41, 59, 10, 9,102,108,111, 97,116, 32,114,115,108,116, 32, 61, 32,100,111,116, 40,104, 44, 32, +110, 41, 59, 10, 9,102,108,111, 97,116, 32, 97,110,103, 32, 61, 32, 97, 99,111,115, 40,114,115,108,116, 41, 59, 10, 10, 9,105, +102, 40, 97,110,103, 32, 60, 32,115,105,122,101, 41, 32,114,115,108,116, 32, 61, 32, 49, 46, 48, 59, 10, 9,101,108,115,101, 32, +105,102, 40, 97,110,103, 32, 62, 61, 32, 40,115,105,122,101, 32, 43, 32,116,115,109,111,111,116,104, 41, 32,124,124, 32,116,115, +109,111,111,116,104, 32, 61, 61, 32, 48, 46, 48, 41, 32,114,115,108,116, 32, 61, 32, 48, 46, 48, 59, 10, 9,101,108,115,101, 32, +114,115,108,116, 32, 61, 32, 49, 46, 48, 32, 45, 32, 40, 40, 97,110,103, 32, 45, 32,115,105,122,101, 41, 47,116,115,109,111,111, +116,104, 41, 59, 10, 10, 9,115,112,101, 99,102, 97, 99, 32, 61, 32,114,115,108,116, 59, 10,125, 10, 10,118,111,105,100, 32,115, +104, 97,100,101, 95,115,112,101, 99, 95, 97,114,101, 97, 95,105,110,112, 40,102,108,111, 97,116, 32,115,112,101, 99,102, 97, 99, + 44, 32,102,108,111, 97,116, 32,105,110,112, 44, 32,111,117,116, 32,102,108,111, 97,116, 32,111,117,116,115,112,101, 99,102, 97, + 99, 41, 10,123, 10, 9,111,117,116,115,112,101, 99,102, 97, 99, 32, 61, 32,115,112,101, 99,102, 97, 99, 42,105,110,112, 59, 10, +125, 10, 10,118,111,105,100, 32,115,104, 97,100,101, 95,115,112,101, 99, 95,116, 40,102,108,111, 97,116, 32,115,104, 97,100,102, + 97, 99, 44, 32,102,108,111, 97,116, 32,115,112,101, 99, 44, 32,102,108,111, 97,116, 32,118,105,115,105,102, 97, 99, 44, 32,102, +108,111, 97,116, 32,115,112,101, 99,102, 97, 99, 44, 32,111,117,116, 32,102,108,111, 97,116, 32,116, 41, 10,123, 10, 9,116, 32, + 61, 32,115,104, 97,100,102, 97, 99, 42,115,112,101, 99, 42,118,105,115,105,102, 97, 99, 42,115,112,101, 99,102, 97, 99, 59, 10, +125, 10, 10,118,111,105,100, 32,115,104, 97,100,101, 95, 97,100,100, 95,115,112,101, 99, 40,102,108,111, 97,116, 32,116, 44, 32, +118,101, 99, 51, 32,108, 97,109,112, 99,111,108, 44, 32,118,101, 99, 51, 32,115,112,101, 99, 99,111,108, 44, 32,111,117,116, 32, +118,101, 99, 51, 32,111,117,116, 99,111,108, 41, 10,123, 10, 9,111,117,116, 99,111,108, 32, 61, 32,116, 42,108, 97,109,112, 99, +111,108, 42,115,112,101, 99, 99,111,108, 59, 10,125, 10, 10,118,111,105,100, 32,115,104, 97,100,101, 95, 97,100,100, 40,118,101, + 99, 52, 32, 99,111,108, 49, 44, 32,118,101, 99, 52, 32, 99,111,108, 50, 44, 32,111,117,116, 32,118,101, 99, 52, 32,111,117,116, + 99,111,108, 41, 10,123, 10, 9,111,117,116, 99,111,108, 32, 61, 32, 99,111,108, 49, 32, 43, 32, 99,111,108, 50, 59, 10,125, 10, + 10,118,111,105,100, 32,115,104, 97,100,101, 95,109, 97,100,100, 40,118,101, 99, 52, 32, 99,111,108, 44, 32,118,101, 99, 52, 32, + 99,111,108, 49, 44, 32,118,101, 99, 52, 32, 99,111,108, 50, 44, 32,111,117,116, 32,118,101, 99, 52, 32,111,117,116, 99,111,108, + 41, 10,123, 10, 9,111,117,116, 99,111,108, 32, 61, 32, 99,111,108, 32, 43, 32, 99,111,108, 49, 42, 99,111,108, 50, 59, 10,125, + 10, 10,118,111,105,100, 32,115,104, 97,100,101, 95,109, 97,100,100,102, 40,118,101, 99, 52, 32, 99,111,108, 44, 32,102,108,111, + 97,116, 32,102, 44, 32,118,101, 99, 52, 32, 99,111,108, 49, 44, 32,111,117,116, 32,118,101, 99, 52, 32,111,117,116, 99,111,108, + 41, 10,123, 10, 9,111,117,116, 99,111,108, 32, 61, 32, 99,111,108, 32, 43, 32,102, 42, 99,111,108, 49, 59, 10,125, 10, 10,118, +111,105,100, 32,115,104, 97,100,101, 95,109,117,108, 40,118,101, 99, 52, 32, 99,111,108, 49, 44, 32,118,101, 99, 52, 32, 99,111, +108, 50, 44, 32,111,117,116, 32,118,101, 99, 52, 32,111,117,116, 99,111,108, 41, 10,123, 10, 9,111,117,116, 99,111,108, 32, 61, + 32, 99,111,108, 49, 42, 99,111,108, 50, 59, 10,125, 10, 10,118,111,105,100, 32,115,104, 97,100,101, 95,109,117,108, 95,118, 97, +108,117,101, 40,102,108,111, 97,116, 32,102, 97, 99, 44, 32,118,101, 99, 52, 32, 99,111,108, 44, 32,111,117,116, 32,118,101, 99, + 52, 32,111,117,116, 99,111,108, 41, 10,123, 10, 9,111,117,116, 99,111,108, 32, 61, 32, 99,111,108, 42,102, 97, 99, 59, 10,125, + 10, 10,118,111,105,100, 32,115,104, 97,100,101, 95,111, 98, 99,111,108,111,114, 40,118,101, 99, 52, 32, 99,111,108, 44, 32,118, +101, 99, 52, 32,111, 98, 99,111,108, 44, 32,111,117,116, 32,118,101, 99, 52, 32,111,117,116, 99,111,108, 41, 10,123, 10, 9,111, +117,116, 99,111,108, 32, 61, 32,118,101, 99, 52, 40, 99,111,108, 46,114,103, 98, 42,111, 98, 99,111,108, 46,114,103, 98, 44, 32, + 99,111,108, 46, 97, 41, 59, 10,125, 10, 10,118,111,105,100, 32,114, 97,109,112, 95,114,103, 98,116,111, 98,119, 40,118,101, 99, + 51, 32, 99,111,108,111,114, 44, 32,111,117,116, 32,102,108,111, 97,116, 32,111,117,116,118, 97,108, 41, 10,123, 10, 9,111,117, +116,118, 97,108, 32, 61, 32, 99,111,108,111,114, 46,114, 42, 48, 46, 51, 32, 43, 32, 99,111,108,111,114, 46,103, 42, 48, 46, 53, + 56, 32, 43, 32, 99,111,108,111,114, 46, 98, 42, 48, 46, 49, 50, 59, 10,125, 10, 10,118,111,105,100, 32,115,104, 97,100,101, 95, +111,110,108,121, 95,115,104, 97,100,111,119, 40,102,108,111, 97,116, 32,105, 44, 32,102,108,111, 97,116, 32,115,104, 97,100,102, + 97, 99, 44, 32,102,108,111, 97,116, 32,101,110,101,114,103,121, 44, 32,118,101, 99, 51, 32,114,103, 98, 44, 32,118,101, 99, 51, + 32,115,112,101, 99,114,103, 98, 44, 32,118,101, 99, 52, 32,100,105,102,102, 44, 32,118,101, 99, 52, 32,115,112,101, 99, 44, 32, +111,117,116, 32,118,101, 99, 52, 32,111,117,116,100,105,102,102, 44, 32,111,117,116, 32,118,101, 99, 52, 32,111,117,116,115,112, +101, 99, 41, 10,123, 10, 9,115,104, 97,100,102, 97, 99, 32, 61, 32,105, 42,101,110,101,114,103,121, 42, 40, 49, 46, 48, 32, 45, + 32,115,104, 97,100,102, 97, 99, 41, 59, 10, 10, 9,111,117,116,100,105,102,102, 32, 61, 32,100,105,102,102, 32, 45, 32,118,101, + 99, 52, 40,114,103, 98, 42,115,104, 97,100,102, 97, 99, 44, 32, 48, 46, 48, 41, 59, 10, 9,111,117,116,115,112,101, 99, 32, 61, + 32,115,112,101, 99, 32, 45, 32,118,101, 99, 52, 40,115,112,101, 99,114,103, 98, 42,115,104, 97,100,102, 97, 99, 44, 32, 48, 46, + 48, 41, 59, 10,125, 10, 10,118,111,105,100, 32,116,101,115,116, 95,115,104, 97,100,111,119, 98,117,102, 40,118,101, 99, 51, 32, +114, 99,111, 44, 32,115, 97,109,112,108,101,114, 50, 68, 83,104, 97,100,111,119, 32,115,104, 97,100,111,119,109, 97,112, 44, 32, +109, 97,116, 52, 32,115,104, 97,100,111,119,112,101,114,115,109, 97,116, 44, 32,102,108,111, 97,116, 32,115,104, 97,100,111,119, + 98,105, 97,115, 44, 32,102,108,111, 97,116, 32,105,110,112, 44, 32,111,117,116, 32,102,108,111, 97,116, 32,114,101,115,117,108, +116, 41, 10,123, 10, 9,105,102, 40,105,110,112, 32, 60, 61, 32, 48, 46, 48, 41, 32,123, 10, 9, 9,114,101,115,117,108,116, 32, + 61, 32, 48, 46, 48, 59, 10, 9,125, 10, 9,101,108,115,101, 32,123, 10, 9, 9,118,101, 99, 52, 32, 99,111, 32, 61, 32,115,104, + 97,100,111,119,112,101,114,115,109, 97,116, 42,118,101, 99, 52, 40,114, 99,111, 44, 32, 49, 46, 48, 41, 59, 10, 10, 9, 9, 47, + 47,102,108,111, 97,116, 32, 98,105, 97,115, 32, 61, 32, 40, 49, 46, 53, 32, 45, 32,105,110,112, 42,105,110,112, 41, 42,115,104, + 97,100,111,119, 98,105, 97,115, 59, 10, 9, 9, 99,111, 46,122, 32, 45, 61, 32,115,104, 97,100,111,119, 98,105, 97,115, 42, 99, +111, 46,119, 59, 10, 10, 9, 9,114,101,115,117,108,116, 32, 61, 32,115,104, 97,100,111,119, 50, 68, 80,114,111,106, 40,115,104, + 97,100,111,119,109, 97,112, 44, 32, 99,111, 41, 46,120, 59, 10, 9,125, 10,125, 10, 10,118,111,105,100, 32,115,104, 97,100,101, + 95,101,120,112,111,115,117,114,101, 95, 99,111,114,114,101, 99,116, 40,118,101, 99, 51, 32, 99,111,108, 44, 32,102,108,111, 97, +116, 32,108,105,110,102, 97, 99, 44, 32,102,108,111, 97,116, 32,108,111,103,102, 97, 99, 44, 32,111,117,116, 32,118,101, 99, 51, + 32,111,117,116, 99,111,108, 41, 10,123, 10, 9,111,117,116, 99,111,108, 32, 61, 32,108,105,110,102, 97, 99, 42, 40, 49, 46, 48, + 32, 45, 32,101,120,112, 40, 99,111,108, 42,108,111,103,102, 97, 99, 41, 41, 59, 10,125, 10, 10,118,111,105,100, 32,115,104, 97, +100,101, 95,109,105,115,116, 95,102, 97, 99,116,111,114, 40,118,101, 99, 51, 32, 99,111, 44, 32,102,108,111, 97,116, 32,109,105, +115,116,115,116, 97, 44, 32,102,108,111, 97,116, 32,109,105,115,116,100,105,115,116, 44, 32,102,108,111, 97,116, 32,109,105,115, +116,116,121,112,101, 44, 32,102,108,111, 97,116, 32,109,105,115,105, 44, 32,111,117,116, 32,102,108,111, 97,116, 32,111,117,116, +102, 97, 99, 41, 10,123, 10, 9,102,108,111, 97,116, 32,102, 97, 99, 44, 32,122, 99,111,114, 59, 10, 10, 9,122, 99,111,114, 32, + 61, 32, 40,103,108, 95, 80,114,111,106,101, 99,116,105,111,110, 77, 97,116,114,105,120, 91, 51, 93, 91, 51, 93, 32, 61, 61, 32, + 48, 46, 48, 41, 63, 32,108,101,110,103,116,104, 40, 99,111, 41, 58, 32, 45, 99,111, 91, 50, 93, 59, 10, 9, 10, 9,102, 97, 99, + 32, 61, 32, 99,108, 97,109,112, 40, 40,122, 99,111,114, 45,109,105,115,116,115,116, 97, 41, 47,109,105,115,116,100,105,115,116, + 44, 32, 48, 46, 48, 44, 32, 49, 46, 48, 41, 59, 10, 9,105,102, 40,109,105,115,116,116,121,112,101, 32, 61, 61, 32, 48, 46, 48, + 41, 32,102, 97, 99, 32, 42, 61, 32,102, 97, 99, 59, 10, 9,101,108,115,101, 32,105,102, 40,109,105,115,116,116,121,112,101, 32, + 61, 61, 32, 49, 46, 48, 41, 59, 10, 9,101,108,115,101, 32,102, 97, 99, 32, 61, 32,115,113,114,116, 40,102, 97, 99, 41, 59, 10, + 10, 9,111,117,116,102, 97, 99, 32, 61, 32, 49, 46, 48, 32, 45, 32, 40, 49, 46, 48, 45,102, 97, 99, 41, 42, 40, 49, 46, 48, 45, +109,105,115,105, 41, 59, 10,125, 10, 10,118,111,105,100, 32,115,104, 97,100,101, 95,119,111,114,108,100, 95,109,105,120, 40,118, +101, 99, 51, 32,104,111,114, 44, 32,118,101, 99, 52, 32, 99,111,108, 44, 32,111,117,116, 32,118,101, 99, 52, 32,111,117,116, 99, +111,108, 41, 10,123, 10, 9,102,108,111, 97,116, 32,102, 97, 99, 32, 61, 32, 99,108, 97,109,112, 40, 99,111,108, 46, 97, 44, 32, + 48, 46, 48, 44, 32, 49, 46, 48, 41, 59, 10, 9,111,117,116, 99,111,108, 32, 61, 32,118,101, 99, 52, 40,109,105,120, 40,104,111, +114, 44, 32, 99,111,108, 46,114,103, 98, 44, 32,102, 97, 99, 41, 44, 32, 99,111,108, 46, 97, 41, 59, 10,125, 10, 10,118,111,105, +100, 32,115,104, 97,100,101, 95, 97,108,112,104, 97, 95,111,112, 97,113,117,101, 40,118,101, 99, 52, 32, 99,111,108, 44, 32,111, +117,116, 32,118,101, 99, 52, 32,111,117,116, 99,111,108, 41, 10,123, 10, 9,111,117,116, 99,111,108, 32, 61, 32,118,101, 99, 52, + 40, 99,111,108, 46,114,103, 98, 44, 32, 49, 46, 48, 41, 59, 10,125, 10, 10,118,111,105,100, 32,115,104, 97,100,101, 95, 97,108, +112,104, 97, 95,111, 98, 99,111,108,111,114, 40,118,101, 99, 52, 32, 99,111,108, 44, 32,118,101, 99, 52, 32,111, 98, 99,111,108, + 44, 32,111,117,116, 32,118,101, 99, 52, 32,111,117,116, 99,111,108, 41, 10,123, 10, 9,111,117,116, 99,111,108, 32, 61, 32,118, +101, 99, 52, 40, 99,111,108, 46,114,103, 98, 44, 32, 99,111,108, 46, 97, 42,111, 98, 99,111,108, 46, 97, 41, 59, 10,125, 10, 10, + 0}; + diff --git a/source/blender/gpu/intern/gpu_shader_vertex.glsl b/source/blender/gpu/intern/gpu_shader_vertex.glsl new file mode 100644 index 00000000000..ba9ef7dead6 --- /dev/null +++ b/source/blender/gpu/intern/gpu_shader_vertex.glsl @@ -0,0 +1,12 @@ + +varying vec3 varposition; +varying vec3 varnormal; + +void main() +{ + vec4 co = gl_ModelViewMatrix * gl_Vertex; + + varposition = co.xyz; + varnormal = gl_NormalMatrix * gl_Normal; + gl_Position = gl_ProjectionMatrix * co; + diff --git a/source/blender/gpu/intern/gpu_shader_vertex.glsl.c b/source/blender/gpu/intern/gpu_shader_vertex.glsl.c new file mode 100644 index 00000000000..a89de776864 --- /dev/null +++ b/source/blender/gpu/intern/gpu_shader_vertex.glsl.c @@ -0,0 +1,13 @@ +/* DataToC output of file */ + +int datatoc_gpu_shader_vertex_glsl_size= 217; +char datatoc_gpu_shader_vertex_glsl[]= { + 10,118, 97,114,121,105,110,103, 32,118,101, 99, 51, 32,118, 97,114,112,111,115,105,116,105,111,110, + 59, 10,118, 97,114,121,105,110,103, 32,118,101, 99, 51, 32,118, 97,114,110,111,114,109, 97,108, 59, 10, 10,118,111,105,100, 32, +109, 97,105,110, 40, 41, 10,123, 10, 9,118,101, 99, 52, 32, 99,111, 32, 61, 32,103,108, 95, 77,111,100,101,108, 86,105,101,119, + 77, 97,116,114,105,120, 32, 42, 32,103,108, 95, 86,101,114,116,101,120, 59, 10, 10, 9,118, 97,114,112,111,115,105,116,105,111, +110, 32, 61, 32, 99,111, 46,120,121,122, 59, 10, 9,118, 97,114,110,111,114,109, 97,108, 32, 61, 32,103,108, 95, 78,111,114,109, + 97,108, 77, 97,116,114,105,120, 32, 42, 32,103,108, 95, 78,111,114,109, 97,108, 59, 10, 9,103,108, 95, 80,111,115,105,116,105, +111,110, 32, 61, 32,103,108, 95, 80,114,111,106,101, 99,116,105,111,110, 77, 97,116,114,105,120, 32, 42, 32, 99,111, 59, 10, 10, +}; + diff --git a/source/blender/include/BDR_drawmesh.h b/source/blender/include/BDR_drawmesh.h index 93e08ab452d..34351549345 100644 --- a/source/blender/include/BDR_drawmesh.h +++ b/source/blender/include/BDR_drawmesh.h @@ -30,52 +30,11 @@ #ifndef BDR_DRAWMESH_H #define BDR_DRAWMESH_H -struct Image; -struct MTFace; struct Object; struct DerivedMesh; -struct Mesh; -struct EdgeHash; - -/** - * Enables or disable mipmapping for realtime images (textures). - * Note that this will will destroy all texture bindings in OpenGL. - * @see free_realtime_image() - * @param mipmap Turn mipmapping on (mipmap!=0) or off (mipmap==0). - */ -void set_mipmap(int mipmap); - -/** - * Enables or disable linear mipmap setting for realtime images (textures). - * Note that this will will destroy all texture bindings in OpenGL. - * @see free_realtime_image() - * @param mipmap Turn linear mipmapping on (linear!=0) or off (linear==0). - */ -void set_linear_mipmap(int linear); - -/** - * Returns the current setting for linear mipmapping. - */ -int get_linear_mipmap(void); - -/** - * Resets the realtime image cache variables. - */ -void clear_realtime_image_cache(void); - - -void update_realtime_image(struct Image *ima, int x, int y, int w, int h); -void free_realtime_image(struct Image *ima); -void free_all_realtime_images(void); -void make_repbind(struct Image *ima); -int set_tpage(struct MTFace *tface); - -void texpaint_enable_mipmap(void); -void texpaint_disable_mipmap(void); void draw_mesh_textured(struct Object *ob, struct DerivedMesh *dm, int facesel); -struct EdgeHash *get_tface_mesh_marked_edge_info(struct Mesh *me); -void init_realtime_GL(void); +void draw_mesh_text(struct Object *ob, int glsl); #endif /* BDR_DRAWMESH_H */ diff --git a/source/blender/include/BDR_drawobject.h b/source/blender/include/BDR_drawobject.h index de28db64c3b..635b73af80c 100644 --- a/source/blender/include/BDR_drawobject.h +++ b/source/blender/include/BDR_drawobject.h @@ -47,8 +47,7 @@ struct EditVert; struct EditFace; struct EditEdge; -int set_gl_material(int nr); -int init_gl_materials(struct Object *ob, int check_alpha); +int draw_glsl_material(struct Object *ob, int dt); void mesh_foreachScreenVert(void (*func)(void *userData, struct EditVert *eve, int x, int y, int index), void *userData, int clipVerts); void mesh_foreachScreenEdge(void (*func)(void *userData, struct EditEdge *eed, int x0, int y0, int x1, int y1, int index), void *userData, int clipVerts); diff --git a/source/blender/include/BDR_imagepaint.h b/source/blender/include/BDR_imagepaint.h index 26f2375e60a..bd1ac301416 100644 --- a/source/blender/include/BDR_imagepaint.h +++ b/source/blender/include/BDR_imagepaint.h @@ -34,8 +34,8 @@ void imagepaint_redraw_tool(void); void imagepaint_pick(short mousebutton); void imagepaint_paint(short mousebutton, short texturepaint); -void imagepaint_undo(); -void free_imagepaint(); +void undo_imagepaint_step(int step); +void undo_imagepaint_clear(void); #endif /* BDR_IMAGEPAINT_H */ diff --git a/source/blender/include/BIF_gl.h b/source/blender/include/BIF_gl.h index 2468abdff60..c1b3b056d62 100644 --- a/source/blender/include/BIF_gl.h +++ b/source/blender/include/BIF_gl.h @@ -49,20 +49,7 @@ #endif #endif -#ifdef __APPLE__ - #include - #include -#else -/* #if defined (__sun) || defined (__sun__) - #include - #include - #else -*/ - #include - #include -/* #endif */ -#endif - +#include "GL/glew.h" /* * these should be phased out. cpack should be replaced in diff --git a/source/blender/include/BIF_meshtools.h b/source/blender/include/BIF_meshtools.h index d809d1f21f9..a894d66cb10 100644 --- a/source/blender/include/BIF_meshtools.h +++ b/source/blender/include/BIF_meshtools.h @@ -30,6 +30,8 @@ #ifndef BIF_MESHTOOLS_H #define BIF_MESHTOOLS_H +#include "BLO_sys_types.h" + struct Object; struct EditVert; diff --git a/source/blender/include/BSE_drawview.h b/source/blender/include/BSE_drawview.h index e6f22a4fb67..1b2834b2e3b 100644 --- a/source/blender/include/BSE_drawview.h +++ b/source/blender/include/BSE_drawview.h @@ -36,8 +36,6 @@ struct rctf; struct ScrArea; struct ImBuf; -void default_gl_light(void); -void init_gl_stuff(void); void circf(float x, float y, float rad); void circ(float x, float y, float rad); @@ -55,8 +53,8 @@ struct ImBuf *read_backbuf(short xmin, short ymin, short xmax, short ymax); unsigned int sample_backbuf_rect(short mval[2], int size, unsigned int min, unsigned int max, int *dist, short strict, unsigned int (*indextest)(unsigned int index)); void drawview3dspace(struct ScrArea *sa, void *spacedata); -void drawview3d_render(struct View3D *v3d, int winx, int winy, float winmat[][4]); -void draw_depth(struct ScrArea *sa, void *spacedata); +void drawview3d_render(struct View3D *v3d, float viewmat[][4], int winx, int winy, float winmat[][4], int shadow); +void draw_depth(struct ScrArea *sa, void *spacedata, int (*func)(void *) ); void view3d_update_depths(struct View3D *v3d); int update_time(int cfra); diff --git a/source/blender/makesdna/DNA_brush_types.h b/source/blender/makesdna/DNA_brush_types.h index 1c272105067..c7196763358 100644 --- a/source/blender/makesdna/DNA_brush_types.h +++ b/source/blender/makesdna/DNA_brush_types.h @@ -33,7 +33,7 @@ #include "DNA_ID.h" #ifndef MAX_MTEX -#define MAX_MTEX 10 +#define MAX_MTEX 18 #endif struct MTex; @@ -58,7 +58,7 @@ typedef struct Brush { float alpha; /* opacity */ short texact, pad; - struct MTex *mtex[10]; + struct MTex *mtex[18]; /* MAX_MTEX */ struct BrushClone clone; } Brush; diff --git a/source/blender/makesdna/DNA_group_types.h b/source/blender/makesdna/DNA_group_types.h index 1bb18ca2ca2..0987050261d 100644 --- a/source/blender/makesdna/DNA_group_types.h +++ b/source/blender/makesdna/DNA_group_types.h @@ -54,7 +54,7 @@ typedef struct Group { * the objects that show in the group can change depending * on the last used scene */ unsigned int layer; - int pad; + float dupli_ofs[3]; } Group; diff --git a/source/blender/makesdna/DNA_image_types.h b/source/blender/makesdna/DNA_image_types.h index 42b651a7555..e1d79f0f875 100644 --- a/source/blender/makesdna/DNA_image_types.h +++ b/source/blender/makesdna/DNA_image_types.h @@ -37,6 +37,7 @@ struct PackedFile; struct anim; struct ImBuf; struct RenderResult; +struct GPUTexture; /* ImageUser is in Texture, in Nodes, Background Image, Image Window, .... */ @@ -62,7 +63,8 @@ typedef struct Image { char name[240]; /* file path */ - ListBase ibufs; /* not written in file */ + ListBase ibufs; /* not written in file */ + struct GPUTexture *gputexture; /* not written in file */ /* sources from: */ struct anim *anim; diff --git a/source/blender/makesdna/DNA_ipo_types.h b/source/blender/makesdna/DNA_ipo_types.h index 1e30f3f7640..e7f46b81935 100644 --- a/source/blender/makesdna/DNA_ipo_types.h +++ b/source/blender/makesdna/DNA_ipo_types.h @@ -142,16 +142,24 @@ typedef short IPO_Channel; #define MA_FRESTRAI 25 #define MA_ADD 26 -#define MA_MAP1 0x20 -#define MA_MAP2 0x40 -#define MA_MAP3 0x80 -#define MA_MAP4 0x100 -#define MA_MAP5 0x200 -#define MA_MAP6 0x400 -#define MA_MAP7 0x800 -#define MA_MAP8 0x1000 -#define MA_MAP9 0x2000 -#define MA_MAP10 0x4000 +#define MA_MAP1 1<<5 +#define MA_MAP2 1<<6 +#define MA_MAP3 1<<7 +#define MA_MAP4 1<<8 +#define MA_MAP5 1<<9 +#define MA_MAP6 1<<10 +#define MA_MAP7 1<<11 +#define MA_MAP8 1<<12 +#define MA_MAP9 1<<13 +#define MA_MAP10 1<<14 +#define MA_MAP11 1<<15 +#define MA_MAP12 1<<16 +#define MA_MAP13 1<<17 +#define MA_MAP14 1<<18 +#define MA_MAP15 1<<19 +#define MA_MAP16 1<<20 +#define MA_MAP17 1<<21 +#define MA_MAP18 1<<22 #define TEX_TOTNAM 14 diff --git a/source/blender/makesdna/DNA_lamp_types.h b/source/blender/makesdna/DNA_lamp_types.h index c00dae08eb4..2a39580bb5c 100644 --- a/source/blender/makesdna/DNA_lamp_types.h +++ b/source/blender/makesdna/DNA_lamp_types.h @@ -35,7 +35,7 @@ #include "DNA_scriptlink_types.h" #ifndef MAX_MTEX -#define MAX_MTEX 10 +#define MAX_MTEX 18 #endif struct MTex; @@ -45,7 +45,8 @@ struct CurveMapping; typedef struct Lamp { ID id; - short type, mode; + short type, pad3; + int mode; short colormodel, totex; float r, g, b, k; @@ -55,10 +56,9 @@ typedef struct Lamp { float att1, att2; /* Quad1 and Quad2 attenuation */ - int pad2; struct CurveMapping *curfalloff; short falloff_type; - short pad3; + short pad2; float clipsta, clipend, shadspotsize; float bias, soft; @@ -99,7 +99,7 @@ typedef struct Lamp { float YF_glowint, YF_glowofs; short YF_glowtype, YF_pad2; - struct MTex *mtex[10]; + struct MTex *mtex[18]; /* MAX_MTEX */ struct Ipo *ipo; /* preview */ @@ -137,6 +137,12 @@ typedef struct Lamp { /* yafray: lamp shadowbuffer flag, softlight */ /* Since it is used with LOCAL lamp, can't use LA_SHAD */ #define LA_YF_SOFT 16384 +#define LA_LAYER_SHADOW 32768 + +/* layer_shadow */ +#define LA_LAYER_SHADOW_BOTH 0 +#define LA_LAYER_SHADOW_CAST 1 +#define LA_LAYER_SHADOW_RECEIVE 2 /* sun effect type*/ #define LA_SUN_EFFECT_SKY 1 diff --git a/source/blender/makesdna/DNA_material_types.h b/source/blender/makesdna/DNA_material_types.h index 9412a09d0f4..c92a33bbcbb 100644 --- a/source/blender/makesdna/DNA_material_types.h +++ b/source/blender/makesdna/DNA_material_types.h @@ -36,7 +36,7 @@ #include "DNA_listBase.h" #ifndef MAX_MTEX -#define MAX_MTEX 10 +#define MAX_MTEX 18 #endif struct MTex; @@ -88,11 +88,11 @@ typedef struct Material { float sbias; /* shadow bias to prevent terminator prob */ float lbias; /* factor to multiply lampbias with (0.0 = no mult) */ float shad_alpha; /* in use for irregular shadowbuffer */ - float padf; /* free padding, take me! */ + int septex; /* for buttons and render*/ char rgbsel, texact, pr_type, use_nodes; - short pr_back, pr_lamp, septex, ml_flag; /* ml_flag is for disable base material */ + short pr_back, pr_lamp, pad4, ml_flag; /* ml_flag is for disable base material */ /* shaders */ short diff_shader, spec_shader; @@ -110,7 +110,7 @@ typedef struct Material { short ramp_show, pad3; float rampfac_col, rampfac_spec; - struct MTex *mtex[10]; + struct MTex *mtex[18]; /* MAX_MTEX */ struct bNodeTree *nodetree; struct Ipo *ipo; struct Group *group; /* light group */ @@ -133,6 +133,8 @@ typedef struct Material { int YF_dsmp, YF_preset, YF_djit; ScriptLink scriptlink; + + ListBase gpumaterial; /* runtime */ } Material; /* **************** MATERIAL ********************* */ @@ -203,6 +205,7 @@ typedef struct Material { /* shade_flag */ #define MA_CUBIC 1 +#define MA_OBCOLOR 2 /* diff_shader */ #define MA_DIFF_LAMBERT 0 diff --git a/source/blender/makesdna/DNA_object_types.h b/source/blender/makesdna/DNA_object_types.h index 85c49a03569..d258cf77ef5 100644 --- a/source/blender/makesdna/DNA_object_types.h +++ b/source/blender/makesdna/DNA_object_types.h @@ -223,6 +223,8 @@ typedef struct Object { /*#ifdef WITH_VERSE*/ void *vnode; /* pointer at object VerseNode */ /*#endif*/ + + ListBase gpulamp; /* runtime, for lamps only */ } Object; /* Warning, this is not used anymore because hooks are now modifiers */ diff --git a/source/blender/makesdna/DNA_scene_types.h b/source/blender/makesdna/DNA_scene_types.h index 75affbfa7f5..72050b0809e 100644 --- a/source/blender/makesdna/DNA_scene_types.h +++ b/source/blender/makesdna/DNA_scene_types.h @@ -464,7 +464,7 @@ typedef struct SculptData struct SculptSession *session; /* Pointers to all of sculptmodes's textures */ - struct MTex *mtex[10]; + struct MTex *mtex[18]; /* Editable brush shape */ struct CurveMapping *cumap; diff --git a/source/blender/makesdna/DNA_userdef_types.h b/source/blender/makesdna/DNA_userdef_types.h index 856324695a9..11b35b4d6d4 100644 --- a/source/blender/makesdna/DNA_userdef_types.h +++ b/source/blender/makesdna/DNA_userdef_types.h @@ -188,6 +188,7 @@ typedef struct UserDef { char fontname[256]; // FILE_MAXDIR+FILE length struct ListBase themes; short undosteps; + short undomemory, pad[3]; short curssize; short tb_leftmouse, tb_rightmouse; struct SolidLight light[3]; diff --git a/source/blender/makesdna/DNA_world_types.h b/source/blender/makesdna/DNA_world_types.h index 26b3f051944..ab7e25190ad 100644 --- a/source/blender/makesdna/DNA_world_types.h +++ b/source/blender/makesdna/DNA_world_types.h @@ -38,7 +38,7 @@ struct Ipo; struct MTex; #ifndef MAX_MTEX -#define MAX_MTEX 10 +#define MAX_MTEX 18 #endif @@ -108,7 +108,7 @@ typedef struct World { struct Ipo *ipo; - struct MTex *mtex[10]; + struct MTex *mtex[18]; /* MAX_MTEX */ /* previews */ struct PreviewImage *preview; diff --git a/source/blender/nodes/CMakeLists.txt b/source/blender/nodes/CMakeLists.txt index 2cb855ed440..cf83804b999 100644 --- a/source/blender/nodes/CMakeLists.txt +++ b/source/blender/nodes/CMakeLists.txt @@ -30,7 +30,7 @@ SET(INC ../python ../render/extern/include ../../../intern/decimation/extern ../imbuf ../avi ../../../intern/elbeem/extern ../../../intern/iksolver/extern ../blenloader ../quicktime - ../blenkernel + ../blenkernel ../../../extern/glew/include ../gpu ${SDL_INC} ${ZLIB_INC} ${PYTHON_INC} diff --git a/source/blender/nodes/SConscript b/source/blender/nodes/SConscript index 8682f626b80..8af7b67520e 100644 --- a/source/blender/nodes/SConscript +++ b/source/blender/nodes/SConscript @@ -11,6 +11,7 @@ incs += ' ../python ../render/extern/include ' incs += ' ../imbuf ../avi ' incs += ' ../blenloader ../quicktime' incs += ' ../blenkernel ../renderconverter ' +incs += ' ../gpu #/extern/glew/include ' incs += ' ' + env['BF_PYTHON_INC'] diff --git a/source/blender/nodes/intern/CMP_nodes/Makefile b/source/blender/nodes/intern/CMP_nodes/Makefile index 61b03f237db..8a8d323ac5b 100644 --- a/source/blender/nodes/intern/CMP_nodes/Makefile +++ b/source/blender/nodes/intern/CMP_nodes/Makefile @@ -42,4 +42,5 @@ CPPFLAGS += -I../../../blenlib CPPFLAGS += -I../../../include CPPFLAGS += -I../../../imbuf CPPFLAGS += -I../../../render/extern/include +CPPFLAGS += -I$(NAN_GLEW)/include CPPFLAGS += -I$(OPENGL_HEADERS) diff --git a/source/blender/nodes/intern/Makefile b/source/blender/nodes/intern/Makefile index 7cf2411ed84..6167cf6bc72 100644 --- a/source/blender/nodes/intern/Makefile +++ b/source/blender/nodes/intern/Makefile @@ -42,4 +42,6 @@ CPPFLAGS += -I../../blenlib CPPFLAGS += -I../../include CPPFLAGS += -I../../imbuf CPPFLAGS += -I../../render/extern/include +CPPFLAGS += -I../../gpu +CPPFLAGS += -I$(NAN_GLEW)/include CPPFLAGS += -I$(OPENGL_HEADERS) diff --git a/source/blender/nodes/intern/SHD_nodes/Makefile b/source/blender/nodes/intern/SHD_nodes/Makefile index 1917e9ba15c..ae3cae029d2 100644 --- a/source/blender/nodes/intern/SHD_nodes/Makefile +++ b/source/blender/nodes/intern/SHD_nodes/Makefile @@ -44,4 +44,6 @@ CPPFLAGS += -I../../../blenlib CPPFLAGS += -I../../../include CPPFLAGS += -I../../../imbuf CPPFLAGS += -I../../../render/extern/include +CPPFLAGS += -I../../../gpu +CPPFLAGS += -I$(NAN_GLEW)/include CPPFLAGS += -I$(OPENGL_HEADERS) diff --git a/source/blender/nodes/intern/SHD_nodes/SHD_camera.c b/source/blender/nodes/intern/SHD_nodes/SHD_camera.c index 63260ff91ed..20136d75540 100644 --- a/source/blender/nodes/intern/SHD_nodes/SHD_camera.c +++ b/source/blender/nodes/intern/SHD_nodes/SHD_camera.c @@ -46,8 +46,13 @@ static void node_shader_exec_camera(void *data, bNode *node, bNodeStack **in, bN VECCOPY(out[0]->vec, shi->co); /* get view vector */ out[1]->vec[0]= fabs(shi->co[2]); /* get view z-depth */ out[2]->vec[0]= Normalize(out[0]->vec); /* get view distance */ - } } +} + +static int gpu_shader_camera(GPUMaterial *mat, bNode *node, GPUNodeStack *in, GPUNodeStack *out) +{ + return GPU_stack_link(mat, "camera", in, out, GPU_builtin(GPU_VIEW_POSITION)); +} bNodeType sh_node_camera= { /* *next,*prev */ NULL, NULL, @@ -63,6 +68,7 @@ bNodeType sh_node_camera= { /* initfunc */ NULL, /* freestoragefunc */ NULL, /* copystoragefunc */ NULL, - /* id */ NULL + /* id */ NULL, NULL, NULL, + /* gpufunc */ gpu_shader_camera }; diff --git a/source/blender/nodes/intern/SHD_nodes/SHD_curves.c b/source/blender/nodes/intern/SHD_nodes/SHD_curves.c index b6f1f8d52cd..d277547b636 100644 --- a/source/blender/nodes/intern/SHD_nodes/SHD_curves.c +++ b/source/blender/nodes/intern/SHD_nodes/SHD_curves.c @@ -56,6 +56,15 @@ static void node_shader_init_curve_vec(bNode* node) node->storage= curvemapping_add(3, -1.0f, -1.0f, 1.0f, 1.0f); } +static int gpu_shader_curve_vec(GPUMaterial *mat, bNode *node, GPUNodeStack *in, GPUNodeStack *out) +{ + float *array; + int size; + + curvemapping_table_RGBA(node->storage, &array, &size); + return GPU_stack_link(mat, "curves_vec", in, out, GPU_texture(size, array)); +} + bNodeType sh_node_curve_vec= { /* *next,*prev */ NULL, NULL, /* type code */ SH_NODE_CURVE_VEC, @@ -70,7 +79,8 @@ bNodeType sh_node_curve_vec= { /* initfunc */ node_shader_init_curve_vec, /* freestoragefunc */ node_free_curves, /* copystoragefunc */ node_copy_curves, - /* id */ NULL + /* id */ NULL, NULL, NULL, + /* gpufunc */ gpu_shader_curve_vec }; @@ -100,6 +110,15 @@ static void node_shader_init_curve_rgb(bNode *node) node->storage= curvemapping_add(4, 0.0f, 0.0f, 1.0f, 1.0f); } +static int gpu_shader_curve_rgb(GPUMaterial *mat, bNode *node, GPUNodeStack *in, GPUNodeStack *out) +{ + float *array; + int size; + + curvemapping_table_RGBA(node->storage, &array, &size); + return GPU_stack_link(mat, "curves_rgb", in, out, GPU_texture(size, array)); +} + bNodeType sh_node_curve_rgb= { /* *next,*prev */ NULL, NULL, /* type code */ SH_NODE_CURVE_RGB, @@ -114,6 +133,7 @@ bNodeType sh_node_curve_rgb= { /* initfunc */ node_shader_init_curve_rgb, /* freestoragefunc */ node_free_curves, /* copystoragefunc */ node_copy_curves, - /* id */ NULL + /* id */ NULL, NULL, NULL, + /* gpufunc */ gpu_shader_curve_rgb }; diff --git a/source/blender/nodes/intern/SHD_nodes/SHD_geom.c b/source/blender/nodes/intern/SHD_nodes/SHD_geom.c index 24395059c60..bc345759b98 100644 --- a/source/blender/nodes/intern/SHD_nodes/SHD_geom.c +++ b/source/blender/nodes/intern/SHD_nodes/SHD_geom.c @@ -29,6 +29,7 @@ #include "../SHD_util.h" +#include "DNA_customdata_types.h" /* **************** GEOMETRY ******************** */ @@ -124,6 +125,18 @@ static void node_shader_init_geometry(bNode *node) node->storage= MEM_callocN(sizeof(NodeGeometry), "NodeGeometry"); } +static int gpu_shader_geom(GPUMaterial *mat, bNode *node, GPUNodeStack *in, GPUNodeStack *out) +{ + NodeGeometry *ngeo= (NodeGeometry*)node->storage; + GPUNodeLink *orco = GPU_attribute(CD_ORCO, ""); + GPUNodeLink *mtface = GPU_attribute(CD_MTFACE, ngeo->uvname); + GPUNodeLink *mcol = GPU_attribute(CD_MCOL, ngeo->colname); + + return GPU_stack_link(mat, "geom", in, out, + GPU_builtin(GPU_VIEW_POSITION), GPU_builtin(GPU_VIEW_NORMAL), + GPU_builtin(GPU_INVERSE_VIEW_MATRIX), orco, mtface, mcol); +} + /* node type definition */ bNodeType sh_node_geom= { /* *next,*prev */ NULL, NULL, @@ -139,6 +152,7 @@ bNodeType sh_node_geom= { /* initfunc */ node_shader_init_geometry, /* freestoragefunc */ node_free_standard_storage, /* copystoragefunc */ node_copy_standard_storage, - /* id */ NULL + /* id */ NULL, NULL, NULL, + /* gpufunc */ gpu_shader_geom }; diff --git a/source/blender/nodes/intern/SHD_nodes/SHD_hueSatVal.c b/source/blender/nodes/intern/SHD_nodes/SHD_hueSatVal.c index 67dfc619080..1b7b2dfb8e7 100644 --- a/source/blender/nodes/intern/SHD_nodes/SHD_hueSatVal.c +++ b/source/blender/nodes/intern/SHD_nodes/SHD_hueSatVal.c @@ -71,6 +71,12 @@ static void node_shader_exec_hue_sat(void *data, bNode *node, bNodeStack **in, b do_hue_sat_fac(node, out[0]->vec, in[0]->vec, in[1]->vec, in[2]->vec, in[4]->vec, in[3]->vec); } + +static int gpu_shader_hue_sat(GPUMaterial *mat, bNode *node, GPUNodeStack *in, GPUNodeStack *out) +{ + return GPU_stack_link(mat, "hue_sat", in, out); +} + bNodeType sh_node_hue_sat= { /* *next,*prev */ NULL, NULL, /* type code */ SH_NODE_HUE_SAT, @@ -85,7 +91,8 @@ bNodeType sh_node_hue_sat= { /* initfunc */ NULL, /* freestoragefunc */ NULL, /* copystoragefunc */ NULL, - /* id */ NULL + /* id */ NULL, NULL, NULL, + /* gpufunc */ gpu_shader_hue_sat }; diff --git a/source/blender/nodes/intern/SHD_nodes/SHD_invert.c b/source/blender/nodes/intern/SHD_nodes/SHD_invert.c index 4d1ce282fce..72ee1483ecf 100644 --- a/source/blender/nodes/intern/SHD_nodes/SHD_invert.c +++ b/source/blender/nodes/intern/SHD_nodes/SHD_invert.c @@ -64,6 +64,11 @@ bNodeStack **out) VECCOPY(out[0]->vec, col); } +static int gpu_shader_invert(GPUMaterial *mat, bNode *node, GPUNodeStack *in, GPUNodeStack *out) +{ + return GPU_stack_link(mat, "invert", in, out); +} + bNodeType sh_node_invert= { /* *next,*prev */ NULL, NULL, /* type code */ SH_NODE_INVERT, @@ -78,6 +83,7 @@ bNodeType sh_node_invert= { /* initfunc */ NULL, /* freestoragefunc */ NULL, /* copystoragefunc */ NULL, - /* id */ NULL + /* id */ NULL, NULL, NULL, + /* gpufunc */ gpu_shader_invert }; diff --git a/source/blender/nodes/intern/SHD_nodes/SHD_mapping.c b/source/blender/nodes/intern/SHD_nodes/SHD_mapping.c index 589954c8f7b..c081929a2fc 100644 --- a/source/blender/nodes/intern/SHD_nodes/SHD_mapping.c +++ b/source/blender/nodes/intern/SHD_nodes/SHD_mapping.c @@ -69,6 +69,20 @@ static void node_shader_init_mapping(bNode *node) node->storage= add_mapping(); } +static int gpu_shader_mapping(GPUMaterial *mat, bNode *node, GPUNodeStack *in, GPUNodeStack *out) +{ + TexMapping *texmap= node->storage; + float domin= (texmap->flag & TEXMAP_CLIP_MIN) != 0; + float domax= (texmap->flag & TEXMAP_CLIP_MAX) != 0; + GPUNodeLink *tmat = GPU_uniform((float*)texmap->mat); + GPUNodeLink *tmin = GPU_uniform(texmap->min); + GPUNodeLink *tmax = GPU_uniform(texmap->max); + GPUNodeLink *tdomin = GPU_uniform(&domin); + GPUNodeLink *tdomax = GPU_uniform(&domax); + + return GPU_stack_link(mat, "mapping", in, out, tmat, tmin, tmax, tdomin, tdomax); +} + bNodeType sh_node_mapping= { /* *next,*prev */ NULL, NULL, /* type code */ SH_NODE_MAPPING, @@ -83,7 +97,8 @@ bNodeType sh_node_mapping= { /* initfunc */ node_shader_init_mapping, /* freestoragefunc */ node_free_standard_storage, /* copystoragefunc */ node_copy_standard_storage, - /* id */ NULL + /* id */ NULL, NULL, NULL, + /* gpufunc */ gpu_shader_mapping }; diff --git a/source/blender/nodes/intern/SHD_nodes/SHD_material.c b/source/blender/nodes/intern/SHD_nodes/SHD_material.c index 9396410f850..c0a2534ac4a 100644 --- a/source/blender/nodes/intern/SHD_nodes/SHD_material.c +++ b/source/blender/nodes/intern/SHD_nodes/SHD_material.c @@ -182,6 +182,77 @@ static void node_shader_init_material(bNode* node) node->custom1= SH_NODE_MAT_DIFF|SH_NODE_MAT_SPEC; } +static int gpu_shader_material(GPUMaterial *mat, bNode *node, GPUNodeStack *in, GPUNodeStack *out) +{ + if(node->id) { + GPUShadeInput shi; + GPUShadeResult shr; + + GPU_shadeinput_set(mat, (Material*)node->id, &shi); + + /* write values */ + if(in[MAT_IN_COLOR].hasinput) + shi.rgb = in[MAT_IN_COLOR].link; + + if(in[MAT_IN_SPEC].hasinput) + shi.specrgb = in[MAT_IN_SPEC].link; + + if(in[MAT_IN_REFL].hasinput) + shi.refl = in[MAT_IN_REFL].link; + + /* retrieve normal */ + if(in[MAT_IN_NORMAL].hasinput) { + GPUNodeLink *tmp; + shi.vn = in[MAT_IN_NORMAL].link; + GPU_link(mat, "vec_math_normalize", shi.vn, &shi.vn, &tmp); + } + + /* custom option to flip normal */ + if(node->custom1 & SH_NODE_MAT_NEG) + GPU_link(mat, "vec_math_negate", shi.vn, &shi.vn); + + if (node->type == SH_NODE_MATERIAL_EXT) { + if(in[MAT_IN_AMB].hasinput) + shi.amb= in[MAT_IN_AMB].link; + if(in[MAT_IN_EMIT].hasinput) + shi.emit= in[MAT_IN_EMIT].link; + if(in[MAT_IN_ALPHA].hasinput) + shi.alpha= in[MAT_IN_ALPHA].link; + } + + GPU_shaderesult_set(&shi, &shr); /* clears shr */ + + /* write to outputs */ + if(node->custom1 & SH_NODE_MAT_DIFF) { + if(node->custom1 & SH_NODE_MAT_SPEC) + out[MAT_OUT_COLOR].link= shr.combined; + else + out[MAT_OUT_COLOR].link= shr.diff; + } + else if(node->custom1 & SH_NODE_MAT_SPEC) { + out[MAT_OUT_COLOR].link= shr.spec; + } + else + GPU_link(mat, "set_rgb_zero", &out[MAT_OUT_COLOR].link); + + GPU_link(mat, "mtex_alpha_to_col", out[MAT_OUT_COLOR].link, shr.alpha, &out[MAT_OUT_COLOR].link); + + out[MAT_OUT_ALPHA].link = shr.alpha; // + + if(node->custom1 & SH_NODE_MAT_NEG) + GPU_link(mat, "vec_math_negate", shi.vn, &shi.vn); + out[MAT_OUT_NORMAL].link = shi.vn; + + if (node->type == SH_NODE_MATERIAL_EXT) { + out[MAT_OUT_DIFFUSE].link = shr.diff; + out[MAT_OUT_SPEC].link = shr.spec; + } + + return 1; + } + + return 0; +} bNodeType sh_node_material= { /* *next,*prev */ NULL, NULL, @@ -197,8 +268,8 @@ bNodeType sh_node_material= { /* initfunc */ node_shader_init_material, /* freestoragefunc */ NULL, /* copystoragefunc */ NULL, - /* id */ NULL - + /* id */ NULL, NULL, NULL, + /* gpufunc */ gpu_shader_material }; bNodeType sh_node_material_ext= { @@ -215,7 +286,7 @@ bNodeType sh_node_material_ext= { /* initfunc */ node_shader_init_material, /* freestoragefunc */ NULL, /* copystoragefunc */ NULL, - /* id */ NULL - + /* id */ NULL, NULL, NULL, + /* gpufunc */ gpu_shader_material }; diff --git a/source/blender/nodes/intern/SHD_nodes/SHD_math.c b/source/blender/nodes/intern/SHD_nodes/SHD_math.c index 2e156cf12bf..050c2cdcc95 100644 --- a/source/blender/nodes/intern/SHD_nodes/SHD_math.c +++ b/source/blender/nodes/intern/SHD_nodes/SHD_math.c @@ -194,6 +194,46 @@ bNodeStack **out) } } +static int gpu_shader_math(GPUMaterial *mat, bNode *node, GPUNodeStack *in, GPUNodeStack *out) +{ + static char *names[] = {"math_add", "math_subtract", "math_multiply", + "math_divide", "math_sine", "math_cosine", "math_tangnet", "math_asin", + "math_acos", "math_atan", "math_pow", "math_log", "math_min", "math_max", + "math_round", "math_less_than", "math_greater_than"}; + + switch (node->custom1) { + case 0: + case 1: + case 2: + case 3: + case 10: + case 11: + case 12: + case 13: + case 15: + case 16: + GPU_stack_link(mat, names[node->custom1], NULL, out, + GPU_socket(&in[0]), GPU_socket(&in[1])); + break; + case 4: + case 5: + case 6: + case 7: + case 8: + case 9: + case 14: + if(in[0].hasinput || !in[1].hasinput) + GPU_stack_link(mat, names[node->custom1], NULL, out, GPU_socket(&in[0])); + else + GPU_stack_link(mat, names[node->custom1], NULL, out, GPU_socket(&in[1])); + break; + default: + return 0; + } + + return 1; +} + bNodeType sh_node_math= { /* *next,*prev */ NULL, NULL, /* type code */ SH_NODE_MATH, @@ -208,6 +248,7 @@ bNodeType sh_node_math= { /* initfunc */ NULL, /* freestoragefunc */ NULL, /* copystoragefunc */ NULL, - /* id */ NULL + /* id */ NULL, NULL, NULL, + /* gpufunc */ gpu_shader_math }; diff --git a/source/blender/nodes/intern/SHD_nodes/SHD_mixRgb.c b/source/blender/nodes/intern/SHD_nodes/SHD_mixRgb.c index dba70253fda..2da1dee5623 100644 --- a/source/blender/nodes/intern/SHD_nodes/SHD_mixRgb.c +++ b/source/blender/nodes/intern/SHD_nodes/SHD_mixRgb.c @@ -60,6 +60,17 @@ static void node_shader_exec_mix_rgb(void *data, bNode *node, bNodeStack **in, b VECCOPY(out[0]->vec, col); } +static int gpu_shader_mix_rgb(GPUMaterial *mat, bNode *node, GPUNodeStack *in, GPUNodeStack *out) +{ + static char *names[] = {"mix_blend", "mix_add", "mix_mult", "mix_sub", + "mix_screen", "mix_div", "mix_diff", "mix_dark", "mix_light", + "mix_overlay", "mix_dodge", "mix_burn", "mix_hue", "mix_sat", + "mix_val", "mix_color"}; + + return GPU_stack_link(mat, names[node->custom1], in, out); +} + + bNodeType sh_node_mix_rgb= { /* *next,*prev */ NULL, NULL, /* type code */ SH_NODE_MIX_RGB, @@ -74,6 +85,7 @@ bNodeType sh_node_mix_rgb= { /* initfunc */ NULL, /* freestoragefunc */ NULL, /* copystoragefunc */ NULL, - /* id */ NULL + /* id */ NULL, NULL, NULL, + /* gpufunc */ gpu_shader_mix_rgb }; diff --git a/source/blender/nodes/intern/SHD_nodes/SHD_normal.c b/source/blender/nodes/intern/SHD_nodes/SHD_normal.c index f1ffd3446af..9d4ea1ccf67 100644 --- a/source/blender/nodes/intern/SHD_nodes/SHD_normal.c +++ b/source/blender/nodes/intern/SHD_nodes/SHD_normal.c @@ -57,6 +57,14 @@ static void node_shader_exec_normal(void *data, bNode *node, bNodeStack **in, bN out[1]->vec[0]= -INPR(out[0]->vec, vec); } +static int gpu_shader_normal(GPUMaterial *mat, bNode *node, GPUNodeStack *in, GPUNodeStack *out) +{ + bNodeSocket *sock= node->outputs.first; + GPUNodeLink *vec = GPU_uniform(sock->ns.vec); + + return GPU_stack_link(mat, "normal", in, out, vec); +} + bNodeType sh_node_normal= { /* *next,*prev */ NULL, NULL, /* type code */ SH_NODE_NORMAL, @@ -71,6 +79,7 @@ bNodeType sh_node_normal= { /* initfunc */ NULL, /* freestoragefunc */ NULL, /* copystoragefunc */ NULL, - /* id */ NULL + /* id */ NULL, NULL, NULL, + /* gpufunc */ gpu_shader_normal }; diff --git a/source/blender/nodes/intern/SHD_nodes/SHD_output.c b/source/blender/nodes/intern/SHD_nodes/SHD_output.c index 0a9a30c452b..76856cfd2e8 100644 --- a/source/blender/nodes/intern/SHD_nodes/SHD_output.c +++ b/source/blender/nodes/intern/SHD_nodes/SHD_output.c @@ -62,6 +62,19 @@ static void node_shader_exec_output(void *data, bNode *node, bNodeStack **in, bN } } +static int gpu_shader_output(GPUMaterial *mat, bNode *node, GPUNodeStack *in, GPUNodeStack *out) +{ + GPUNodeLink *outlink; + + /*if(in[1].hasinput) + GPU_material_enable_alpha(mat);*/ + + GPU_stack_link(mat, "output_node", in, out, &outlink); + GPU_material_output_link(mat, outlink); + + return 1; +} + bNodeType sh_node_output= { /* *next,*prev */ NULL, NULL, /* type code */ SH_NODE_OUTPUT, @@ -76,7 +89,8 @@ bNodeType sh_node_output= { /* initfunc */ NULL, /* freestoragefunc */ NULL, /* copystoragefunc */ NULL, - /* id */ NULL + /* id */ NULL, NULL, NULL, + /* gpufunc */ gpu_shader_output }; diff --git a/source/blender/nodes/intern/SHD_nodes/SHD_rgb.c b/source/blender/nodes/intern/SHD_nodes/SHD_rgb.c index 4e56e26d3ad..1aa1a2ffc33 100644 --- a/source/blender/nodes/intern/SHD_nodes/SHD_rgb.c +++ b/source/blender/nodes/intern/SHD_nodes/SHD_rgb.c @@ -42,6 +42,14 @@ static void node_shader_exec_rgb(void *data, bNode *node, bNodeStack **in, bNode VECCOPY(out[0]->vec, sock->ns.vec); } +static int gpu_shader_rgb(GPUMaterial *mat, bNode *node, GPUNodeStack *in, GPUNodeStack *out) +{ + bNodeSocket *sock= node->outputs.first; + GPUNodeLink *vec = GPU_uniform(sock->ns.vec); + + return GPU_stack_link(mat, "set_rgba", in, out, vec); +} + bNodeType sh_node_rgb= { /* *next,*prev */ NULL, NULL, /* type code */ SH_NODE_RGB, @@ -56,6 +64,7 @@ bNodeType sh_node_rgb= { /* initfunc */ NULL, /* freestoragefunc */ NULL, /* copystoragefunc */ NULL, - /* id */ NULL + /* id */ NULL, NULL, NULL, + /* gpufunc */ gpu_shader_rgb }; diff --git a/source/blender/nodes/intern/SHD_nodes/SHD_sepcombRGB.c b/source/blender/nodes/intern/SHD_nodes/SHD_sepcombRGB.c index 2b52a8e2229..6d5df2a1321 100644 --- a/source/blender/nodes/intern/SHD_nodes/SHD_sepcombRGB.c +++ b/source/blender/nodes/intern/SHD_nodes/SHD_sepcombRGB.c @@ -48,6 +48,11 @@ static void node_shader_exec_seprgb(void *data, bNode *node, bNodeStack **in, bN out[2]->vec[0] = in[0]->vec[2]; } +static int gpu_shader_seprgb(GPUMaterial *mat, bNode *node, GPUNodeStack *in, GPUNodeStack *out) +{ + return GPU_stack_link(mat, "separate_rgb", in, out); +} + bNodeType sh_node_seprgb= { /* *next,*prev */ NULL, NULL, /* type code */ SH_NODE_SEPRGB, @@ -62,7 +67,8 @@ bNodeType sh_node_seprgb= { /* initfunc */ NULL, /* freestoragefunc */ NULL, /* copystoragefunc */ NULL, - /* id */ NULL + /* id */ NULL, NULL, NULL, + /* gpufunc */ gpu_shader_seprgb }; @@ -86,6 +92,11 @@ static void node_shader_exec_combrgb(void *data, bNode *node, bNodeStack **in, b out[0]->vec[2] = in[2]->vec[0]; } +static int gpu_shader_combrgb(GPUMaterial *mat, bNode *node, GPUNodeStack *in, GPUNodeStack *out) +{ + return GPU_stack_link(mat, "combine_rgb", in, out); +} + bNodeType sh_node_combrgb= { /* *next,*prev */ NULL, NULL, /* type code */ SH_NODE_COMBRGB, @@ -100,6 +111,7 @@ bNodeType sh_node_combrgb= { /* initfunc */ NULL, /* freestoragefunc */ NULL, /* copystoragefunc */ NULL, - /* id */ NULL + /* id */ NULL, NULL, NULL, + /* gpufunc */ gpu_shader_combrgb }; diff --git a/source/blender/nodes/intern/SHD_nodes/SHD_squeeze.c b/source/blender/nodes/intern/SHD_nodes/SHD_squeeze.c index 30abad666c4..d3480a6ae9d 100644 --- a/source/blender/nodes/intern/SHD_nodes/SHD_squeeze.c +++ b/source/blender/nodes/intern/SHD_nodes/SHD_squeeze.c @@ -54,6 +54,11 @@ bNodeStack **out) out[0]->vec[0] = 1.0f / (1.0f + pow(2.71828183,-((vec[0]-vec[2])*vec[1]))) ; } +static int gpu_shader_squeeze(GPUMaterial *mat, bNode *node, GPUNodeStack *in, GPUNodeStack *out) +{ + return GPU_stack_link(mat, "squeeze", in, out); +} + bNodeType sh_node_squeeze= { /* *next,*prev */ NULL, NULL, /* type code */ SH_NODE_SQUEEZE, @@ -68,6 +73,7 @@ bNodeType sh_node_squeeze= { /* initfunc */ NULL, /* freestoragefunc */ NULL, /* copystoragefunc */ NULL, - /* id */ NULL + /* id */ NULL, NULL, NULL, + /* gpufunc */ gpu_shader_squeeze }; diff --git a/source/blender/nodes/intern/SHD_nodes/SHD_texture.c b/source/blender/nodes/intern/SHD_nodes/SHD_texture.c index ace11a20d42..31dbde940fd 100644 --- a/source/blender/nodes/intern/SHD_nodes/SHD_texture.c +++ b/source/blender/nodes/intern/SHD_nodes/SHD_texture.c @@ -27,6 +27,8 @@ * ***** END GPL LICENSE BLOCK ***** */ +#include "DNA_texture_types.h" + #include "../SHD_util.h" /* **************** TEXTURE ******************** */ @@ -110,6 +112,18 @@ static void node_shader_exec_texture(void *data, bNode *node, bNodeStack **in, b } } +static int gpu_shader_texture(GPUMaterial *mat, bNode *node, GPUNodeStack *in, GPUNodeStack *out) +{ + Tex *tex = (Tex*)node->id; + + if(tex && tex->type == TEX_IMAGE && tex->ima) { + GPUNodeLink *texlink = GPU_image(tex->ima, NULL); + return GPU_stack_link(mat, "texture_image", in, out, texlink); + } + else + return 0; +} + bNodeType sh_node_texture= { /* *next,*prev */ NULL, NULL, /* type code */ SH_NODE_TEXTURE, @@ -124,7 +138,8 @@ bNodeType sh_node_texture= { /* initfunc */ NULL, /* freestoragefunc */ NULL, /* copystoragefunc */ NULL, - /* id */ NULL + /* id */ NULL, NULL, NULL, + /* gpufunc */ gpu_shader_texture }; diff --git a/source/blender/nodes/intern/SHD_nodes/SHD_valToRgb.c b/source/blender/nodes/intern/SHD_nodes/SHD_valToRgb.c index cf7e33d9dca..301c0cb7031 100644 --- a/source/blender/nodes/intern/SHD_nodes/SHD_valToRgb.c +++ b/source/blender/nodes/intern/SHD_nodes/SHD_valToRgb.c @@ -59,6 +59,15 @@ static void node_shader_init_valtorgb(bNode *node) node->storage= add_colorband(1); } +static int gpu_shader_valtorgb(GPUMaterial *mat, bNode *node, GPUNodeStack *in, GPUNodeStack *out) +{ + float *array; + int size; + + colorband_table_RGBA(node->storage, &array, &size); + return GPU_stack_link(mat, "valtorgb", in, out, GPU_texture(size, array)); +} + bNodeType sh_node_valtorgb= { /* *next,*prev */ NULL, NULL, /* type code */ SH_NODE_VALTORGB, @@ -73,7 +82,8 @@ bNodeType sh_node_valtorgb= { /* initfunc */ node_shader_init_valtorgb, /* freestoragefunc */ node_free_standard_storage, /* copystoragefunc */ node_copy_standard_storage, - /* id */ NULL + /* id */ NULL, NULL, NULL, + /* gpufunc */ gpu_shader_valtorgb }; @@ -96,6 +106,11 @@ static void node_shader_exec_rgbtobw(void *data, bNode *node, bNodeStack **in, b out[0]->vec[0]= in[0]->vec[0]*0.35f + in[0]->vec[1]*0.45f + in[0]->vec[2]*0.2f; } +static int gpu_shader_rgbtobw(GPUMaterial *mat, bNode *node, GPUNodeStack *in, GPUNodeStack *out) +{ + return GPU_stack_link(mat, "rgbtobw", in, out); +} + bNodeType sh_node_rgbtobw= { /* *next,*prev */ NULL, NULL, /* type code */ SH_NODE_RGBTOBW, @@ -110,7 +125,8 @@ bNodeType sh_node_rgbtobw= { /* initfunc */ NULL, /* freestoragefunc */ NULL, /* copystoragefunc */ NULL, - /* id */ NULL + /* id */ NULL, NULL, NULL, + /* gpufunc */ gpu_shader_rgbtobw }; diff --git a/source/blender/nodes/intern/SHD_nodes/SHD_value.c b/source/blender/nodes/intern/SHD_nodes/SHD_value.c index 57ef7226066..768ef3cda3d 100644 --- a/source/blender/nodes/intern/SHD_nodes/SHD_value.c +++ b/source/blender/nodes/intern/SHD_nodes/SHD_value.c @@ -42,7 +42,13 @@ static void node_shader_exec_value(void *data, bNode *node, bNodeStack **in, bNo out[0]->vec[0]= sock->ns.vec[0]; } +static int gpu_shader_value(GPUMaterial *mat, bNode *node, GPUNodeStack *in, GPUNodeStack *out) +{ + bNodeSocket *sock= node->outputs.first; + GPUNodeLink *vec = GPU_uniform(sock->ns.vec); + return GPU_stack_link(mat, "set_value", in, out, vec); +} bNodeType sh_node_value= { /* *next,*prev */ NULL, NULL, @@ -58,7 +64,8 @@ bNodeType sh_node_value= { /* initfunc */ NULL, /* freestoragefunc */ NULL, /* copystoragefunc */ NULL, - /* id */ NULL + /* id */ NULL, NULL, NULL, + /* gpufunc */ gpu_shader_value }; diff --git a/source/blender/nodes/intern/SHD_nodes/SHD_vectMath.c b/source/blender/nodes/intern/SHD_nodes/SHD_vectMath.c index 8d0a4b3abe3..96db8db18a6 100644 --- a/source/blender/nodes/intern/SHD_nodes/SHD_vectMath.c +++ b/source/blender/nodes/intern/SHD_nodes/SHD_vectMath.c @@ -99,6 +99,34 @@ static void node_shader_exec_vect_math(void *data, bNode *node, bNodeStack **in, } +static int gpu_shader_vect_math(GPUMaterial *mat, bNode *node, GPUNodeStack *in, GPUNodeStack *out) +{ + static char *names[] = {"vec_math_add", "vec_math_subtract", + "vec_math_average", "vec_math_dot", "vec_math_cross", + "vec_math_normalize"}; + + switch (node->custom1) { + case 0: + case 1: + case 2: + case 3: + case 4: + GPU_stack_link(mat, names[node->custom1], NULL, out, + GPU_socket(&in[0]), GPU_socket(&in[1])); + break; + case 5: + if(in[0].hasinput || !in[1].hasinput) + GPU_stack_link(mat, names[node->custom1], NULL, out, GPU_socket(&in[0])); + else + GPU_stack_link(mat, names[node->custom1], NULL, out, GPU_socket(&in[1])); + break; + default: + return 0; + } + + return 1; +} + bNodeType sh_node_vect_math= { /* *next,*prev */ NULL, NULL, /* type code */ SH_NODE_VECT_MATH, @@ -113,6 +141,7 @@ bNodeType sh_node_vect_math= { /* initfunc */ NULL, /* freestoragefunc */ NULL, /* copystoragefunc */ NULL, - /* id */ NULL + /* id */ NULL, NULL, NULL, + /* gpufunc */ gpu_shader_vect_math }; diff --git a/source/blender/nodes/intern/SHD_util.h b/source/blender/nodes/intern/SHD_util.h index bdb2bb3707d..eda985529c1 100644 --- a/source/blender/nodes/intern/SHD_util.h +++ b/source/blender/nodes/intern/SHD_util.h @@ -88,6 +88,8 @@ #include "RE_pipeline.h" #include "RE_shader_ext.h" +#include "GPU_material.h" + #include "butspace.h" #include "blendef.h" #include "mydevice.h" diff --git a/source/blender/python/CMakeLists.txt b/source/blender/python/CMakeLists.txt index 0106ab77843..63a1e67236e 100644 --- a/source/blender/python/CMakeLists.txt +++ b/source/blender/python/CMakeLists.txt @@ -34,7 +34,7 @@ SET(INC api2_2x ../blenkernel ../blenlib ../blenloader ../render/extern/include ../radiosity/extern/include ../makesdna ../../../intern/guardedalloc ../../../intern/bmfont ../imbuf ../include - ${PYTHON_INC} + ${PYTHON_INC} ../../../extern/glew/include ../gpu ) IF(WITH_QUICKTIME) @@ -50,5 +50,9 @@ IF(WITH_FFMPEG) ADD_DEFINITIONS(-DWITH_FFMPEG) ENDIF(WITH_FFMPEG) +IF(BF_BUILDINFO) + ADD_DEFINITIONS(-DNAN_BUILDINFO) +ENDIF(BF_BUILDINFO) + BLENDERLIB_NOLIST(blender_python "${SRC}" "${INC}") #env.BlenderLib ( libname='blender_python', sources = Split(sources), includes = Split(incs), defines = defs, libtype=['core','game2'], priority = [60,115] ) diff --git a/source/blender/python/SConscript b/source/blender/python/SConscript index 481fdcbe13e..27dd510f944 100644 --- a/source/blender/python/SConscript +++ b/source/blender/python/SConscript @@ -6,6 +6,7 @@ sources = Split('BPY_interface.c BPY_menus.c') + env.Glob('api2_2x/*.c') incs = 'api2_2x ../blenkernel ../nodes ../blenlib ../blenloader' incs += ' ../render/extern/include ../radiosity/extern/include' incs += ' ../makesdna #intern/guardedalloc #intern/bmfont ../imbuf ../include' +incs += ' #extern/glew/include ../gpu' incs += ' ' + env['BF_PYTHON_INC'] incs += ' ' + env['BF_OPENGL_INC'] @@ -23,4 +24,7 @@ if env['WITH_BF_OPENEXR'] == 1: if env['WITH_BF_FFMPEG'] == 1: defs.append('WITH_FFMPEG') +if env['BF_BUILDINFO'] == 1: + defs.append('NAN_BUILDINFO') + env.BlenderLib ( libname='blender_python', sources = Split(sources), includes = Split(incs), defines = defs, libtype=['core','game2'], priority = [60,115] ) diff --git a/source/blender/python/api2_2x/Blender.c b/source/blender/python/api2_2x/Blender.c index 2b190a6c828..47e7bcb2007 100644 --- a/source/blender/python/api2_2x/Blender.c +++ b/source/blender/python/api2_2x/Blender.c @@ -34,7 +34,7 @@ struct ID; /*keep me up here */ /* for open, close in Blender_Load */ #include #include "BDR_editobject.h" /* exit_editmode() */ -#include "BDR_drawmesh.h" /* set_mipmap() */ +#include "GPU_draw.h" /* GPU_set_mipmap() */ #include "BIF_usiblender.h" #include "BLI_blenlib.h" #include "BLI_bpath.h" @@ -314,8 +314,8 @@ static PyObject *Blender_Set( PyObject * self, PyObject * args ) else U.gameflags |= USER_DISABLE_MIPMAP; - set_mipmap(!(U.gameflags & USER_DISABLE_MIPMAP)); - }else + GPU_set_mipmap(!(U.gameflags & USER_DISABLE_MIPMAP)); + } else return ( EXPP_ReturnPyObjError( PyExc_AttributeError, "value given is not a blender setting" ) ); Py_RETURN_NONE; @@ -543,7 +543,21 @@ static PyObject *Blender_Get( PyObject * self, PyObject * value ) } /* End 'quick hack' part. */ else if(StringEqual( str, "version" )) ret = PyInt_FromLong( G.version ); - + else if(StringEqual( str, "buildinfo" )) { +#ifdef NAN_BUILDINFO + char buffer[1024]; + extern char * build_date; + extern char * build_time; + extern char * build_rev; + extern char * build_platform; + extern char * build_type; + + sprintf(buffer, "Built on %s %s, Rev-%s Version %s %s", build_date, build_time, build_rev, build_platform, build_type); + ret = PyString_FromString( buffer ); +#else + ret = PyString_FromString( "No Build Info" ); +#endif + } else if(StringEqual( str, "compressfile" )) ret = PyInt_FromLong( (U.flag & USER_FILECOMPRESS) >> 15 ); else if(StringEqual( str, "mipmap" )) diff --git a/source/blender/python/api2_2x/Group.c b/source/blender/python/api2_2x/Group.c index 3e7f02c3797..3152d3a973f 100644 --- a/source/blender/python/api2_2x/Group.c +++ b/source/blender/python/api2_2x/Group.c @@ -46,6 +46,8 @@ #include "gen_utils.h" #include "gen_library.h" +#include "vector.h" + /* checks for the group being removed */ #define GROUP_DEL_CHECK_PY(bpy_group) if (!(bpy_group->group)) return ( EXPP_ReturnPyObjError( PyExc_RuntimeError, "Group has been removed" ) ) #define GROUP_DEL_CHECK_INT(bpy_group) if (!(bpy_group->group)) return ( EXPP_ReturnIntError( PyExc_RuntimeError, "Group has been removed" ) ) @@ -200,6 +202,31 @@ static int Group_setObjects( BPy_Group * self, PyObject * args ) return 0; } +static PyObject *Group_getDupliOfs( BPy_Group * self ) +{ + GROUP_DEL_CHECK_PY(self); + return newVectorObject( self->group->dupli_ofs, 3, Py_WRAP ); +} + +static int Group_setDupliOfs( BPy_Group * self, PyObject * value ) +{ + VectorObject *bpy_vec; + GROUP_DEL_CHECK_INT(self); + if (!VectorObject_Check(value)) + return ( EXPP_ReturnIntError( PyExc_TypeError, + "expected a vector" ) ); + + bpy_vec = (VectorObject *)value; + + if (bpy_vec->size != 3) + return ( EXPP_ReturnIntError( PyExc_ValueError, + "can only assign a 3D vector" ) ); + + self->group->dupli_ofs[0] = bpy_vec->vec[0]; + self->group->dupli_ofs[1] = bpy_vec->vec[1]; + self->group->dupli_ofs[2] = bpy_vec->vec[2]; + return 0; +} /*****************************************************************************/ @@ -251,6 +278,10 @@ static PyGetSetDef BPy_Group_getseters[] = { (getter)Group_getObjects, (setter)Group_setObjects, "objects in this group", NULL}, + {"dupliOffset", + (getter)Group_getDupliOfs, (setter)Group_setDupliOfs, + "offset to use when instancing this group as a DupliGroup", + NULL}, {NULL,NULL,NULL,NULL,NULL} /* Sentinel */ }; diff --git a/source/blender/python/api2_2x/Image.c b/source/blender/python/api2_2x/Image.c index 94da5a77170..5ef2cbadbdc 100644 --- a/source/blender/python/api2_2x/Image.c +++ b/source/blender/python/api2_2x/Image.c @@ -29,7 +29,6 @@ */ #include "Image.h" /*This must come first */ -#include "BDR_drawmesh.h" /* free_realtime_image */ #include "BKE_main.h" #include "BKE_global.h" #include "BKE_library.h" @@ -48,6 +47,7 @@ #include "BKE_icons.h" #include "IMB_imbuf.h" #include "IDProp.h" +#include "GPU_draw.h" /* used so we can get G.scene->r.cfra for getting the current image frame, some images change frame if they are a sequence */ @@ -1003,7 +1003,7 @@ static PyObject *Image_glFree( BPy_Image * self ) { Image *image = self->image; - free_realtime_image( image ); + GPU_free_image( image ); /* remove the nocollect flag, image is available for garbage collection again */ image->flag &= ~IMA_NOCOLLECT; Py_RETURN_NONE; diff --git a/source/blender/python/api2_2x/Lamp.c b/source/blender/python/api2_2x/Lamp.c index 53d25a6429d..2e58cb71b90 100644 --- a/source/blender/python/api2_2x/Lamp.c +++ b/source/blender/python/api2_2x/Lamp.c @@ -84,6 +84,8 @@ #define EXPP_LAMP_MODE_NODIFFUSE 2048 #define EXPP_LAMP_MODE_NOSPECULAR 4096 #define EXPP_LAMP_MODE_SHAD_RAY 8192 +#define EXPP_LAMP_MODE_LAYER_SHADOW 32768 + /* Lamp MIN, MAX values */ #define EXPP_LAMP_SAMPLES_MIN 1 @@ -780,6 +782,8 @@ static PyObject *Lamp_ModesDict( void ) PyInt_FromLong( EXPP_LAMP_MODE_NOSPECULAR ) ); PyConstant_Insert( c, "RayShadow", PyInt_FromLong( EXPP_LAMP_MODE_SHAD_RAY ) ); + PyConstant_Insert( c, "LayerShadow", + PyInt_FromLong( EXPP_LAMP_MODE_LAYER_SHADOW ) ); } return Modes; @@ -1011,8 +1015,8 @@ static int Lamp_setType( BPy_Lamp * self, PyObject * value ) static int Lamp_setMode( BPy_Lamp * self, PyObject * value ) { - short param; - static short bitmask = EXPP_LAMP_MODE_SHADOWS + int param; + static int bitmask = EXPP_LAMP_MODE_SHADOWS | EXPP_LAMP_MODE_HALO | EXPP_LAMP_MODE_LAYER | EXPP_LAMP_MODE_QUAD @@ -1022,14 +1026,15 @@ static int Lamp_setMode( BPy_Lamp * self, PyObject * value ) | EXPP_LAMP_MODE_SQUARE | EXPP_LAMP_MODE_NODIFFUSE | EXPP_LAMP_MODE_NOSPECULAR - | EXPP_LAMP_MODE_SHAD_RAY; + | EXPP_LAMP_MODE_SHAD_RAY + | EXPP_LAMP_MODE_LAYER_SHADOW; if( !PyInt_Check ( value ) ) { char errstr[128]; sprintf ( errstr , "expected int bitmask of 0x%04x", bitmask ); return EXPP_ReturnIntError( PyExc_TypeError, errstr ); } - param = (short)PyInt_AS_LONG ( value ); + param = PyInt_AS_LONG ( value ); if ( ( param & bitmask ) != param ) return EXPP_ReturnIntError( PyExc_ValueError, @@ -1373,7 +1378,8 @@ static PyObject *Lamp_getModesConst( void ) EXPP_LAMP_MODE_SQUARE, "NoDiffuse", EXPP_LAMP_MODE_NODIFFUSE, "NoSpecular", EXPP_LAMP_MODE_NOSPECULAR, "RayShadow", - EXPP_LAMP_MODE_SHAD_RAY); + EXPP_LAMP_MODE_SHAD_RAY, "LayerShadow", + EXPP_LAMP_MODE_LAYER_SHADOW); } static PyObject *Lamp_getTypesConst( void ) @@ -1597,6 +1603,8 @@ static PyObject *Lamp_oldsetMode( BPy_Lamp * self, PyObject * args ) flag |= ( short ) EXPP_LAMP_MODE_NOSPECULAR; else if( !strcmp( name, "RayShadow" ) ) flag |= ( short ) EXPP_LAMP_MODE_SHAD_RAY; + else if( !strcmp( name, "LayerShadow" ) ) + flag |= ( short ) EXPP_LAMP_MODE_LAYER_SHADOW; else return EXPP_ReturnPyObjError( PyExc_AttributeError, "unknown lamp flag argument" ); diff --git a/source/blender/python/api2_2x/MTex.c b/source/blender/python/api2_2x/MTex.c index b9a8f7fff65..a95836f0596 100644 --- a/source/blender/python/api2_2x/MTex.c +++ b/source/blender/python/api2_2x/MTex.c @@ -677,7 +677,7 @@ static int MTex_setMapping( BPy_MTex *self, PyObject *value, void *closure) static PyObject *MTex_getFlag( BPy_MTex *self, void *closure ) { - return PyBool_FromLong( self->mtex->texflag & ((int) closure) ); + return PyBool_FromLong( self->mtex->texflag & (GET_INT_FROM_POINTER(closure)) ); } static int MTex_setFlag( BPy_MTex *self, PyObject *value, void *closure) @@ -687,9 +687,9 @@ static int MTex_setFlag( BPy_MTex *self, PyObject *value, void *closure) "expected a bool"); if ( value == Py_True ) - self->mtex->texflag |= (int)closure; + self->mtex->texflag |= GET_INT_FROM_POINTER(closure); else - self->mtex->texflag &= ~((int) closure); + self->mtex->texflag &= ~(GET_INT_FROM_POINTER(closure)); return 0; } @@ -774,7 +774,7 @@ static int MTex_setProjZ( BPy_MTex *self, PyObject *value, void *closure) static PyObject *MTex_getMapToFlag( BPy_MTex *self, void *closure ) { - int flag = (int) closure; + int flag = GET_INT_FROM_POINTER(closure); if ( self->mtex->mapto & flag ) { @@ -786,7 +786,7 @@ static PyObject *MTex_getMapToFlag( BPy_MTex *self, void *closure ) static int MTex_setMapToFlag( BPy_MTex *self, PyObject *value, void *closure) { - int flag = (int) closure; + int flag = GET_INT_FROM_POINTER(closure); int intVal; if ( !PyInt_Check( value ) ) diff --git a/source/blender/python/api2_2x/Makefile b/source/blender/python/api2_2x/Makefile index 7c831952042..a2b77bf8c98 100644 --- a/source/blender/python/api2_2x/Makefile +++ b/source/blender/python/api2_2x/Makefile @@ -37,6 +37,10 @@ include nan_compile.mk CFLAGS += $(LEVEL_1_C_WARNINGS) +ifdef NAN_BUILDINFO + CPPFLAGS += -DNAN_BUILDINFO +endif + ifeq ($(WITH_FFMPEG), true) CPPFLAGS += -DWITH_FFMPEG endif @@ -45,6 +49,7 @@ ifeq ($(WITH_OPENEXR),true) CPPFLAGS += -DWITH_OPENEXR endif +CPPFLAGS += -I$(NAN_GLEW)/include CPPFLAGS += -I$(OPENGL_HEADERS) CPPFLAGS += -I$(NAN_GUARDEDALLOC)/include CPPFLAGS += -I../../makesdna @@ -52,6 +57,7 @@ CPPFLAGS += -I../../blenkernel CPPFLAGS += -I../../blenlib CPPFLAGS += -I../../blenloader CPPFLAGS += -I../../include +CPPFLAGS += -I../../gpu CPPFLAGS += -I../../render/extern/include CPPFLAGS += -I../../radiosity/extern/include CPPFLAGS += -I$(NAN_BMFONT)/include diff --git a/source/blender/python/api2_2x/Material.c b/source/blender/python/api2_2x/Material.c index 20747a167e6..54c2d9b20bd 100644 --- a/source/blender/python/api2_2x/Material.c +++ b/source/blender/python/api2_2x/Material.c @@ -1754,8 +1754,7 @@ static PyObject *Material_getTextures( BPy_Material * self ) } /* turn the array into a tuple */ - tuple = Py_BuildValue( "NNNNNNNNNN", t[0], t[1], t[2], t[3], - t[4], t[5], t[6], t[7], t[8], t[9] ); + tuple = Py_BuildValue( "NNNNNNNNNNNNNNNNNN", t[0], t[1], t[2], t[3], t[4], t[5], t[6], t[7], t[8], t[9], t[10], t[11], t[12], t[13], t[14], t[15], t[16], t[17] ); if( !tuple ) return EXPP_ReturnPyObjError( PyExc_MemoryError, "Material_getTextures: couldn't create PyTuple" ); diff --git a/source/blender/python/api2_2x/doc/Group.py b/source/blender/python/api2_2x/doc/Group.py index 6bd6e105ec3..1266d2efb6e 100644 --- a/source/blender/python/api2_2x/doc/Group.py +++ b/source/blender/python/api2_2x/doc/Group.py @@ -105,6 +105,8 @@ class Group: This object gives access to Groups in Blender. @ivar layers: Layer bitmask for this group. @type layers: int + @ivar dupliOffset: Object offset when instanced as a dupligroup + @type dupliOffset: vector @ivar objects: Objects that this group uses. This is a sequence with-list like access so use list(grp.objects) if you need to use a list (where grp is a group). The groups objects can be set by assigning a list or iterator of objects to the groups objects. diff --git a/source/blender/radiosity/CMakeLists.txt b/source/blender/radiosity/CMakeLists.txt index 941da41a5b2..502acf1e211 100644 --- a/source/blender/radiosity/CMakeLists.txt +++ b/source/blender/radiosity/CMakeLists.txt @@ -29,7 +29,7 @@ FILE(GLOB SRC intern/source/*.c) SET(INC extern/include ../blenlib ../blenkernel ../makesdna ../include ../../../intern/guardedalloc ../render/extern/include - ../render/intern/include ../blenloader + ../render/intern/include ../blenloader ../../../extern/glew/include ) BLENDERLIB_NOLIST(blender_radiosity "${SRC}" "${INC}") diff --git a/source/blender/radiosity/SConscript b/source/blender/radiosity/SConscript index a86b76bb4b1..82d84f5ef16 100644 --- a/source/blender/radiosity/SConscript +++ b/source/blender/radiosity/SConscript @@ -5,7 +5,7 @@ sources = env.Glob('intern/source/*.c') incs = 'extern/include ../blenlib ../blenkernel ../makesdna ../include' incs += ' #/intern/guardedalloc ../render/extern/include' -incs += ' ../render/intern/include ../blenloader' +incs += ' ../render/intern/include ../blenloader #/extern/glew/include' incs += ' ' + env['BF_OPENGL_INC'] diff --git a/source/blender/radiosity/intern/source/Makefile b/source/blender/radiosity/intern/source/Makefile index e5ff8c40d08..5912cdba590 100644 --- a/source/blender/radiosity/intern/source/Makefile +++ b/source/blender/radiosity/intern/source/Makefile @@ -36,6 +36,7 @@ include nan_compile.mk CFLAGS += $(LEVEL_1_C_WARNINGS) +CPPFLAGS += -I$(NAN_GLEW)/include CPPFLAGS += -I$(OPENGL_HEADERS) # not very neat.... diff --git a/source/blender/render/intern/include/render_types.h b/source/blender/render/intern/include/render_types.h index f83bbd7e8b2..7e2194549cc 100644 --- a/source/blender/render/intern/include/render_types.h +++ b/source/blender/render/intern/include/render_types.h @@ -418,7 +418,8 @@ typedef struct LampRen { float xs, ys, dist; float co[3]; - short type, mode; + short type; + int mode; float r, g, b, k; float energy, haint; int lay; diff --git a/source/blender/render/intern/source/pipeline.c b/source/blender/render/intern/source/pipeline.c index 3cd7bdc6772..1ebd0fda6c9 100644 --- a/source/blender/render/intern/source/pipeline.c +++ b/source/blender/render/intern/source/pipeline.c @@ -138,7 +138,7 @@ static void print_error(char *str) {printf("ERROR: %s\n", str);} static void stats_background(RenderStats *rs) { - extern uintptr_t mem_in_use; + uintptr_t mem_in_use= MEM_get_memory_in_use(); float megs_used_memory= mem_in_use/(1024.0*1024.0); char str[400], *spos= str; diff --git a/source/blender/render/intern/source/rayshade.c b/source/blender/render/intern/source/rayshade.c index c352a83d0f4..0fd9365477c 100644 --- a/source/blender/render/intern/source/rayshade.c +++ b/source/blender/render/intern/source/rayshade.c @@ -2056,7 +2056,10 @@ void ray_shadow(ShadeInput *shi, LampRen *lar, float *shadfac) if(shi->mat->mode & MA_SHADOW_TRA) isec.mode= RE_RAY_SHADOW_TRA; else isec.mode= RE_RAY_SHADOW; - if(lar->mode & LA_LAYER) isec.lay= lar->lay; else isec.lay= -1; + if(lar->mode & (LA_LAYER|LA_LAYER_SHADOW)) + isec.lay= lar->lay; + else + isec.lay= -1; /* only when not mir tracing, first hit optimm */ if(shi->depth==0) { diff --git a/source/blender/render/intern/source/shadbuf.c b/source/blender/render/intern/source/shadbuf.c index f477df3ed8c..c53a2b68c9c 100644 --- a/source/blender/render/intern/source/shadbuf.c +++ b/source/blender/render/intern/source/shadbuf.c @@ -296,7 +296,7 @@ static void shadowbuf_autoclip(Render *re, LampRen *lar) minz= 1.0e30f; maxz= -1.0e30f; Mat4CpyMat4(viewmat, lar->shb->viewmat); - if(lar->mode & LA_LAYER) lay= lar->lay; + if(lar->mode & (LA_LAYER|LA_LAYER_SHADOW)) lay= lar->lay; maxtotvert= 0; for(obr=re->objecttable.first; obr; obr=obr->next) @@ -1520,7 +1520,7 @@ static void isb_bsp_fillfaces(Render *re, LampRen *lar, ISBBranch *root) minmaxf[2]= (2.0f*root->box.ymin - size-2.0f)/size; minmaxf[3]= (2.0f*root->box.ymax - size+2.0f)/size; - if(lar->mode & LA_LAYER) lay= lar->lay; + if(lar->mode & (LA_LAYER|LA_LAYER_SHADOW)) lay= lar->lay; /* (ab)use zspan, since we use zbuffer clipping code */ zbuf_alloc_span(&zspan, size, size, re->clipcrop); diff --git a/source/blender/render/intern/source/shadeoutput.c b/source/blender/render/intern/source/shadeoutput.c index 5b69323667e..5a80173d1f1 100644 --- a/source/blender/render/intern/source/shadeoutput.c +++ b/source/blender/render/intern/source/shadeoutput.c @@ -1761,7 +1761,21 @@ void shade_lamp_loop(ShadeInput *shi, ShadeResult *shr) if(shi->combinedflag & SCE_PASS_SPEC) VECADD(shr->combined, shr->combined, shr->spec); + /* modulate by the object color */ + if((ma->shade_flag & MA_OBCOLOR) && shi->obr->ob) { + if(!(ma->sss_flag & MA_DIFF_SSS) || !has_sss_tree(&R, ma)) { + float obcol[4]; + + QUATCOPY(obcol, shi->obr->ob->col); + CLAMP(obcol[3], 0.0f, 1.0f); + + shr->combined[0] *= obcol[0]; + shr->combined[1] *= obcol[1]; + shr->combined[2] *= obcol[2]; + shr->alpha *= obcol[3]; + } + } + shr->combined[3]= shr->alpha; } - diff --git a/source/blender/render/intern/source/zbuf.c b/source/blender/render/intern/source/zbuf.c index 29aa6e3be29..be555443605 100644 --- a/source/blender/render/intern/source/zbuf.c +++ b/source/blender/render/intern/source/zbuf.c @@ -2410,7 +2410,7 @@ void zbuffer_shadow(Render *re, float winmat[][4], LampRen *lar, int *rectz, int float obwinmat[4][4], ho1[4], ho2[4], ho3[4], ho4[4]; int a, b, c, i, c1, c2, c3, c4, ok=1, lay= -1; - if(lar->mode & LA_LAYER) lay= lar->lay; + if(lar->mode & (LA_LAYER|LA_LAYER_SHADOW)) lay= lar->lay; /* 1.0f for clipping in clippyra()... bad stuff actually */ zbuf_alloc_span(&zspan, size, size, 1.0f); diff --git a/source/blender/src/CMakeLists.txt b/source/blender/src/CMakeLists.txt index 342579fb3b0..d95551940f8 100644 --- a/source/blender/src/CMakeLists.txt +++ b/source/blender/src/CMakeLists.txt @@ -35,7 +35,7 @@ SET(INC ../../kernel/gen_system ../../../intern/SoundSystem ../readstreamglue ../quicktime ../../../intern/elbeem/extern ../../../intern/ghost ../../../intern/opennl/extern - ../nodes ../../../extern/glew/include + ../nodes ../../../extern/glew/include ../gpu ${PYTHON_INC} ${SDL_INC} ) diff --git a/source/blender/src/Makefile b/source/blender/src/Makefile index 001efc58b5d..46e916b0437 100644 --- a/source/blender/src/Makefile +++ b/source/blender/src/Makefile @@ -68,6 +68,7 @@ CPPFLAGS += -I.. CPPFLAGS += -I../../kernel/gen_system CPPFLAGS += -I../../gameengine/SoundSystem CPPFLAGS += -I../ftfont +CPPFLAGS += -I../gpu # Only used by py_demo.c !!! CPPFLAGS += -I../radiosity/extern/include diff --git a/source/blender/src/SConscript b/source/blender/src/SConscript index 229cc87ef37..c8c517e15ff 100644 --- a/source/blender/src/SConscript +++ b/source/blender/src/SConscript @@ -26,7 +26,8 @@ incs += ' #/intern/bsp/extern ../radiosity/extern/include' incs += ' #/intern/decimation/extern ../blenloader ../python' incs += ' ../../kernel/gen_system #/intern/SoundSystem ../readstreamglue ../nodes' incs += ' ../quicktime #/intern/elbeem/extern' -incs += ' #/intern/ghost #/intern/opennl/extern #/extern/glew/include' +incs += ' #/intern/ghost #/intern/opennl/extern' +incs += ' ../gpu #extern/glew/include' incs += ' ' + env['BF_PYTHON_INC'] diff --git a/source/blender/src/buttons_object.c b/source/blender/src/buttons_object.c index b0d612456d2..18384dd90b3 100644 --- a/source/blender/src/buttons_object.c +++ b/source/blender/src/buttons_object.c @@ -2590,19 +2590,32 @@ static void object_panel_object(Object *ob) /* all groups */ for(group= G.main->group.first; group; group= group->id.next) { if(object_in_group(ob, group)) { - xco= 160; - - uiBlockBeginAlign(block); - uiSetButLock(GET_INT_FROM_POINTER(group->id.lib), ERROR_LIBDATA_MESSAGE); /* We cant actually use this button */ - but = uiDefBut(block, TEX, B_IDNAME, "GR:", 10, 120-yco, 150, 20, group->id.name+2, 0.0, 21.0, 0, 0, "Displays Group name. Click to change."); - uiButSetFunc(but, test_idbutton_cb, group->id.name, NULL); - uiClearButLock(); + xco= 130; if(group->id.lib) { - but= uiDefIconBut(block, BUT, B_NOP, ICON_PARLIB, 160, 120-yco, 20, 20, NULL, 0.0, 0.0, 0.0, 0.0, "Make Group local"); + uiBlockBeginAlign(block); + uiSetButLock(GET_INT_FROM_POINTER(group->id.lib), ERROR_LIBDATA_MESSAGE); /* We cant actually use this button */ + uiDefBut(block, TEX, B_IDNAME, "GR:", 10, 120-yco, 100, 20, group->id.name+2, 0.0, 21.0, 0, 0, "Displays Group name. Click to change."); + uiClearButLock(); + + but= uiDefIconBut(block, BUT, B_NOP, ICON_PARLIB, 110, 120-yco, 20, 20, NULL, 0.0, 0.0, 0.0, 0.0, "Make Group local"); uiButSetFunc(but, group_local, group, NULL); - xco= 180; - } else { /* cant remove objects from linked groups */ + uiBlockEndAlign(block); + } else { + but = uiDefBut(block, TEX, B_IDNAME, "GR:", 10, 120-yco, 120, 20, group->id.name+2, 0.0, 21.0, 0, 0, "Displays Group name. Click to change."); + uiButSetFunc(but, test_idbutton_cb, group->id.name, NULL); + } + + uiSetButLock(GET_INT_FROM_POINTER(group->id.lib), ERROR_LIBDATA_MESSAGE); + uiBlockBeginAlign(block); + uiDefButF(block, NUM, REDRAWALL, "X:", xco+5, 120-yco, 50, 20, &group->dupli_ofs[0], -100000, 100000, 100, 0, "Offset to use when instacing the group"); + uiDefButF(block, NUM, REDRAWALL, "Y:", xco+55, 120-yco, 50, 20, &group->dupli_ofs[1], -100000, 100000, 100, 0, "Offset to use when instacing the group"); + uiDefButF(block, NUM, REDRAWALL, "Z:", xco+105, 120-yco, 50, 20, &group->dupli_ofs[2], -100000, 100000, 100, 0, "Offset to use when instacing the group"); + uiBlockEndAlign(block); + uiClearButLock(); + + xco = 290; + if(group->id.lib==0) { /* cant remove objects from linked groups */ but = uiDefIconBut(block, BUT, B_NOP, VICON_X, xco, 120-yco, 20, 20, NULL, 0.0, 0.0, 0.0, 0.0, "Remove Group membership"); uiButSetFunc(but, group_ob_rem, group, ob); } diff --git a/source/blender/src/buttons_shading.c b/source/blender/src/buttons_shading.c index 1b580381ca5..3f65f686e93 100644 --- a/source/blender/src/buttons_shading.c +++ b/source/blender/src/buttons_shading.c @@ -113,6 +113,8 @@ #include "RE_pipeline.h" +#include "GPU_material.h" + /* -----includes for this file specific----- */ #include "butspace.h" // own module @@ -1542,10 +1544,35 @@ static void texture_panel_colors(Tex *tex) uiDefButF(block, NUMSLI, B_TEXPRV, "Contr", 160,10,150,20, &tex->contrast, 0.01, 5.0, 0, 0, "Changes the contrast of the color or intensity of a texture"); } - -static void texture_panel_texture(MTex *mtex, Material *ma, World *wrld, Lamp *la, bNode *node, Brush *br, SculptData *sd) +static int texture_channels_num_display(MTex **mtex) { - MTex *mt=NULL; + int a, num_mtex; + + if(!mtex) + return 0; + + /* compute number of texture channels to draw, 1 more + * than the last, used texture channel, and at least 10 */ + num_mtex = 0; + + for(a=MAX_MTEX-1; a>=0; a--) { + if (mtex[a]) { + num_mtex = a+1; + break; + } + } + + if (num_mtex < 10) + return 10; + else if(num_mtex < MAX_MTEX) + return num_mtex + 1; + else + return MAX_MTEX; +} + +static void texture_panel_texture(MTex *actmtex, Material *ma, World *wrld, Lamp *la, bNode *node, Brush *br, SculptData *sd) +{ + MTex **mtex, *mt; uiBlock *block; ID *id=NULL, *idfrom; int a, yco, loos; @@ -1556,17 +1583,35 @@ static void texture_panel_texture(MTex *mtex, Material *ma, World *wrld, Lamp *l if(uiNewPanel(curarea, block, "Texture", "Texture", 320, 0, 318, 204)==0) return; /* first do the browse but */ - if(mtex) - id= (ID *)mtex->tex; + if(actmtex) + id= (ID *)actmtex->tex; else if(node) id= node->id; - if(ma) idfrom= &ma->id; - else if(wrld) idfrom= &wrld->id; - else if(la) idfrom= &la->id; - else if(br) idfrom= &br->id; - else if(sd) idfrom= NULL; /* Not sure what this does */ - else idfrom= NULL; + if(ma) { + idfrom= &ma->id; + mtex= ma->mtex; + } + else if(wrld) { + idfrom= &wrld->id; + mtex= wrld->mtex; + } + else if(la) { + idfrom= &la->id; + mtex= la->mtex; + } + else if(br) { + idfrom= &br->id; + mtex= br->mtex; + } + else if(sd) { + idfrom= NULL; /* Not sure what this does */ + mtex= sd->mtex; + } + else { + idfrom= NULL; + mtex= NULL; + } uiBlockSetCol(block, TH_BUT_SETTING2); if(ma) { @@ -1595,15 +1640,13 @@ static void texture_panel_texture(MTex *mtex, Material *ma, World *wrld, Lamp *l /* CHANNELS */ if(node==NULL) { + int num_mtex; uiBlockBeginAlign(block); yco= 150; - for(a= 0; amtex[a]; - else if(wrld) mt= wrld->mtex[a]; - else if(la) mt= la->mtex[a]; - else if(br) mt= br->mtex[a]; - else if(sd) mt= sd->mtex[a]; + + num_mtex= texture_channels_num_display(mtex); + for(a=0; atex) splitIDname(mt->tex->id.name+2, str, &loos); else strcpy(str, ""); @@ -2030,7 +2073,7 @@ static void world_panel_texture(World *wrld) uiBlock *block; MTex *mtex; ID *id; - int a, loos; + int a, loos, num_mtex; char str[64], *strp; block= uiNewBlock(&curarea->uiblocks, "world_panel_texture", UI_EMBOSS, UI_HELV, curarea->win); @@ -2041,7 +2084,8 @@ static void world_panel_texture(World *wrld) /* TEX CHANNELS */ uiBlockSetCol(block, TH_BUT_NEUTRAL); uiBlockBeginAlign(block); - for(a= 0; amtex); + for(a= 0; amtex[a]; if(mtex && mtex->tex) splitIDname(mtex->tex->id.name+2, str, &loos); else strcpy(str, ""); @@ -2506,7 +2550,7 @@ static void lamp_panel_texture(Object *ob, Lamp *la) uiBlock *block; MTex *mtex; ID *id; - int a, loos; + int a, loos, num_mtex; char *strp, str[64]; block= uiNewBlock(&curarea->uiblocks, "lamp_panel_texture", UI_EMBOSS, UI_HELV, curarea->win); @@ -2517,7 +2561,8 @@ static void lamp_panel_texture(Object *ob, Lamp *la) /* TEX CHANNELS */ uiBlockSetCol(block, TH_BUT_NEUTRAL); uiBlockBeginAlign(block); - for(a= 0; amtex); + for(a= 0; amtex[a]; if(mtex && mtex->tex) splitIDname(mtex->tex->id.name+2, str, &loos); else strcpy(str, ""); @@ -2603,9 +2648,9 @@ static void lamp_panel_spot(Object *ob, Lamp *la) uiBlockSetCol(block, TH_BUT_SETTING1); uiBlockBeginAlign(block); - uiDefButBitS(block, TOG, LA_SHAD_RAY, B_SHADRAY,"Ray Shadow",10,180,80,19,&la->mode, 0, 0, 0, 0, "Use ray tracing for shadow"); + uiDefButBitI(block, TOG, LA_SHAD_RAY, B_SHADRAY,"Ray Shadow",10,180,80,19,&la->mode, 0, 0, 0, 0, "Use ray tracing for shadow"); if(la->type==LA_SPOT) { - uiDefButBitS(block, TOG, LA_SHAD_BUF, B_SHADBUF, "Buf.Shadow",10,160,80,19,&la->mode, 0, 0, 0, 0, "Lets spotlight produce shadows using shadow buffer"); + uiDefButBitI(block, TOG, LA_SHAD_BUF, B_SHADBUF, "Buf.Shadow",10,160,80,19,&la->mode, 0, 0, 0, 0, "Lets spotlight produce shadows using shadow buffer"); if(la->mode & LA_SHAD_BUF) { char *tip= "Regular buffer type"; if(la->buftype==LA_SHADBUF_IRREGULAR) @@ -2618,12 +2663,15 @@ static void lamp_panel_spot(Object *ob, Lamp *la) } uiBlockEndAlign(block); - uiDefButBitS(block, TOG, LA_ONLYSHADOW, B_LAMPPRV,"OnlyShadow", 10,110,80,19,&la->mode, 0, 0, 0, 0, "Causes light to cast shadows only without illuminating objects"); + uiBlockBeginAlign(block); + uiDefButBitI(block, TOG, LA_ONLYSHADOW, B_LAMPPRV,"OnlyShadow", 10,110,80,19,&la->mode, 0, 0, 0, 0, "Causes light to cast shadows only without illuminating objects"); + uiDefButBitI(block, TOG, LA_LAYER_SHADOW, B_LAMPPRV,"Layer", 10,90,80,19,&la->mode, 0, 0, 0, 0, "Causes only objects on the same layer to cast shadows"); + uiBlockEndAlign(block); if(la->type==LA_SPOT) { uiBlockBeginAlign(block); - uiDefButBitS(block, TOG, LA_SQUARE, B_LAMPREDRAW,"Square", 10,60,80,19,&la->mode, 0, 0, 0, 0, "Sets square spotbundles"); - uiDefButBitS(block, TOG, LA_HALO, B_LAMPREDRAW,"Halo", 10,40,80,19,&la->mode, 0, 0, 0, 0, "Renders spotlight with a volumetric halo"); + uiDefButBitI(block, TOG, LA_SQUARE, B_LAMPREDRAW,"Square", 10,60,80,19,&la->mode, 0, 0, 0, 0, "Sets square spotbundles"); + uiDefButBitI(block, TOG, LA_HALO, B_LAMPREDRAW,"Halo", 10,40,80,19,&la->mode, 0, 0, 0, 0, "Renders spotlight with a volumetric halo"); uiBlockBeginAlign(block); uiDefButF(block, NUMSLI,B_LAMPREDRAW,"SpotSi ", 100,180,200,19,&la->spotsize, 1.0, 180.0, 0, 0, "Sets the angle of the spotlight beam in degrees"); @@ -2747,12 +2795,12 @@ static void lamp_panel_yafray(Object *ob, Lamp *la) /* in yafray arealights always cast shadows, so ray shadow flag not needed */ /* ray shadow also not used when halo for spot enabled */ if ((la->type!=LA_AREA) && (!((la->type==LA_SPOT) && (la->mode & LA_HALO)))) - uiDefButBitS(block, TOG, LA_SHAD_RAY, B_SHADRAY,"Ray Shadow",10,180,80,19,&la->mode, 0, 0, 0, 0, "Use ray tracing for shadow"); + uiDefButBitI(block, TOG, LA_SHAD_RAY, B_SHADRAY,"Ray Shadow",10,180,80,19,&la->mode, 0, 0, 0, 0, "Use ray tracing for shadow"); /* in yafray the regular lamp can use shadowbuffers (softlight), used by spot with halo as well */ /* to prevent clash with blender shadowbuf flag, a special flag is used for yafray */ if (la->type==LA_LOCAL) { - uiDefButBitS(block, TOG, LA_YF_SOFT, B_SHADBUF, "Buf.Shadow",10,160,80,19,&la->mode, 0, 0, 0, 0, "Lets light produce shadows using shadow buffer"); + uiDefButBitI(block, TOG, LA_YF_SOFT, B_SHADBUF, "Buf.Shadow",10,160,80,19,&la->mode, 0, 0, 0, 0, "Lets light produce shadows using shadow buffer"); uiDefButF(block, NUM, B_DIFF, "GloInt:", 100,155,200,19, &la->YF_glowint, 0.0, 1.0, 1, 0, "Sets light glow intensity, 0 is off"); uiDefButF(block, NUM, B_DIFF, "GloOfs:", 100,135,100,19, &la->YF_glowofs, 0.0, 2.0, 1, 0, "Sets light glow offset, the higher, the less 'peaked' the glow"); uiDefButS(block, NUM, B_DIFF, "GlowType:", 200,135,100,19, &la->YF_glowtype, 0, 1, 1, 0, "Sets light glow type"); @@ -2780,7 +2828,7 @@ static void lamp_panel_yafray(Object *ob, Lamp *la) if (la->type==LA_SPOT) { - uiDefButBitS(block, TOG, LA_HALO, B_LAMPREDRAW,"Halo", 10,50,80,19,&la->mode, 0, 0, 0, 0, "Renders spotlight with a volumetric halo"); + uiDefButBitI(block, TOG, LA_HALO, B_LAMPREDRAW,"Halo", 10,50,80,19,&la->mode, 0, 0, 0, 0, "Renders spotlight with a volumetric halo"); uiBlockSetCol(block, TH_AUTO); uiBlockBeginAlign(block); @@ -2900,15 +2948,15 @@ static void lamp_panel_lamp(Object *ob, Lamp *la) uiBlockSetCol(block, TH_BUT_SETTING1); uiDefButS(block, MENU, B_LAMPREDRAW, "Falloff %t|Constant %x0|Inverse Linear %x1|Inverse Square %x2|Custom Curve %x3|Lin/Quad Weighted %x4|", 10,150,100,19, &la->falloff_type, 0,0,0,0, "Lamp falloff - intensity decay with distance"); - uiDefButBitS(block, TOG, LA_SPHERE, B_LAMPPRV,"Sphere", 10,130,100,19,&la->mode, 0, 0, 0, 0, "Sets light intensity to zero for objects beyond the distance value"); + uiDefButBitI(block, TOG, LA_SPHERE, B_LAMPPRV,"Sphere", 10,130,100,19,&la->mode, 0, 0, 0, 0, "Sets light intensity to zero for objects beyond the distance value"); } uiBlockBeginAlign(block); uiBlockSetCol(block, TH_BUT_SETTING1); - uiDefButBitS(block, TOG, LA_LAYER, 0,"Layer", 10,70,100,19,&la->mode, 0, 0, 0, 0, "Illuminates objects in the same layer as the lamp only"); - uiDefButBitS(block, TOG, LA_NEG, B_LAMPPRV,"Negative", 10,50,100,19,&la->mode, 0, 0, 0, 0, "Sets lamp to cast negative light"); - uiDefButBitS(block, TOG, LA_NO_DIFF, B_LAMPPRV,"No Diffuse", 10,30,100,19,&la->mode, 0, 0, 0, 0, "Disables diffuse shading of material illuminated by this lamp"); - uiDefButBitS(block, TOG, LA_NO_SPEC, B_LAMPPRV,"No Specular", 10,10,100,19,&la->mode, 0, 0, 0, 0, "Disables specular shading of material illuminated by this lamp"); + uiDefButBitI(block, TOG, LA_LAYER, 0,"Layer", 10,70,100,19,&la->mode, 0, 0, 0, 0, "Illuminates objects in the same layer as the lamp only"); + uiDefButBitI(block, TOG, LA_NEG, B_LAMPPRV,"Negative", 10,50,100,19,&la->mode, 0, 0, 0, 0, "Sets lamp to cast negative light"); + uiDefButBitI(block, TOG, LA_NO_DIFF, B_LAMPPRV,"No Diffuse", 10,30,100,19,&la->mode, 0, 0, 0, 0, "Disables diffuse shading of material illuminated by this lamp"); + uiDefButBitI(block, TOG, LA_NO_SPEC, B_LAMPPRV,"No Specular", 10,10,100,19,&la->mode, 0, 0, 0, 0, "Disables specular shading of material illuminated by this lamp"); uiBlockEndAlign(block); uiBlockSetCol(block, TH_AUTO); @@ -3523,7 +3571,7 @@ static void material_panel_texture(Object *ob, Material *ma) ID *id; ParticleSystem *psys; int loos, psys_mapto=0; - int a; + int a, num_mtex; char str[64], *strp; block= uiNewBlock(&curarea->uiblocks, "material_panel_texture", UI_EMBOSS, UI_HELV, curarea->win); @@ -3539,7 +3587,8 @@ static void material_panel_texture(Object *ob, Material *ma) uiBlockSetCol(block, TH_BUT_NEUTRAL); uiBlockBeginAlign(block); - for(a= 0; amtex); + for(a= 0; amtex[a]; if(mtex && mtex->tex) splitIDname(mtex->tex->id.name+2, str, &loos); else strcpy(str, ""); @@ -3553,10 +3602,10 @@ static void material_panel_texture(Object *ob, Material *ma) /* SEPTEX */ uiBlockSetCol(block, TH_AUTO); - for(a= 0; amtex[a]; if(mtex && mtex->tex) { - but=uiDefIconButBitS(block, ICONTOGN, 1<septex, 0.0, 0.0, 0, 0, "Click to disable or enable this texture channel"); + but=uiDefIconButBitI(block, ICONTOGN, 1<septex, 0.0, 0.0, 0, 0, "Click to disable or enable this texture channel"); if(psys_mapto && ma->mtex[a]->mapto & MAP_PA_IVEL) uiButSetFunc(but, particle_recalc_material, ma, NULL); @@ -4091,13 +4140,14 @@ static void material_panel_material(Material *ma) uiBlockSetCol(block, TH_BUT_SETTING1); uiDefButBitI(block, TOG, MA_VERTEXCOL, B_MAT_VCOL_LIGHT, "VCol Light", 8,166,74,20, &(ma->mode), 0, 0, 0, 0, "Adds vertex colors as extra light"); uiDefButBitI(block, TOG, MA_VERTEXCOLP, B_MAT_VCOL_PAINT, "VCol Paint", 82,166,74,20, &(ma->mode), 0, 0, 0, 0, "Replaces material's colors with vertex colors"); - uiDefButBitI(block, TOG, MA_FACETEXTURE, B_REDR, "TexFace", 156,166,64,20, &(ma->mode), 0, 0, 0, 0, "Sets UV-Editor assigned texture as color and texture info for faces"); - if (ma->mode & MA_FACETEXTURE) uiDefButBitI(block, TOG, MA_FACETEXTURE_ALPHA, B_REDR, "A", 220,166,20,20, &(ma->mode), 0, 0, 0, 0, "Use alpha channel in 'TexFace' assigned images"); - uiDefButBitI(block, TOG, MA_SHLESS, B_MATPRV, "Shadeless", 240,166,63,20, &(ma->mode), 0, 0, 0, 0, "Makes material insensitive to light or shadow"); + uiDefButBitI(block, TOG, MA_FACETEXTURE, B_MATPRV, "TexFace", 156,166,60,20, &(ma->mode), 0, 0, 0, 0, "Sets UV-Editor assigned texture as color and texture info for faces"); + uiDefButBitI(block, TOG, MA_FACETEXTURE_ALPHA, B_MATPRV, "A", 216,166,20,20, &(ma->mode), 0, 0, 0, 0, "Use alpha channel in 'TexFace' assigned images"); + uiDefButBitI(block, TOG, MA_SHLESS, B_MATPRV, "Shadeless", 236,166,67,20, &(ma->mode), 0, 0, 0, 0, "Makes material insensitive to light or shadow"); - uiDefButBitI(block, TOG, MA_NOMIST, B_NOP, "No Mist", 8,146,74,20, &(ma->mode), 0, 0, 0, 0, "Sets the material to ignore mist values"); + uiDefButBitI(block, TOG, MA_NOMIST, B_MATPRV, "No Mist", 8,146,74,20, &(ma->mode), 0, 0, 0, 0, "Sets the material to ignore mist values"); uiDefButBitI(block, TOG, MA_ENV, B_MATPRV, "Env", 82,146,74,20, &(ma->mode), 0, 0, 0, 0, "Causes faces to render with alpha zero: allows sky/backdrop to show through (only for solid faces)"); - uiDefButF(block, NUM, B_NOP, "Shad A ", 156,146,147,19, &ma->shad_alpha, 0.001, 1.0f, 100, 0, "Shadow casting alpha, only in use for Irregular Shadowbuffer"); + uiDefButBitS(block, TOG, MA_OBCOLOR, B_MATPRV, "ObColor", 156,146,60,20, &(ma->shade_flag), 0, 0, 0, 0, "Modulate the result with a per object color"); + uiDefButF(block, NUM, B_NOP, "Shad A ", 216,146,87,20, &ma->shad_alpha, 0.001, 1.0f, 10, 2, "Shadow casting alpha, only in use for Irregular Shadowbuffer"); } uiBlockSetCol(block, TH_AUTO); uiBlockBeginAlign(block); diff --git a/source/blender/src/drawarmature.c b/source/blender/src/drawarmature.c index 6d78b21dfbb..c37eaf7986c 100644 --- a/source/blender/src/drawarmature.c +++ b/source/blender/src/drawarmature.c @@ -2505,6 +2505,9 @@ int draw_armature(Base *base, int dt, int flag) Object *ob= base->object; bArmature *arm= ob->data; int retval= 0; + + if(G.f & G_SIMULATION) + return 1; if(dt>OB_WIRE && arm->drawtype!=ARM_LINE) { /* we use color for solid lighting */ diff --git a/source/blender/src/drawmesh.c b/source/blender/src/drawmesh.c index 09f74c01c71..8f22c704fd0 100644 --- a/source/blender/src/drawmesh.c +++ b/source/blender/src/drawmesh.c @@ -76,534 +76,12 @@ #include "BSE_drawview.h" +#include "GPU_extensions.h" +#include "GPU_draw.h" + #include "blendef.h" #include "nla.h" -#ifndef GL_CLAMP_TO_EDGE -#define GL_CLAMP_TO_EDGE 0x812F -#endif - -//#include "glext.h" -/* some local functions */ -#if defined(GL_EXT_texture_object) && (!defined(__sun__) || (!defined(__sun))) && !defined(__APPLE__) && !defined(__linux__) && !defined(WIN32) - #define glBindTexture(A,B) glBindTextureEXT(A,B) - #define glGenTextures(A,B) glGenTexturesEXT(A,B) - #define glDeleteTextures(A,B) glDeleteTexturesEXT(A,B) - #define glPolygonOffset(A,B) glPolygonOffsetEXT(A,B) - -#else - -/* #define GL_FUNC_ADD_EXT GL_FUNC_ADD */ -/* #define GL_FUNC_REVERSE_SUBTRACT_EXT GL_FUNC_REVERSE_SUBTRACT */ -/* #define GL_POLYGON_OFFSET_EXT GL_POLYGON_OFFSET */ - -#endif - - /* (n&(n-1)) zeros the least significant bit of n */ -static int is_pow2(int num) { - return ((num)&(num-1))==0; -} -static int smaller_pow2(int num) { - while (!is_pow2(num)) - num= num&(num-1); - return num; -} - -/* These are used to enable texture clamping */ -static int is_pow2_limit(int num) { - if (U.glreslimit != 0 && num > U.glreslimit) return 0; - return ((num)&(num-1))==0; -} - -static int smaller_pow2_limit(int num) { - if (U.glreslimit != 0 && num > U.glreslimit) - return U.glreslimit; - return smaller_pow2(num); -} - -static int fCurtile=0, fCurmode=0,fCurtileXRep=0,fCurtileYRep=0; -static Image *fCurpage=0; -static short fTexwindx, fTexwindy, fTexwinsx, fTexwinsy; -static int fDoMipMap = 1; -static int fLinearMipMap = 0; - -/* local prototypes --------------- */ -void update_realtime_textures(void); - - -/* static int source, dest; also not used */ - -/** - * Enables or disable mipmapping for realtime images. - * @param mipmap Turn mipmapping on (mipmap!=0) or off (mipmap==0). - */ -void set_mipmap(int mipmap) -{ - if (fDoMipMap != (mipmap != 0)) { - free_all_realtime_images(); - fDoMipMap = mipmap != 0; - } -} - -/** - * Returns the current setting for mipmapping. - */ -static int get_mipmap(void) -{ - return fDoMipMap && (!(G.f & G_TEXTUREPAINT)); -} - -/** - * Enables or disable linear mipmap setting for realtime images (textures). - * Note that this will will destroy all texture bindings in OpenGL. - * @see free_realtime_image() - * @param mipmap Turn linear mipmapping on (linear!=0) or off (linear==0). - */ -void set_linear_mipmap(int linear) -{ - if (fLinearMipMap != (linear != 0)) { - free_all_realtime_images(); - fLinearMipMap = linear != 0; - } -} - -/** - * Returns the current setting for linear mipmapping. - */ -int get_linear_mipmap(void) -{ - return fLinearMipMap; -} - - -/** - * Resets the realtime image cache variables. - */ -void clear_realtime_image_cache() -{ - fCurpage = NULL; - fCurtile = 0; - fCurmode = 0; - fCurtileXRep = 0; - fCurtileYRep = 0; -} - -/* REMEMBER! Changes here must go into my_set_tpage() as well */ -int set_tpage(MTFace *tface) -{ - static int alphamode= -1; - static MTFace *lasttface= 0; - Image *ima; - ImBuf *ibuf; - unsigned int *rect=NULL, *bind; - int tpx=0, tpy=0, tilemode, tileXRep,tileYRep; - - /* disable */ - if(tface==0) { - if(lasttface==0) return 0; - - lasttface= 0; - fCurtile= 0; - fCurpage= 0; - if(fCurmode!=0) { - glMatrixMode(GL_TEXTURE); - glLoadIdentity(); - glMatrixMode(GL_MODELVIEW); - } - fCurmode= 0; - fCurtileXRep=0; - fCurtileYRep=0; - alphamode= -1; - - glDisable(GL_BLEND); - glDisable(GL_TEXTURE_2D); - glDisable(GL_TEXTURE_GEN_S); - glDisable(GL_TEXTURE_GEN_T); - glDisable ( GL_ALPHA_TEST ); - return 0; - } - lasttface= tface; - - if( alphamode != tface->transp) { - alphamode= tface->transp; - - if(alphamode) { - if(alphamode==TF_ADD) { - glEnable(GL_BLEND); - glBlendFunc(GL_ONE, GL_ONE); - glDisable ( GL_ALPHA_TEST ); - /* glBlendEquationEXT(GL_FUNC_ADD_EXT); */ - } - else if(alphamode==TF_ALPHA) { - glEnable(GL_BLEND); - glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); - - /* added after 2.45 to clip alpha */ - - /*if U.glalphaclip == 1.0, some cards go bonkers... turn off alpha test in this case*/ - if(U.glalphaclip == 1.0) glDisable(GL_ALPHA_TEST); - else{ - glEnable ( GL_ALPHA_TEST ); - glAlphaFunc ( GL_GREATER, U.glalphaclip ); - } - } else if (alphamode==TF_CLIP){ - glDisable(GL_BLEND); - glEnable ( GL_ALPHA_TEST ); - glAlphaFunc(GL_GREATER, 0.5f); - } - /* glBlendEquationEXT(GL_FUNC_ADD_EXT); */ - /* else { */ - /* glBlendFunc(GL_ONE, GL_ONE); */ - /* glBlendEquationEXT(GL_FUNC_REVERSE_SUBTRACT_EXT); */ - /* } */ - } else { - glDisable(GL_BLEND); - glDisable ( GL_ALPHA_TEST ); - } - } - - ima= tface->tpage; - - /* Enable or disable reflection mapping */ - if (ima && (ima->flag & IMA_REFLECT)){ - -// glActiveTextureARB(GL_TEXTURE0_ARB); - glTexGeni(GL_S, GL_TEXTURE_GEN_MODE, GL_SPHERE_MAP); - glTexGeni(GL_T, GL_TEXTURE_GEN_MODE, GL_SPHERE_MAP); - - glEnable(GL_TEXTURE_GEN_S); - glEnable(GL_TEXTURE_GEN_T); - - /* Handle multitexturing here */ - } - else{ - glDisable(GL_TEXTURE_GEN_S); - glDisable(GL_TEXTURE_GEN_T); - } - - tilemode= tface->mode & TF_TILES; - tileXRep = 0; - tileYRep = 0; - if (ima) { - tileXRep = ima->xrep; - tileYRep = ima->yrep; - } - - - if(ima==fCurpage && fCurtile==tface->tile && tilemode==fCurmode && fCurtileXRep==tileXRep && fCurtileYRep == tileYRep) return ima!=0; - - if(tilemode!=fCurmode || fCurtileXRep!=tileXRep || fCurtileYRep != tileYRep) { - glMatrixMode(GL_TEXTURE); - glLoadIdentity(); - - if(tilemode && ima!=NULL) - glScalef(ima->xrep, ima->yrep, 1.0); - - glMatrixMode(GL_MODELVIEW); - } - - if(ima==NULL || ima->ok==0) { - glDisable(GL_TEXTURE_2D); - - fCurtile= tface->tile; - fCurpage= 0; - fCurmode= tilemode; - fCurtileXRep = tileXRep; - fCurtileYRep = tileYRep; - - return 0; - } - - ibuf= BKE_image_get_ibuf(ima, NULL); - if(ibuf==NULL) { - - fCurtile= tface->tile; - fCurpage= 0; - fCurmode= tilemode; - fCurtileXRep = tileXRep; - fCurtileYRep = tileYRep; - - glDisable(GL_TEXTURE_2D); - return 0; - } - - if ((ibuf->rect==NULL) && ibuf->rect_float) - IMB_rect_from_float(ibuf); - - if(ima->tpageflag & IMA_TWINANIM) fCurtile= ima->lastframe; - else fCurtile= tface->tile; - - if(tilemode) { - if(ima->repbind==0) make_repbind(ima); - - if(fCurtile>=ima->totbind) fCurtile= 0; - - /* this happens when you change repeat buttons */ - if(ima->repbind) bind= ima->repbind+fCurtile; - else bind= &ima->bindcode; - - if(*bind==0) { - - fTexwindx= ibuf->x/ima->xrep; - fTexwindy= ibuf->y/ima->yrep; - - if(fCurtile>=ima->xrep*ima->yrep) fCurtile= ima->xrep*ima->yrep-1; - - fTexwinsy= fCurtile / ima->xrep; - fTexwinsx= fCurtile - fTexwinsy*ima->xrep; - - fTexwinsx*= fTexwindx; - fTexwinsy*= fTexwindy; - - tpx= fTexwindx; - tpy= fTexwindy; - - rect= ibuf->rect + fTexwinsy*ibuf->x + fTexwinsx; - } - } - else { - bind= &ima->bindcode; - - if(*bind==0) { - tpx= ibuf->x; - tpy= ibuf->y; - rect= ibuf->rect; - } - } - - if(*bind==0) { - int rectw= tpx, recth= tpy; - unsigned int *tilerect= NULL, *scalerect= NULL; - - /* - * Maarten: - * According to Ton this code is not needed anymore. It was used only - * in really old Blenders. - * Reevan: - * Actually it is needed for backwards compatibility. Simpledemo 6 does not display correctly without it. - */ -#if 1 - if (tilemode) { - int y; - - tilerect= MEM_mallocN(rectw*recth*sizeof(*tilerect), "tilerect"); - for (y=0; yx]; - unsigned int *tilerectrow= &tilerect[y*rectw]; - - memcpy(tilerectrow, rectrow, tpx*sizeof(*rectrow)); - } - - rect= tilerect; - } -#endif - if (!is_pow2_limit(rectw) || !is_pow2_limit(recth)) { - rectw= smaller_pow2_limit(rectw); - recth= smaller_pow2_limit(recth); - - scalerect= MEM_mallocN(rectw*recth*sizeof(*scalerect), "scalerect"); - gluScaleImage(GL_RGBA, tpx, tpy, GL_UNSIGNED_BYTE, rect, rectw, recth, GL_UNSIGNED_BYTE, scalerect); - rect= scalerect; - } - - glGenTextures(1, (GLuint *)bind); - - if((G.f & G_DEBUG) || !*bind) { - GLenum error = glGetError(); - printf("Texture: %s\n", ima->id.name+2); - printf("name: %d, tpx: %d\n", *bind, tpx); - printf("tile: %d, mode: %d\n", fCurtile, tilemode); - if (error) - printf("error: %s\n", gluErrorString(error)); - } - glBindTexture( GL_TEXTURE_2D, *bind); - - if (!get_mipmap()) - { - glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, rectw, recth, 0, GL_RGBA, GL_UNSIGNED_BYTE, rect); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); - } else - { - int minfilter= fLinearMipMap?GL_LINEAR_MIPMAP_LINEAR:GL_LINEAR_MIPMAP_NEAREST; - - gluBuild2DMipmaps(GL_TEXTURE_2D, GL_RGBA, rectw, recth, GL_RGBA, GL_UNSIGNED_BYTE, rect); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, minfilter); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); - - ima->tpageflag |= IMA_MIPMAP_COMPLETE; - } - - glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE); - - if (tilerect) - MEM_freeN(tilerect); - if (scalerect) - MEM_freeN(scalerect); - } - else glBindTexture( GL_TEXTURE_2D, *bind); - - /* dont tile x/y as set the the game properties */ - if (ima->tpageflag & IMA_CLAMP_U) - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); - else - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); - if (ima->tpageflag & IMA_CLAMP_V) - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); - else - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); - - /* tag_image_time(ima);*/ /* Did this get lost in the image recode? */ - - glEnable(GL_TEXTURE_2D); - - fCurpage= ima; - fCurmode= tilemode; - fCurtileXRep = tileXRep; - fCurtileYRep = tileYRep; - - return 1; -} - -void update_realtime_image(Image *ima, int x, int y, int w, int h) -{ - ImBuf *ibuf= BKE_image_get_ibuf(ima, NULL); - - if (ima->repbind || get_mipmap() || !ima->bindcode || !ibuf || - (!is_pow2(ibuf->x) || !is_pow2(ibuf->y)) || - (w == 0) || (h == 0)) { - /* these special cases require full reload still */ - free_realtime_image(ima); - } - else { - int row_length = glaGetOneInteger(GL_UNPACK_ROW_LENGTH); - int skip_pixels = glaGetOneInteger(GL_UNPACK_SKIP_PIXELS); - int skip_rows = glaGetOneInteger(GL_UNPACK_SKIP_ROWS); - - if ((ibuf->rect==NULL) && ibuf->rect_float) - IMB_rect_from_float(ibuf); - - glBindTexture(GL_TEXTURE_2D, ima->bindcode); - - glPixelStorei(GL_UNPACK_ROW_LENGTH, ibuf->x); - glPixelStorei(GL_UNPACK_SKIP_PIXELS, x); - glPixelStorei(GL_UNPACK_SKIP_ROWS, y); - - glTexSubImage2D(GL_TEXTURE_2D, 0, x, y, w, h, GL_RGBA, - GL_UNSIGNED_BYTE, ibuf->rect); - - glPixelStorei(GL_UNPACK_ROW_LENGTH, row_length); - glPixelStorei(GL_UNPACK_SKIP_PIXELS, skip_pixels); - glPixelStorei(GL_UNPACK_SKIP_ROWS, skip_rows); - - if(ima->tpageflag & IMA_MIPMAP_COMPLETE) - ima->tpageflag &= ~IMA_MIPMAP_COMPLETE; - } -} - -void free_realtime_image(Image *ima) -{ - if(ima->bindcode) { - glDeleteTextures(1, (GLuint *)&ima->bindcode); - ima->bindcode= 0; - ima->tpageflag &= ~IMA_MIPMAP_COMPLETE; - } - if(ima->repbind) { - glDeleteTextures(ima->totbind, (GLuint *)ima->repbind); - - MEM_freeN(ima->repbind); - ima->repbind= NULL; - ima->tpageflag &= ~IMA_MIPMAP_COMPLETE; - } -} - -void free_all_realtime_images(void) -{ - Image* ima; - - for(ima=G.main->image.first; ima; ima=ima->id.next) - free_realtime_image(ima); -} - -/* these two functions are called on entering and exiting texture paint mode, - temporary disabling/enabling mipmapping on all images for quick texture - updates with glTexSubImage2D. images that didn't change don't have to be - re-uploaded to OpenGL */ -void texpaint_disable_mipmap(void) -{ - Image* ima; - - if(!fDoMipMap) - return; - - for(ima=G.main->image.first; ima; ima=ima->id.next) { - if(ima->bindcode) { - glBindTexture(GL_TEXTURE_2D, ima->bindcode); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); - } - } -} - -void texpaint_enable_mipmap(void) -{ - Image* ima; - - if(!fDoMipMap) - return; - - for(ima=G.main->image.first; ima; ima=ima->id.next) { - if(ima->bindcode) { - if(ima->tpageflag & IMA_MIPMAP_COMPLETE) { - int minfilter= fLinearMipMap?GL_LINEAR_MIPMAP_LINEAR:GL_LINEAR_MIPMAP_NEAREST; - - glBindTexture(GL_TEXTURE_2D, ima->bindcode); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, minfilter); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); - } - else - free_realtime_image(ima); - } - } -} - -void make_repbind(Image *ima) -{ - ImBuf *ibuf= BKE_image_get_ibuf(ima, NULL); - - if(ibuf==NULL) return; - - if(ima->repbind) { - glDeleteTextures(ima->totbind, (GLuint *)ima->repbind); - MEM_freeN(ima->repbind); - ima->repbind= 0; - ima->tpageflag &= ~IMA_MIPMAP_COMPLETE; - } - ima->totbind= ima->xrep*ima->yrep; - if(ima->totbind>1) { - ima->repbind= MEM_callocN(sizeof(int)*ima->totbind, "repbind"); - } -} - -void update_realtime_textures() -{ - Image *ima; - - ima= G.main->image.first; - while(ima) { - if(ima->tpageflag & IMA_TWINANIM) { - if(ima->twend >= ima->xrep*ima->yrep) ima->twend= ima->xrep*ima->yrep-1; - - /* check: is bindcode not in the array? Free. (to do) */ - - ima->lastframe++; - if(ima->lastframe > ima->twend) ima->lastframe= ima->twsta; - - } - ima= ima->id.next; - } -} - /***/ /* Flags for marked edges */ @@ -627,7 +105,7 @@ static void get_marked_edge_info__orFlags(EdgeHash *eh, int v0, int v1, int flag *flags_p |= flags; } -EdgeHash *get_tface_mesh_marked_edge_info(Mesh *me) +static EdgeHash *get_tface_mesh_marked_edge_info(Mesh *me) { EdgeHash *eh = BLI_edgehash_new(); int i; @@ -775,81 +253,6 @@ static void draw_tfaces3D(Object *ob, Mesh *me, DerivedMesh *dm) BLI_edgehash_free(data.eh, NULL); } -static int set_gl_light(Object *ob) -{ - Base *base; - Lamp *la; - int count; - /* float zero[4]= {0.0, 0.0, 0.0, 0.0}; */ - float vec[4]; - - vec[3]= 1.0; - - for(count=0; count<8; count++) glDisable(GL_LIGHT0+count); - - count= 0; - - base= FIRSTBASE; - while(base) { - if(base->object->type==OB_LAMP ) { - if(base->lay & G.vd->lay) { - if(base->lay & ob->lay) - { - la= base->object->data; - - glPushMatrix(); - glLoadMatrixf((float *)G.vd->viewmat); - - where_is_object_simul(base->object); - VECCOPY(vec, base->object->obmat[3]); - - if(la->type==LA_SUN) { - vec[0]= base->object->obmat[2][0]; - vec[1]= base->object->obmat[2][1]; - vec[2]= base->object->obmat[2][2]; - vec[3]= 0.0; - glLightfv(GL_LIGHT0+count, GL_POSITION, vec); - } - else { - vec[3]= 1.0; - glLightfv(GL_LIGHT0+count, GL_POSITION, vec); - glLightf(GL_LIGHT0+count, GL_CONSTANT_ATTENUATION, 1.0); - glLightf(GL_LIGHT0+count, GL_LINEAR_ATTENUATION, la->att1/la->dist); - /* post 2.25 engine supports quad lights */ - glLightf(GL_LIGHT0+count, GL_QUADRATIC_ATTENUATION, la->att2/(la->dist*la->dist)); - - if(la->type==LA_SPOT) { - vec[0]= -base->object->obmat[2][0]; - vec[1]= -base->object->obmat[2][1]; - vec[2]= -base->object->obmat[2][2]; - glLightfv(GL_LIGHT0+count, GL_SPOT_DIRECTION, vec); - glLightf(GL_LIGHT0+count, GL_SPOT_CUTOFF, la->spotsize/2.0); - glLightf(GL_LIGHT0+count, GL_SPOT_EXPONENT, 128.0*la->spotblend); - } - else glLightf(GL_LIGHT0+count, GL_SPOT_CUTOFF, 180.0); - } - - vec[0]= la->energy*la->r; - vec[1]= la->energy*la->g; - vec[2]= la->energy*la->b; - vec[3]= 1.0; - glLightfv(GL_LIGHT0+count, GL_DIFFUSE, vec); - glLightfv(GL_LIGHT0+count, GL_SPECULAR, vec);//zero); - glEnable(GL_LIGHT0+count); - - glPopMatrix(); - - count++; - if(count>7) break; - } - } - } - base= base->next; - } - - return count; -} - static Material *give_current_material_or_def(Object *ob, int matnr) { extern Material defmaterial; // render module abuse... @@ -893,9 +296,9 @@ static int set_draw_settings_cached(int clearcache, int textured, MTFace *texfac if (textured!=c_textured || texface!=c_texface) { if (textured ) { - c_badtex= !set_tpage(texface); + c_badtex= !GPU_set_tpage(texface); } else { - set_tpage(0); + GPU_set_tpage(0); c_badtex= 0; } c_textured= textured; @@ -950,7 +353,7 @@ static void draw_textured_begin(Object *ob) } else /* draw with lights in the scene otherwise */ - Gtexdraw.islit= set_gl_light(ob); + Gtexdraw.islit= GPU_scene_object_lights(G.scene, ob, G.vd->lay, G.vd->viewmat); obcol[0]= CLAMPIS(ob->col[0]*255, 0, 255); obcol[1]= CLAMPIS(ob->col[1]*255, 0, 255); @@ -971,12 +374,12 @@ static void draw_textured_begin(Object *ob) static void draw_textured_end() { /* switch off textures */ - set_tpage(0); + GPU_set_tpage(0); glShadeModel(GL_FLAT); glDisable(GL_CULL_FACE); - /* XXX, bad patch - default_gl_light() calls + /* XXX, bad patch - GPU_default_lights() calls * glLightfv(GL_LIGHT_POSITION, ...) which * is transformed by the current matrix... we * need to make sure that matrix is identity. @@ -987,7 +390,7 @@ static void draw_textured_end() */ glPushMatrix(); glLoadIdentity(); - default_gl_light(); + GPU_default_lights(); glPopMatrix(); } @@ -1057,50 +460,71 @@ static int wpaint__setSolidDrawOptions(void *userData, int index, int *drawSmoot return 1; } -static void draw_game_text_mesh(Object *ob, Mesh *me) +void draw_mesh_text(Object *ob, int glsl) { - DerivedMesh *ddm = mesh_get_derived_deform(ob, CD_MASK_BAREMESH); - MFace *mface= me->mface; + Mesh *me = ob->data; + DerivedMesh *ddm; + MFace *mf, *mface= me->mface; MTFace *tface= me->mtface; MCol *mcol= me->mcol; /* why does mcol exist? */ bProperty *prop = get_property(ob, "Text"); - int a, start= 0, totface= me->totface; + GPUVertexAttribs gattribs; + int a, totface= me->totface; - tface+= start; - mcol+= start*4; - for (a=start; amode; int matnr= mf->mat_nr; int mf_smooth= mf->flag & ME_SMOOTH; if (!(mf->flag&ME_HIDE) && !(mode&TF_INVISIBLE) && (mode&TF_BMFONT)) { - int badtex= set_draw_settings_cached(0, Gtexdraw.istex, tface, Gtexdraw.islit, Gtexdraw.ob, matnr, TF_TWOSIDE); float v1[3], v2[3], v3[3], v4[3]; char string[MAX_PROPSTRING]; - int characters, index; - ImBuf *ibuf; - float curpos; + int characters, i, glattrib= -1, badtex= 0; - if (badtex) - continue; + if(glsl) { + GPU_enable_material(matnr+1, &gattribs); + + for(i=0; igetVertCo(ddm, mf->v1, v1); ddm->getVertCo(ddm, mf->v2, v2); ddm->getVertCo(ddm, mf->v3, v3); if (mf->v4) ddm->getVertCo(ddm, mf->v4, v4); - // The BM_FONT handling code is duplicated in the gameengine - // Search for 'Frank van Beek' ;-) - // string = "Frank van Beek"; + // The BM_FONT handling is in the gpu module, shared with the + // game engine, was duplicated previously set_property_valstr(prop, string); characters = strlen(string); - ibuf= BKE_image_get_ibuf(tface->tpage, NULL); - if (ibuf == NULL) { + if(!BKE_image_get_ibuf(tface->tpage, NULL)) characters = 0; - } if (!mf_smooth) { float nor[3]; @@ -1110,46 +534,11 @@ static void draw_game_text_mesh(Object *ob, Mesh *me) glNormal3fv(nor); } - curpos= 0.0; - glBegin(mf->v4?GL_QUADS:GL_TRIANGLES); - for (index = 0; index < characters; index++) { - float centerx, centery, sizex, sizey, transx, transy, movex, movey, advance; - int character = string[index]; - char *cp= NULL; - - // lets calculate offset stuff - // space starts at offset 1 - // character = character - ' ' + 1; - - matrixGlyph(ibuf, character, & centerx, ¢ery, &sizex, &sizey, &transx, &transy, &movex, &movey, &advance); - movex+= curpos; - - if (tface->mode & TF_OBCOL) - glColor3ubv(Gtexdraw.obcol); - else if (me->mcol) cp= (char *)mcol; - else glColor3ub(255, 255, 255); - - glTexCoord2f((tface->uv[0][0] - centerx) * sizex + transx, (tface->uv[0][1] - centery) * sizey + transy); - if (cp) glColor3ub(cp[3], cp[2], cp[1]); - glVertex3f(sizex * v1[0] + movex, sizey * v1[1] + movey, v1[2]); - - glTexCoord2f((tface->uv[1][0] - centerx) * sizex + transx, (tface->uv[1][1] - centery) * sizey + transy); - if (cp) glColor3ub(cp[7], cp[6], cp[5]); - glVertex3f(sizex * v2[0] + movex, sizey * v2[1] + movey, v2[2]); - - glTexCoord2f((tface->uv[2][0] - centerx) * sizex + transx, (tface->uv[2][1] - centery) * sizey + transy); - if (cp) glColor3ub(cp[11], cp[10], cp[9]); - glVertex3f(sizex * v3[0] + movex, sizey * v3[1] + movey, v3[2]); - - if(mf->v4) { - glTexCoord2f((tface->uv[3][0] - centerx) * sizex + transx, (tface->uv[3][1] - centery) * sizey + transy); - if (cp) glColor3ub(cp[15], cp[14], cp[13]); - glVertex3f(sizex * v4[0] + movex, sizey * v4[1] + movey, v4[2]); - } - - curpos+= advance; - } - glEnd(); + GPU_render_text(tface, tface->mode, string, characters, + (unsigned int*)mcol, v1, v2, v3, (mf->v4? v4: NULL), glattrib); + } + if (mcol) { + mcol+=4; } } @@ -1159,7 +548,6 @@ static void draw_game_text_mesh(Object *ob, Mesh *me) void draw_mesh_textured(Object *ob, DerivedMesh *dm, int faceselect) { Mesh *me= ob->data; - int editing= 0; /* correct for negative scale */ if(ob->transflag & OB_NEG_SCALE) glFrontFace(GL_CW); @@ -1168,38 +556,20 @@ void draw_mesh_textured(Object *ob, DerivedMesh *dm, int faceselect) /* draw the textured mesh */ draw_textured_begin(ob); -#ifdef WITH_VERSE - if(me->vnode) { - /* verse-blender doesn't support uv mapping of textures yet */ - dm->drawFacesTex(dm, NULL); - } - else { -#endif - if(ob==G.obedit) { - dm->drawMappedFacesTex(dm, draw_em_tf_mapped__set_draw, G.editMesh); - } else if(faceselect) { - if(G.f & G_WEIGHTPAINT) - dm->drawMappedFaces(dm, wpaint__setSolidDrawOptions, me, 1); - else - dm->drawMappedFacesTex(dm, draw_tface_mapped__set_draw, me); - } + if(ob==G.obedit) { + dm->drawMappedFacesTex(dm, draw_em_tf_mapped__set_draw, G.editMesh); + } else if(faceselect) { + if(G.f & G_WEIGHTPAINT) + dm->drawMappedFaces(dm, wpaint__setSolidDrawOptions, me, 1); else - dm->drawFacesTex(dm, draw_tface__set_draw); -#ifdef WITH_VERSE + dm->drawMappedFacesTex(dm, draw_tface_mapped__set_draw, me); } -#endif + else + dm->drawFacesTex(dm, draw_tface__set_draw); - /* draw game engine text hack - but not if we are editing the mesh */ - if (me->mtface && get_property(ob, "Text")) { - if(ob==G.obedit) - editing= 1; - else if(ob==OBACT) - if(FACESEL_PAINT_TEST) - editing= 1; - - if(!editing) - draw_game_text_mesh(ob, me); - } + /* draw game engine text hack */ + if(get_property(ob, "Text")) + draw_mesh_text(ob, 0); draw_textured_end(); @@ -1214,10 +584,3 @@ void draw_mesh_textured(Object *ob, DerivedMesh *dm, int faceselect) glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); } -void init_realtime_GL(void) -{ - glMatrixMode(GL_TEXTURE); - glLoadIdentity(); - glMatrixMode(GL_MODELVIEW); -} - diff --git a/source/blender/src/drawobject.c b/source/blender/src/drawobject.c index 213f49528f0..4876e6cae7c 100644 --- a/source/blender/src/drawobject.c +++ b/source/blender/src/drawobject.c @@ -93,6 +93,7 @@ #include "BKE_object.h" #include "BKE_anim.h" //for the where_on_path function #include "BKE_particle.h" +#include "BKE_property.h" #include "BKE_utildefines.h" #ifdef WITH_VERSE #include "BKE_verse.h" @@ -129,6 +130,10 @@ #include "BKE_deform.h" +#include "GPU_draw.h" +#include "GPU_material.h" +#include "GPU_extensions.h" + /* pretty stupid */ /* extern Lattice *editLatt; already in BKE_lattice.h */ /* editcurve.c */ @@ -143,114 +148,37 @@ static void drawcircle_size(float size); static void draw_empty_sphere(float size); static void draw_empty_cone(float size); -/* ************* Setting OpenGL Material ************ */ +/* check for glsl drawing */ -// Materials start counting at # one.... -#define MAXMATBUF (MAXMAT + 1) -static float matbuf[MAXMATBUF][2][4]; -static int totmat_gl= 0; - -int set_gl_material(int nr) +int draw_glsl_material(Object *ob, int dt) { - static int last_gl_matnr= -1; - static int last_ret_val= 1; + if(!GPU_extensions_minimum_support()) + return 0; + if(G.f & G_PICKSEL) + return 0; + if(!CHECK_OB_DRAWTEXTURE(G.vd, dt)) + return 0; + if(ob==OBACT && (G.f & G_WEIGHTPAINT)) + return 0; - /* prevent index to use un-initialized array items */ - if(nr>totmat_gl) nr= totmat_gl; - - if(nr<0) { - last_gl_matnr= -1; - last_ret_val= 1; - } - else if(nr= OB_SHADED)); } -/* returns 1: when there's alpha needed to be drawn in a 2nd pass */ -int init_gl_materials(Object *ob, int check_alpha) +static int check_material_alpha(Base *base, Object *ob, int glsl) { - extern Material defmaterial; // render module abuse... - Material *ma; - int a, has_alpha= 0; - - if(ob->totcol==0) { - matbuf[0][0][0]= defmaterial.r; - matbuf[0][0][1]= defmaterial.g; - matbuf[0][0][2]= defmaterial.b; - matbuf[0][0][3]= 1.0; + if(base->flag & OB_FROMDUPLI) + return 0; - matbuf[0][1][0]= defmaterial.specr; - matbuf[0][1][1]= defmaterial.specg; - matbuf[0][1][2]= defmaterial.specb; - matbuf[0][1][3]= 1.0; - - /* do material 1 too, for displists! */ - QUATCOPY(matbuf[1][0], matbuf[0][0]); - QUATCOPY(matbuf[1][1], matbuf[0][1]); - } - - for(a=1; a<=ob->totcol; a++) { - ma= give_current_material(ob, a); - ma= editnode_get_active_material(ma); - if(ma==NULL) ma= &defmaterial; - - if(amode & MA_SHLESS) { - matbuf[a][0][0]= ma->r; - matbuf[a][0][1]= ma->g; - matbuf[a][0][2]= ma->b; - } else { - matbuf[a][0][0]= (ma->ref+ma->emit)*ma->r; - matbuf[a][0][1]= (ma->ref+ma->emit)*ma->g; - matbuf[a][0][2]= (ma->ref+ma->emit)*ma->b; - } - - /* draw transparent, not in pick-select, nor editmode */ - if(check_alpha && !(G.f & G_PICKSEL) && (ob->dtx & OB_DRAWTRANSP) && !(G.obedit && G.obedit->data==ob->data)) { - if(G.vd->transp) { // drawing the transparent pass - if(ma->alpha==1.0) matbuf[a][0][3]= 0.0; // means skip solid - else matbuf[a][0][3]= ma->alpha; - } - else { // normal pass - if(ma->alpha==1.0) matbuf[a][0][3]= 1.0; - else { - matbuf[a][0][3]= 0.0; // means skip transparent - has_alpha= 1; // return value, to indicate adding to after-draw queue - } - } - } - else - matbuf[a][0][3]= 1.0; + if(G.f & G_PICKSEL) + return 0; - if (!(ma->mode & MA_SHLESS)) { - matbuf[a][1][0]= ma->spec*ma->specr; - matbuf[a][1][1]= ma->spec*ma->specg; - matbuf[a][1][2]= ma->spec*ma->specb; - matbuf[a][1][3]= 1.0; - } - } - } - - totmat_gl= ob->totcol; - set_gl_material(-1); // signal for static variable - return has_alpha; + if(G.obedit && G.obedit->data==ob->data) + return 0; + + return (glsl || (ob->dtx & OB_DRAWTRANSP)); } - /***/ static unsigned int colortab[24]= {0x0, 0xFF88FF, 0xFFBBFF, @@ -352,6 +280,9 @@ void drawaxes(float size, int flag, char drawtype) float v1[3]= {0.0, 0.0, 0.0}; float v2[3]= {0.0, 0.0, 0.0}; float v3[3]= {0.0, 0.0, 0.0}; + + if(G.f & G_SIMULATION) + return; switch(drawtype) { @@ -734,6 +665,9 @@ static void drawlamp(Object *ob) float pixsize, lampsize; float imat[4][4], curcol[4]; char col[4]; + + if(G.f & G_SIMULATION) + return; la= ob->data; @@ -1024,6 +958,9 @@ static void drawcamera(Object *ob, int flag) float vec[8][4], tmat[4][4], fac, facx, facy, depth; int i; + if(G.f & G_SIMULATION) + return; + cam= ob->data; glDisable(GL_LIGHTING); @@ -1830,6 +1767,9 @@ static void draw_verse_debug(Object *ob, EditMesh *em) struct EditFace *efa=NULL; float v1[3], v2[3], v3[3], v4[3], fvec[3], col[3]; char val[32]; + + if(G.f & G_SIMULATION) + return; if(G.vd->zbuf && (G.vd->flag & V3D_ZBUF_SELECT)==0) glDisable(GL_DEPTH_TEST); @@ -1894,6 +1834,9 @@ static void draw_em_measure_stats(Object *ob, EditMesh *em) char conv_float[5]; /* Use a float conversion matching the grid size */ float area, col[3]; /* area of the face, color of the text to draw */ + if(G.f & G_SIMULATION) + return; + /* make the precission of the pronted value proportionate to the gridsize */ if ((G.vd->grid) < 0.01) strcpy(conv_float, "%.6f"); @@ -2054,12 +1997,20 @@ static int draw_em_fancy__setFaceOpts(void *userData, int index, int *drawSmooth EditFace *efa = EM_get_face_for_index(index); if (efa->h==0) { - set_gl_material(efa->mat_nr+1); + GPU_enable_material(efa->mat_nr+1, NULL); return 1; - } else { - return 0; } + else + return 0; } + +static int draw_em_fancy__setGLSLFaceOpts(void *userData, int index) +{ + EditFace *efa = EM_get_face_for_index(index); + + return (efa->h==0); +} + static void draw_em_fancy(Object *ob, EditMesh *em, DerivedMesh *cageDM, DerivedMesh *finalDM, int dt) { Mesh *me = ob->data; @@ -2082,9 +2033,21 @@ static void draw_em_fancy(Object *ob, EditMesh *em, DerivedMesh *cageDM, Derived EM_init_index_arrays(1, 1, 1); if(dt>OB_WIRE) { - if( CHECK_OB_DRAWTEXTURE(G.vd, dt) ) { - draw_mesh_textured(ob, finalDM, 0); - } else { + if(CHECK_OB_DRAWTEXTURE(G.vd, dt)) { + if(draw_glsl_material(ob, dt)) { + glFrontFace((ob->transflag&OB_NEG_SCALE)?GL_CW:GL_CCW); + + finalDM->drawMappedFacesGLSL(finalDM, GPU_enable_material, + draw_em_fancy__setGLSLFaceOpts, NULL); + GPU_disable_material(); + + glFrontFace(GL_CCW); + } + else { + draw_mesh_textured(ob, finalDM, 0); + } + } + else { glLightModeli(GL_LIGHT_MODEL_TWO_SIDE, me->flag & ME_TWOSIDED); glEnable(GL_LIGHTING); @@ -2208,6 +2171,7 @@ static void draw_em_fancy(Object *ob, EditMesh *em, DerivedMesh *cageDM, Derived if(dt>OB_WIRE) { glDepthMask(1); bglPolygonOffset(0.0); + GPU_disable_material(); } EM_free_index_arrays(); @@ -2226,8 +2190,9 @@ static void draw_mesh_object_outline(Object *ob, DerivedMesh *dm) drawFacesSolid() doesn't draw the transparent faces */ if(ob->dtx & OB_DRAWTRANSP) { glPolygonMode(GL_FRONT_AND_BACK, GL_LINE); - dm->drawFacesSolid(dm, set_gl_material); + dm->drawFacesSolid(dm, GPU_enable_material); glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); + GPU_disable_material(); } else { dm->drawEdges(dm, 0); @@ -2312,7 +2277,19 @@ static void draw_mesh_fancy(Base *base, int dt, int flag) draw_mesh_object_outline(ob, dm); } - draw_mesh_textured(ob, dm, faceselect); + if(draw_glsl_material(ob, dt)) { + glFrontFace((ob->transflag&OB_NEG_SCALE)?GL_CW:GL_CCW); + + dm->drawFacesGLSL(dm, GPU_enable_material); + if(get_property(ob, "Text")) + draw_mesh_text(ob, 1); + GPU_disable_material(); + + glFrontFace(GL_CCW); + } + else { + draw_mesh_textured(ob, dm, faceselect); + } if(!faceselect) { if(base->flag & SELECT) @@ -2323,18 +2300,17 @@ static void draw_mesh_fancy(Base *base, int dt, int flag) dm->drawLooseEdges(dm); } } - else if(dt==OB_SOLID ) { - - if ((G.vd->flag&V3D_SELECT_OUTLINE) && (base->flag&SELECT) && !draw_wire) { + else if(dt==OB_SOLID) { + if((G.vd->flag&V3D_SELECT_OUTLINE) && (base->flag&SELECT) && !draw_wire) draw_mesh_object_outline(ob, dm); - } glLightModeli(GL_LIGHT_MODEL_TWO_SIDE, me->flag & ME_TWOSIDED ); glEnable(GL_LIGHTING); glFrontFace((ob->transflag&OB_NEG_SCALE)?GL_CW:GL_CCW); - dm->drawFacesSolid(dm, set_gl_material); + dm->drawFacesSolid(dm, GPU_enable_material); + GPU_disable_material(); glFrontFace(GL_CCW); glDisable(GL_LIGHTING); @@ -2352,7 +2328,8 @@ static void draw_mesh_fancy(Base *base, int dt, int flag) if(ob==OBACT) { do_draw= 0; if( (G.f & G_WEIGHTPAINT)) { - set_gl_material(0); /* enforce defmaterial settings */ + /* enforce default material settings */ + GPU_enable_material(0, NULL); /* but set default spec */ glColorMaterial(GL_FRONT_AND_BACK, GL_SPECULAR); @@ -2367,6 +2344,8 @@ static void draw_mesh_fancy(Base *base, int dt, int flag) dm->drawMappedFaces(dm, wpaint__setSolidDrawOptions, me->mface, 1); glDisable(GL_COLOR_MATERIAL); glDisable(GL_LIGHTING); + + GPU_disable_material(); } else if((G.f & (G_VERTEXPAINT+G_TEXTUREPAINT)) && me->mcol) { dm->drawMappedFaces(dm, wpaint__setSolidDrawOptions, NULL, 1); @@ -2385,7 +2364,7 @@ static void draw_mesh_fancy(Base *base, int dt, int flag) dm->release(dm); shadeDispList(base); dl = find_displist(&ob->disp, DL_VERTCOL); - dm= mesh_get_derived_final(ob, get_viewedit_datamask()); + dm= mesh_get_derived_final(ob, get_viewedit_datamask()); } if ((G.vd->flag&V3D_SELECT_OUTLINE) && (base->flag&SELECT) && !draw_wire) { @@ -2462,7 +2441,7 @@ static int draw_mesh_object(Base *base, int dt, int flag) { Object *ob= base->object; Mesh *me= ob->data; - int has_alpha= 0, drawlinked= 0, retval= 0; + int do_alpha_pass= 0, drawlinked= 0, retval= 0, glsl, check_alpha; if(G.obedit && ob!=G.obedit && ob->data==G.obedit->data) { if(ob_get_key(ob)); @@ -2478,7 +2457,12 @@ static int draw_mesh_object(Base *base, int dt, int flag) cageDM = editmesh_get_derived_cage_and_final(&finalDM, get_viewedit_datamask()); - if(dt>OB_WIRE) init_gl_materials(ob, 0); // no transp in editmode, the fancy draw over goes bad then + if(dt>OB_WIRE) { + // no transp in editmode, the fancy draw over goes bad then + glsl = draw_glsl_material(ob, dt); + GPU_set_object_materials(G.scene, ob, glsl, NULL); + } + draw_em_fancy(ob, G.editMesh, cageDM, finalDM, dt); if (G.obedit!=ob && finalDM) @@ -2491,15 +2475,22 @@ static int draw_mesh_object(Base *base, int dt, int flag) else { /* don't create boundbox here with mesh_get_bb(), the derived system will make it, puts deformed bb's OK */ if(me->totface<=4 || boundbox_clip(ob->obmat, (ob->bb)? ob->bb: me->bb)) { - if(dt==OB_SOLID) has_alpha= init_gl_materials(ob, (base->flag & OB_FROMDUPLI)==0); + glsl = draw_glsl_material(ob, dt); + check_alpha = check_material_alpha(base, ob, glsl); + + if(dt==OB_SOLID || glsl) { + GPU_set_object_materials(G.scene, ob, glsl, + (check_alpha)? &do_alpha_pass: NULL); + } + draw_mesh_fancy(base, dt, flag); if(me->totvert==0) retval= 1; } } - /* init_gl_materials did the proper checking if this is needed */ - if(has_alpha) add_view3d_after(G.vd, base, V3D_TRANSP, flag); + /* GPU_set_object_materials checked if this is needed */ + if(do_alpha_pass) add_view3d_after(G.vd, base, V3D_TRANSP, flag); return retval; } @@ -2601,9 +2592,10 @@ static int drawDispListwire(ListBase *dlbase) return 0; } -static void drawDispListsolid(ListBase *lb, Object *ob) +static void drawDispListsolid(ListBase *lb, Object *ob, int glsl) { DispList *dl; + GPUVertexAttribs gattribs; float *data, curcol[4]; float *ndata; @@ -2667,7 +2659,7 @@ static void drawDispListsolid(ListBase *lb, Object *ob) case DL_SURF: if(dl->index) { - set_gl_material(dl->col+1); + GPU_enable_material(dl->col+1, (glsl)? &gattribs: NULL); if(dl->rt & CU_SMOOTH) glShadeModel(GL_SMOOTH); else glShadeModel(GL_FLAT); @@ -2675,12 +2667,12 @@ static void drawDispListsolid(ListBase *lb, Object *ob) glVertexPointer(3, GL_FLOAT, 0, dl->verts); glNormalPointer(GL_FLOAT, 0, dl->nors); glDrawElements(GL_QUADS, 4*dl->totindex, GL_UNSIGNED_INT, dl->index); + GPU_disable_material(); } break; case DL_INDEX3: - - set_gl_material(dl->col+1); + GPU_enable_material(dl->col+1, (glsl)? &gattribs: NULL); glVertexPointer(3, GL_FLOAT, 0, dl->verts); @@ -2693,6 +2685,7 @@ static void drawDispListsolid(ListBase *lb, Object *ob) glNormalPointer(GL_FLOAT, 0, dl->nors); glDrawElements(GL_TRIANGLES, 3*dl->parts, GL_UNSIGNED_INT, dl->index); + GPU_disable_material(); if(index3_nors_incr==0) glEnableClientState(GL_NORMAL_ARRAY); @@ -2700,12 +2693,13 @@ static void drawDispListsolid(ListBase *lb, Object *ob) break; case DL_INDEX4: - - set_gl_material(dl->col+1); + GPU_enable_material(dl->col+1, (glsl)? &gattribs: NULL); glVertexPointer(3, GL_FLOAT, 0, dl->verts); glNormalPointer(GL_FLOAT, 0, dl->nors); glDrawElements(GL_QUADS, 4*dl->parts, GL_UNSIGNED_INT, dl->index); + + GPU_disable_material(); break; } @@ -2799,14 +2793,18 @@ static int drawDispList(Base *base, int dt) draw_index_wire= 1; } else { - if(dt==OB_SHADED) { + if(draw_glsl_material(ob, dt)) { + GPU_set_object_materials(G.scene, ob, 1, NULL); + drawDispListsolid(lb, ob, 1); + } + else if(dt == OB_SHADED) { if(ob->disp.first==0) shadeDispList(base); drawDispListshaded(lb, ob); } else { - init_gl_materials(ob, 0); + GPU_set_object_materials(G.scene, ob, 0, NULL); glLightModeli(GL_LIGHT_MODEL_TWO_SIDE, 0); - drawDispListsolid(lb, ob); + drawDispListsolid(lb, ob, 0); } if(ob==G.obedit && cu->bevobj==NULL && cu->taperobj==NULL && cu->ext1 == 0.0 && cu->ext2 == 0.0) { cpack(0); @@ -2833,15 +2831,19 @@ static int drawDispList(Base *base, int dt) if(dl->nors==NULL) addnormalsDispList(ob, lb); - if(dt==OB_SHADED) { + if(draw_glsl_material(ob, dt)) { + GPU_set_object_materials(G.scene, ob, 1, NULL); + drawDispListsolid(lb, ob, 1); + } + else if(dt==OB_SHADED) { if(ob->disp.first==NULL) shadeDispList(base); drawDispListshaded(lb, ob); } else { - init_gl_materials(ob, 0); + GPU_set_object_materials(G.scene, ob, 0, NULL); glLightModeli(GL_LIGHT_MODEL_TWO_SIDE, 0); - drawDispListsolid(lb, ob); + drawDispListsolid(lb, ob, 0); } } else { @@ -2857,16 +2859,20 @@ static int drawDispList(Base *base, int dt) if(solid) { - if(dt==OB_SHADED) { + if(draw_glsl_material(ob, dt)) { + GPU_set_object_materials(G.scene, ob, 1, NULL); + drawDispListsolid(lb, ob, 1); + } + else if(dt == OB_SHADED) { dl= lb->first; if(dl && dl->col1==0) shadeDispList(base); drawDispListshaded(lb, ob); } else { - init_gl_materials(ob, 0); + GPU_set_object_materials(G.scene, ob, 0, NULL); glLightModeli(GL_LIGHT_MODEL_TWO_SIDE, 0); - drawDispListsolid(lb, ob); + drawDispListsolid(lb, ob, 0); } } else{ @@ -4624,9 +4630,8 @@ static void drawSolidSelect(Base *base) drawDispListwire(&ob->disp); } else if(ob->type==OB_ARMATURE) { - if(!(ob->flag & OB_POSEMODE)) { + if(!(ob->flag & OB_POSEMODE)) draw_armature(base, OB_WIRE, 0); - } } glLineWidth(1.0); @@ -5094,8 +5099,9 @@ void draw_object(Base *base, int flag) drawlattice(ob); break; case OB_ARMATURE: - if(dt>OB_WIRE) set_gl_material(0); // we use defmaterial + if(dt>OB_WIRE) GPU_enable_material(0, NULL); // we use default material empty_object= draw_armature(base, dt, flag); + if(dt>OB_WIRE) GPU_disable_material(); break; default: drawaxes(1.0, flag, OB_ARROWS); @@ -5138,9 +5144,8 @@ void draw_object(Base *base, int flag) } /* draw extra: after normal draw because of makeDispList */ - if(dtx) { - if(G.f & G_SIMULATION); - else if(dtx & OB_AXIS) { + if(dtx && !(G.f & G_SIMULATION)) { + if(dtx & OB_AXIS) { drawaxes(1.0f, flag, OB_ARROWS); } if(dtx & OB_BOUNDBOX) draw_bounding_volume(ob); @@ -5411,19 +5416,6 @@ static int bbs_mesh_solid__setDrawOpts(void *userData, int index, int *drawSmoot } } -static int bbs_mesh_wire__setDrawOpts(void *userData, int index) -{ - struct { Mesh *me; EdgeHash *eh; int offset; } *data = userData; - MEdge *med = data->me->medge + index; - uintptr_t flags = (intptr_t)BLI_edgehash_lookup(data->eh, med->v1, med->v2); - - if (flags & 1) { - set_framebuffer_index_color(data->offset+index); - return 1; - } else - return 0; -} - /* TODO remove this - since face select mode now only works with painting */ static void bbs_mesh_solid(Object *ob) { @@ -5433,22 +5425,6 @@ static void bbs_mesh_solid(Object *ob) glColor3ub(0, 0, 0); dm->drawMappedFaces(dm, bbs_mesh_solid__setDrawOpts, me, 0); - /* draw edges for seam marking in faceselect mode, but not when painting, - so that painting doesn't get interrupted on an edge */ - if ((G.f & G_FACESELECT) && !(G.f & (G_VERTEXPAINT|G_TEXTUREPAINT|G_WEIGHTPAINT))) { - struct { Mesh *me; EdgeHash *eh; int offset; } userData; - - userData.me = me; - userData.eh = get_tface_mesh_marked_edge_info(me); - userData.offset = userData.me->totface+1; - - bglPolygonOffset(1.0); - dm->drawMappedEdges(dm, bbs_mesh_wire__setDrawOpts, (void*)&userData); - bglPolygonOffset(0.0); - - BLI_edgehash_free(userData.eh, NULL); - } - dm->release(dm); } @@ -5504,6 +5480,7 @@ void draw_object_backbufsel(Object *ob) static void draw_object_mesh_instance(Object *ob, int dt, int outline) { DerivedMesh *dm=NULL, *edm=NULL; + int glsl; if(G.obedit && ob->data==G.obedit->data) edm= editmesh_get_derived_base(); @@ -5520,8 +5497,10 @@ static void draw_object_mesh_instance(Object *ob, int dt, int outline) if(outline) draw_mesh_object_outline(ob, dm?dm:edm); - if(dm) - init_gl_materials(ob, 0); + if(dm) { + glsl = draw_glsl_material(ob, dt); + GPU_set_object_materials(G.scene, ob, glsl, NULL); + } else { glEnable(GL_COLOR_MATERIAL); BIF_ThemeColor(TH_BONE_SOLID); @@ -5532,8 +5511,10 @@ static void draw_object_mesh_instance(Object *ob, int dt, int outline) glFrontFace((ob->transflag&OB_NEG_SCALE)?GL_CW:GL_CCW); glEnable(GL_LIGHTING); - if(dm) - dm->drawFacesSolid(dm, set_gl_material); + if(dm) { + dm->drawFacesSolid(dm, GPU_enable_material); + GPU_disable_material(); + } else if(edm) edm->drawMappedFaces(edm, NULL, NULL, 0); diff --git a/source/blender/src/drawview.c b/source/blender/src/drawview.c index 2030eb658de..020dfd407ad 100644 --- a/source/blender/src/drawview.c +++ b/source/blender/src/drawview.c @@ -64,6 +64,7 @@ #include "DNA_gpencil_types.h" #include "DNA_image_types.h" #include "DNA_key_types.h" +#include "DNA_lamp_types.h" #include "DNA_lattice_types.h" #include "DNA_mesh_types.h" #include "DNA_meshdata_types.h" @@ -162,6 +163,9 @@ #include "RE_pipeline.h" // make_stars +#include "GPU_draw.h" +#include "GPU_material.h" + #include "multires.h" /* For MULTISAMPLE_ARB #define. @@ -193,132 +197,6 @@ static void star_stuff_term_func(void) glEnd(); } -void default_gl_light(void) -{ - int a; - - /* initialize */ - if(U.light[0].flag==0 && U.light[1].flag==0 && U.light[2].flag==0) { - U.light[0].flag= 1; - U.light[0].vec[0]= -0.3; U.light[0].vec[1]= 0.3; U.light[0].vec[2]= 0.9; - U.light[0].col[0]= 0.8; U.light[0].col[1]= 0.8; U.light[0].col[2]= 0.8; - U.light[0].spec[0]= 0.5; U.light[0].spec[1]= 0.5; U.light[0].spec[2]= 0.5; - U.light[0].spec[3]= 1.0; - - U.light[1].flag= 0; - U.light[1].vec[0]= 0.5; U.light[1].vec[1]= 0.5; U.light[1].vec[2]= 0.1; - U.light[1].col[0]= 0.4; U.light[1].col[1]= 0.4; U.light[1].col[2]= 0.8; - U.light[1].spec[0]= 0.3; U.light[1].spec[1]= 0.3; U.light[1].spec[2]= 0.5; - U.light[1].spec[3]= 1.0; - - U.light[2].flag= 0; - U.light[2].vec[0]= 0.3; U.light[2].vec[1]= -0.3; U.light[2].vec[2]= -0.2; - U.light[2].col[0]= 0.8; U.light[2].col[1]= 0.5; U.light[2].col[2]= 0.4; - U.light[2].spec[0]= 0.5; U.light[2].spec[1]= 0.4; U.light[2].spec[2]= 0.3; - U.light[2].spec[3]= 1.0; - } - - - glLightfv(GL_LIGHT0, GL_POSITION, U.light[0].vec); - glLightfv(GL_LIGHT0, GL_DIFFUSE, U.light[0].col); - glLightfv(GL_LIGHT0, GL_SPECULAR, U.light[0].spec); - - glLightfv(GL_LIGHT1, GL_POSITION, U.light[1].vec); - glLightfv(GL_LIGHT1, GL_DIFFUSE, U.light[1].col); - glLightfv(GL_LIGHT1, GL_SPECULAR, U.light[1].spec); - - glLightfv(GL_LIGHT2, GL_POSITION, U.light[2].vec); - glLightfv(GL_LIGHT2, GL_DIFFUSE, U.light[2].col); - glLightfv(GL_LIGHT2, GL_SPECULAR, U.light[2].spec); - - for(a=0; a<8; a++) { - if(a<3) { - if(U.light[a].flag) glEnable(GL_LIGHT0+a); - else glDisable(GL_LIGHT0+a); - - // clear stuff from other opengl lamp usage - glLightf(GL_LIGHT0+a, GL_SPOT_CUTOFF, 180.0); - glLightf(GL_LIGHT0+a, GL_CONSTANT_ATTENUATION, 1.0); - glLightf(GL_LIGHT0+a, GL_LINEAR_ATTENUATION, 0.0); - } - else glDisable(GL_LIGHT0+a); - } - - glDisable(GL_LIGHTING); - - glDisable(GL_COLOR_MATERIAL); -} - -/* also called when render 'ogl' - keep synced with Myinit_gl_stuff in the game engine! */ -void init_gl_stuff(void) -{ - float mat_ambient[] = { 0.0, 0.0, 0.0, 0.0 }; - float mat_specular[] = { 0.5, 0.5, 0.5, 1.0 }; - float mat_shininess[] = { 35.0 }; - int a, x, y; - GLubyte pat[32*32]; - const GLubyte *patc= pat; - - - glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT, mat_ambient); - glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE, mat_specular); - glMaterialfv(GL_FRONT_AND_BACK, GL_SPECULAR, mat_specular); - glMaterialfv(GL_FRONT_AND_BACK, GL_SHININESS, mat_shininess); - - default_gl_light(); - - /* no local viewer, looks ugly in ortho mode */ - /* glLightModelfv(GL_LIGHT_MODEL_LOCAL_VIEWER, &one); */ - - glDepthFunc(GL_LEQUAL); - /* scaling matrices */ - glEnable(GL_NORMALIZE); - - glShadeModel(GL_FLAT); - - glDisable(GL_ALPHA_TEST); - glDisable(GL_BLEND); - glDisable(GL_DEPTH_TEST); - glDisable(GL_FOG); - glDisable(GL_LIGHTING); - glDisable(GL_LOGIC_OP); - glDisable(GL_STENCIL_TEST); - glDisable(GL_TEXTURE_1D); - glDisable(GL_TEXTURE_2D); - - /* default on, disable/enable should be local per function */ - glEnableClientState(GL_VERTEX_ARRAY); - glEnableClientState(GL_NORMAL_ARRAY); - - glPixelTransferi(GL_MAP_COLOR, GL_FALSE); - glPixelTransferi(GL_RED_SCALE, 1); - glPixelTransferi(GL_RED_BIAS, 0); - glPixelTransferi(GL_GREEN_SCALE, 1); - glPixelTransferi(GL_GREEN_BIAS, 0); - glPixelTransferi(GL_BLUE_SCALE, 1); - glPixelTransferi(GL_BLUE_BIAS, 0); - glPixelTransferi(GL_ALPHA_SCALE, 1); - glPixelTransferi(GL_ALPHA_BIAS, 0); - - glPixelTransferi(GL_DEPTH_BIAS, 0); - glPixelTransferi(GL_DEPTH_SCALE, 1); - glDepthRange(0.0, 1.0); - - a= 0; - for(x=0; x<32; x++) { - for(y=0; y<4; y++) { - if( (x) & 1) pat[a++]= 0x88; - else pat[a++]= 0x22; - } - } - - glPolygonStipple(patc); - - - init_realtime_GL(); -} - void circf(float x, float y, float rad) { GLUquadricObj *qobj = gluNewQuadric(); @@ -2737,7 +2615,7 @@ void add_view3d_after(View3D *v3d, Base *base, int type, int flag) } /* clears zbuffer and draws it over */ -static void view3d_draw_xray(View3D *v3d) +static void view3d_draw_xray(View3D *v3d, int clear) { View3DAfter *v3da, *next; int doit= 0; @@ -2746,7 +2624,7 @@ static void view3d_draw_xray(View3D *v3d) if(v3da->type==V3D_XRAY) doit= 1; if(doit) { - if(v3d->zbuf) glClear(GL_DEPTH_BUFFER_BIT); + if(clear && v3d->zbuf) glClear(GL_DEPTH_BUFFER_BIT); v3d->xray= TRUE; for(v3da= v3d->afterdraw.first; v3da; v3da= next) { @@ -2768,7 +2646,7 @@ static void view3d_draw_transp(View3D *v3d) glDepthMask(0); v3d->transp= TRUE; - + for(v3da= v3d->afterdraw.first; v3da; v3da= next) { next= v3da->next; if(v3da->type==V3D_TRANSP) { @@ -2946,7 +2824,7 @@ static void draw_sculpt_depths(View3D *v3d) } } -void draw_depth(ScrArea *sa, void *spacedata) +void draw_depth(ScrArea *sa, void *spacedata, int (* func)(void *)) { View3D *v3d= spacedata; Base *base; @@ -2986,9 +2864,11 @@ void draw_depth(ScrArea *sa, void *spacedata) if(G.scene->set) { for(SETLOOPER(G.scene->set, base)) { if(v3d->lay & base->lay) { - draw_object(base, 0); - if(base->object->transflag & OB_DUPLI) { - draw_dupli_objects_color(v3d, base, TH_WIRE); + if (func == NULL || func(base)) { + draw_object(base, 0); + if(base->object->transflag & OB_DUPLI) { + draw_dupli_objects_color(v3d, base, TH_WIRE); + } } } } @@ -2996,12 +2876,13 @@ void draw_depth(ScrArea *sa, void *spacedata) for(base= G.scene->base.first; base; base= base->next) { if(v3d->lay & base->lay) { - - /* dupli drawing */ - if(base->object->transflag & OB_DUPLI) { - draw_dupli_objects(v3d, base); + if (func == NULL || func(base)) { + /* dupli drawing */ + if(base->object->transflag & OB_DUPLI) { + draw_dupli_objects(v3d, base); + } + draw_object(base, 0); } - draw_object(base, 0); } } @@ -3046,6 +2927,84 @@ void draw_depth(ScrArea *sa, void *spacedata) static void draw_viewport_fps(ScrArea *sa); +typedef struct View3DShadow{ + struct View3DShadow*next, *prev; + GPULamp *lamp; +} View3DShadow; + +static void gpu_render_lamp_update(View3D *v3d, Object *ob, Object *par, float obmat[][4], ListBase *shadows) +{ + GPULamp *lamp; + View3DShadow *shadow; + + lamp = GPU_lamp_from_blender(G.scene, ob, par); + + if(lamp) { + GPU_lamp_update(lamp, obmat); + + if(GPU_lamp_has_shadow_buffer(lamp)) { + shadow= MEM_callocN(sizeof(View3DShadow), "View3DShadow"); + shadow->lamp = lamp; + BLI_addtail(shadows, shadow); + } + } +} + +static void gpu_update_lamps_shadows(Scene *scene, View3D *v3d) +{ + ListBase shadows; + View3DShadow *shadow; + Scene *sce; + Base *base; + Object *ob; + + shadows.first= shadows.last= NULL; + + /* update lamp transform and gather shadow lamps */ + for(SETLOOPER(G.scene, base)) { + ob= base->object; + + if(ob->type == OB_LAMP) + gpu_render_lamp_update(v3d, ob, NULL, ob->obmat, &shadows); + + if (ob->transflag & OB_DUPLI) { + DupliObject *dob; + ListBase *lb = object_duplilist(G.scene, ob); + + for(dob=lb->first; dob; dob=dob->next) + if(dob->ob->type==OB_LAMP) + gpu_render_lamp_update(v3d, dob->ob, ob, dob->mat, &shadows); + + free_object_duplilist(lb); + } + } + + /* render shadows after updating all lamps, nested object_duplilist + * don't work correct since it's replacing object matrices */ + for(shadow=shadows.first; shadow; shadow=shadow->next) { + /* this needs to be done better .. */ + float viewmat[4][4], winmat[4][4]; + int drawtype, lay, winsize, flag2; + + drawtype= v3d->drawtype; + lay= v3d->lay; + flag2= v3d->flag2 & V3D_SOLID_TEX; + + v3d->drawtype = OB_SOLID; + v3d->lay &= GPU_lamp_shadow_layer(shadow->lamp); + v3d->flag2 &= ~V3D_SOLID_TEX; + + GPU_lamp_shadow_buffer_bind(shadow->lamp, viewmat, &winsize, winmat); + drawview3d_render(v3d, viewmat, winsize, winsize, winmat, 1); + GPU_lamp_shadow_buffer_unbind(shadow->lamp); + + v3d->drawtype= drawtype; + v3d->lay= lay; + v3d->flag2 |= flag2; + } + + BLI_freelistN(&shadows); +} void drawview3dspace(ScrArea *sa, void *spacedata) { @@ -3066,6 +3025,10 @@ void drawview3dspace(ScrArea *sa, void *spacedata) for(base= G.scene->base.first; base; base= base->next) object_handle_update(base->object); // bke_object.h + + /* shadow buffers, before we setup matrices */ + if(draw_glsl_material(NULL, v3d->drawtype)) + gpu_update_lamps_shadows(G.scene, v3d); setwinmatrixview3d(sa->winx, sa->winy, NULL); /* 0= no pick rect */ setviewmatrixview3d(); /* note: calls where_is_object for camera... */ @@ -3208,8 +3171,8 @@ void drawview3dspace(ScrArea *sa, void *spacedata) if(G.scene->radio) RAD_drawall(v3d->drawtype>=OB_SOLID); /* Transp and X-ray afterdraw stuff */ - view3d_draw_xray(v3d); // clears zbuffer if it is used! view3d_draw_transp(v3d); + view3d_draw_xray(v3d, 1); // clears zbuffer if it is used! if(!retopo && sculptparticle && (obact && (OBACT->dtx & OB_DRAWXRAY))) { if(G.f & G_SCULPTMODE) @@ -3328,18 +3291,29 @@ void drawview3dspace(ScrArea *sa, void *spacedata) } - -void drawview3d_render(struct View3D *v3d, int winx, int winy, float winmat[][4]) +void drawview3d_render(struct View3D *v3d, float viewmat[][4], int winx, int winy, float winmat[][4], int shadow) { Base *base; Scene *sce; - float v3dwinmat[4][4]; + float v3dviewmat[4][4], v3dwinmat[4][4]; + + /* shadow buffers, before we setup matrices */ + if(!shadow && draw_glsl_material(NULL, v3d->drawtype)) + gpu_update_lamps_shadows(G.scene, v3d); if(!winmat) setwinmatrixview3d(winx, winy, NULL); - setviewmatrixview3d(); - myloadmatrix(v3d->viewmat); + if(viewmat) { + Mat4CpyMat4(v3dviewmat, viewmat); + Mat4CpyMat4(v3d->viewmat, viewmat); + } + else { + setviewmatrixview3d(); + Mat4CpyMat4(v3dviewmat, v3d->viewmat); + } + + myloadmatrix(v3dviewmat); /* when winmat is not NULL, it overrides the regular window matrix */ glMatrixMode(GL_PROJECTION); @@ -3348,12 +3322,14 @@ void drawview3d_render(struct View3D *v3d, int winx, int winy, float winmat[][4] mygetmatrix(v3dwinmat); glMatrixMode(GL_MODELVIEW); - Mat4MulMat4(v3d->persmat, v3d->viewmat, v3dwinmat); + Mat4MulMat4(v3d->persmat, v3dviewmat, v3dwinmat); Mat4Invert(v3d->persinv, v3d->persmat); Mat4Invert(v3d->viewinv, v3d->viewmat); - free_all_realtime_images(); - reshadeall_displist(); + if(!shadow) { + GPU_free_images(); + reshadeall_displist(); + } if(v3d->drawtype > OB_WIRE) { v3d->zbuf= TRUE; @@ -3431,8 +3407,8 @@ void drawview3d_render(struct View3D *v3d, int winx, int winy, float winmat[][4] if(G.scene->radio) RAD_drawall(v3d->drawtype>=OB_SOLID); /* Transp and X-ray afterdraw stuff */ - view3d_draw_xray(v3d); // clears zbuffer if it is used! view3d_draw_transp(v3d); + view3d_draw_xray(v3d, !shadow); // clears zbuffer if it is used! if(v3d->flag & V3D_CLIPPING) view3d_clr_clipping(); @@ -3451,11 +3427,12 @@ void drawview3d_render(struct View3D *v3d, int winx, int winy, float winmat[][4] G.f &= ~G_SIMULATION; - glFlush(); + if(!shadow) { + glFlush(); + GPU_free_images(); + } glLoadIdentity(); - - free_all_realtime_images(); } diff --git a/source/blender/src/editdeform.c b/source/blender/src/editdeform.c index 5de4c6ed23c..3f178e1ea2b 100644 --- a/source/blender/src/editdeform.c +++ b/source/blender/src/editdeform.c @@ -270,7 +270,7 @@ static void del_defgroup_update_users(Object *ob, int id) int a; /* these cases don't use names to refer to vertex groups, so when - * they get deleted the numbers get out of synce, this corrects that */ + * they get deleted the numbers get out of sync, this corrects that */ if(ob->soft) { if(ob->soft->vertgroup == id) diff --git a/source/blender/src/editface.c b/source/blender/src/editface.c index 781210cd373..008ddf3b5f0 100644 --- a/source/blender/src/editface.c +++ b/source/blender/src/editface.c @@ -82,13 +82,14 @@ #include "BIF_space.h" /* for allqueue */ #include "BIF_drawimage.h" /* for allqueue */ -#include "BDR_drawmesh.h" #include "BDR_editface.h" #include "BDR_vpaint.h" #include "BDR_editface.h" #include "BDR_vpaint.h" +#include "GPU_draw.h" + #include "mydevice.h" #include "blendef.h" #include "butspace.h" @@ -1315,7 +1316,7 @@ void set_texturepaint() /* toggle */ if(G.f & G_TEXTUREPAINT) { G.f &= ~G_TEXTUREPAINT; - texpaint_enable_mipmap(); + GPU_paint_set_mipmap(1); } else if (me) { G.f |= G_TEXTUREPAINT; @@ -1324,7 +1325,7 @@ void set_texturepaint() /* toggle */ make_tfaces(me); brush_check_exists(&G.scene->toolsettings->imapaint.brush); - texpaint_disable_mipmap(); + GPU_paint_set_mipmap(0); } allqueue(REDRAWVIEW3D, 0); diff --git a/source/blender/src/editipo_lib.c b/source/blender/src/editipo_lib.c index e1e286e10cf..7bfd097b87f 100644 --- a/source/blender/src/editipo_lib.c +++ b/source/blender/src/editipo_lib.c @@ -392,7 +392,15 @@ int texchannel_to_adrcode(int channel) case 6: return MA_MAP7; case 7: return MA_MAP8; case 8: return MA_MAP9; - case 9: return MA_MAP10; + case 9: return MA_MAP10; + case 10: return MA_MAP11; + case 11: return MA_MAP12; + case 12: return MA_MAP13; + case 13: return MA_MAP14; + case 14: return MA_MAP15; + case 15: return MA_MAP16; + case 16: return MA_MAP17; + case 17: return MA_MAP18; default: return 0; } } diff --git a/source/blender/src/editlattice.c b/source/blender/src/editlattice.c index 0782e012f68..06b092a30ac 100644 --- a/source/blender/src/editlattice.c +++ b/source/blender/src/editlattice.c @@ -131,7 +131,7 @@ void make_editLatt(void) copy_dverts(editLatt->dvert, lt->dvert, tot); } - BIF_undo_push("original"); + BIF_undo_push("Original"); } diff --git a/source/blender/src/editmode_undo.c b/source/blender/src/editmode_undo.c index d0a44360ad5..7893dac2408 100644 --- a/source/blender/src/editmode_undo.c +++ b/source/blender/src/editmode_undo.c @@ -107,6 +107,7 @@ typedef struct UndoElem { Object *ob; // pointer to edited object int type; // type of edited object void *undodata; + uintptr_t undosize; char name[MAXUNDONAME]; void (*freedata)(void *); void (*to_editmode)(void *); @@ -138,6 +139,7 @@ void undo_editmode_push(char *name, void (*freedata)(void *), { UndoElem *uel; int nr; + uintptr_t memused, totmem, maxmem; /* at first here was code to prevent an "original" key to be insterted twice this was giving conflicts for example when mesh changed due to keys or apply */ @@ -145,9 +147,8 @@ void undo_editmode_push(char *name, void (*freedata)(void *), /* remove all undos after (also when curundo==NULL) */ while(undobase.last != curundo) { uel= undobase.last; - BLI_remlink(&undobase, uel); uel->freedata(uel->undodata); - MEM_freeN(uel); + BLI_freelinkN(&undobase, uel); } /* make new */ @@ -160,7 +161,7 @@ void undo_editmode_push(char *name, void (*freedata)(void *), uel->from_editmode= from_editmode; uel->validate_undo= validate_undo; - /* and limit amount to the maximum */ + /* limit amount to the maximum amount*/ nr= 0; uel= undobase.last; while(uel) { @@ -171,19 +172,43 @@ void undo_editmode_push(char *name, void (*freedata)(void *), if(uel) { while(undobase.first!=uel) { UndoElem *first= undobase.first; - BLI_remlink(&undobase, first); first->freedata(first->undodata); - MEM_freeN(first); + BLI_freelinkN(&undobase, first); } } /* copy */ + memused= MEM_get_memory_in_use(); curundo->undodata= curundo->from_editmode(); + curundo->undosize= MEM_get_memory_in_use() - memused; curundo->ob= G.obedit; curundo->id= G.obedit->id; curundo->type= G.obedit->type; -} + if(U.undomemory != 0) { + /* limit to maximum memory (afterwards, we can't know in advance) */ + totmem= 0; + maxmem= ((uintptr_t)U.undomemory)*1024*1024; + + uel= undobase.last; + while(uel && uel->prev) { + totmem+= uel->undosize; + if(totmem>maxmem) break; + uel= uel->prev; + } + + if(uel) { + if(uel->prev && uel->prev->prev) + uel= uel->prev; + + while(undobase.first!=uel) { + UndoElem *first= undobase.first; + first->freedata(first->undodata); + BLI_freelinkN(&undobase, first); + } + } + } +} /* helper to remove clean other objects from undo stack */ static void undo_clean_stack(void) @@ -205,9 +230,8 @@ static void undo_clean_stack(void) } else { mixed= 1; - BLI_remlink(&undobase, uel); uel->freedata(uel->undodata); - MEM_freeN(uel); + BLI_freelinkN(&undobase, uel); } uel= next; diff --git a/source/blender/src/editview.c b/source/blender/src/editview.c index d2e59ae676d..2133a92a54e 100644 --- a/source/blender/src/editview.c +++ b/source/blender/src/editview.c @@ -2247,7 +2247,7 @@ void view3d_border_zoom(void) /* Get Z Depths, needed for perspective, nice for ortho */ bgl_get_mats(&mats); - draw_depth(curarea, (void *)v3d); + draw_depth(curarea, (void *)v3d, NULL); /* force updating */ if (v3d->depths) { diff --git a/source/blender/src/header_image.c b/source/blender/src/header_image.c index fac9e3af1af..1b90c406f0e 100644 --- a/source/blender/src/header_image.c +++ b/source/blender/src/header_image.c @@ -239,8 +239,10 @@ void do_image_buttons(unsigned short event) if(ima->twsta>=nr) ima->twsta= 1; if(ima->twend>=nr) ima->twend= nr-1; if(ima->twsta>ima->twend) ima->twsta= 1; - allqueue(REDRAWIMAGE, 0); } + + allqueue(REDRAWIMAGE, 0); + allqueue(REDRAWVIEW3D, 0); } break; } @@ -1293,7 +1295,7 @@ void image_buttons(void) uiBlockEndAlign(block); xco+= 166; } - uiDefIconButBitI(block, TOG, SI_DRAWTOOL, B_SIMAGEPAINTTOOL, ICON_TPAINT_HLT, xco,0,XIC,YIC, &G.sima->flag, 0, 0, 0, 0, "Enables painting textures on the image with left mouse button"); + uiDefIconButBitI(block, TOG, SI_DRAWTOOL, B_SIMAGEPAINTTOOL, ICON_TPAINT_HLT, xco,0,XIC,YIC, &G.sima->flag, 0, 0, 0, 0, "Enable image painting"); xco+= XIC+8; diff --git a/source/blender/src/header_info.c b/source/blender/src/header_info.c index 8b8fd9ef266..9bacc2b6351 100644 --- a/source/blender/src/header_info.c +++ b/source/blender/src/header_info.c @@ -39,8 +39,6 @@ #include #endif -#include "BLO_sys_types.h" // for intptr_t support - #include "DNA_group_types.h" #include "DNA_ID.h" #include "DNA_image_types.h" @@ -120,6 +118,9 @@ #include "BPY_extern.h" #include "BPY_menus.h" +#include "GPU_extensions.h" +#include "GPU_material.h" + #include "blendef.h" #include "interface.h" #include "mydevice.h" @@ -926,7 +927,7 @@ static void do_info_filemenu(void *arg, int event) winqueue_break= 1; /* leave queues everywhere */ BKE_reset_undo(); - BKE_write_undo("original"); /* save current state */ + BKE_write_undo("Original"); /* save current state */ refresh_interface_font(); } break; @@ -1591,20 +1592,83 @@ static uiBlock *info_addmenu(void *arg_unused) /************************** GAME *****************************/ +void do_info_game_glslmenu(void *arg, int event) +{ + switch (event) { + case G_FILE_GLSL_NO_LIGHTS: + case G_FILE_GLSL_NO_SHADERS: + case G_FILE_GLSL_NO_SHADOWS: + case G_FILE_GLSL_NO_RAMPS: + case G_FILE_GLSL_NO_NODES: + case G_FILE_GLSL_NO_EXTRA_TEX: + G.fileflags ^= event; + GPU_materials_free(); + allqueue(REDRAWINFO, 0); + allqueue(REDRAWVIEW3D, 0); + break; + default: + break; + } +} + +static uiBlock *info_game_glslmenu(void *arg_unused) +{ + uiBlock *block; + short yco= 0, menuwidth=160; + int check; + block= uiNewBlock(&curarea->uiblocks, "game_glslmenu", UI_EMBOSSP, UI_HELV, G.curscreen->mainwin); + uiBlockSetButmFunc(block, do_info_game_glslmenu, NULL); + + check = (G.fileflags & G_FILE_GLSL_NO_LIGHTS)? ICON_CHECKBOX_DEHLT: ICON_CHECKBOX_HLT; + uiDefIconTextBut(block, BUTM, 1, check, "Enable Lights", 0, yco-=20, menuwidth, 19, NULL, 0.0, 0.0, 1, G_FILE_GLSL_NO_LIGHTS, + "Enable using lights in GLSL materials."); + check = (G.fileflags & G_FILE_GLSL_NO_SHADERS)? ICON_CHECKBOX_DEHLT: ICON_CHECKBOX_HLT; + uiDefIconTextBut(block, BUTM, 1, check, "Enable Shaders", 0, yco-=20, menuwidth, 19, NULL, 0.0, 0.0, 1, G_FILE_GLSL_NO_SHADERS, + "Enable using shaders other than Lambert in GLSL materials"); + check = (G.fileflags & G_FILE_GLSL_NO_SHADOWS)? ICON_CHECKBOX_DEHLT: ICON_CHECKBOX_HLT; + uiDefIconTextBut(block, BUTM, 1, check, "Enable Shadows", 0, yco-=20, menuwidth, 19, NULL, 0.0, 0.0, 1, G_FILE_GLSL_NO_SHADOWS, + "Enable using shadows in GLSL materials"); + check = (G.fileflags & G_FILE_GLSL_NO_RAMPS)? ICON_CHECKBOX_DEHLT: ICON_CHECKBOX_HLT; + uiDefIconTextBut(block, BUTM, 1, check, "Enable Ramps", 0, yco-=20, menuwidth, 19, NULL, 0.0, 0.0, 1, G_FILE_GLSL_NO_RAMPS, + "Enable using ramps in GLSL materials"); + check = (G.fileflags & G_FILE_GLSL_NO_NODES)? ICON_CHECKBOX_DEHLT: ICON_CHECKBOX_HLT; + uiDefIconTextBut(block, BUTM, 1, check, "Enable Nodes", 0, yco-=20, menuwidth, 19, NULL, 0.0, 0.0, 1, G_FILE_GLSL_NO_NODES, + "Enable using nodes in GLSL materials."); + check = (G.fileflags & G_FILE_GLSL_NO_EXTRA_TEX)? ICON_CHECKBOX_DEHLT: ICON_CHECKBOX_HLT; + uiDefIconTextBut(block, BUTM, 1, check, "Enable Extra Textures", 0, yco-=20, menuwidth, 19, NULL, 0.0, 0.0, 1, G_FILE_GLSL_NO_EXTRA_TEX, + "Enable using texture channels other than Col and Alpha in GLSL materials."); + + uiBlockSetDirection(block, UI_RIGHT); + uiTextBoundsBlock(block, 50); + + return block; +} + static void do_info_gamemenu(void *arg, int event) { switch (event) { case G_FILE_ENABLE_ALL_FRAMES: - case G_FILE_DIAPLAY_LISTS: + case G_FILE_DISPLAY_LISTS: case G_FILE_SHOW_FRAMERATE: case G_FILE_SHOW_DEBUG_PROPS: case G_FILE_AUTOPLAY: case G_FILE_GAME_TO_IPO: - case G_FILE_GAME_MAT: case G_FILE_SHOW_PHYSICS: G.fileflags ^= event; break; + case G_FILE_GAME_MAT|G_FILE_GAME_MAT_GLSL: + G.fileflags &= ~(G_FILE_GAME_MAT|G_FILE_GAME_MAT_GLSL); + break; + case G_FILE_GAME_MAT: + G.fileflags |= G_FILE_GAME_MAT; + G.fileflags &= ~G_FILE_GAME_MAT_GLSL; + break; + case G_FILE_GAME_MAT_GLSL: + if(!GPU_extensions_minimum_support()) + error("GLSL not supported with this graphics card or driver."); + G.fileflags |= (G_FILE_GAME_MAT|G_FILE_GAME_MAT_GLSL); + break; default: ; /* ignore the rest */ } @@ -1635,22 +1699,14 @@ static uiBlock *info_gamemenu(void *arg_unused) uiDefIconTextBut(block, BUTM, 1, ICON_CHECKBOX_HLT, "Record Game Physics to IPO", 0, yco-=20, menuwidth, 19, NULL, 0.0, 0.0, 1, G_FILE_GAME_TO_IPO, ""); } else { - if(G.fileflags & G_FILE_DIAPLAY_LISTS) { - uiDefIconTextBut(block, BUTM, 1, ICON_CHECKBOX_HLT, "Generate Display Lists", 0, yco-=20, menuwidth, 19, NULL, 0.0, 0.0, 1, G_FILE_DIAPLAY_LISTS, ""); + if(G.fileflags & G_FILE_DISPLAY_LISTS) { + uiDefIconTextBut(block, BUTM, 1, ICON_CHECKBOX_HLT, "Generate Display Lists", 0, yco-=20, menuwidth, 19, NULL, 0.0, 0.0, 1, G_FILE_DISPLAY_LISTS, ""); } else { - uiDefIconTextBut(block, BUTM, 1, ICON_CHECKBOX_DEHLT, "Generate Display Lists", 0, yco-=20, menuwidth, 19, NULL, 0.0, 0.0, 1, G_FILE_DIAPLAY_LISTS, ""); + uiDefIconTextBut(block, BUTM, 1, ICON_CHECKBOX_DEHLT, "Generate Display Lists", 0, yco-=20, menuwidth, 19, NULL, 0.0, 0.0, 1, G_FILE_DISPLAY_LISTS, ""); } uiDefIconTextBut(block, BUTM, 1, ICON_CHECKBOX_DEHLT, "Record Game Physics to IPO", 0, yco-=20, menuwidth, 19, NULL, 0.0, 0.0, 1, G_FILE_GAME_TO_IPO, ""); } - if(G.fileflags & G_FILE_GAME_MAT) { - uiDefIconTextBut(block, BUTM, 1, ICON_CHECKBOX_HLT, "Use Blender Materials", 0, yco-=20, menuwidth, 19, NULL, 0.0, 0.0, 1, G_FILE_GAME_MAT, ""); - } else { - uiDefIconTextBut(block, BUTM, 1, ICON_CHECKBOX_DEHLT, "Use Blender Materials", 0, yco-=20, menuwidth, 19, NULL, 0.0, 0.0, 1, G_FILE_GAME_MAT, ""); - } - - - if(G.fileflags & G_FILE_SHOW_FRAMERATE) { uiDefIconTextBut(block, BUTM, 1, ICON_CHECKBOX_HLT, "Show Framerate and Profile", 0, yco-=20, menuwidth, 19, NULL, 0.0, 0.0, 1, G_FILE_SHOW_FRAMERATE, ""); } else { @@ -1669,6 +1725,28 @@ static uiBlock *info_gamemenu(void *arg_unused) } else { uiDefIconTextBut(block, BUTM, 1, ICON_CHECKBOX_DEHLT, "Show Debug Properties", 0, yco-=20, menuwidth, 19, NULL, 0.0, 0.0, 1, G_FILE_SHOW_DEBUG_PROPS, ""); } + + uiDefBut(block, SEPR, 0, "", 0, yco-=6, menuwidth, 6, NULL, 0.0, 0.0, 1, 0, ""); + + if(!(G.fileflags & G_FILE_GAME_MAT)) { + uiDefIconTextBut(block, BUTM, 1, ICON_CHECKBOX_HLT, "Texture Face Materials", 0, yco-=20, menuwidth, 19, NULL, 0.0, 0.0, 1, 0, ""); + } else { + uiDefIconTextBut(block, BUTM, 1, ICON_CHECKBOX_DEHLT, "Texture Face Materials", 0, yco-=20, menuwidth, 19, NULL, 0.0, 0.0, 1, G_FILE_GAME_MAT|G_FILE_GAME_MAT_GLSL, ""); + } + + if((G.fileflags & G_FILE_GAME_MAT) && !(G.fileflags & G_FILE_GAME_MAT_GLSL)) { + uiDefIconTextBut(block, BUTM, 1, ICON_CHECKBOX_HLT, "Blender Multitexture Materials", 0, yco-=20, menuwidth, 19, NULL, 0.0, 0.0, 1, 0, ""); + } else { + uiDefIconTextBut(block, BUTM, 1, ICON_CHECKBOX_DEHLT, "Blender Multitexture Materials", 0, yco-=20, menuwidth, 19, NULL, 0.0, 0.0, 1, G_FILE_GAME_MAT, ""); + } + + if((G.fileflags & G_FILE_GAME_MAT) && (G.fileflags & G_FILE_GAME_MAT_GLSL)) { + uiDefIconTextBut(block, BUTM, 1, ICON_CHECKBOX_HLT, "Blender GLSL Materials", 0, yco-=20, menuwidth, 19, NULL, 0.0, 0.0, 1, 0, ""); + } else { + uiDefIconTextBut(block, BUTM, 1, ICON_CHECKBOX_DEHLT, "Blender GLSL Materials", 0, yco-=20, menuwidth, 19, NULL, 0.0, 0.0, 1, G_FILE_GAME_MAT_GLSL, ""); + } + + uiDefIconTextBlockBut(block, info_game_glslmenu, NULL, ICON_RIGHTARROW_THIN, "GLSL Material Settings", 0, yco-=20, menuwidth, 19, ""); uiDefBut(block, SEPR, 0, "", 0, yco-=6, menuwidth, 6, NULL, 0.0, 0.0, 1, 0, ""); @@ -2108,13 +2186,16 @@ static void info_text(int x, int y) { Object *ob= OBACT; extern float hashvectf[]; - extern uintptr_t mem_in_use, mmap_in_use; + uintptr_t mem_in_use, mmap_in_use; unsigned int swatch_color; float fac1, fac2, fac3; char infostr[300], memstr[64]; char *headerstr, *s; int hsize; + mem_in_use= MEM_get_memory_in_use(); + mmap_in_use= MEM_get_mapped_memory_in_use(); + s= memstr + sprintf(memstr," | Mem:%.2fM ", ((mem_in_use-mmap_in_use)>>10)/1024.0); if(mmap_in_use) sprintf(s,"(%.2fM) ", ((mmap_in_use)>>10)/1024.0); diff --git a/source/blender/src/header_view3d.c b/source/blender/src/header_view3d.c index e57a3480b52..5d284f5eab4 100644 --- a/source/blender/src/header_view3d.c +++ b/source/blender/src/header_view3d.c @@ -4512,7 +4512,7 @@ static void do_view3d_tpaintmenu(void *arg, int event) { switch(event) { case 0: /* undo image painting */ - imagepaint_undo(); + undo_imagepaint_step(1); break; } diff --git a/source/blender/src/headerbuttons.c b/source/blender/src/headerbuttons.c index 1a91ada1562..44044841a99 100644 --- a/source/blender/src/headerbuttons.c +++ b/source/blender/src/headerbuttons.c @@ -154,7 +154,6 @@ #include "BSE_editipo.h" #include "BSE_drawipo.h" -#include "BDR_drawmesh.h" #include "BDR_vpaint.h" #include "BDR_editface.h" #include "BDR_editobject.h" @@ -165,6 +164,8 @@ #include "BPY_extern.h" #include "BPY_menus.h" +#include "GPU_draw.h" + #include "mydevice.h" #include "blendef.h" #include "interface.h" @@ -1425,11 +1426,11 @@ void do_global_buttons(unsigned short event) show_splash(); break; case B_MIPMAPCHANGED: - set_mipmap(!(U.gameflags & USER_DISABLE_MIPMAP)); + GPU_set_mipmap(!(U.gameflags & USER_DISABLE_MIPMAP)); allqueue(REDRAWVIEW3D, 0); break; case B_GLRESLIMITCHANGED: - free_all_realtime_images(); /* force reloading with new res limit */ + GPU_free_images(); /* force reloading with new res limit */ allqueue(REDRAWVIEW3D, 0); break; case B_NEWSPACE: diff --git a/source/blender/src/imagepaint.c b/source/blender/src/imagepaint.c index 15c289cc21c..164c368b6fa 100644 --- a/source/blender/src/imagepaint.c +++ b/source/blender/src/imagepaint.c @@ -44,6 +44,8 @@ #include "BLI_winstuff.h" #endif #include "BLI_arithb.h" +#include "BLI_blenlib.h" +#include "BLI_dynstr.h" #include "PIL_time.h" #include "IMB_imbuf.h" @@ -64,10 +66,12 @@ #include "BKE_brush.h" #include "BKE_global.h" #include "BKE_image.h" +#include "BKE_main.h" #include "BKE_mesh.h" #include "BKE_node.h" #include "BKE_utildefines.h" +#include "BIF_interface.h" #include "BIF_mywindow.h" #include "BIF_screen.h" #include "BIF_space.h" @@ -78,10 +82,11 @@ #include "BSE_trans_types.h" #include "BSE_view.h" -#include "BDR_drawmesh.h" #include "BDR_imagepaint.h" #include "BDR_vpaint.h" +#include "GPU_draw.h" + #include "GHOST_Types.h" #include "blendef.h" @@ -103,6 +108,8 @@ #define IMAPAINT_TILE_SIZE (1 << IMAPAINT_TILE_BITS) #define IMAPAINT_TILE_NUMBER(size) (((size)+IMAPAINT_TILE_SIZE-1) >> IMAPAINT_TILE_BITS) +#define MAXUNDONAME 64 + typedef struct ImagePaintState { Brush *brush; short tool, blend; @@ -120,48 +127,206 @@ typedef struct ImagePaintState { float uv[2]; } ImagePaintState; -typedef struct ImagePaintUndo { - Image *image; - ImBuf *tilebuf; - void **tiles; - int xtiles, ytiles; -} ImagePaintUndo; +typedef struct UndoTile { + struct UndoTile *next, *prev; + ID id; + void *rect; + int x, y; +} UndoTile; + +typedef struct UndoElem { + struct UndoElem *next, *prev; + char name[MAXUNDONAME]; + unsigned long undosize; + + ImBuf *ibuf; + ListBase tiles; +} UndoElem; typedef struct ImagePaintPartialRedraw { int x1, y1, x2, y2; int enabled; } ImagePaintPartialRedraw; -static ImagePaintUndo imapaintundo = {NULL, NULL, NULL, 0, 0}; +static ListBase undobase = {NULL, NULL}; +static UndoElem *curundo = NULL; static ImagePaintPartialRedraw imapaintpartial = {0, 0, 0, 0, 0}; -static void init_imagapaint_undo(Image *ima, ImBuf *ibuf) +/* UNDO */ + +/* internal functions */ + +static void undo_copy_tile(UndoTile *tile, ImBuf *tmpibuf, ImBuf *ibuf, int restore) { - int xt, yt; + /* copy or swap contents of tile->rect and region in ibuf->rect */ + IMB_rectcpy(tmpibuf, ibuf, 0, 0, tile->x*IMAPAINT_TILE_SIZE, + tile->y*IMAPAINT_TILE_SIZE, IMAPAINT_TILE_SIZE, IMAPAINT_TILE_SIZE); - imapaintundo.image = ima; - imapaintundo.xtiles = xt = IMAPAINT_TILE_NUMBER(ibuf->x); - imapaintundo.ytiles = yt = IMAPAINT_TILE_NUMBER(ibuf->y); - imapaintundo.tiles = MEM_callocN(sizeof(void*)*xt*yt, "ImagePaintUndoTiles"); - imapaintundo.tilebuf = IMB_allocImBuf(IMAPAINT_TILE_SIZE, IMAPAINT_TILE_SIZE, - ibuf->depth, (ibuf->rect_float)? IB_rectfloat: IB_rect, 0); -} - -static void imapaint_copy_tile(ImBuf *ibuf, int tile, int x, int y, int swapundo) -{ - IMB_rectcpy(imapaintundo.tilebuf, ibuf, 0, 0, x*IMAPAINT_TILE_SIZE, - y*IMAPAINT_TILE_SIZE, IMAPAINT_TILE_SIZE, IMAPAINT_TILE_SIZE); - - if (imapaintundo.tilebuf->rect_float) - SWAP(void*, imapaintundo.tilebuf->rect_float, imapaintundo.tiles[tile]) - else - SWAP(void*, imapaintundo.tilebuf->rect, imapaintundo.tiles[tile]) + if(ibuf->rect_float) SWAP(void*, tmpibuf->rect_float, tile->rect) + else SWAP(void*, tmpibuf->rect, tile->rect) - if (swapundo) - IMB_rectcpy(ibuf, imapaintundo.tilebuf, x*IMAPAINT_TILE_SIZE, - y*IMAPAINT_TILE_SIZE, 0, 0, IMAPAINT_TILE_SIZE, IMAPAINT_TILE_SIZE); + if(restore) + IMB_rectcpy(ibuf, tmpibuf, tile->x*IMAPAINT_TILE_SIZE, + tile->y*IMAPAINT_TILE_SIZE, 0, 0, IMAPAINT_TILE_SIZE, IMAPAINT_TILE_SIZE); } +static void undo_restore(UndoElem *undo) +{ + Image *ima = NULL; + ImBuf *ibuf, *tmpibuf; + UndoTile *tile; + + if(!undo) + return; + + tmpibuf= IMB_allocImBuf(IMAPAINT_TILE_SIZE, IMAPAINT_TILE_SIZE, 32, + IB_rectfloat|IB_rect, 0); + + for(tile=undo->tiles.first; tile; tile=tile->next) { + /* find image based on name, pointer becomes invalid with global undo */ + if(ima && strcmp(tile->id.name, ima->id.name)==0); + else { + for(ima=G.main->image.first; ima; ima=ima->id.next) + if(strcmp(tile->id.name, ima->id.name)==0) + break; + } + + ibuf= BKE_image_get_ibuf(ima, NULL); + + if (!ima || !ibuf || !(ibuf->rect || ibuf->rect_float)) + continue; + + undo_copy_tile(tile, tmpibuf, ibuf, 1); + + GPU_free_image(ima); /* force OpenGL reload */ + if(ibuf->rect_float) + imb_freerectImBuf(ibuf); /* force recreate of char rect */ + } + + IMB_freeImBuf(tmpibuf); +} + +static void undo_free(UndoElem *undo) +{ + UndoTile *tile; + + for(tile=undo->tiles.first; tile; tile=tile->next) + MEM_freeN(tile->rect); + BLI_freelistN(&undo->tiles); +} + +static void undo_imagepaint_push_begin(char *name) +{ + UndoElem *uel; + int nr; + + /* Undo push is split up in begin and end, the reason is that as painting + * happens more tiles are added to the list, and at the very end we know + * how much memory the undo used to remove old undo elements */ + + /* remove all undos after (also when curundo==NULL) */ + while(undobase.last != curundo) { + uel= undobase.last; + undo_free(uel); + BLI_freelinkN(&undobase, uel); + } + + /* make new */ + curundo= uel= MEM_callocN(sizeof(UndoElem), "undo file"); + BLI_addtail(&undobase, uel); + + /* name can be a dynamic string */ + strncpy(uel->name, name, MAXUNDONAME-1); + + /* limit amount to the maximum amount*/ + nr= 0; + uel= undobase.last; + while(uel) { + nr++; + if(nr==U.undosteps) break; + uel= uel->prev; + } + if(uel) { + while(undobase.first!=uel) { + UndoElem *first= undobase.first; + undo_free(first); + BLI_freelinkN(&undobase, first); + } + } +} + +static void undo_imagepaint_push_end() +{ + UndoElem *uel; + unsigned long totmem, maxmem; + + if(U.undomemory != 0) { + /* limit to maximum memory (afterwards, we can't know in advance) */ + totmem= 0; + maxmem= ((unsigned long)U.undomemory)*1024*1024; + + uel= undobase.last; + while(uel) { + totmem+= uel->undosize; + if(totmem>maxmem) break; + uel= uel->prev; + } + + if(uel) { + while(undobase.first!=uel) { + UndoElem *first= undobase.first; + undo_free(first); + BLI_freelinkN(&undobase, first); + } + } + } +} + +/* external functions */ + +/* 1= an undo, -1 is a redo. */ +void undo_imagepaint_step(int step) +{ + UndoElem *undo; + + if(step==1) { + if(curundo==NULL) error("No more steps to undo"); + else { + if(G.f & G_DEBUG) printf("undo %s\n", curundo->name); + undo_restore(curundo); + curundo= curundo->prev; + } + } + else if(step==-1) { + if((curundo!=NULL && curundo->next==NULL) || undobase.first==NULL) error("No more steps to redo"); + else { + undo= (curundo && curundo->next)? curundo->next: undobase.first; + undo_restore(undo); + curundo= undo; + if(G.f & G_DEBUG) printf("redo %s\n", undo->name); + } + } + + allqueue(REDRAWVIEW3D, 0); + allqueue(REDRAWIMAGE, 0); +} + +void undo_imagepaint_clear(void) +{ + UndoElem *uel; + + uel= undobase.first; + while(uel) { + undo_free(uel); + uel= uel->next; + } + + BLI_freelistN(&undobase); + curundo= NULL; +} + +/* Imagepaint Partial Redraw & Dirty Region */ + static void imapaint_clear_partial_redraw() { memset(&imapaintpartial, 0, sizeof(imapaintpartial)); @@ -169,7 +334,9 @@ static void imapaint_clear_partial_redraw() static void imapaint_dirty_region(Image *ima, ImBuf *ibuf, int x, int y, int w, int h) { - int srcx= 0, srcy= 0, origx, tile, allocsize; + ImBuf *tmpibuf; + UndoTile *tile; + int srcx= 0, srcy= 0, origx, allocsize; IMB_rectclip(ibuf, NULL, &x, &y, &srcx, &srcy, &w, &h); @@ -195,24 +362,36 @@ static void imapaint_dirty_region(Image *ima, ImBuf *ibuf, int x, int y, int w, origx = (x >> IMAPAINT_TILE_BITS); y = (y >> IMAPAINT_TILE_BITS); + tmpibuf= IMB_allocImBuf(IMAPAINT_TILE_SIZE, IMAPAINT_TILE_SIZE, 32, + IB_rectfloat|IB_rect, 0); + for (; y <= h; y++) { for (x=origx; x <= w; x++) { - if (ima != imapaintundo.image) { - free_imagepaint(); - init_imagapaint_undo(ima, ibuf); - } + for(tile=curundo->tiles.first; tile; tile=tile->next) + if(tile->x == x && tile->y == y && strcmp(tile->id.name, ima->id.name)==0) + break; - tile = y*imapaintundo.xtiles + x; - if (!imapaintundo.tiles[tile]) { - allocsize= (ibuf->rect_float)? sizeof(float): sizeof(char); - imapaintundo.tiles[tile]= MEM_mapallocN(allocsize*4* - IMAPAINT_TILE_SIZE*IMAPAINT_TILE_SIZE, "ImagePaintUndoTile"); - imapaint_copy_tile(ibuf, tile, x, y, 0); + if(!tile) { + tile= MEM_callocN(sizeof(UndoTile), "ImaUndoTile"); + tile->id= ima->id; + tile->x= x; + tile->y= y; + + allocsize= IMAPAINT_TILE_SIZE*IMAPAINT_TILE_SIZE*4; + allocsize *= (ibuf->rect_float)? sizeof(float): sizeof(char); + tile->rect= MEM_mapallocN(allocsize, "ImaUndoRect"); + + undo_copy_tile(tile, tmpibuf, ibuf, 0); + curundo->undosize += allocsize; + + BLI_addtail(&curundo->tiles, tile); } } } ibuf->userflags |= IB_BITMAPDIRTY; + + IMB_freeImBuf(tmpibuf); } static void imapaint_image_update(Image *image, ImBuf *ibuf, short texpaint) @@ -226,7 +405,7 @@ static void imapaint_image_update(Image *image, ImBuf *ibuf, short texpaint) if(texpaint || G.sima->lock) { int w = imapaintpartial.x2 - imapaintpartial.x1; int h = imapaintpartial.y2 - imapaintpartial.y1; - update_realtime_image(image, imapaintpartial.x1, imapaintpartial.y1, w, h); + GPU_paint_update_image(image, imapaintpartial.x1, imapaintpartial.y1, w, h); } } @@ -239,7 +418,7 @@ static void imapaint_redraw(int final, int texpaint, Image *image) allqueue(REDRAWIMAGE, 0); else if(!G.sima->lock) { if(image) - free_realtime_image(image); /* force OpenGL reload */ + GPU_free_image(image); /* force OpenGL reload */ allqueue(REDRAWVIEW3D, 0); } allqueue(REDRAWHEADERS, 0); @@ -269,46 +448,6 @@ static void imapaint_redraw(int final, int texpaint, Image *image) force_draw(0); } -void imagepaint_undo() -{ - Image *ima= imapaintundo.image; - ImBuf *ibuf= BKE_image_get_ibuf(ima, G.sima?&G.sima->iuser:NULL); - int x, y, tile; - - if (!ima || !ibuf || !(ibuf->rect || ibuf->rect_float)) - return; - - for (tile = 0, y = 0; y < imapaintundo.ytiles; y++) - for (x = 0; x < imapaintundo.xtiles; x++, tile++) - if (imapaintundo.tiles[tile]) - imapaint_copy_tile(ibuf, tile, x, y, 1); - - free_realtime_image(ima); /* force OpenGL reload */ - if(ibuf->rect_float) - imb_freerectImBuf(ibuf); /* force recreate of char rect */ - - allqueue(REDRAWIMAGE, 0); - allqueue(REDRAWVIEW3D, 0); -} - -void free_imagepaint() -{ - /* todo: does this need to be in the same places as editmode_undo_clear, - vertex paint isn't? */ - int i, size = imapaintundo.xtiles*imapaintundo.ytiles; - - if (imapaintundo.tiles) { - for (i = 0; i < size; i++) - if (imapaintundo.tiles[i]) - MEM_freeN(imapaintundo.tiles[i]); - MEM_freeN(imapaintundo.tiles); - } - if (imapaintundo.tilebuf) - IMB_freeImBuf(imapaintundo.tilebuf); - - memset(&imapaintundo, 0, sizeof(imapaintundo)); -} - /* Image Paint Operations */ static void imapaint_ibuf_get_set_rgb(ImBuf *ibuf, int x, int y, short torus, short set, float *rgb) @@ -580,7 +719,6 @@ static void imapaint_paint_stroke(ImagePaintState *s, BrushPainter *painter, sho int breakstroke = 0, redraw = 0; if (texpaint) { - /* pick new face and image */ if (facesel_face_pick(s->me, mval, &newfaceindex, 0)) { ImBuf *ibuf; @@ -692,7 +830,7 @@ void imagepaint_paint(short mousebutton, short texpaint) } settings->imapaint.flag |= IMAGEPAINT_DRAWING; - free_imagepaint(); + undo_imagepaint_push_begin("Image Paint"); /* create painter and paint once */ painter= brush_painter_new(s.brush); @@ -741,6 +879,7 @@ void imagepaint_paint(short mousebutton, short texpaint) brush_painter_free(painter); imapaint_redraw(1, texpaint, s.image); + undo_imagepaint_push_end(); if (texpaint) { if (s.warnmultifile) diff --git a/source/blender/src/meshtools.c b/source/blender/src/meshtools.c index 99833625baa..eed7737c26d 100644 --- a/source/blender/src/meshtools.c +++ b/source/blender/src/meshtools.c @@ -84,7 +84,6 @@ void sort_faces(void); #include "BIF_toolbox.h" #include "BIF_editconstraint.h" -#include "BDR_drawmesh.h" #include "BDR_editobject.h" #include "BDR_editface.h" #include "BDR_sculptmode.h" @@ -107,6 +106,8 @@ void sort_faces(void); #include "IMB_imbuf_types.h" #include "IMB_imbuf.h" +#include "GPU_draw.h" + #include "BLO_sys_types.h" // for intptr_t support /* from rendercode.c */ @@ -1130,7 +1131,7 @@ void objects_bake_render(short event, char **error_msg) if(ima->ok==IMA_OK_LOADED) { ImBuf *ibuf= BKE_image_get_ibuf(ima, NULL); if(ibuf && (ibuf->userflags & IB_BITMAPDIRTY)) { - free_realtime_image(ima); + GPU_free_image(ima); imb_freemipmapImBuf(ibuf); } } diff --git a/source/blender/src/playanim.c b/source/blender/src/playanim.c index 7a61368b4cd..8421101f66c 100644 --- a/source/blender/src/playanim.c +++ b/source/blender/src/playanim.c @@ -45,15 +45,6 @@ #endif #include "MEM_guardedalloc.h" -#ifdef WITH_QUICKTIME -#ifdef _WIN32 -#include -#include -#elif defined(__APPLE__) -#include -#endif /* __APPLE__ */ -#endif /* WITH_QUICKTIME */ - #include "PIL_time.h" #include @@ -77,6 +68,15 @@ #include "BMF_Api.h" +#ifdef WITH_QUICKTIME +#ifdef _WIN32 +#include +#include +#elif defined(__APPLE__) +#include +#endif /* __APPLE__ */ +#endif /* WITH_QUICKTIME */ + #include "playanim_ext.h" #include "mydevice.h" #include "blendef.h" @@ -346,6 +346,7 @@ void playanim(int argc, char **argv) int start_x= 0, start_y= 0; int sfra= -1; int efra= -1; + int totblock; while (argc > 1) { if (argv[1][0] == '-'){ @@ -823,6 +824,7 @@ void playanim(int argc, char **argv) free_blender(); window_destroy(g_window); + totblock= MEM_get_memory_blocks_in_use(); if(totblock!=0) { printf("Error Totblock: %d\n",totblock); MEM_printmemlist(); diff --git a/source/blender/src/previewrender.c b/source/blender/src/previewrender.c index 0be63197dd1..1730bb890bc 100644 --- a/source/blender/src/previewrender.c +++ b/source/blender/src/previewrender.c @@ -97,6 +97,8 @@ #include "RE_pipeline.h" #include "BLO_readfile.h" +#include "GPU_material.h" + #include "blendef.h" /* CLAMP */ #include "interface.h" /* ui_graphics_to_window(), SOLVE! (ton) */ #include "mydevice.h" @@ -221,6 +223,36 @@ void BIF_preview_changed(short id_code) } } } + + if(ELEM4(id_code, ID_MA, ID_TE, ID_LA, ID_WO)) { + Object *ob; + Material *ma; + + if(id_code == ID_WO) { + for(ma=G.main->mat.first; ma; ma=ma->id.next) { + if(ma->gpumaterial.first) { + GPU_material_free(ma); + allqueue(REDRAWVIEW3D, 0); + } + } + } + else if(id_code == ID_LA) { + for(ob=G.main->object.first; ob; ob=ob->id.next) { + if(ob->gpulamp.first) { + GPU_lamp_free(ob); + allqueue(REDRAWVIEW3D, 0); + } + } + } else if(OBACT) { + Object *ob = OBACT; + + ma= give_current_material(ob, ob->actcol); + if(ma && ma->gpumaterial.first) { + GPU_material_free(ma); + allqueue(REDRAWVIEW3D, 0); + } + } + } } /* *************************** Preview for buttons *********************** */ diff --git a/source/blender/src/renderwin.c b/source/blender/src/renderwin.c index 88f5f6efe15..33484500328 100644 --- a/source/blender/src/renderwin.c +++ b/source/blender/src/renderwin.c @@ -50,8 +50,6 @@ #endif -#include "BLO_sys_types.h" // for intptr_t support - #include #include "BLI_blenlib.h" @@ -102,6 +100,8 @@ #include "IMB_imbuf.h" #include "IMB_imbuf_types.h" +#include "GPU_draw.h" + #include "blendef.h" #include "mydevice.h" #include "winlay.h" @@ -676,7 +676,7 @@ static void open_renderwin(int winpos[2], int winsize[2], int imagesize[2]) /* mywindow has to know about it too */ mywindow_build_and_set_renderwin(winpos[0], winpos[1], winsize[0], winsize[1]+RW_HEADERY); /* and we should be able to draw 3d in it */ - init_gl_stuff(); + GPU_state_init(); renderwin_draw(render_win, 1); renderwin_draw(render_win, 1); @@ -903,10 +903,13 @@ static void renderwin_progress_display_cb(RenderResult *rr, volatile rcti *rect) void make_renderinfo_string(RenderStats *rs, char *str) { extern char info_time_str[32]; // header_info.c - extern uintptr_t mem_in_use, mmap_in_use; + uintptr_t mem_in_use, mmap_in_use; float megs_used_memory, mmap_used_memory; char *spos= str; + mem_in_use= MEM_get_memory_in_use(); + mmap_in_use= MEM_get_mapped_memory_in_use(); + megs_used_memory= (mem_in_use-mmap_in_use)/(1024.0*1024.0); mmap_used_memory= (mmap_in_use)/(1024.0*1024.0); @@ -1304,10 +1307,10 @@ void do_ogl_view3d_render(Render *re, View3D *v3d, int winx, int winy) if(v3d->persp==V3D_CAMOB && v3d->camera) { /* in camera view, use actual render winmat */ RE_GetCameraWindow(re, v3d->camera, CFRA, winmat); - drawview3d_render(v3d, winx, winy, winmat); + drawview3d_render(v3d, NULL, winx, winy, winmat, 0); } else - drawview3d_render(v3d, winx, winy, NULL); + drawview3d_render(v3d, NULL, winx, winy, NULL, 0); } /* set up display, render the current area view in an image */ @@ -1336,7 +1339,7 @@ void BIF_do_ogl_render(View3D *v3d, int anim) if(render_win) render_win->flags &= ~RW_FLAGS_ESCAPE; - init_gl_stuff(); + GPU_state_init(); waitcursor(1); diff --git a/source/blender/src/sculptmode.c b/source/blender/src/sculptmode.c index 24f4100efdb..31d5ae4610d 100644 --- a/source/blender/src/sculptmode.c +++ b/source/blender/src/sculptmode.c @@ -82,7 +82,6 @@ #include "BIF_space.h" #include "BIF_toolbox.h" -#include "BDR_drawobject.h" #include "BDR_sculptmode.h" #include "BSE_drawview.h" @@ -98,6 +97,8 @@ #include "RE_render_ext.h" #include "RE_shader_ext.h" /*for multitex_ext*/ +#include "GPU_draw.h" + #include #include #include @@ -1514,7 +1515,7 @@ void sculptmode_draw_mesh(int only_damaged) mymultmatrix(OBACT->obmat); glEnable(GL_DEPTH_TEST); glEnable(GL_LIGHTING); - init_gl_materials(OBACT, 0); + GPU_set_object_materials(G.scene, OBACT, 0, NULL); glEnable(GL_CULL_FACE); glShadeModel(GL_SMOOTH); @@ -1532,7 +1533,7 @@ void sculptmode_draw_mesh(int only_damaged) int new_matnr= f->mat_nr + 1; if(new_matnr != matnr) - drawCurrentMat= set_gl_material(matnr = new_matnr); + drawCurrentMat= GPU_enable_material(matnr = new_matnr, NULL); /* If only_damaged!=0, only draw faces that are partially inside the area(s) modified by the brush */ diff --git a/source/blender/src/sequence.c b/source/blender/src/sequence.c index 7e2ffc3ba63..bf24c02e723 100644 --- a/source/blender/src/sequence.c +++ b/source/blender/src/sequence.c @@ -2949,12 +2949,16 @@ void do_render_seq(RenderResult *rr, int cfra) (schlaile) */ { - extern int mem_in_use; - extern int mmap_in_use; + uintptr_t mem_in_use; + uintptr_t mmap_in_use; + uintptr_t max; + + mem_in_use= MEM_get_memory_in_use(); + mmap_in_use= MEM_get_mapped_memory_in_use(); + max = MEM_CacheLimiter_get_maximum(); - int max = MEM_CacheLimiter_get_maximum(); if (max != 0 && mem_in_use + mmap_in_use > max) { - fprintf(stderr, "mem_in_use = %d, max = %d\n", + fprintf(stderr, "mem_in_use = %lu, max = %lu\n", mem_in_use + mmap_in_use, max); fprintf(stderr, "Cleaning up, please wait...\n" "If this happens very often,\n" diff --git a/source/blender/src/space.c b/source/blender/src/space.c index 81b0efeef0d..88a0bf0f9b1 100644 --- a/source/blender/src/space.c +++ b/source/blender/src/space.c @@ -182,6 +182,9 @@ #include "SYS_System.h" /* for the user def menu ... should move elsewhere. */ +#include "GPU_extensions.h" +#include "GPU_draw.h" + #include "BLO_sys_types.h" // for intptr_t support /* maybe we need this defined somewhere else */ @@ -386,7 +389,7 @@ void space_set_commmandline_options(void) { SYS_WriteCommandLineInt(syshandle, "noaudio", a); a= (U.gameflags & USER_DISABLE_MIPMAP); - set_mipmap(!a); + GPU_set_mipmap(!a); SYS_WriteCommandLineInt(syshandle, "nomipmap", a); /* File specific settings: */ @@ -415,7 +418,9 @@ void space_set_commmandline_options(void) { a=(G.fileflags & G_FILE_GAME_MAT); SYS_WriteCommandLineInt(syshandle, "blender_material", a); - a=(G.fileflags & G_FILE_DIAPLAY_LISTS); + a=(G.fileflags & G_FILE_GAME_MAT_GLSL); + SYS_WriteCommandLineInt(syshandle, "blender_glsl_material", a); + a=(G.fileflags & G_FILE_DISPLAY_LISTS); SYS_WriteCommandLineInt(syshandle, "displaylists", a); @@ -432,11 +437,10 @@ static void SaveState(void) { glPushAttrib(GL_ALL_ATTRIB_BITS); - init_realtime_GL(); - init_gl_stuff(); + GPU_state_init(); if(G.f & G_TEXTUREPAINT) - texpaint_enable_mipmap(); + GPU_paint_set_mipmap(1); waitcursor(1); } @@ -444,7 +448,7 @@ static void SaveState(void) static void RestoreState(void) { if(G.f & G_TEXTUREPAINT) - texpaint_disable_mipmap(); + GPU_paint_set_mipmap(0); curarea->win_swap = 0; curarea->head_swap=0; @@ -1024,9 +1028,9 @@ void BIF_undo(void) } else { if(G.f & G_TEXTUREPAINT) - imagepaint_undo(); + undo_imagepaint_step(1); else if(curarea->spacetype==SPACE_IMAGE && (G.sima->flag & SI_DRAWTOOL)) - imagepaint_undo(); + undo_imagepaint_step(1); else if(G.f & G_PARTICLEEDIT) PE_undo(); else { @@ -1048,9 +1052,9 @@ void BIF_redo(void) } else { if(G.f & G_TEXTUREPAINT) - imagepaint_undo(); + undo_imagepaint_step(-1); else if(curarea->spacetype==SPACE_IMAGE && (G.sima->flag & SI_DRAWTOOL)) - imagepaint_undo(); + undo_imagepaint_step(-1); else if(G.f & G_PARTICLEEDIT) PE_redo(); else { @@ -2643,10 +2647,9 @@ static void winqreadview3dspace(ScrArea *sa, void *spacedata, BWinEvent *evt) else if(G.f & G_VERTEXPAINT) BIF_undo(); else if(G.f & G_TEXTUREPAINT) - imagepaint_undo(); - else { + undo_imagepaint_step(1); + else single_user(); - } } break; @@ -3259,7 +3262,7 @@ void initipo(ScrArea *sa) /* ******************** SPACE: INFO ********************** */ void space_mipmap_button_function(int event) { - set_mipmap(!(U.gameflags & USER_DISABLE_MIPMAP)); + GPU_set_mipmap(!(U.gameflags & USER_DISABLE_MIPMAP)); allqueue(REDRAWVIEW3D, 0); } @@ -3949,20 +3952,23 @@ void drawinfospace(ScrArea *sa, void *spacedata) uiDefBut(block, LABEL,0,"Transform:", - (xpos+(2*edgsp)+mpref),y5label, mpref,buth, + (xpos+(2*edgsp)+mpref),y6label, mpref,buth, 0, 0, 0, 0, 0, ""); uiDefButBitI(block, TOG, USER_DRAGIMMEDIATE, B_DRAWINFO, "Drag Immediately", - (xpos+edgsp+mpref+midsp),y4,mpref,buth, + (xpos+edgsp+mpref+midsp),y5,mpref,buth, &(U.flag), 0, 0, 0, 0, "Moving things with a mouse drag doesn't require a click to confirm (Best for tablet users)"); uiBlockEndAlign(block); uiDefBut(block, LABEL,0,"Undo:", - (xpos+(2*edgsp)+mpref),y3label, mpref,buth, + (xpos+(2*edgsp)+mpref),y4label, mpref,buth, 0, 0, 0, 0, 0, ""); uiBlockBeginAlign(block); uiDefButS(block, NUMSLI, B_DRAWINFO, "Steps: ", - (xpos+edgsp+mpref+midsp),y2,mpref,buth, + (xpos+edgsp+mpref+midsp),y3,mpref,buth, &(U.undosteps), 0, 64, 0, 0, "Number of undo steps available (smaller values conserve memory)"); + uiDefButS(block, NUM, B_DRAWINFO, "Memory Limit: ", + (xpos+edgsp+mpref+midsp),y2,mpref,buth, + &(U.undomemory), 0, 32767, -1, 0, "Maximum memory usage in megabytes (0 means unlimited)"); uiDefButBitI(block, TOG, USER_GLOBALUNDO, B_DRAWINFO, "Global Undo", (xpos+edgsp+mpref+midsp),y1,mpref,buth, @@ -4297,6 +4303,7 @@ void drawinfospace(ScrArea *sa, void *spacedata) uiDefButI(block, NUM, 0, "Collect Rate ", (xpos+edgsp+(5*mpref)+(5*midsp)), y2, mpref, buth, &U.texcollectrate, 1.0, 3600.0, 30, 2, "Number of seconds between each run of the GL texture garbage collector."); + uiBlockEndAlign(block); /* *** */ uiDefBut(block, LABEL,0,"Color range for weight paint", @@ -4533,7 +4540,7 @@ static void winqreadinfospace(ScrArea *sa, void *spacedata, BWinEvent *evt) if(U.light[0].flag==0 && U.light[1].flag==0 && U.light[2].flag==0) U.light[0].flag= 1; - default_gl_light(); + GPU_default_lights(); addqueue(sa->win, REDRAW, 1); allqueue(REDRAWVIEW3D, 0); } @@ -5173,8 +5180,8 @@ static void init_seqspace(ScrArea *sa) sseq->v2d.max[0]= MAXFRAMEF; sseq->v2d.max[1]= MAXSEQ; - sseq->v2d.minzoom= 0.1f; - sseq->v2d.maxzoom= 10.0; + sseq->v2d.minzoom= 0.01f; + sseq->v2d.maxzoom= 100.0; sseq->v2d.scroll= L_SCROLL+B_SCROLL; sseq->v2d.keepaspect= 0; @@ -5989,7 +5996,7 @@ static void init_oopsspace(ScrArea *sa) soops= MEM_callocN(sizeof(SpaceOops), "initoopsspace"); BLI_addhead(&sa->spacedata, soops); - soops->visiflag= OOPS_OB+OOPS_MA+OOPS_ME+OOPS_TE+OOPS_CU+OOPS_IP; + soops->visiflag= OOPS_OB|OOPS_MA|OOPS_ME|OOPS_TE|OOPS_CU|OOPS_IP; /* new oops is default an outliner */ soops->type= SO_OUTLINER; diff --git a/source/blender/src/toets.c b/source/blender/src/toets.c index 5f80f14d069..efd97ed9786 100644 --- a/source/blender/src/toets.c +++ b/source/blender/src/toets.c @@ -104,6 +104,8 @@ #include "IMB_imbuf.h" #include "IMB_imbuf_types.h" +#include "GPU_draw.h" + #include "mydevice.h" #include "transform.h" @@ -964,7 +966,7 @@ int blenderqread(unsigned short event, short val) /* Reset lights * This isn't done when reading userdef, do it now * */ - default_gl_light(); + GPU_default_lights(); } return 0; } diff --git a/source/blender/src/usiblender.c b/source/blender/src/usiblender.c index e757f634a45..21bec1ec978 100644 --- a/source/blender/src/usiblender.c +++ b/source/blender/src/usiblender.c @@ -34,8 +34,6 @@ #include #include -#include "GL/glew.h" - #ifdef WIN32 #include /* need to include windows.h so _WIN32_IE is defined */ #ifndef _WIN32_IE @@ -149,6 +147,9 @@ #include "PIL_time.h" +#include "GPU_extensions.h" +#include "GPU_draw.h" + /***/ /* define for setting colors in theme below */ @@ -577,8 +578,9 @@ void BIF_read_file(char *name) if (retval!=0) G.relbase_valid = 1; undo_editmode_clear(); + undo_imagepaint_clear(); BKE_reset_undo(); - BKE_write_undo("original"); /* save current state */ + BKE_write_undo("Original"); /* save current state */ refresh_interface_font(); } @@ -650,8 +652,9 @@ int BIF_read_homefile(int from_memory) init_userdef_file(); undo_editmode_clear(); + undo_imagepaint_clear(); BKE_reset_undo(); - BKE_write_undo("original"); /* save current state */ + BKE_write_undo("Original"); /* save current state */ /* if from memory, need to refresh python scripts */ if (from_memory) { @@ -1049,8 +1052,9 @@ void BIF_init(void) BIF_filelist_init_icons(); - init_gl_stuff(); /* drawview.c, after homefile */ - glewInit(); + GPU_state_init(); + GPU_extensions_init(); + readBlog(); BLI_strncpy(G.lib, G.sce, FILE_MAX); } @@ -1063,6 +1067,7 @@ extern ListBase editelems; void exit_usiblender(void) { struct TmpFont *tf; + int totblock; BIF_clear_tempfiles(); @@ -1108,7 +1113,6 @@ void exit_usiblender(void) free_ipocopybuf(); free_actcopybuf(); free_vertexpaint(); - free_imagepaint(); free_texttools(); /* editnurb can remain to exist outside editmode */ @@ -1127,6 +1131,7 @@ void exit_usiblender(void) sound_exit_audio(); if(G.listener) MEM_freeN(G.listener); + GPU_extensions_exit(); libtiff_exit(); @@ -1136,6 +1141,7 @@ void exit_usiblender(void) /* undo free stuff */ undo_editmode_clear(); + undo_imagepaint_clear(); BKE_undo_save_quit(); // saves quit.blend if global undo is on BKE_reset_undo(); @@ -1161,6 +1167,7 @@ void exit_usiblender(void) BLI_freelistN(&U.themes); BIF_preview_free_dbase(); + totblock= MEM_get_memory_blocks_in_use(); if(totblock!=0) { printf("Error Totblock: %d\n",totblock); MEM_printmemlist(); diff --git a/source/blender/src/verse_image.c b/source/blender/src/verse_image.c index fe9e6137091..4a78126e3f8 100644 --- a/source/blender/src/verse_image.c +++ b/source/blender/src/verse_image.c @@ -327,7 +327,7 @@ void post_bitmap_tile_set(VBitmapLayer *vblayer, unsigned int xs, unsigned int y rect[channel] = (char)vuint8[i]; } - free_realtime_image(image); + GPU_free_image(image); /* redraw preview of image ... uncommented, because rendering * was computed too often */ diff --git a/source/creator/CMakeLists.txt b/source/creator/CMakeLists.txt index d17b94c631d..04219ac5868 100644 --- a/source/creator/CMakeLists.txt +++ b/source/creator/CMakeLists.txt @@ -37,8 +37,10 @@ INCLUDE_DIRECTORIES(../../intern/guardedalloc ../blender/render/extern/include ../blender/python ../blender/makesdna + ../blender/gpu ../kernel/gen_messaging ../kernel/gen_system + ../../extern/glew/include ) @@ -210,6 +212,7 @@ IF(UNIX) blender_python bf_blenkernel bf_nodes + bf_gpu bf_blenloader bf_blenpluginapi bf_imbuf diff --git a/source/creator/Makefile b/source/creator/Makefile index 8a0d20264ea..158aee1a647 100644 --- a/source/creator/Makefile +++ b/source/creator/Makefile @@ -49,9 +49,11 @@ CPPFLAGS += -I../blender/renderconverter CPPFLAGS += -I../blender/blenkernel CPPFLAGS += -I../blender/python CPPFLAGS += -I../blender/blenloader +CPPFLAGS += -I../blender/gpu CPPFLAGS += -I../kernel/gen_system CPPFLAGS += -I../kernel/gen_messaging CPPFLAGS += -I$(NAN_GUARDEDALLOC)/include +CPPFLAGS += -I$(NAN_GLEW)/include ifeq ($(WITH_QUICKTIME), true) CPPFLAGS += -I$(NAN_QUICKTIME)/include -DWITH_QUICKTIME diff --git a/source/creator/SConscript b/source/creator/SConscript index cac9e895a97..a4c218f89d6 100644 --- a/source/creator/SConscript +++ b/source/creator/SConscript @@ -7,7 +7,7 @@ incs = '#/intern/guardedalloc ../blender/blenlib ../blender/blenkernel' incs += ' ../blender/include ../blender/blenloader ../blender/imbuf' incs += ' ../blender/renderconverter ../blender/render/extern/include' incs += ' ../blender/python ../blender/makesdna ../kernel/gen_messaging' -incs += ' ../kernel/gen_system' +incs += ' ../kernel/gen_system #/extern/glew/include ../blender/gpu' incs += ' ' + env['BF_OPENGL_INC'] defs = [] diff --git a/source/creator/creator.c b/source/creator/creator.c index e17b0f66977..ec87cdd8cf7 100644 --- a/source/creator/creator.c +++ b/source/creator/creator.c @@ -70,14 +70,14 @@ #include "BLO_writefile.h" #include "BLO_readfile.h" -#include "BDR_drawmesh.h" - #include "IMB_imbuf.h" // for quicktime_init #include "BPY_extern.h" #include "RE_pipeline.h" +#include "GPU_draw.h" + #include "playanim_ext.h" #include "mydevice.h" #include "nla.h" @@ -600,12 +600,12 @@ int main(int argc, char **argv) /* doMipMap */ if (!strcmp(argv[a],"nomipmap")) { - set_mipmap(0); //doMipMap = 0; + GPU_set_mipmap(0); //doMipMap = 0; } /* linearMipMap */ if (!strcmp(argv[a],"linearmipmap")) { - set_linear_mipmap(1); //linearMipMap = 1; + GPU_set_linear_mipmap(1); //linearMipMap = 1; } diff --git a/source/gameengine/BlenderRoutines/BL_KetsjiEmbedStart.cpp b/source/gameengine/BlenderRoutines/BL_KetsjiEmbedStart.cpp index 16f8ae0095a..1f66335c749 100644 --- a/source/gameengine/BlenderRoutines/BL_KetsjiEmbedStart.cpp +++ b/source/gameengine/BlenderRoutines/BL_KetsjiEmbedStart.cpp @@ -79,6 +79,8 @@ #include "DNA_scene_types.h" /***/ +#include "GPU_extensions.h" + #ifdef __cplusplus extern "C" { #endif @@ -138,6 +140,9 @@ extern "C" void StartKetsjiShell(struct ScrArea *area, if(GLEW_ARB_multitexture && GLEW_VERSION_1_1) usemat = (SYS_GetCommandLineInt(syshandle, "blender_material", 0) != 0); + if(GPU_extensions_minimum_support()) + useglslmat = (SYS_GetCommandLineInt(syshandle, "blender_glsl_material", 0) != 0); + // create the canvas, rasterizer and rendertools RAS_ICanvas* canvas = new KX_BlenderCanvas(area); canvas->SetMouseState(RAS_ICanvas::MOUSE_INVISIBLE); @@ -304,13 +309,14 @@ extern "C" void StartKetsjiShell(struct ScrArea *area, mousedevice, networkdevice, audiodevice, - startscenename); + startscenename, + blscene); // some python things PyObject* dictionaryobject = initGamePythonScripting("Ketsji", psl_Lowest); ketsjiengine->SetPythonDictionary(dictionaryobject); initRasterizer(rasterizer, canvas); - PyObject *gameLogic = initGameLogic(startscene); + PyObject *gameLogic = initGameLogic(ketsjiengine, startscene); PyDict_SetItemString(dictionaryobject, "GameLogic", gameLogic); // Same as importing the module. PyDict_SetItemString(PyModule_GetDict(gameLogic), "globalDict", pyGlobalDict); // Same as importing the module. initGameKeys(); @@ -526,8 +532,6 @@ extern "C" void StartKetsjiShellSimulation(struct ScrArea *area, // create the ketsjiengine KX_KetsjiEngine* ketsjiengine = new KX_KetsjiEngine(kxsystem); - int i; - Scene *blscene = NULL; if (!bfd) { @@ -543,7 +547,7 @@ extern "C" void StartKetsjiShellSimulation(struct ScrArea *area, } else { blscene = bfd->curscene; } - int cframe,startFrame; + int cframe = 1, startFrame; if (blscene) { cframe=blscene->r.cfra; @@ -574,12 +578,14 @@ extern "C" void StartKetsjiShellSimulation(struct ScrArea *area, mousedevice, networkdevice, audiodevice, - startscenename); + startscenename, + blscene); + // some python things PyObject* dictionaryobject = initGamePythonScripting("Ketsji", psl_Lowest); ketsjiengine->SetPythonDictionary(dictionaryobject); initRasterizer(rasterizer, canvas); - PyObject *gameLogic = initGameLogic(startscene); + PyObject *gameLogic = initGameLogic(ketsjiengine, startscene); PyDict_SetItemString(dictionaryobject, "GameLogic", gameLogic); // Same as importing the module initGameKeys(); initPythonConstraintBinding(); diff --git a/source/gameengine/BlenderRoutines/CMakeLists.txt b/source/gameengine/BlenderRoutines/CMakeLists.txt index 1d72fb9cde1..340a1ae310b 100644 --- a/source/gameengine/BlenderRoutines/CMakeLists.txt +++ b/source/gameengine/BlenderRoutines/CMakeLists.txt @@ -31,6 +31,7 @@ SET(INC ../../../intern/SoundSystem ../../../source/blender/misc ../../../source/blender/blenloader + ../../../source/blender/gpu ../../../extern/bullet2/src ../../../extern/solid ../../../extern/glew/include diff --git a/source/gameengine/BlenderRoutines/KX_BlenderGL.cpp b/source/gameengine/BlenderRoutines/KX_BlenderGL.cpp index da52be56d1b..669e7bd1b3f 100644 --- a/source/gameengine/BlenderRoutines/KX_BlenderGL.cpp +++ b/source/gameengine/BlenderRoutines/KX_BlenderGL.cpp @@ -26,7 +26,6 @@ * ***** END GPL LICENSE BLOCK ***** */ -#include "GL/glew.h" #include "KX_BlenderGL.h" #ifdef HAVE_CONFIG_H @@ -93,80 +92,6 @@ void BL_SwapBuffers() myswapbuffers(); } -void BL_RenderText(int mode,const char* textstr,int textlen,struct MTFace* tface, - unsigned int *col,float v1[3],float v2[3],float v3[3],float v4[3]) -{ - Image* ima; - - if(mode & TF_BMFONT) { - //char string[MAX_PROPSTRING]; - int characters, index, character; - float centerx, centery, sizex, sizey, transx, transy, movex, movey, advance; - -// bProperty *prop; - - // string = "Frank van Beek"; - - characters = textlen; - - ima = (struct Image*) tface->tpage; - if (ima == NULL) { - characters = 0; - } - - /* When OBCOL flag is on the color is set in IndexPrimitives_3DText */ - if (tface->mode & TF_OBCOL) { /* Color has been set */ - col= NULL; - } else { - if(!col) glColor3f(1.0f, 1.0f, 1.0f); - } - - glPushMatrix(); - for (index = 0; index < characters; index++) { - // lets calculate offset stuff - character = textstr[index]; - - // space starts at offset 1 - // character = character - ' ' + 1; - - matrixGlyph((ImBuf *)ima->ibufs.first, character, & centerx, ¢ery, &sizex, &sizey, &transx, &transy, &movex, &movey, &advance); - - glBegin(GL_POLYGON); - // printf(" %c %f %f %f %f\n", character, tface->uv[0][0], tface->uv[0][1], ); - // glTexCoord2f((tface->uv[0][0] - centerx) * sizex + transx, (tface->uv[0][1] - centery) * sizey + transy); - glTexCoord2f((tface->uv[0][0] - centerx) * sizex + transx, (tface->uv[0][1] - centery) * sizey + transy); - - if(col) spack(col[0]); - // glVertex3fv(v1); - glVertex3f(sizex * v1[0] + movex, sizey * v1[1] + movey, v1[2]); - - glTexCoord2f((tface->uv[1][0] - centerx) * sizex + transx, (tface->uv[1][1] - centery) * sizey + transy); - if(col) spack(col[1]); - // glVertex3fv(v2); - glVertex3f(sizex * v2[0] + movex, sizey * v2[1] + movey, v2[2]); - - glTexCoord2f((tface->uv[2][0] - centerx) * sizex + transx, (tface->uv[2][1] - centery) * sizey + transy); - if(col) spack(col[2]); - // glVertex3fv(v3); - glVertex3f(sizex * v3[0] + movex, sizey * v3[1] + movey, v3[2]); - - if(v4) { - // glTexCoord2f((tface->uv[3][0] - centerx) * sizex + transx, 1.0 - (1.0 - tface->uv[3][1]) * sizey - transy); - glTexCoord2f((tface->uv[3][0] - centerx) * sizex + transx, (tface->uv[3][1] - centery) * sizey + transy); - if(col) spack(col[3]); - // glVertex3fv(v4); - glVertex3f(sizex * v4[0] + movex, sizey * v4[1] + movey, v4[2]); - } - glEnd(); - - glTranslatef(advance, 0.0, 0.0); - } - glPopMatrix(); - - } -} - - void DisableForText() { if(glIsEnabled(GL_BLEND)) glDisable(GL_BLEND); diff --git a/source/gameengine/BlenderRoutines/KX_BlenderGL.h b/source/gameengine/BlenderRoutines/KX_BlenderGL.h index c8e0d47afb6..b891a7343c2 100644 --- a/source/gameengine/BlenderRoutines/KX_BlenderGL.h +++ b/source/gameengine/BlenderRoutines/KX_BlenderGL.h @@ -46,9 +46,6 @@ void BL_HideMouse(); void BL_NormalMouse(); void BL_WaitMouse(); -void BL_RenderText(int mode,const char* textstr,int textlen,struct MTFace* tface, - unsigned int *col,float v1[3],float v2[3],float v3[3],float v4[3]); - void BL_print_gamedebug_line(char* text, int xco, int yco, int width, int height); void BL_print_gamedebug_line_padded(char* text, int xco, int yco, int width, int height); diff --git a/source/gameengine/BlenderRoutines/KX_BlenderRenderTools.cpp b/source/gameengine/BlenderRoutines/KX_BlenderRenderTools.cpp index dafc2599850..1797d6c1a0f 100644 --- a/source/gameengine/BlenderRoutines/KX_BlenderRenderTools.cpp +++ b/source/gameengine/BlenderRoutines/KX_BlenderRenderTools.cpp @@ -26,8 +26,6 @@ * ***** END GPL LICENSE BLOCK ***** */ -#include "KX_BlenderRenderTools.h" - #include "GL/glew.h" #include "RAS_IRenderTools.h" @@ -36,23 +34,22 @@ #include "RAS_ICanvas.h" #include "RAS_GLExtensionManager.h" -// next two includes/dependencies come from the shadow feature -// it needs the gameobject and the sumo physics scene for a raycast #include "KX_GameObject.h" - #include "KX_PolygonMaterial.h" #include "KX_BlenderMaterial.h" - -#include "Value.h" - -#include "KX_BlenderGL.h" // for text printing -#include "STR_String.h" -#include "RAS_BucketManager.h" // for polymaterial (needed for textprinting) - #include "KX_RayCast.h" #include "KX_IPhysicsController.h" + #include "PHY_IPhysicsEnvironment.h" -#include "KX_Scene.h" + +#include "STR_String.h" + +#include "GPU_draw.h" + +#include "KX_BlenderGL.h" // for text printing +#include "KX_BlenderRenderTools.h" + +unsigned int KX_BlenderRenderTools::m_numgllights; KX_BlenderRenderTools::KX_BlenderRenderTools() { @@ -61,73 +58,90 @@ KX_BlenderRenderTools::KX_BlenderRenderTools() m_numgllights = 8; } -/** -ProcessLighting performs lighting on objects. the layer is a bitfield that contains layer information. -There are 20 'official' layers in blender. -A light is applied on an object only when they are in the same layer. -OpenGL has a maximum of 8 lights (simultaneous), so 20 * 8 lights are possible in a scene. -*/ - -int KX_BlenderRenderTools::ProcessLighting(int layer) +KX_BlenderRenderTools::~KX_BlenderRenderTools() { - - int result = false; - - if (layer < 0) - { - DisableOpenGLLights(); - result = false; - } else - { - if (m_clientobject) - { - if (layer == RAS_LIGHT_OBJECT_LAYER) - { - layer = static_cast(m_clientobject)->GetLayer(); - } - if (applyLights(layer)) - { - EnableOpenGLLights(); - result = true; - } else - { - DisableOpenGLLights(); - result = false; - } - } - } - return result; - - } - void KX_BlenderRenderTools::BeginFrame(RAS_IRasterizer* rasty) { m_clientobject = NULL; - m_lastblenderobject = NULL; - m_lastblenderlights = false; - m_lastlayer = -1; + m_lastlightlayer = -1; m_lastlighting = false; - m_modified = true; DisableOpenGLLights(); - - } -void KX_BlenderRenderTools::SetClientObject(void* obj) +void KX_BlenderRenderTools::EndFrame(RAS_IRasterizer* rasty) +{ +} + +/* ProcessLighting performs lighting on objects. the layer is a bitfield that + * contains layer information. There are 20 'official' layers in blender. A + * light is applied on an object only when they are in the same layer. OpenGL + * has a maximum of 8 lights (simultaneous), so 20 * 8 lights are possible in + * a scene. */ + +void KX_BlenderRenderTools::ProcessLighting(int layer, const MT_Transform& viewmat) +{ + if(m_lastlightlayer == layer) + return; + + m_lastlightlayer = layer; + + bool enable = false; + + if (layer >= 0) + { + if (m_clientobject) + { + if (layer == RAS_LIGHT_OBJECT_LAYER) + layer = static_cast(m_clientobject)->GetLayer(); + + enable = applyLights(layer, viewmat); + } + } + + if(enable) + EnableOpenGLLights(); + else + DisableOpenGLLights(); +} + +void KX_BlenderRenderTools::EnableOpenGLLights() +{ + if(m_lastlighting == true) + return; + + glEnable(GL_LIGHTING); + glEnable(GL_COLOR_MATERIAL); + + glColorMaterial(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE); + glLightModeli(GL_LIGHT_MODEL_TWO_SIDE, true); + if (GLEW_EXT_separate_specular_color || GLEW_VERSION_1_2) + glLightModeli(GL_LIGHT_MODEL_COLOR_CONTROL, GL_SEPARATE_SPECULAR_COLOR); + + m_lastlighting = true; +} + +void KX_BlenderRenderTools::DisableOpenGLLights() +{ + if(m_lastlighting == false) + return; + + glDisable(GL_LIGHTING); + glDisable(GL_COLOR_MATERIAL); + + m_lastlighting = false; +} + + +void KX_BlenderRenderTools::SetClientObject(RAS_IRasterizer *rasty, void* obj) { if (m_clientobject != obj) { - if (obj == NULL || !((KX_GameObject*)obj)->IsNegativeScaling()) - { - glFrontFace(GL_CCW); - } else - { - glFrontFace(GL_CW); - } + bool ccw = (obj == NULL || !((KX_GameObject*)obj)->IsNegativeScaling()); + rasty->SetFrontFace(ccw); + m_clientobject = obj; - m_modified = true; } } @@ -182,7 +196,7 @@ void KX_BlenderRenderTools::applyTransform(RAS_IRasterizer* rasty,double* oglmat MT_Vector3 dir = (campos - objpos).safe_normalized(); MT_Vector3 up(0,0,1.0); - KX_GameObject* gameobj = (KX_GameObject*) this->m_clientobject; + KX_GameObject* gameobj = (KX_GameObject*)m_clientobject; // get scaling of halo object MT_Vector3 size = gameobj->GetSGNode()->GetLocalScale(); @@ -218,7 +232,7 @@ void KX_BlenderRenderTools::applyTransform(RAS_IRasterizer* rasty,double* oglmat { // shadow must be cast to the ground, physics system needed here! MT_Point3 frompoint(oglmatrix[12],oglmatrix[13],oglmatrix[14]); - KX_GameObject *gameobj = (KX_GameObject*) this->m_clientobject; + KX_GameObject *gameobj = (KX_GameObject*)m_clientobject; MT_Vector3 direction = MT_Vector3(0,0,-1); direction.normalize(); @@ -252,13 +266,29 @@ void KX_BlenderRenderTools::applyTransform(RAS_IRasterizer* rasty,double* oglmat } -/** -Render Text renders text into a (series of) polygon, using a texture font, -Each character consists of one polygon (one quad or two triangles) -*/ -void KX_BlenderRenderTools::RenderText(int mode,RAS_IPolyMaterial* polymat,float v1[3],float v2[3],float v3[3],float v4[3]) +void KX_BlenderRenderTools::RenderText2D(RAS_TEXT_RENDER_MODE mode, + const char* text, + int xco, + int yco, + int width, + int height) +{ + STR_String tmpstr(text); + + if(mode == RAS_IRenderTools::RAS_TEXT_PADDED) + BL_print_gamedebug_line_padded(tmpstr.Ptr(), xco, yco, width, height); + else + BL_print_gamedebug_line(tmpstr.Ptr(), xco, yco, width, height); +} + +/* Render Text renders text into a (series of) polygon, using a texture font, + * Each character consists of one polygon (one quad or two triangles) */ + +void KX_BlenderRenderTools::RenderText( + int mode, + RAS_IPolyMaterial* polymat, + float v1[3], float v2[3], float v3[3], float v4[3], int glattrib) { - STR_String mytext = ((CValue*)m_clientobject)->GetPropertyText("Text"); const unsigned int flag = polymat->GetFlag(); @@ -275,68 +305,10 @@ void KX_BlenderRenderTools::RenderText(int mode,RAS_IPolyMaterial* polymat,float col = blenderpoly->GetMCol(); } - BL_RenderText( mode,mytext,mytext.Length(),tface,col,v1,v2,v3,v4); - + GPU_render_text(tface, mode, mytext, mytext.Length(), col, v1, v2, v3, v4, glattrib); } - -KX_BlenderRenderTools::~KX_BlenderRenderTools() -{ -}; - - -void KX_BlenderRenderTools::EndFrame(RAS_IRasterizer* rasty) -{ -} - - - -void KX_BlenderRenderTools::DisableOpenGLLights() -{ - glDisable(GL_LIGHTING); - glDisable(GL_COLOR_MATERIAL); -} - - -void KX_BlenderRenderTools::EnableOpenGLLights() -{ - glEnable(GL_LIGHTING); - - glEnable(GL_COLOR_MATERIAL); - glColorMaterial(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE); - glLightModeli(GL_LIGHT_MODEL_TWO_SIDE, true); - if (GLEW_EXT_separate_specular_color || GLEW_VERSION_1_2) - glLightModeli(GL_LIGHT_MODEL_COLOR_CONTROL, GL_SEPARATE_SPECULAR_COLOR); - -} - - -/** - * Rendering text using 2D bitmap functionality. - */ -void KX_BlenderRenderTools::RenderText2D(RAS_TEXT_RENDER_MODE mode, - const char* text, - int xco, - int yco, - int width, - int height) -{ - switch (mode) { - case RAS_IRenderTools::RAS_TEXT_PADDED: { - STR_String tmpstr(text); - BL_print_gamedebug_line_padded(tmpstr.Ptr(),xco,yco,width,height); - break; - } - default: { - STR_String tmpstr(text); - BL_print_gamedebug_line(tmpstr.Ptr(),xco,yco,width,height); - } - } -} - - - void KX_BlenderRenderTools::PushMatrix() { glPushMatrix(); @@ -348,14 +320,13 @@ void KX_BlenderRenderTools::PopMatrix() } - -int KX_BlenderRenderTools::applyLights(int objectlayer) +int KX_BlenderRenderTools::applyLights(int objectlayer, const MT_Transform& viewmat) { -// taken from blender source, incompatibility between Blender Object / GameObject - + // taken from blender source, incompatibility between Blender Object / GameObject + float glviewmat[16]; unsigned int count; float vec[4]; - + vec[3]= 1.0; for(count=0; count m_lights; std::vector::iterator lit = m_lights.begin(); + + viewmat.getValue(glviewmat); glPushMatrix(); - glLoadMatrixf(m_viewmat); + glLoadMatrixf(glviewmat); for (lit = m_lights.begin(), count = 0; !(lit==m_lights.end()) && count < m_numgllights; ++lit) { RAS_LightObject* lightdata = (*lit); @@ -433,7 +406,6 @@ int KX_BlenderRenderTools::applyLights(int objectlayer) glEnable((GLenum)(GL_LIGHT0+count)); count++; - } } glPopMatrix(); @@ -442,22 +414,6 @@ int KX_BlenderRenderTools::applyLights(int objectlayer) } - - -RAS_IPolyMaterial* KX_BlenderRenderTools::CreateBlenderPolyMaterial( - const STR_String &texname, - bool ba,const STR_String& matname,int tile,int tilexrep,int tileyrep,int mode,bool transparant,bool zsort, int lightlayer - ,bool bIsTriangle,void* clientobject,void* tface) -{ - assert(!"Deprecated"); -/* return new KX_BlenderPolyMaterial( - - texname, - ba,matname,tile,tilexrep,tileyrep,mode,transparant,zsort, lightlayer - ,bIsTriangle,clientobject,(struct MTFace*)tface);*/ - return NULL; -} - void KX_BlenderRenderTools::MotionBlur(RAS_IRasterizer* rasterizer) { int state = rasterizer->GetMotionBlurState(); @@ -491,4 +447,3 @@ void KX_BlenderRenderTools::Render2DFilters(RAS_ICanvas* canvas) m_filtermanager.RenderFilters(canvas); } -unsigned int KX_BlenderRenderTools::m_numgllights; diff --git a/source/gameengine/BlenderRoutines/KX_BlenderRenderTools.h b/source/gameengine/BlenderRoutines/KX_BlenderRenderTools.h index 8027136aa52..a7618462c9b 100644 --- a/source/gameengine/BlenderRoutines/KX_BlenderRenderTools.h +++ b/source/gameengine/BlenderRoutines/KX_BlenderRenderTools.h @@ -26,6 +26,7 @@ * * ***** END GPL LICENSE BLOCK ***** */ + #ifndef __KX_BLENDERRENDERTOOLS #define __KX_BLENDERRENDERTOOLS @@ -39,65 +40,50 @@ struct KX_ClientObjectInfo; class KX_RayCast; -/** -BlenderRenderTools are a set of tools to apply 2D/3D graphics effects, which are not -part of the (polygon) Rasterizer. -Effects like 2D text, 3D (polygon) text, lighting. -*/ +/* BlenderRenderTools are a set of tools to apply 2D/3D graphics effects, which + * are not part of the (polygon) Rasterizer. Effects like 2D text, 3D (polygon) + * text, lighting. + * + * Most of this code is duplicated in GPC_RenderTools, so this should be + * moved to some common location to avoid duplication. */ class KX_BlenderRenderTools : public RAS_IRenderTools { - bool m_lastblenderlights; - void* m_lastblenderobject; - int m_lastlayer; + int m_lastlightlayer; bool m_lastlighting; static unsigned int m_numgllights; - - + public: - KX_BlenderRenderTools(); virtual ~KX_BlenderRenderTools(); - virtual void EndFrame(class RAS_IRasterizer* rasty); - virtual void BeginFrame(class RAS_IRasterizer* rasty); - void DisableOpenGLLights(); - void EnableOpenGLLights(); - int ProcessLighting(int layer); + void EndFrame(RAS_IRasterizer* rasty); + void BeginFrame(RAS_IRasterizer* rasty); - virtual void RenderText2D(RAS_TEXT_RENDER_MODE mode, + void EnableOpenGLLights(); + void DisableOpenGLLights(); + void ProcessLighting(int layer, const MT_Transform& viewmat); + + void RenderText2D(RAS_TEXT_RENDER_MODE mode, const char* text, int xco, int yco, int width, int height); - virtual void RenderText(int mode, + void RenderText(int mode, class RAS_IPolyMaterial* polymat, float v1[3], float v2[3], float v3[3], - float v4[3]); - void applyTransform(class RAS_IRasterizer* rasty, - double* oglmatrix, - int objectdrawmode ); - int applyLights(int objectlayer); - virtual void PushMatrix(); - virtual void PopMatrix(); + float v4[3], + int glattrib); + + void applyTransform(RAS_IRasterizer* rasty, double* oglmatrix, int objectdrawmode); + int applyLights(int objectlayer, const MT_Transform& viewmat); + + void PushMatrix(); + void PopMatrix(); - virtual class RAS_IPolyMaterial* CreateBlenderPolyMaterial(const STR_String &texname, - bool ba, - const STR_String& matname, - int tile, - int tilexrep, - int tileyrep, - int mode, - bool transparant, - bool zsort, - int lightlayer, - bool bIsTriangle, - void* clientobject, - void* tface); - bool RayHit(KX_ClientObjectInfo* client, class KX_RayCast* result, void * const data); bool NeedRayCast(KX_ClientObjectInfo*) { return true; } @@ -107,8 +93,7 @@ public: virtual void Render2DFilters(RAS_ICanvas* canvas); - virtual void SetClientObject(void* obj); - + virtual void SetClientObject(RAS_IRasterizer *rasty, void* obj); }; #endif //__KX_BLENDERRENDERTOOLS diff --git a/source/gameengine/BlenderRoutines/Makefile b/source/gameengine/BlenderRoutines/Makefile index a7394158a20..4b9a2a3af17 100644 --- a/source/gameengine/BlenderRoutines/Makefile +++ b/source/gameengine/BlenderRoutines/Makefile @@ -54,6 +54,7 @@ CPPFLAGS += -I../../blender/blenkernel CPPFLAGS += -I../../blender/render/extern/include CPPFLAGS += -I../../blender/blenloader CPPFLAGS += -I../../blender/blenkernel +CPPFLAGS += -I../../blender/gpu CPPFLAGS += -I../Converter CPPFLAGS += -I../Expressions CPPFLAGS += -I../GameLogic @@ -72,9 +73,5 @@ ifeq ($(OS),windows) CPPFLAGS += -I../../blender endif -ifeq ($(WITH_BF_GLEXT),true) - CPPFLAGS += -DWITH_GLEXT -endif - CPPFLAGS += -I$(NAN_PYTHON)/include/python$(NAN_PYTHON_VERSION) diff --git a/source/gameengine/BlenderRoutines/SConscript b/source/gameengine/BlenderRoutines/SConscript index 327f4798e04..78adbc83d9b 100644 --- a/source/gameengine/BlenderRoutines/SConscript +++ b/source/gameengine/BlenderRoutines/SConscript @@ -15,7 +15,7 @@ incs += ' #source/gameengine/SceneGraph #source/gameengine/Physics/common' incs += ' #source/gameengine/Physics/Bullet #source/gameengine/Physics/Sumo' incs += ' #source/gameengine/Physics/Sumo/Fuzzics/include #source/gameengine/Network/LoopBackNetwork' incs += ' #intern/SoundSystem #source/blender/misc #source/blender/blenloader' -incs += ' #extern/glew/include' +incs += ' #extern/glew/include #source/blender/gpu' incs += ' ' + env['BF_PYTHON_INC'] incs += ' ' + env['BF_SOLID_INC'] @@ -26,7 +26,4 @@ cxxflags = [] if env['OURPLATFORM']=='win32-vc': cxxflags.append ('/GR') -if env['WITH_BF_GLEXT'] == 1: - env['CPPFLAGS'].append('-DWITH_GLEXT') - env.BlenderLib ( 'bf_bloutines', sources, Split(incs), [], libtype=['game', 'game2', 'player'], priority=[0, 0, 55] , compileflags=cxxflags) diff --git a/source/gameengine/Converter/BL_ArmatureObject.cpp b/source/gameengine/Converter/BL_ArmatureObject.cpp index cdfce321713..bf774bf7568 100644 --- a/source/gameengine/Converter/BL_ArmatureObject.cpp +++ b/source/gameengine/Converter/BL_ArmatureObject.cpp @@ -53,16 +53,20 @@ BL_ArmatureObject::BL_ArmatureObject( : KX_GameObject(sgReplicationInfo,callbacks), m_objArma(armature), - m_mrdPose(NULL), m_framePose(NULL), - m_lastframe(0.), + m_lastframe(0.0), m_activeAct(NULL), - m_activePriority(999) + m_activePriority(999), + m_lastapplyframe(0.0) { m_armature = get_armature(m_objArma); - m_pose = m_objArma->pose; -} + /* we make a copy of blender object's pose, and then always swap it with + * the original pose before calling into blender functions, to deal with + * replica's or other objects using the same blender object */ + m_pose = NULL; + copy_pose(&m_pose, m_objArma->pose, 1 /* copy_constraint_channels_hack */); +} CValue* BL_ArmatureObject::GetReplica() { @@ -79,34 +83,39 @@ void BL_ArmatureObject::ProcessReplica(BL_ArmatureObject *replica) { KX_GameObject::ProcessReplica(replica); + replica->m_pose = NULL; + copy_pose(&replica->m_pose, m_pose, 1 /* copy_constraint_channels_hack */); } BL_ArmatureObject::~BL_ArmatureObject() { - if (m_mrdPose) - free_pose(m_mrdPose); + if (m_pose) + free_pose(m_pose); +} + +bool BL_ArmatureObject::VerifyPose() +{ + if(m_lastapplyframe != m_lastframe) { + extract_pose_from_pose(m_objArma->pose, m_pose); + where_is_pose(m_objArma); + m_lastapplyframe = m_lastframe; + extract_pose_from_pose(m_pose, m_objArma->pose); + return false; + } + else + return true; } -/* note, you can only call this for exisiting Armature objects, and not mix it with other Armatures */ -/* there is only 1 unique Pose per Armature */ void BL_ArmatureObject::ApplyPose() { - if (m_pose) { - // copy to armature object - if (m_objArma->pose != m_pose)/* This should never happen but it does - Campbell */ - extract_pose_from_pose(m_objArma->pose, m_pose); - - // is this needed anymore? - //if (!m_mrdPose) - // copy_pose (&m_mrdPose, m_pose, 0); - //else - // extract_pose_from_pose(m_mrdPose, m_pose); - } + if(VerifyPose()) + extract_pose_from_pose(m_objArma->pose, m_pose); } void BL_ArmatureObject::SetPose(bPose *pose) { - m_pose = pose; + extract_pose_from_pose(m_pose, pose); + m_lastapplyframe = -1.0; } bool BL_ArmatureObject::SetActiveAction(BL_ActionActuator *act, short priority, double curtime) @@ -162,6 +171,7 @@ void BL_ArmatureObject::GetPose(bPose **pose) if (*pose == m_pose) // no need to copy if the pointers are the same return; + extract_pose_from_pose(*pose, m_pose); } } @@ -171,20 +181,16 @@ void BL_ArmatureObject::GetMRDPose(bPose **pose) /* If the caller supplies a null pose, create a new one. */ /* Otherwise, copy the armature's pose channels into the caller-supplied pose */ - // is this needed anymore? - //if (!m_mrdPose){ - // copy_pose (&m_mrdPose, m_pose, 0); - //} - if (!*pose) { // must duplicate the constraints too otherwise we have corruption in free_pose_channels() // because it will free the blender constraints. // Ideally, blender should rememeber that the constraints were not copied so that // free_pose_channels() would not free them. - copy_pose(pose, m_objArma->pose, 1); + copy_pose(pose, m_pose, 1); + } + else { + extract_pose_from_pose(*pose, m_pose); } - else - extract_pose_from_pose(*pose, m_objArma->pose); } @@ -198,16 +204,18 @@ double BL_ArmatureObject::GetLastFrame() return m_lastframe; } -bool BL_ArmatureObject::GetBoneMatrix(Bone* bone, MT_Matrix4x4& matrix) const +bool BL_ArmatureObject::GetBoneMatrix(Bone* bone, MT_Matrix4x4& matrix) { - Object* par_arma = m_objArma; - where_is_pose(par_arma); - bPoseChannel *pchan= get_pose_channel(par_arma->pose, bone->name); + bPoseChannel *pchan; + + ApplyPose(); + pchan = get_pose_channel(m_objArma->pose, bone->name); if(pchan) { matrix.setValue(&pchan->pose_mat[0][0]); return true; } + return false; } diff --git a/source/gameengine/Converter/BL_ArmatureObject.h b/source/gameengine/Converter/BL_ArmatureObject.h index a612ca77ec0..6f2c0d2f4c9 100644 --- a/source/gameengine/Converter/BL_ArmatureObject.h +++ b/source/gameengine/Converter/BL_ArmatureObject.h @@ -59,7 +59,10 @@ public: void GetMRDPose(struct bPose **pose); void GetPose(struct bPose **pose); void SetPose (struct bPose *pose); + void ApplyPose(); + bool VerifyPose(); + bool SetActiveAction(class BL_ActionActuator *act, short priority, double curtime); struct bArmature * GetArmature() { return m_armature; } @@ -69,7 +72,7 @@ public: /// Retrieve the pose matrix for the specified bone. /// Returns true on success. - bool GetBoneMatrix(Bone* bone, MT_Matrix4x4& matrix) const; + bool GetBoneMatrix(Bone* bone, MT_Matrix4x4& matrix); /// Returns the bone length. The end of the bone is in the local y direction. float GetBoneLength(Bone* bone) const; @@ -79,11 +82,12 @@ protected: Object *m_objArma; struct bArmature *m_armature; struct bPose *m_pose; - struct bPose *m_mrdPose; struct bPose *m_framePose; double m_lastframe; class BL_ActionActuator *m_activeAct; short m_activePriority; + + double m_lastapplyframe; }; #endif diff --git a/source/gameengine/Converter/BL_BlenderDataConversion.cpp b/source/gameengine/Converter/BL_BlenderDataConversion.cpp index edc14dabc70..def4938b053 100644 --- a/source/gameengine/Converter/BL_BlenderDataConversion.cpp +++ b/source/gameengine/Converter/BL_BlenderDataConversion.cpp @@ -601,7 +601,6 @@ BL_Material* ConvertMaterial( (tface->mode & TF_INVISIBLE) )?POLY_VIS:0; - material->ras_mode |= ( (tface->mode & TF_DYNAMIC)!= 0 )?COLLIDER:0; material->transp = tface->transp; material->tile = tface->tile; material->mode = tface->mode; @@ -617,7 +616,7 @@ BL_Material* ConvertMaterial( } else { // nothing at all - material->ras_mode |= (COLLIDER|POLY_VIS| (validmat?0:USE_LIGHT)); + material->ras_mode |= (POLY_VIS| (validmat?0:USE_LIGHT)); material->mode = default_face_mode; material->transp = TF_SOLID; material->tile = 0; @@ -627,13 +626,19 @@ BL_Material* ConvertMaterial( if(validmat && (mat->mode & MA_ZTRA) && (material->transp == TF_SOLID)) material->transp = TF_ALPHA; - // always zsort alpha + add - if((material->transp == TF_ALPHA || material->transp == TF_ADD || texalpha) - && (material->transp != TF_CLIP)) { + // always zsort alpha + add + if((material->transp == TF_ALPHA || texalpha) && (material->transp != TF_CLIP)) { material->ras_mode |= ALPHA; material->ras_mode |= (material->mode & TF_ALPHASORT)? ZSORT: 0; } + // collider or not? + material->ras_mode |= (material->mode & TF_DYNAMIC)? COLLIDER: 0; + + // these flags are irrelevant at this point, remove so they + // don't hurt material bucketing + material->mode &= ~(TF_DYNAMIC|TF_ALPHASORT|TF_TEX); + // get uv sets if(validmat) { @@ -644,6 +649,7 @@ BL_Material* ConvertMaterial( for (int vind = 0; vindnum_enabled; vind++) { BL_Mapping &map = material->mapping[vind]; + if (map.uvCoName.IsEmpty()) isFirstSet = false; else @@ -673,7 +679,7 @@ BL_Material* ConvertMaterial( isFirstSet = false; uvName = layer.name; } - else + else if(strcmp(layer.name, uvName) != 0) { uv2[0] = uvSet[0]; uv2[1] = uvSet[1]; uv2[2] = uvSet[2]; uv2[3] = uvSet[3]; @@ -702,7 +708,6 @@ BL_Material* ConvertMaterial( material->SetConversionUV(uvName, uv); material->SetConversionUV2(uv2Name, uv2); - material->ras_mode |= (mface->v4==0)?TRIANGLE:0; if(validmat) material->matname =(mat->id.name); @@ -767,7 +772,7 @@ RAS_MeshObject* BL_ConvertMesh(Mesh* mesh, Object* blenderobj, RAS_IRenderTools* } meshobj->SetName(mesh->id.name); - meshobj->m_xyz_index_to_vertex_index_mapping.resize(totvert); + meshobj->m_sharedvertex_map.resize(totvert); for (int f=0;fmat_nr+1); { - bool polyvisible = true; + bool visible = true; RAS_IPolyMaterial* polymat = NULL; BL_Material *bl_mat = NULL; @@ -845,7 +850,7 @@ RAS_MeshObject* BL_ConvertMesh(Mesh* mesh, Object* blenderobj, RAS_IRenderTools* bl_mat->material_index = (int)mface->mat_nr; - polyvisible = ((bl_mat->ras_mode & POLY_VIS)!=0); + visible = ((bl_mat->ras_mode & POLY_VIS)!=0); collider = ((bl_mat->ras_mode & COLLIDER)!=0); /* vertex colors and uv's were stored in bl_mat temporarily */ @@ -862,7 +867,7 @@ RAS_MeshObject* BL_ConvertMesh(Mesh* mesh, Object* blenderobj, RAS_IRenderTools* uv22 = uv[2]; uv23 = uv[3]; /* then the KX_BlenderMaterial */ - polymat = new KX_BlenderMaterial(scene, bl_mat, skinMesh, lightlayer, blenderobj ); + polymat = new KX_BlenderMaterial(scene, bl_mat, skinMesh, lightlayer); } else { /* do Texture Face materials */ @@ -886,7 +891,7 @@ RAS_MeshObject* BL_ConvertMesh(Mesh* mesh, Object* blenderobj, RAS_IRenderTools* tile = tface->tile; mode = tface->mode; - polyvisible = !((mface->flag & ME_HIDE)||(tface->mode & TF_INVISIBLE)); + visible = !((mface->flag & ME_HIDE)||(tface->mode & TF_INVISIBLE)); uv0 = MT_Point2(tface->uv[0]); uv1 = MT_Point2(tface->uv[1]); @@ -940,15 +945,13 @@ RAS_MeshObject* BL_ConvertMesh(Mesh* mesh, Object* blenderobj, RAS_IRenderTools* rgb3 = KX_rgbaint2uint_new(color); } - bool istriangle = (mface->v4==0); - // only zsort alpha + add bool alpha = (transp == TF_ALPHA || transp == TF_ADD); bool zsort = (mode & TF_ALPHASORT)? alpha: 0; polymat = new KX_PolygonMaterial(imastr, ma, tile, tilexrep, tileyrep, - mode, transp, alpha, zsort, lightlayer, istriangle, blenderobj, tface, (unsigned int*)mcol); + mode, transp, alpha, zsort, lightlayer, tface, (unsigned int*)mcol); if (ma) { polymat->m_specular = MT_Vector3(ma->specr, ma->specg, ma->specb)*ma->spec; @@ -961,6 +964,9 @@ RAS_MeshObject* BL_ConvertMesh(Mesh* mesh, Object* blenderobj, RAS_IRenderTools* } } + /* mark face as flat, so vertices are split */ + bool flat = (mface->flag & ME_SMOOTH) == 0; + // see if a bucket was reused or a new one was created // this way only one KX_BlenderMaterial object has to exist per bucket bool bucketCreated; @@ -981,49 +987,19 @@ RAS_MeshObject* BL_ConvertMesh(Mesh* mesh, Object* blenderobj, RAS_IRenderTools* polymat = bucket->GetPolyMaterial(); } - int nverts = mface->v4?4:3; - int vtxarray = meshobj->FindVertexArray(nverts,polymat); - RAS_Polygon* poly = new RAS_Polygon(bucket,polyvisible,nverts,vtxarray); + int nverts = (mface->v4)? 4: 3; + RAS_Polygon *poly = meshobj->AddPolygon(bucket, nverts); - bool flat; - - if (skinMesh) { - /* If the face is set to solid, all fnors are the same */ - if (mface->flag & ME_SMOOTH) - flat = false; - else - flat = true; - } - else - flat = false; - - poly->SetVertex(0,meshobj->FindOrAddVertex(vtxarray,pt0,uv0,uv20,tan0,rgb0,no0,flat,polymat,mface->v1)); - poly->SetVertex(1,meshobj->FindOrAddVertex(vtxarray,pt1,uv1,uv21,tan1,rgb1,no1,flat,polymat,mface->v2)); - poly->SetVertex(2,meshobj->FindOrAddVertex(vtxarray,pt2,uv2,uv22,tan2,rgb2,no2,flat,polymat,mface->v3)); - if (nverts==4) - poly->SetVertex(3,meshobj->FindOrAddVertex(vtxarray,pt3,uv3,uv23,tan3,rgb3,no3,flat,polymat,mface->v4)); - - meshobj->AddPolygon(poly); - if (poly->IsCollider()) - { - RAS_TriangleIndex idx; - idx.m_index[0] = mface->v1; - idx.m_index[1] = mface->v2; - idx.m_index[2] = mface->v3; - idx.m_collider = collider; - meshobj->m_triangle_indices.push_back(idx); - if (nverts==4) - { - idx.m_index[0] = mface->v1; - idx.m_index[1] = mface->v3; - idx.m_index[2] = mface->v4; - idx.m_collider = collider; - meshobj->m_triangle_indices.push_back(idx); - } - } - -// poly->SetVisibleWireframeEdges(mface->edcode); + poly->SetVisible(visible); poly->SetCollider(collider); + //poly->SetEdgeCode(mface->edcode); + + meshobj->AddVertex(poly,0,pt0,uv0,uv20,tan0,rgb0,no0,flat,mface->v1); + meshobj->AddVertex(poly,1,pt1,uv1,uv21,tan1,rgb1,no1,flat,mface->v2); + meshobj->AddVertex(poly,2,pt2,uv2,uv22,tan2,rgb2,no2,flat,mface->v3); + + if (nverts==4) + meshobj->AddVertex(poly,3,pt3,uv3,uv23,tan3,rgb3,no3,flat,mface->v4); } if (tface) @@ -1039,13 +1015,12 @@ RAS_MeshObject* BL_ConvertMesh(Mesh* mesh, Object* blenderobj, RAS_IRenderTools* layer.face++; } } - meshobj->m_xyz_index_to_vertex_index_mapping.clear(); - meshobj->UpdateMaterialList(); + meshobj->m_sharedvertex_map.clear(); // pre calculate texture generation - for(RAS_MaterialBucket::Set::iterator mit = meshobj->GetFirstMaterial(); + for(list::iterator mit = meshobj->GetFirstMaterial(); mit != meshobj->GetLastMaterial(); ++ mit) { - (*mit)->GetPolyMaterial()->OnConstruction(); + mit->m_bucket->GetPolyMaterial()->OnConstruction(); } if (layers) @@ -1490,14 +1465,9 @@ static KX_LightObject *gamelight_from_blamp(Object *ob, Lamp *la, unsigned int l lightobj.m_type = RAS_LightObject::LIGHT_NORMAL; } -#ifdef BLENDER_GLSL - if(converter->GetGLSLMaterials()) - GPU_lamp_from_blender(ob, la); - - gamelight = new KX_LightObject(kxscene, KX_Scene::m_callbacks, rendertools, lightobj, ob->gpulamp); -#else - gamelight = new KX_LightObject(kxscene, KX_Scene::m_callbacks, rendertools, lightobj, NULL); -#endif + gamelight = new KX_LightObject(kxscene, KX_Scene::m_callbacks, rendertools, + lightobj, converter->GetGLSLMaterials()); + BL_ConvertLampIpos(la, gamelight, converter); return gamelight; @@ -1534,7 +1504,7 @@ static KX_GameObject *gameobject_from_blenderobject( gamelight->AddRef(); kxscene->GetLightList()->Add(gamelight); - + break; } @@ -1643,20 +1613,6 @@ struct parentChildLink { SG_Node* m_gamechildnode; }; - /** - * Find the specified scene by name, or the first - * scene if nothing matches (shouldn't happen). - */ -static struct Scene *GetSceneForName(struct Main *maggie, const STR_String& scenename) { - Scene *sce; - - for (sce= (Scene*) maggie->scene.first; sce; sce= (Scene*) sce->id.next) - if (scenename == (sce->id.name+2)) - return sce; - - return (Scene*) maggie->scene.first; -} - #include "DNA_constraint_types.h" #include "BIF_editconstraint.h" @@ -1755,7 +1711,7 @@ void BL_ConvertBlenderObjects(struct Main* maggie, ) { - Scene *blenderscene = GetSceneForName(maggie, scenename); + Scene *blenderscene = converter->GetBlenderSceneForName(scenename); // for SETLOOPER Scene *sce; Base *base; @@ -1990,7 +1946,7 @@ void BL_ConvertBlenderObjects(struct Main* maggie, //tf.Add(gameobj->GetSGNode()); gameobj->NodeUpdateGS(0,true); - gameobj->Bucketize(); + gameobj->AddMeshUser(); } else @@ -2187,7 +2143,7 @@ void BL_ConvertBlenderObjects(struct Main* maggie, //tf.Add(gameobj->GetSGNode()); gameobj->NodeUpdateGS(0,true); - gameobj->Bucketize(); + gameobj->AddMeshUser(); } else @@ -2273,8 +2229,11 @@ void BL_ConvertBlenderObjects(struct Main* maggie, { // parent this to a bone Bone *parent_bone = get_named_bone(get_armature(blenderchild->parent), blenderchild->parsubstr); - KX_BoneParentRelation *bone_parent_relation = KX_BoneParentRelation::New(parent_bone); - pcit->m_gamechildnode->SetParentRelation(bone_parent_relation); + + if(parent_bone) { + KX_BoneParentRelation *bone_parent_relation = KX_BoneParentRelation::New(parent_bone); + pcit->m_gamechildnode->SetParentRelation(bone_parent_relation); + } break; } @@ -2511,5 +2470,10 @@ void BL_ConvertBlenderObjects(struct Main* maggie, kxscene->DupliGroupRecurse(gameobj, 0); } } + + KX_Camera *activecam = kxscene->GetActiveCamera(); + MT_Scalar distance = (activecam)? activecam->GetCameraFar() - activecam->GetCameraNear(): 100.0f; + RAS_BucketManager *bucketmanager = kxscene->GetBucketManager(); + bucketmanager->OptimizeBuckets(distance); } diff --git a/source/gameengine/Converter/BL_DeformableGameObject.cpp b/source/gameengine/Converter/BL_DeformableGameObject.cpp index d23274324ee..1d62a41cce9 100644 --- a/source/gameengine/Converter/BL_DeformableGameObject.cpp +++ b/source/gameengine/Converter/BL_DeformableGameObject.cpp @@ -41,12 +41,14 @@ BL_DeformableGameObject::~BL_DeformableGameObject() delete m_pDeformer; // __NLA : Temporary until we decide where to put this } -void BL_DeformableGameObject::ProcessReplica(KX_GameObject* replica) +void BL_DeformableGameObject::ProcessReplica(KX_GameObject* replica) { + BL_MeshDeformer *deformer; KX_GameObject::ProcessReplica(replica); - if (m_pDeformer){ - ((BL_DeformableGameObject*)replica)->m_pDeformer = m_pDeformer->GetReplica(); + if (m_pDeformer) { + deformer = (BL_MeshDeformer*)m_pDeformer->GetReplica(); + ((BL_DeformableGameObject*)replica)->m_pDeformer = deformer; } } diff --git a/source/gameengine/Converter/BL_MeshDeformer.cpp b/source/gameengine/Converter/BL_MeshDeformer.cpp index 39d66a90e92..fa3b8185fe2 100644 --- a/source/gameengine/Converter/BL_MeshDeformer.cpp +++ b/source/gameengine/Converter/BL_MeshDeformer.cpp @@ -50,26 +50,26 @@ bool BL_MeshDeformer::Apply(RAS_IPolyMaterial*) { - size_t i, j; + size_t i; float *co; // only apply once per frame if the mesh is actually modified if(m_pMeshObject->MeshModified() && m_lastDeformUpdate != m_gameobj->GetLastFrame()) { // For each material - for(RAS_MaterialBucket::Set::iterator mit = m_pMeshObject->GetFirstMaterial(); + for(list::iterator mit= m_pMeshObject->GetFirstMaterial(); mit != m_pMeshObject->GetLastMaterial(); ++ mit) { - RAS_IPolyMaterial *mat = (*mit)->GetPolyMaterial(); + if(!mit->m_slots[(void*)m_gameobj]) + continue; - vecVertexArray& vertexarrays = m_pMeshObject->GetVertexCache(mat); - - // For each array - for (i=0; im_slots[(void*)m_gameobj]; + RAS_MeshSlot::iterator it; + // for each array + for(slot->begin(it); !slot->end(it); slot->next(it)) { // For each vertex - for (j=0; jmvert[v.getOrigIndex()].co; v.SetXYZ(MT_Point3(co)); } @@ -90,7 +90,17 @@ BL_MeshDeformer::~BL_MeshDeformer() delete [] m_transverts; if (m_transnors) delete [] m_transnors; -}; +} + +void BL_MeshDeformer::Relink(GEN_Map*map) +{ + void **h_obj = (*map)[m_gameobj]; + + if (h_obj) + m_gameobj = (BL_DeformableGameObject*)(*h_obj); + else + m_gameobj = NULL; +} /** * @warning This function is expensive! @@ -101,41 +111,41 @@ void BL_MeshDeformer::RecalcNormals() * gives area-weight normals which often look better anyway, and use * GL_NORMALIZE so we don't have to do per vertex normalization either * since the GPU can do it faster */ - size_t i, j; + list::iterator mit; + RAS_MeshSlot::iterator it; + size_t i; /* set vertex normals to zero */ memset(m_transnors, 0, sizeof(float)*3*m_bmesh->totvert); /* add face normals to vertices. */ - for(RAS_MaterialBucket::Set::iterator mit = m_pMeshObject->GetFirstMaterial(); + for(mit = m_pMeshObject->GetFirstMaterial(); mit != m_pMeshObject->GetLastMaterial(); ++ mit) { - RAS_IPolyMaterial *mat = (*mit)->GetPolyMaterial(); + if(!mit->m_slots[(void*)m_gameobj]) + continue; - const vecIndexArrays& indexarrays = m_pMeshObject->GetIndexCache(mat); - vecVertexArray& vertexarrays = m_pMeshObject->GetVertexCache(mat); + RAS_MeshSlot *slot = *mit->m_slots[(void*)m_gameobj]; - for (i=0; iUsesTriangles()? 3: 4; + for(slot->begin(it); !slot->end(it); slot->next(it)) { + int nvert = (int)it.array->m_type; - for(j=0; jgetLocalXYZ(); + v4 = &it.vertex[it.index[i+3]]; + co4 = v4->getXYZ(); n1[0]= co1[0]-co3[0]; n1[1]= co1[1]-co3[1]; @@ -174,7 +184,7 @@ void BL_MeshDeformer::RecalcNormals() } /* in case of flat - just assign, the vertices are split */ - if(v1.getFlag() & TV_CALCFACENORMAL) { + if(v1.getFlag() & RAS_TexVert::FLAT) { v1.SetNormal(fnor); v2.SetNormal(fnor); v3.SetNormal(fnor); @@ -186,19 +196,18 @@ void BL_MeshDeformer::RecalcNormals() } /* assign smooth vertex normals */ - for(RAS_MaterialBucket::Set::iterator mit = m_pMeshObject->GetFirstMaterial(); + for(mit = m_pMeshObject->GetFirstMaterial(); mit != m_pMeshObject->GetLastMaterial(); ++ mit) { - RAS_IPolyMaterial *mat = (*mit)->GetPolyMaterial(); + if(!mit->m_slots[(void*)m_gameobj]) + continue; - vecVertexArray& vertexarrays = m_pMeshObject->GetVertexCache(mat); + RAS_MeshSlot *slot = *mit->m_slots[(void*)m_gameobj]; - for (i=0; ibegin(it); !slot->end(it); slot->next(it)) { + for(i=it.startvertex; itotvert; } } - + diff --git a/source/gameengine/Converter/BL_MeshDeformer.h b/source/gameengine/Converter/BL_MeshDeformer.h index e9f7f0b192f..9d3d2e78123 100644 --- a/source/gameengine/Converter/BL_MeshDeformer.h +++ b/source/gameengine/Converter/BL_MeshDeformer.h @@ -47,7 +47,7 @@ class BL_MeshDeformer : public RAS_Deformer public: void VerifyStorage(); void RecalcNormals(); - virtual void Relink(GEN_Map*map){}; + virtual void Relink(GEN_Map*map); BL_MeshDeformer(BL_DeformableGameObject *gameobj, struct Object* obj, class BL_SkinMeshObject *meshobj ): @@ -67,6 +67,7 @@ public: virtual RAS_Deformer* GetReplica(){return NULL;}; struct Mesh* GetMesh() { return m_bmesh; }; // virtual void InitDeform(double time){}; + protected: class BL_SkinMeshObject* m_pMeshObject; struct Mesh* m_bmesh; diff --git a/source/gameengine/Converter/BL_ShapeActionActuator.cpp b/source/gameengine/Converter/BL_ShapeActionActuator.cpp index 942e3b502e0..799b6b74b66 100644 --- a/source/gameengine/Converter/BL_ShapeActionActuator.cpp +++ b/source/gameengine/Converter/BL_ShapeActionActuator.cpp @@ -134,7 +134,6 @@ void BL_ShapeActionActuator::BlendShape(Key* key, float srcweight) { vector::const_iterator it; float dstweight; - int i; KeyBlock *kb; dstweight = 1.0F - srcweight; diff --git a/source/gameengine/Converter/BL_ShapeDeformer.cpp b/source/gameengine/Converter/BL_ShapeDeformer.cpp index b2e54539b19..236cd1a6667 100644 --- a/source/gameengine/Converter/BL_ShapeDeformer.cpp +++ b/source/gameengine/Converter/BL_ShapeDeformer.cpp @@ -111,10 +111,7 @@ bool BL_ShapeDeformer::ExecuteShapeDrivers(void) int type; // the shape drivers use the bone matrix as input. Must // update the matrix now - Object* par_arma = m_armobj->GetArmatureObject(); m_armobj->ApplyPose(); - where_is_pose( par_arma ); - PoseApplied(true); for (it=m_shapeDrivers.begin(); it!=m_shapeDrivers.end(); it++) { // no need to set a specific time: this curve has a driver diff --git a/source/gameengine/Converter/BL_ShapeDeformer.h b/source/gameengine/Converter/BL_ShapeDeformer.h index 5f0188e3a42..1465bb01e22 100644 --- a/source/gameengine/Converter/BL_ShapeDeformer.h +++ b/source/gameengine/Converter/BL_ShapeDeformer.h @@ -43,17 +43,6 @@ struct IpoCurve; class BL_ShapeDeformer : public BL_SkinDeformer { public: - virtual void Relink(GEN_Map*map) - { - void **h_obj = (*map)[m_gameobj]; - if (h_obj){ - m_gameobj = (BL_DeformableGameObject*)(*h_obj); - } - else - m_gameobj=NULL; - // relink the underlying skin deformer - BL_SkinDeformer::Relink(map); - }; BL_ShapeDeformer(BL_DeformableGameObject *gameobj, Object *bmeshobj, BL_SkinMeshObject *mesh) diff --git a/source/gameengine/Converter/BL_SkinDeformer.cpp b/source/gameengine/Converter/BL_SkinDeformer.cpp index f96c40c098f..d8e7a9cdadf 100644 --- a/source/gameengine/Converter/BL_SkinDeformer.cpp +++ b/source/gameengine/Converter/BL_SkinDeformer.cpp @@ -99,9 +99,26 @@ BL_SkinDeformer::~BL_SkinDeformer() m_armobj->Release(); } +void BL_SkinDeformer::Relink(GEN_Map*map) +{ + if (m_armobj) { + void **h_obj = (*map)[m_armobj]; + + if (h_obj) + SetArmature( (BL_ArmatureObject*)(*h_obj) ); + else + m_armobj=NULL; + } + + BL_MeshDeformer::Relink(map); +} + bool BL_SkinDeformer::Apply(RAS_IPolyMaterial *mat) { - size_t i, j; + RAS_MeshSlot::iterator it; + RAS_MeshMaterial *mmat; + RAS_MeshSlot *slot; + size_t i; // update the vertex in m_transverts Update(); @@ -110,16 +127,18 @@ bool BL_SkinDeformer::Apply(RAS_IPolyMaterial *mat) // Duplicated objects with more than one ploymaterial (=multiple mesh slot per object) // share the same mesh (=the same cache). As the rendering is done per polymaterial // cycling through the objects, the entire mesh cache cannot be updated in one shot. - vecVertexArray& vertexarrays = m_pMeshObject->GetVertexCache(mat); + mmat = m_pMeshObject->GetMeshMaterial(mat); + if(!mmat->m_slots[(void*)m_gameobj]) + return true; - // For each array - for (i=0; im_slots[(void*)m_gameobj]; - // For each vertex + // for each array + for(slot->begin(it); !slot->end(it); slot->next(it)) { + // for each vertex // copy the untransformed data from the original mvert - for (j=0; jGetArmatureObject(); - if (!PoseApplied()){ - m_armobj->ApplyPose(); - where_is_pose( par_arma ); - } /* store verts locally */ VerifyStorage(); @@ -163,6 +178,8 @@ bool BL_SkinDeformer::Update(void) for (int v =0; vtotvert; v++) VECCOPY(m_transverts[v], m_bmesh->mvert[v].co); + m_armobj->ApplyPose(); + // save matrix first Mat4CpyMat4(obmat, m_objMesh->obmat); // set reference matrix @@ -179,11 +196,11 @@ bool BL_SkinDeformer::Update(void) /* Update the current frame */ m_lastArmaUpdate=m_armobj->GetLastFrame(); - /* reset for next frame */ - PoseApplied(false); + /* indicate that the m_transverts and normals are up to date */ return true; } + return false; } diff --git a/source/gameengine/Converter/BL_SkinDeformer.h b/source/gameengine/Converter/BL_SkinDeformer.h index d3fc5ae2a81..e08de8c478a 100644 --- a/source/gameengine/Converter/BL_SkinDeformer.h +++ b/source/gameengine/Converter/BL_SkinDeformer.h @@ -50,17 +50,7 @@ class BL_SkinDeformer : public BL_MeshDeformer { public: // void SetArmatureController (BL_ArmatureController *cont); - virtual void Relink(GEN_Map*map) - { - if (m_armobj){ - void **h_obj = (*map)[m_armobj]; - if (h_obj){ - SetArmature( (BL_ArmatureObject*)(*h_obj) ); - } - else - m_armobj=NULL; - } - } + virtual void Relink(GEN_Map*map); void SetArmature (class BL_ArmatureObject *armobj); BL_SkinDeformer(BL_DeformableGameObject *gameobj, @@ -81,10 +71,6 @@ public: virtual ~BL_SkinDeformer(); bool Update (void); bool Apply (class RAS_IPolyMaterial *polymat); - bool PoseApplied() - { return m_poseApplied; } - void PoseApplied(bool applied) - { m_poseApplied = applied; } bool PoseUpdated(void) { if (m_armobj && m_lastArmaUpdate!=m_armobj->GetLastFrame()) { diff --git a/source/gameengine/Converter/BL_SkinMeshObject.cpp b/source/gameengine/Converter/BL_SkinMeshObject.cpp index fa215df1e1c..4f9f1a434b5 100644 --- a/source/gameengine/Converter/BL_SkinMeshObject.cpp +++ b/source/gameengine/Converter/BL_SkinMeshObject.cpp @@ -28,42 +28,69 @@ * Deformer that supports armature skinning */ -#ifdef HAVE_CONFIG_H -#include -#endif - #ifdef WIN32 #pragma warning (disable:4786) // get rid of stupid stl-visual compiler debug warning #endif //WIN32 -#include "RAS_IPolygonMaterial.h" -#include "BL_SkinMeshObject.h" -#include "BL_DeformableGameObject.h" + +#include "MEM_guardedalloc.h" + +#include "DNA_key_types.h" #include "DNA_mesh_types.h" #include "DNA_meshdata_types.h" -#include "KX_GameObject.h" + #include "RAS_BucketManager.h" +#include "RAS_IPolygonMaterial.h" -//void BL_SkinMeshObject::Bucketize(double* oglmatrix,void* clientobj,bool useObjectColor,const MT_Vector4& rgbavec,RAS_BucketManager* bucketmgr) -void BL_SkinMeshObject::Bucketize(double* oglmatrix,void* clientobj,bool useObjectColor,const MT_Vector4& rgbavec) -{ +#include "KX_GameObject.h" - KX_MeshSlot ms; - ms.m_clientObj = clientobj; - ms.m_mesh = this; - ms.m_OpenGLMatrix = oglmatrix; - ms.m_bObjectColor = useObjectColor; - ms.m_RGBAcolor = rgbavec; - ms.m_pDeformer = ((BL_DeformableGameObject*)clientobj)->m_pDeformer; - - for (RAS_MaterialBucket::Set::iterator it = m_materials.begin();it!=m_materials.end();it++) +#include "BL_SkinMeshObject.h" +#include "BL_DeformableGameObject.h" + +BL_SkinMeshObject::BL_SkinMeshObject(Mesh* mesh, int lightlayer) + : RAS_MeshObject (mesh, lightlayer) +{ + m_bDeformed = true; + + if (m_mesh && m_mesh->key) { + KeyBlock *kb; + int count=0; + // initialize weight cache for shape objects + // count how many keys in this mesh + for(kb= (KeyBlock*)m_mesh->key->block.first; kb; kb= (KeyBlock*)kb->next) + count++; + m_cacheWeightIndex.resize(count,-1); + } +} - RAS_MaterialBucket* materialbucket = (*it); +BL_SkinMeshObject::~BL_SkinMeshObject() +{ + if (m_mesh && m_mesh->key) + { + KeyBlock *kb; + // remove the weight cache to avoid memory leak + for(kb= (KeyBlock*)m_mesh->key->block.first; kb; kb= (KeyBlock*)kb->next) { + if(kb->weights) + MEM_freeN(kb->weights); + kb->weights= NULL; + } + } +} -// KX_ArrayOptimizer* oa = GetArrayOptimizer(materialbucket->GetPolyMaterial()); - materialbucket->SetMeshSlot(ms); +void BL_SkinMeshObject::UpdateBuckets(void* clientobj,double* oglmatrix,bool useObjectColor,const MT_Vector4& rgbavec, bool visible, bool culled) +{ + list::iterator it; + list::iterator sit; + + for(it = m_materials.begin();it!=m_materials.end();++it) { + if(!it->m_slots[clientobj]) + continue; + + RAS_MeshSlot *slot = *it->m_slots[clientobj]; + slot->m_pDeformer = ((BL_DeformableGameObject*)clientobj)->m_pDeformer; } + RAS_MeshObject::UpdateBuckets(clientobj, oglmatrix, useObjectColor, rgbavec, visible, culled); } static int get_def_index(Object* ob, const char* vgroup) @@ -74,6 +101,7 @@ static int get_def_index(Object* ob, const char* vgroup) for (curdef = (bDeformGroup*)ob->defbase.first; curdef; curdef=(bDeformGroup*)curdef->next, index++) if (!strcmp(curdef->name, vgroup)) return index; + return -1; } diff --git a/source/gameengine/Converter/BL_SkinMeshObject.h b/source/gameengine/Converter/BL_SkinMeshObject.h index c21fb64204b..8544a2b958c 100644 --- a/source/gameengine/Converter/BL_SkinMeshObject.h +++ b/source/gameengine/Converter/BL_SkinMeshObject.h @@ -33,62 +33,27 @@ #ifdef WIN32 #pragma warning (disable:4786) // get rid of stupid stl-visual compiler debug warning #endif //WIN32 -#include "MEM_guardedalloc.h" + #include "RAS_MeshObject.h" #include "RAS_Deformer.h" #include "RAS_IPolygonMaterial.h" #include "BL_MeshDeformer.h" -#include "DNA_mesh_types.h" -#include "DNA_key_types.h" -#include "DNA_meshdata_types.h" - class BL_SkinMeshObject : public RAS_MeshObject { - -// enum { BUCKET_MAX_INDICES = 16384};//2048};//8192}; -// enum { BUCKET_MAX_TRIANGLES = 4096}; - protected: vector m_cacheWeightIndex; public: - void Bucketize(double* oglmatrix,void* clientobj,bool useObjectColor,const MT_Vector4& rgbavec); -// void Bucketize(double* oglmatrix,void* clientobj,bool useObjectColor,const MT_Vector4& rgbavec,class RAS_BucketManager* bucketmgr); + BL_SkinMeshObject(Mesh* mesh, int lightlayer); + ~BL_SkinMeshObject(); - BL_SkinMeshObject(Mesh* mesh, int lightlayer) : RAS_MeshObject (mesh, lightlayer) - { - m_class = 1; - if (m_mesh && m_mesh->key) - { - KeyBlock *kb; - int count=0; - // initialize weight cache for shape objects - // count how many keys in this mesh - for(kb= (KeyBlock*)m_mesh->key->block.first; kb; kb= (KeyBlock*)kb->next) - count++; - m_cacheWeightIndex.resize(count,-1); - } - }; - - virtual ~BL_SkinMeshObject() - { - if (m_mesh && m_mesh->key) - { - KeyBlock *kb; - // remove the weight cache to avoid memory leak - for(kb= (KeyBlock*)m_mesh->key->block.first; kb; kb= (KeyBlock*)kb->next) { - if(kb->weights) - MEM_freeN(kb->weights); - kb->weights= NULL; - } - } - }; + void UpdateBuckets(void* clientobj, double* oglmatrix, + bool useObjectColor, const MT_Vector4& rgbavec, bool visible, bool culled); // for shape keys, void CheckWeightCache(struct Object* obj); - }; #endif diff --git a/source/gameengine/Converter/CMakeLists.txt b/source/gameengine/Converter/CMakeLists.txt index adb7304b10e..217bdb30907 100644 --- a/source/gameengine/Converter/CMakeLists.txt +++ b/source/gameengine/Converter/CMakeLists.txt @@ -64,6 +64,7 @@ SET(INC ../../../source/gameengine/Network/LoopBackNetwork ../../../source/blender/misc ../../../source/blender/blenloader + ../../../source/blender/gpu ../../../extern/bullet2/src ../../../extern/solid ${PYTHON_INC} diff --git a/source/gameengine/Converter/KX_BlenderSceneConverter.cpp b/source/gameengine/Converter/KX_BlenderSceneConverter.cpp index de91bce2ab1..1f5b578d441 100644 --- a/source/gameengine/Converter/KX_BlenderSceneConverter.cpp +++ b/source/gameengine/Converter/KX_BlenderSceneConverter.cpp @@ -184,20 +184,21 @@ bool KX_BlenderSceneConverter::TryAndLoadNewFile() return result; } - +Scene *KX_BlenderSceneConverter::GetBlenderSceneForName(const STR_String& name) +{ + Scene *sce; /** * Find the specified scene by name, or the first * scene if nothing matches (shouldn't happen). */ -static struct Scene *GetSceneForName2(struct Main *maggie, const STR_String& scenename) { - Scene *sce; - for (sce= (Scene*) maggie->scene.first; sce; sce= (Scene*) sce->id.next) - if (scenename == (sce->id.name+2)) + for (sce= (Scene*) m_maggie->scene.first; sce; sce= (Scene*) sce->id.next) + if (name == (sce->id.name+2)) return sce; - return (Scene*) maggie->scene.first; + return (Scene*)m_maggie->scene.first; + } #include "KX_PythonInit.h" @@ -258,7 +259,7 @@ void KX_BlenderSceneConverter::ConvertScene(const STR_String& scenename, class RAS_ICanvas* canvas) { //find out which physics engine - Scene *blenderscene = GetSceneForName2(m_maggie, scenename); + Scene *blenderscene = GetBlenderSceneForName(scenename); e_PhysicsEngine physics_engine = UseBullet; // hook for registration function during conversion. @@ -818,7 +819,7 @@ void KX_BlenderSceneConverter::WritePhysicsObjectToAnimationIpo(int frameNumber) KX_GameObject* gameObj = (KX_GameObject*)parentList->GetValue(g); if (gameObj->IsDynamic()) { - KX_IPhysicsController* physCtrl = gameObj->GetPhysicsController(); + //KX_IPhysicsController* physCtrl = gameObj->GetPhysicsController(); Object* blenderObject = FindBlenderObject(gameObj); if (blenderObject) @@ -846,7 +847,7 @@ void KX_BlenderSceneConverter::WritePhysicsObjectToAnimationIpo(int frameNumber) - const MT_Vector3& scale = gameObj->NodeGetWorldScaling(); + //const MT_Vector3& scale = gameObj->NodeGetWorldScaling(); const MT_Point3& position = gameObj->NodeGetWorldPosition(); Ipo* ipo = blenderObject->ipo; @@ -974,7 +975,7 @@ void KX_BlenderSceneConverter::TestHandlesPhysicsObjectToAnimationIpo() KX_GameObject* gameObj = (KX_GameObject*)parentList->GetValue(g); if (gameObj->IsDynamic()) { - KX_IPhysicsController* physCtrl = gameObj->GetPhysicsController(); + //KX_IPhysicsController* physCtrl = gameObj->GetPhysicsController(); Object* blenderObject = FindBlenderObject(gameObj); if (blenderObject) @@ -1002,8 +1003,8 @@ void KX_BlenderSceneConverter::TestHandlesPhysicsObjectToAnimationIpo() - const MT_Vector3& scale = gameObj->NodeGetWorldScaling(); - const MT_Point3& position = gameObj->NodeGetWorldPosition(); + //const MT_Vector3& scale = gameObj->NodeGetWorldScaling(); + //const MT_Point3& position = gameObj->NodeGetWorldPosition(); Ipo* ipo = blenderObject->ipo; if (ipo) diff --git a/source/gameengine/Converter/KX_BlenderSceneConverter.h b/source/gameengine/Converter/KX_BlenderSceneConverter.h index e5d6ccc5caf..2317e952a0a 100644 --- a/source/gameengine/Converter/KX_BlenderSceneConverter.h +++ b/source/gameengine/Converter/KX_BlenderSceneConverter.h @@ -45,6 +45,7 @@ class BL_Material; struct IpoCurve; struct Main; struct SpaceIpo; +struct Scene; class KX_BlenderSceneConverter : public KX_ISceneConverter { @@ -151,6 +152,7 @@ public: virtual void SetGLSLMaterials(bool val); virtual bool GetGLSLMaterials(); + struct Scene* GetBlenderSceneForName(const STR_String& name); }; #endif //__KX_BLENDERSCENECONVERTER_H diff --git a/source/gameengine/Converter/KX_ConvertActuators.cpp b/source/gameengine/Converter/KX_ConvertActuators.cpp index 7e976beaf44..321fc325bb8 100644 --- a/source/gameengine/Converter/KX_ConvertActuators.cpp +++ b/source/gameengine/Converter/KX_ConvertActuators.cpp @@ -1064,7 +1064,7 @@ void BL_ConvertActuators(char* maggiename, { bParentActuator *parAct = (bParentActuator *) bact->data; int mode = KX_ParentActuator::KX_PARENT_NODEF; - KX_GameObject *tmpgob; + KX_GameObject *tmpgob = NULL; switch(parAct->type) { diff --git a/source/gameengine/Converter/Makefile b/source/gameengine/Converter/Makefile index f312fc13221..4dd63e428bd 100644 --- a/source/gameengine/Converter/Makefile +++ b/source/gameengine/Converter/Makefile @@ -51,6 +51,7 @@ CPPFLAGS += -I../../blender/include CPPFLAGS += -I../../blender/blenlib CPPFLAGS += -I../../blender/blenkernel CPPFLAGS += -I../../blender/render/extern/include +CPPFLAGS += -I../../blender/gpu CPPFLAGS += -I$(NAN_GUARDEDALLOC)/include CPPFLAGS += -I../Expressions -I../Rasterizer -I../GameLogic CPPFLAGS += -I../Ketsji -I../BlenderRoutines -I../SceneGraph diff --git a/source/gameengine/Converter/SConscript b/source/gameengine/Converter/SConscript index f5e382b471e..3be352c568b 100644 --- a/source/gameengine/Converter/SConscript +++ b/source/gameengine/Converter/SConscript @@ -16,7 +16,7 @@ incs += ' #source/gameengine/Expressions #source/gameengine/Network #source/game incs += ' #source/gameengine/Physics/common #source/gameengine/Physics/Bullet #source/gameengine/Physics/BlOde' incs += ' #source/gameengine/Physics/Dummy #source/gameengine/Physics/Sumo' incs += ' #source/gameengine/Physics/Sumo/Fuzzics/include #source/gameengine/Network/LoopBackNetwork' -incs += ' #source/blender/misc #source/blender/blenloader' +incs += ' #source/blender/misc #source/blender/blenloader #source/blender/gpu' incs += ' ' + env['BF_PYTHON_INC'] incs += ' ' + env['BF_SOLID_INC'] diff --git a/source/gameengine/GamePlayer/common/CMakeLists.txt b/source/gameengine/GamePlayer/common/CMakeLists.txt index e26f8b9d69a..0c6c4179e2d 100644 --- a/source/gameengine/GamePlayer/common/CMakeLists.txt +++ b/source/gameengine/GamePlayer/common/CMakeLists.txt @@ -30,7 +30,6 @@ SET(SRC GPC_Engine.cpp GPC_KeyboardDevice.cpp GPC_MouseDevice.cpp - GPC_PolygonMaterial.cpp GPC_RawImage.cpp GPC_RawLoadDotBlendArray.cpp GPC_RawLogoArrays.cpp @@ -69,6 +68,7 @@ SET(INC ../../../../source/gameengine/GamePlayer/ghost ../../../../source/blender/misc ../../../../source/blender/blenloader + ../../../../source/blender/gpu ../../../../extern/glew/include ${PYTHON_INC} ${SOLID_INC} diff --git a/source/gameengine/GamePlayer/common/GPC_RenderTools.cpp b/source/gameengine/GamePlayer/common/GPC_RenderTools.cpp index a64c85f6c17..78d8eaf2aa3 100644 --- a/source/gameengine/GamePlayer/common/GPC_RenderTools.cpp +++ b/source/gameengine/GamePlayer/common/GPC_RenderTools.cpp @@ -27,141 +27,256 @@ * ***** END GPL LICENSE BLOCK ***** */ -#include - -#ifdef WIN32 -#pragma warning (disable : 4786) -#include -#endif - #include "GL/glew.h" -#include - -#include "GPC_RenderTools.h" - #include "RAS_IRenderTools.h" #include "RAS_IRasterizer.h" #include "RAS_LightObject.h" #include "RAS_ICanvas.h" #include "RAS_GLExtensionManager.h" -// next two includes/dependencies come from the shadow feature -// it needs the gameobject and the sumo physics scene for a raycast #include "KX_GameObject.h" - -#include "GPC_PolygonMaterial.h" #include "KX_PolygonMaterial.h" -#include "Value.h" - -//#include "KX_BlenderGL.h" // for text printing -//#include "KX_BlenderClientObject.h" -#include "STR_String.h" -#include "RAS_BucketManager.h" // for polymaterial (needed for textprinting) - - -// Blender includes -/* This list includes only data type definitions */ -#include "DNA_object_types.h" -#include "DNA_material_types.h" -#include "DNA_image_types.h" -#include "DNA_lamp_types.h" -#include "DNA_group_types.h" -#include "DNA_scene_types.h" -#include "DNA_camera_types.h" -#include "DNA_property_types.h" -#include "DNA_text_types.h" -#include "DNA_sensor_types.h" -#include "DNA_controller_types.h" -#include "DNA_actuator_types.h" -#include "DNA_mesh_types.h" -#include "DNA_meshdata_types.h" -#include "DNA_view3d_types.h" -#include "DNA_world_types.h" - -#include "BKE_global.h" -#include "BKE_image.h" -#include "BKE_bmfont.h" -#include "BKE_bmfont_types.h" -#include "BKE_main.h" - -#include "IMB_imbuf_types.h" -// End of Blender includes - -#include "KX_Scene.h" +#include "KX_BlenderMaterial.h" #include "KX_RayCast.h" #include "KX_IPhysicsController.h" + #include "PHY_IPhysicsEnvironment.h" -#include "KX_BlenderMaterial.h" + +#include "STR_String.h" + +#include "GPU_draw.h" + +#include "BKE_bmfont.h" // for text printing +#include "BKE_bmfont_types.h" + +#include "GPC_RenderTools.h" + +unsigned int GPC_RenderTools::m_numgllights; GPC_RenderTools::GPC_RenderTools() { m_font = BMF_GetFont(BMF_kHelvetica10); + glGetIntegerv(GL_MAX_LIGHTS, (GLint*) &m_numgllights); if (m_numgllights < 8) m_numgllights = 8; } - GPC_RenderTools::~GPC_RenderTools() { } +void GPC_RenderTools::BeginFrame(RAS_IRasterizer* rasty) +{ + m_clientobject = NULL; + m_lastlightlayer = -1; + m_lastlighting = false; + DisableOpenGLLights(); +} void GPC_RenderTools::EndFrame(RAS_IRasterizer* rasty) { } +/* ProcessLighting performs lighting on objects. the layer is a bitfield that + * contains layer information. There are 20 'official' layers in blender. A + * light is applied on an object only when they are in the same layer. OpenGL + * has a maximum of 8 lights (simultaneous), so 20 * 8 lights are possible in + * a scene. */ -void GPC_RenderTools::BeginFrame(RAS_IRasterizer* rasty) +void GPC_RenderTools::ProcessLighting(int layer, const MT_Transform& viewmat) { - m_clientobject=NULL; - m_modified=true; - DisableOpenGLLights(); + if(m_lastlightlayer == layer) + return; -} + m_lastlightlayer = layer; -int GPC_RenderTools::ProcessLighting(int layer) -{ - int result = false; + bool enable = false; - if (layer < 0) - { - DisableOpenGLLights(); - result = false; - } else + if (layer >= 0) { if (m_clientobject) - { - if (applyLights(layer)) - { - EnableOpenGLLights(); - result = true; - } else - { - DisableOpenGLLights(); - result = false; - } + { + if (layer == RAS_LIGHT_OBJECT_LAYER) + layer = static_cast(m_clientobject)->GetLayer(); + + enable = applyLights(layer, viewmat); } } - return result; + + if(enable) + EnableOpenGLLights(); + else + DisableOpenGLLights(); } void GPC_RenderTools::EnableOpenGLLights() { + if(m_lastlighting == true) + return; + glEnable(GL_LIGHTING); glEnable(GL_COLOR_MATERIAL); - glColorMaterial(GL_FRONT_AND_BACK,GL_DIFFUSE); + + glColorMaterial(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE); + glLightModeli(GL_LIGHT_MODEL_TWO_SIDE, true); if (GLEW_EXT_separate_specular_color || GLEW_VERSION_1_2) glLightModeli(GL_LIGHT_MODEL_COLOR_CONTROL, GL_SEPARATE_SPECULAR_COLOR); + + m_lastlighting = true; } -void GPC_RenderTools::RenderText2D(RAS_TEXT_RENDER_MODE mode, - const char* text, - int xco, - int yco, - int width, - int height) +void GPC_RenderTools::DisableOpenGLLights() +{ + if(m_lastlighting == false) + return; + + glDisable(GL_LIGHTING); + glDisable(GL_COLOR_MATERIAL); + + m_lastlighting = false; +} + + +void GPC_RenderTools::SetClientObject(RAS_IRasterizer *rasty, void* obj) +{ + if (m_clientobject != obj) + { + bool ccw = (obj == NULL || !((KX_GameObject*)obj)->IsNegativeScaling()); + rasty->SetFrontFace(ccw); + + m_clientobject = obj; + } +} + +bool GPC_RenderTools::RayHit(KX_ClientObjectInfo* client, KX_RayCast* result, void * const data) +{ + double* const oglmatrix = (double* const) data; + MT_Point3 resultpoint(result->m_hitPoint); + MT_Vector3 resultnormal(result->m_hitNormal); + MT_Vector3 left(oglmatrix[0],oglmatrix[1],oglmatrix[2]); + MT_Vector3 dir = -(left.cross(resultnormal)).safe_normalized(); + left = (dir.cross(resultnormal)).safe_normalized(); + // for the up vector, we take the 'resultnormal' returned by the physics + + double maat[16]={ + left[0], left[1], left[2], 0, + dir[0], dir[1], dir[2], 0, + resultnormal[0],resultnormal[1],resultnormal[2], 0, + 0, 0, 0, 1}; + glTranslated(resultpoint[0],resultpoint[1],resultpoint[2]); + //glMultMatrixd(oglmatrix); + glMultMatrixd(maat); + return true; +} + +void GPC_RenderTools::applyTransform(RAS_IRasterizer* rasty,double* oglmatrix,int objectdrawmode ) +{ + /* FIXME: + blender: intern/moto/include/MT_Vector3.inl:42: MT_Vector3 operator/(const + MT_Vector3&, double): Assertion `!MT_fuzzyZero(s)' failed. + + Program received signal SIGABRT, Aborted. + [Switching to Thread 16384 (LWP 1519)] + 0x40477571 in kill () from /lib/libc.so.6 + (gdb) bt + #7 0x08334368 in MT_Vector3::normalized() const () + #8 0x0833e6ec in GPC_RenderTools::applyTransform(RAS_IRasterizer*, double*, int) () + */ + + if (objectdrawmode & RAS_IPolyMaterial::BILLBOARD_SCREENALIGNED || + objectdrawmode & RAS_IPolyMaterial::BILLBOARD_AXISALIGNED) + { + // rotate the billboard/halo + //page 360/361 3D Game Engine Design, David Eberly for a discussion + // on screen aligned and axis aligned billboards + // assumed is that the preprocessor transformed all billboard polygons + // so that their normal points into the positive x direction (1.0 , 0.0 , 0.0) + // when new parenting for objects is done, this rotation + // will be moved into the object + + MT_Point3 objpos (oglmatrix[12],oglmatrix[13],oglmatrix[14]); + MT_Point3 campos = rasty->GetCameraPosition(); + MT_Vector3 dir = (campos - objpos).safe_normalized(); + MT_Vector3 up(0,0,1.0); + + KX_GameObject* gameobj = (KX_GameObject*) this->m_clientobject; + // get scaling of halo object + MT_Vector3 size = gameobj->GetSGNode()->GetLocalScale(); + + bool screenaligned = (objectdrawmode & RAS_IPolyMaterial::BILLBOARD_SCREENALIGNED)!=0;//false; //either screen or axisaligned + if (screenaligned) + { + up = (up - up.dot(dir) * dir).safe_normalized(); + } else + { + dir = (dir - up.dot(dir)*up).safe_normalized(); + } + + MT_Vector3 left = dir.normalized(); + dir = (left.cross(up)).normalized(); + + // we have calculated the row vectors, now we keep + // local scaling into account: + + left *= size[0]; + dir *= size[1]; + up *= size[2]; + double maat[16]={ + left[0], left[1],left[2], 0, + dir[0], dir[1],dir[2],0, + up[0],up[1],up[2],0, + 0,0,0,1}; + glTranslated(objpos[0],objpos[1],objpos[2]); + glMultMatrixd(maat); + + } else + { + if (objectdrawmode & RAS_IPolyMaterial::SHADOW) + { + // shadow must be cast to the ground, physics system needed here! + MT_Point3 frompoint(oglmatrix[12],oglmatrix[13],oglmatrix[14]); + KX_GameObject *gameobj = (KX_GameObject*) this->m_clientobject; + MT_Vector3 direction = MT_Vector3(0,0,-1); + + direction.normalize(); + direction *= 100000; + + MT_Point3 topoint = frompoint + direction; + + KX_Scene* kxscene = (KX_Scene*) m_auxilaryClientInfo; + PHY_IPhysicsEnvironment* physics_environment = kxscene->GetPhysicsEnvironment(); + KX_IPhysicsController* physics_controller = gameobj->GetPhysicsController(); + + KX_GameObject *parent = gameobj->GetParent(); + if (!physics_controller && parent) + physics_controller = parent->GetPhysicsController(); + if (parent) + parent->Release(); + + KX_RayCast::Callback callback(this, physics_controller, oglmatrix); + if (!KX_RayCast::RayTest(physics_environment, frompoint, topoint, callback)) + { + // couldn't find something to cast the shadow on... + glMultMatrixd(oglmatrix); + } + } else + { + + // 'normal' object + glMultMatrixd(oglmatrix); + } + } +} + + +void GPC_RenderTools::RenderText2D(RAS_TEXT_RENDER_MODE mode, + const char* text, + int xco, + int yco, + int width, + int height) { STR_String tmpstr(text); int lines; @@ -234,21 +349,19 @@ void GPC_RenderTools::RenderText2D(RAS_TEXT_RENDER_MODE mode, glDisable(GL_LIGHTING); } -/** - * Copied from KX_BlenderRenderTools.cpp in KX_blenderhook - * Renders text into a (series of) polygon(s), using a texture font, - * Each character consists of one polygon (one quad or two triangles) - */ +/* Render Text renders text into a (series of) polygon, using a texture font, + * Each character consists of one polygon (one quad or two triangles) */ + void GPC_RenderTools::RenderText( int mode, RAS_IPolyMaterial* polymat, - float v1[3], float v2[3], float v3[3], float v4[3]) + float v1[3], float v2[3], float v3[3], float v4[3], int glattrib) { STR_String mytext = ((CValue*)m_clientobject)->GetPropertyText("Text"); const unsigned int flag = polymat->GetFlag(); struct MTFace* tface = 0; - unsigned int* col = 0; + unsigned int *col = 0; if(flag & RAS_BLENDERMAT) { KX_BlenderMaterial *bl_mat = static_cast(polymat); @@ -259,110 +372,29 @@ void GPC_RenderTools::RenderText( tface = blenderpoly->GetMTFace(); col = blenderpoly->GetMCol(); } - - BL_RenderText(mode, mytext, mytext.Length(), tface, col, v1, v2, v3, v4); -} - - - -/** - * Copied from KX_BlenderGL.cpp in KX_blenderhook - */ -void GPC_RenderTools::BL_RenderText( - int mode, - const char* textstr, - int textlen, - struct MTFace* tface, - unsigned int* col, - float v1[3],float v2[3],float v3[3],float v4[3]) -{ - struct Image* ima; - - if (mode & TF_BMFONT) { - //char string[MAX_PROPSTRING]; -// float tmat[4][4]; - int characters, index, character; - float centerx, centery, sizex, sizey, transx, transy, movex, movey, advance; - -// bProperty *prop; - - // string = "Frank van Beek"; - - characters = textlen; - - ima = (struct Image*) tface->tpage; - if (ima == NULL) { - characters = 0; - } - - if(!col) glColor3f(1.0f, 1.0f, 1.0f); - - glPushMatrix(); - for (index = 0; index < characters; index++) { - // lets calculate offset stuff - character = textstr[index]; - - // space starts at offset 1 - // character = character - ' ' + 1; - - matrixGlyph((ImBuf *)ima->ibufs.first, character, & centerx, ¢ery, &sizex, &sizey, &transx, &transy, &movex, &movey, &advance); - - glBegin(GL_POLYGON); - // printf(" %c %f %f %f %f\n", character, tface->uv[0][0], tface->uv[0][1], ); - // glTexCoord2f((tface->uv[0][0] - centerx) * sizex + transx, (tface->uv[0][1] - centery) * sizey + transy); - glTexCoord2f((tface->uv[0][0] - centerx) * sizex + transx, (tface->uv[0][1] - centery) * sizey + transy); - - if(col) BL_spack(col[0]); - // glVertex3fv(v1); - glVertex3f(sizex * v1[0] + movex, sizey * v1[1] + movey, v1[2]); - - glTexCoord2f((tface->uv[1][0] - centerx) * sizex + transx, (tface->uv[1][1] - centery) * sizey + transy); - if(col) BL_spack(col[1]); - // glVertex3fv(v2); - glVertex3f(sizex * v2[0] + movex, sizey * v2[1] + movey, v2[2]); - glTexCoord2f((tface->uv[2][0] - centerx) * sizex + transx, (tface->uv[2][1] - centery) * sizey + transy); - if(col) BL_spack(col[2]); - // glVertex3fv(v3); - glVertex3f(sizex * v3[0] + movex, sizey * v3[1] + movey, v3[2]); - - if(v4) { - // glTexCoord2f((tface->uv[3][0] - centerx) * sizex + transx, 1.0 - (1.0 - tface->uv[3][1]) * sizey - transy); - glTexCoord2f((tface->uv[3][0] - centerx) * sizex + transx, (tface->uv[3][1] - centery) * sizey + transy); - if(col) BL_spack(col[3]); - // glVertex3fv(v4); - glVertex3f(sizex * v4[0] + movex, sizey * v4[1] + movey, v4[2]); - } - glEnd(); - - glTranslatef(advance, 0.0, 0.0); - } - glPopMatrix(); - - } + GPU_render_text(tface, mode, mytext, mytext.Length(), col, v1, v2, v3, v4, glattrib); } -RAS_IPolyMaterial* GPC_RenderTools::CreateBlenderPolyMaterial( - const STR_String &texname, - bool ba,const STR_String& matname,int tile,int tilexrep,int tileyrep,int mode,bool transparant, bool zsort, - int lightlayer,bool bIsTriangle,void* clientobject,void* tface) +void GPC_RenderTools::PushMatrix() { - assert(!"Deprecated"); -/* return new GPC_PolygonMaterial(texname, ba,matname,tile,tilexrep,tileyrep, - mode,transparant,zsort,lightlayer,bIsTriangle,clientobject,tface); - */ - return NULL; + glPushMatrix(); +} + +void GPC_RenderTools::PopMatrix() +{ + glPopMatrix(); } -int GPC_RenderTools::applyLights(int objectlayer) +int GPC_RenderTools::applyLights(int objectlayer, const MT_Transform& viewmat) { -// taken from blender source, incompatibility between Blender Object / GameObject - - int count; + // taken from blender source, incompatibility between Blender Object / GameObject + float glviewmat[16]; + unsigned int count; float vec[4]; - + vec[3]= 1.0; for(count=0; count m_lights; std::vector::iterator lit = m_lights.begin(); + viewmat.getValue(glviewmat); + glPushMatrix(); + glLoadMatrixf(glviewmat); for (lit = m_lights.begin(), count = 0; !(lit==m_lights.end()) && count < m_numgllights; ++lit) { RAS_LightObject* lightdata = (*lit); if (lightdata->m_layer & objectlayer) { - - glPushMatrix(); - glLoadMatrixf(m_viewmat); - - vec[0] = (*(lightdata->m_worldmatrix))(0,3); vec[1] = (*(lightdata->m_worldmatrix))(1,3); vec[2] = (*(lightdata->m_worldmatrix))(2,3); vec[3] = 1; - if(lightdata->m_type==RAS_LightObject::LIGHT_SUN) { vec[0] = (*(lightdata->m_worldmatrix))(0,2); @@ -443,141 +472,16 @@ int GPC_RenderTools::applyLights(int objectlayer) } glLightfv((GLenum)(GL_LIGHT0+count), GL_SPECULAR, vec); glEnable((GLenum)(GL_LIGHT0+count)); - - count++; - glPopMatrix(); + count++; } } + glPopMatrix(); return count; } -void GPC_RenderTools::SetClientObject(void* obj) -{ - if (m_clientobject != obj) - { - if (obj == NULL || !((KX_GameObject*)obj)->IsNegativeScaling()) - { - glFrontFace(GL_CCW); - } else - { - glFrontFace(GL_CW); - } - m_clientobject = obj; - m_modified = true; - } -} - -bool GPC_RenderTools::RayHit(KX_ClientObjectInfo* client, KX_RayCast* result, void * const data) -{ - double* const oglmatrix = (double* const) data; - MT_Point3 resultpoint(result->m_hitPoint); - MT_Vector3 resultnormal(result->m_hitNormal); - MT_Vector3 left(oglmatrix[0],oglmatrix[1],oglmatrix[2]); - MT_Vector3 dir = -(left.cross(resultnormal)).safe_normalized(); - left = (dir.cross(resultnormal)).safe_normalized(); - // for the up vector, we take the 'resultnormal' returned by the physics - - double maat[16]={ - left[0], left[1], left[2], 0, - dir[0], dir[1], dir[2], 0, - resultnormal[0],resultnormal[1],resultnormal[2], 0, - 0, 0, 0, 1}; - glTranslated(resultpoint[0],resultpoint[1],resultpoint[2]); - //glMultMatrixd(oglmatrix); - glMultMatrixd(maat); - return true; -} - -void GPC_RenderTools::applyTransform(RAS_IRasterizer* rasty,double* oglmatrix,int objectdrawmode ) -{ - if (objectdrawmode & RAS_IPolyMaterial::BILLBOARD_SCREENALIGNED || - objectdrawmode & RAS_IPolyMaterial::BILLBOARD_AXISALIGNED) - { - // rotate the billboard/halo - //page 360/361 3D Game Engine Design, David Eberly for a discussion - // on screen aligned and axis aligned billboards - // assumed is that the preprocessor transformed all billboard polygons - // so that their normal points into the positive x direction (1.0 , 0.0 , 0.0) - // when new parenting for objects is done, this rotation - // will be moved into the object - - MT_Point3 objpos (oglmatrix[12],oglmatrix[13],oglmatrix[14]); - MT_Point3 campos = rasty->GetCameraPosition(); - MT_Vector3 dir = (campos - objpos).safe_normalized(); - MT_Vector3 up(0,0,1.0); - - KX_GameObject* gameobj = (KX_GameObject*) this->m_clientobject; - // get scaling of halo object - MT_Vector3 size = gameobj->GetSGNode()->GetLocalScale(); - - bool screenaligned = (objectdrawmode & RAS_IPolyMaterial::BILLBOARD_SCREENALIGNED)!=0;//false; //either screen or axisaligned - if (screenaligned) - { - up = (up - up.dot(dir) * dir).safe_normalized(); - } else - { - dir = (dir - up.dot(dir)*up).safe_normalized(); - } - - MT_Vector3 left = dir.normalized(); - dir = (left.cross(up)).normalized(); - - // we have calculated the row vectors, now we keep - // local scaling into account: - - left *= size[0]; - dir *= size[1]; - up *= size[2]; - double maat[16]={ - left[0], left[1],left[2], 0, - dir[0], dir[1],dir[2],0, - up[0],up[1],up[2],0, - 0,0,0,1}; - glTranslated(objpos[0],objpos[1],objpos[2]); - glMultMatrixd(maat); - - } else - { - if (objectdrawmode & RAS_IPolyMaterial::SHADOW) - { - // shadow must be cast to the ground, physics system needed here! - MT_Point3 frompoint(oglmatrix[12],oglmatrix[13],oglmatrix[14]); - KX_GameObject *gameobj = (KX_GameObject*) this->m_clientobject; - MT_Vector3 direction = MT_Vector3(0,0,-1); - - direction.normalize(); - direction *= 100000; - - MT_Point3 topoint = frompoint + direction; - - KX_Scene* kxscene = (KX_Scene*) m_auxilaryClientInfo; - PHY_IPhysicsEnvironment* physics_environment = kxscene->GetPhysicsEnvironment(); - KX_IPhysicsController* physics_controller = gameobj->GetPhysicsController(); - - KX_GameObject *parent = gameobj->GetParent(); - if (!physics_controller && parent) - physics_controller = parent->GetPhysicsController(); - if (parent) - parent->Release(); - - KX_RayCast::Callback callback(this, physics_controller, oglmatrix); - if (!KX_RayCast::RayTest(physics_environment, frompoint, topoint, callback)) - { - // couldn't find something to cast the shadow on... - glMultMatrixd(oglmatrix); - } - } else - { - - // 'normal' object - glMultMatrixd(oglmatrix); - } - } -} - void GPC_RenderTools::MotionBlur(RAS_IRasterizer* rasterizer) { int state = rasterizer->GetMotionBlurState(); @@ -608,7 +512,6 @@ void GPC_RenderTools::Update2DFilter(vector& propNames, void* gameOb void GPC_RenderTools::Render2DFilters(RAS_ICanvas* canvas) { - m_filtermanager.RenderFilters( canvas); + m_filtermanager.RenderFilters(canvas); } -unsigned int GPC_RenderTools::m_numgllights; diff --git a/source/gameengine/GamePlayer/common/GPC_RenderTools.h b/source/gameengine/GamePlayer/common/GPC_RenderTools.h index 9f70f67caf2..382956e73ea 100644 --- a/source/gameengine/GamePlayer/common/GPC_RenderTools.h +++ b/source/gameengine/GamePlayer/common/GPC_RenderTools.h @@ -31,11 +31,11 @@ #define __GPC_RENDERTOOLS_H #ifdef WIN32 - #include +// don't show stl-warnings +#pragma warning (disable:4786) +#include #endif // WIN32 -#include "GL/glew.h" - #include "RAS_IRenderTools.h" #include "BMF_Api.h" @@ -43,100 +43,52 @@ struct KX_ClientObjectInfo; class KX_RayCast; +/* BlenderRenderTools are a set of tools to apply 2D/3D graphics effects, which + * are not part of the (polygon) Rasterizer. Effects like 2D text, 3D (polygon) + * text, lighting. + * + * Most of this code is duplicated in KX_BlenderRenderTools, so this should be + * moved to some common location to avoid duplication. */ + class GPC_RenderTools : public RAS_IRenderTools { + int m_lastlightlayer; + bool m_lastlighting; + static unsigned int m_numgllights; + + BMF_Font* m_font; + public: - GPC_RenderTools(); - virtual ~GPC_RenderTools(); + GPC_RenderTools(); + virtual ~GPC_RenderTools(); - virtual void EndFrame(RAS_IRasterizer* rasty); - virtual void BeginFrame(RAS_IRasterizer* rasty); + void EndFrame(RAS_IRasterizer* rasty); + void BeginFrame(RAS_IRasterizer* rasty); - void DisableOpenGLLights() - { - glDisable(GL_LIGHTING); - glDisable(GL_COLOR_MATERIAL); - } + void EnableOpenGLLights(); + void DisableOpenGLLights(); + void ProcessLighting(int layer, const MT_Transform& viewmat); - void EnableOpenGLLights(); + /* @attention mode is ignored here */ + void RenderText2D(RAS_TEXT_RENDER_MODE mode, + const char* text, + int xco, + int yco, + int width, + int height); + void RenderText(int mode, + class RAS_IPolyMaterial* polymat, + float v1[3], + float v2[3], + float v3[3], + float v4[3], + int glattrib); - int ProcessLighting(int layer); + void applyTransform(RAS_IRasterizer* rasty, double* oglmatrix, int objectdrawmode); + int applyLights(int objectlayer, const MT_Transform& viewmat); - void Perspective(int a, int width, int height, float mat[4][4], float viewmat[4][4]) - { - if(a== 0) - { - glMatrixMode(GL_PROJECTION); - glMatrixMode(GL_MODELVIEW); - glLoadIdentity(); - } - else - { - if(a== 1) - { - glMatrixMode(GL_PROJECTION); - glMatrixMode(GL_MODELVIEW); - } - } - } - - /** - * @attention mode is ignored here - */ - virtual void RenderText2D( - RAS_TEXT_RENDER_MODE mode, - const char* text, - int xco, - int yco, - int width, - int height); - - /** - * Renders text into a (series of) polygon(s), using a texture font, - * Each character consists of one polygon (one quad or two triangles) - */ - virtual void RenderText( - int mode, - RAS_IPolyMaterial* polymat, - float v1[3], - float v2[3], - float v3[3], - float v4[3]); - - void Render(RAS_IRasterizer* rasty,double* oglmatrix,int objectdrawmode) - { - glPopMatrix(); - glPushMatrix(); - glMultMatrixd(oglmatrix); - } - - void applyTransform(RAS_IRasterizer* rasty, double* oglmatrix, int objectdrawmode); - - virtual void PushMatrix() - { - glPushMatrix(); - } - - virtual void PopMatrix() - { - glPopMatrix(); - } - - virtual class RAS_IPolyMaterial* CreateBlenderPolyMaterial( - const STR_String &texname, - bool ba, - const STR_String& matname, - int tile, - int tilexrep,int tileyrep, - int mode, - bool transparant, - bool zsort, - int lightlayer, - bool bIsTriangle, - void* clientobject, - void* tface); - - int applyLights(int objectlayer); + void PushMatrix(); + void PopMatrix(); bool RayHit(KX_ClientObjectInfo* client, KX_RayCast* result, void * const data); bool NeedRayCast(KX_ClientObjectInfo* client) { return true; } @@ -147,28 +99,7 @@ public: virtual void Render2DFilters(RAS_ICanvas* canvas); - virtual void SetClientObject(void* obj); - -protected: - /** - * Copied from KX_BlenderGL.cpp in KX_blenderhook - */ - void BL_RenderText( - int mode, - const char* textstr, - int textlen, - struct MTFace* tface, - unsigned int* col, - float v1[3],float v2[3],float v3[3],float v4[3]); - void BL_spack(unsigned int ucol) - { - char *cp = (char *)&ucol; - glColor3ub(cp[3], cp[2], cp[1]); - } - - - BMF_Font* m_font; - static unsigned int m_numgllights; + virtual void SetClientObject(RAS_IRasterizer *rasty, void* obj); }; #endif // __GPC_RENDERTOOLS_H diff --git a/source/gameengine/GamePlayer/common/Makefile b/source/gameengine/GamePlayer/common/Makefile index 19d792ddbdb..6a12e659be6 100644 --- a/source/gameengine/GamePlayer/common/Makefile +++ b/source/gameengine/GamePlayer/common/Makefile @@ -43,6 +43,7 @@ CPPFLAGS += -I../../../blender/blenloader CPPFLAGS += -I../../../blender/blenlib CPPFLAGS += -I../../../blender/imbuf CPPFLAGS += -I../../../blender/makesdna +CPPFLAGS += -I../../../blender/gpu CPPFLAGS += -I../../../kernel/gen_system CPPFLAGS += -I$(NAN_GUARDEDALLOC)/include @@ -72,10 +73,6 @@ CPPFLAGS += -I../../../gameengine/Rasterizer/RAS_OpenGLRasterizer CPPFLAGS += -I../../../gameengine/Physics/Sumo CPPFLAGS += -I../../../gameengine/Physics/common -ifeq ($(WITH_BF_GLEXT),true) - CPPFLAGS += -DWITH_GLEXT -endif - ############################### SOURCEDIR = source/gameengine/GamePlayer/common diff --git a/source/gameengine/GamePlayer/common/SConscript b/source/gameengine/GamePlayer/common/SConscript index 3b2367d2592..30f20a670d3 100644 --- a/source/gameengine/GamePlayer/common/SConscript +++ b/source/gameengine/GamePlayer/common/SConscript @@ -8,7 +8,6 @@ source_files = ['bmfont.cpp', 'GPC_Engine.cpp', 'GPC_KeyboardDevice.cpp', 'GPC_MouseDevice.cpp', - 'GPC_PolygonMaterial.cpp', 'GPC_RawImage.cpp', 'GPC_RawLoadDotBlendArray.cpp', 'GPC_RawLogoArrays.cpp', @@ -46,6 +45,7 @@ incs = ['.', '#source/gameengine/GamePlayer/ghost', '#source/blender/misc', '#source/blender/blenloader', + '#source/blender/gpu', '#extern/glew/include'] #This is all plugin stuff! diff --git a/source/gameengine/GamePlayer/common/unix/GPU_PolygonMaterial.h b/source/gameengine/GamePlayer/common/unix/GPU_PolygonMaterial.h index fee729a84ac..e5ed7f39811 100644 --- a/source/gameengine/GamePlayer/common/unix/GPU_PolygonMaterial.h +++ b/source/gameengine/GamePlayer/common/unix/GPU_PolygonMaterial.h @@ -37,9 +37,9 @@ class GPU_PolygonMaterial : public BP_PolygonMaterial public: GPUPolygonMaterial(const STR_String& texname, bool ba,const STR_String& matname, int tile, int tileXrep, int tileYrep, int mode, int transparant, - int lightlayer,bool bIsTriangle,void* clientobject,void* tpage) : + int lightlayer,,void* tpage) : BP_PolygonMaterial(texname, ba,matname, tile, tileXrep, tileYrep, - mode, transparant, lightlayer, bIsTriangle, clientobject), + mode, transparant, lightlayer), m_tface(tpage) { } diff --git a/source/gameengine/GamePlayer/ghost/CMakeLists.txt b/source/gameengine/GamePlayer/ghost/CMakeLists.txt index d9f0675001f..5e0ca93ac06 100644 --- a/source/gameengine/GamePlayer/ghost/CMakeLists.txt +++ b/source/gameengine/GamePlayer/ghost/CMakeLists.txt @@ -64,6 +64,7 @@ SET(INC ../../../../source/gameengine/GamePlayer/common ../../../../source/blender/misc ../../../../source/blender/blenloader + ../../../../source/blender/gpu ../../../../extern/solid ../../../../extern/glew/include ${PYTHON_INC} diff --git a/source/gameengine/GamePlayer/ghost/GPG_Application.cpp b/source/gameengine/GamePlayer/ghost/GPG_Application.cpp index c56a6d0da23..a690beb9f38 100644 --- a/source/gameengine/GamePlayer/ghost/GPG_Application.cpp +++ b/source/gameengine/GamePlayer/ghost/GPG_Application.cpp @@ -38,6 +38,7 @@ #endif #include "GL/glew.h" +#include "GPU_extensions.h" #include "GPG_Application.h" @@ -104,9 +105,10 @@ static void frameTimerProc(GHOST_ITimerTask* task, GHOST_TUns64 time); static GHOST_ISystem* fSystem = 0; static const int kTimerFreq = 10; -GPG_Application::GPG_Application(GHOST_ISystem* system, struct Main* maggie, STR_String startSceneName) - : m_startSceneName(startSceneName), - m_maggie(maggie), +GPG_Application::GPG_Application(GHOST_ISystem* system) + : m_startSceneName(""), + m_startScene(0), + m_maggie(0), m_exitRequested(0), m_system(system), m_mainWindow(0), @@ -142,15 +144,16 @@ GPG_Application::~GPG_Application(void) -bool GPG_Application::SetGameEngineData(struct Main* maggie, STR_String startSceneName) +bool GPG_Application::SetGameEngineData(struct Main* maggie, Scene *scene) { bool result = false; - if (maggie != NULL && startSceneName != "") + if (maggie != NULL && scene != NULL) { - G.scene = (Scene*)maggie->scene.first; + G.scene = scene; m_maggie = maggie; - m_startSceneName = startSceneName; + m_startSceneName = scene->id.name+2; + m_startScene = scene; result = true; } @@ -480,7 +483,7 @@ bool GPG_Application::initEngine(GHOST_IWindow* window, const int stereoMode) { if (!m_engineInitialized) { - glewInit(); + GPU_extensions_init(); bgl::InitExtensions(true); // get and set the preferences @@ -499,12 +502,18 @@ bool GPG_Application::initEngine(GHOST_IWindow* window, const int stereoMode) bool fixed_framerate= (SYS_GetCommandLineInt(syshandle, "fixed_framerate", fixedFr) != 0); bool frameRate = (SYS_GetCommandLineInt(syshandle, "show_framerate", 0) != 0); - bool useLists = (SYS_GetCommandLineInt(syshandle, "displaylists", G.fileflags & G_FILE_DIAPLAY_LISTS) != 0); + bool useLists = (SYS_GetCommandLineInt(syshandle, "displaylists", G.fileflags & G_FILE_DISPLAY_LISTS) != 0); if(GLEW_ARB_multitexture && GLEW_VERSION_1_1) { int gameflag =(G.fileflags & G_FILE_GAME_MAT); m_blendermat = (SYS_GetCommandLineInt(syshandle, "blender_material", gameflag) != 0); } + + if(GPU_extensions_minimum_support()) { + int gameflag = (G.fileflags & G_FILE_GAME_MAT_GLSL); + + m_blenderglslmat = (SYS_GetCommandLineInt(syshandle, "blender_glsl_material", gameflag) != 0); + } // create the canvas, rasterizer and rendertools m_canvas = new GPG_Canvas(window); @@ -640,14 +649,15 @@ bool GPG_Application::startEngine(void) m_mouse, m_networkdevice, m_audiodevice, - startscenename); + startscenename, + m_startScene); // some python things PyObject* dictionaryobject = initGamePlayerPythonScripting("Ketsji", psl_Lowest); m_ketsjiengine->SetPythonDictionary(dictionaryobject); initRasterizer(m_rasterizer, m_canvas); - PyObject *gameLogic = initGameLogic(startscene); + PyObject *gameLogic = initGameLogic(m_ketsjiengine, startscene); PyDict_SetItemString(dictionaryobject, "GameLogic", gameLogic); // Same as importing the module initGameKeys(); initPythonConstraintBinding(); @@ -745,6 +755,8 @@ void GPG_Application::stopEngine() void GPG_Application::exitEngine() { + GPU_extensions_exit(); + if (m_ketsjiengine) { stopEngine(); diff --git a/source/gameengine/GamePlayer/ghost/GPG_Application.h b/source/gameengine/GamePlayer/ghost/GPG_Application.h index 31f5eb75e52..5242a419808 100644 --- a/source/gameengine/GamePlayer/ghost/GPG_Application.h +++ b/source/gameengine/GamePlayer/ghost/GPG_Application.h @@ -50,14 +50,15 @@ class GPG_Canvas; class GPG_KeyboardDevice; class GPG_System; struct Main; +struct Scene; class GPG_Application : public GHOST_IEventConsumer { public: - GPG_Application(GHOST_ISystem* system, struct Main* maggie, STR_String startSceneName); + GPG_Application(GHOST_ISystem* system); ~GPG_Application(void); - bool SetGameEngineData(struct Main* maggie,STR_String startSceneName); + bool SetGameEngineData(struct Main* maggie, struct Scene* scene); bool startWindow(STR_String& title, int windowLeft, int windowTop, int windowWidth, int windowHeight, const bool stereoVisual, const int stereoMode); bool startFullScreen(int width, int height, int bpp, int frequency, const bool stereoVisual, const int stereoMode); @@ -123,6 +124,7 @@ protected: /* The game data */ STR_String m_startSceneName; + struct Scene* m_startScene; struct Main* m_maggie; /* Exit state. */ diff --git a/source/gameengine/GamePlayer/ghost/GPG_ghost.cpp b/source/gameengine/GamePlayer/ghost/GPG_ghost.cpp index 26a85128025..cc781a38bbb 100644 --- a/source/gameengine/GamePlayer/ghost/GPG_ghost.cpp +++ b/source/gameengine/GamePlayer/ghost/GPG_ghost.cpp @@ -64,13 +64,15 @@ extern "C" #ifdef __cplusplus } #endif // __cplusplus + +#include "GPU_draw.h" + /********************************** * End Blender include block **********************************/ #include "SYS_System.h" #include "GPG_Application.h" -#include "GPC_PolygonMaterial.h" #include "GHOST_ISystem.h" #include "RAS_IRasterizer.h" @@ -282,7 +284,7 @@ int main(int argc, char** argv) bool fullScreenParFound = false; bool windowParFound = false; bool closeConsole = true; - RAS_IRasterizer::StereoMode stereomode; + RAS_IRasterizer::StereoMode stereomode = RAS_IRasterizer::RAS_STEREO_NOSTEREO; bool stereoWindow = false; bool stereoParFound = false; int windowLeft = 100; @@ -525,8 +527,6 @@ int main(int argc, char** argv) return 0; } - if (!stereoParFound) stereomode = RAS_IRasterizer::RAS_STEREO_NOSTEREO; - #ifdef WIN32 if (scr_saver_mode != SCREEN_SAVER_MODE_CONFIGURATION) #endif @@ -539,7 +539,7 @@ int main(int argc, char** argv) if (SYS_GetCommandLineInt(syshandle, "nomipmap", 0)) { - GPC_PolygonMaterial::SetMipMappingEnabled(0); + GPU_set_mipmap(0); } // Create the system @@ -561,7 +561,7 @@ int main(int argc, char** argv) { int exitcode = KX_EXIT_REQUEST_NO_REQUEST; STR_String exitstring = ""; - GPG_Application app(system, NULL, exitstring); + GPG_Application app(system); bool firstTimeRunning = true; char *filename = get_filename(argc, argv); char *titlename; @@ -619,7 +619,7 @@ int main(int argc, char** argv) #endif // WIN32 Main *maggie = bfd->main; Scene *scene = bfd->curscene; - char *startscenename = scene->id.name + 2; + G.main = maggie; G.fileflags = bfd->fileflags; //Seg Fault; icon.c gIcons == 0 @@ -661,7 +661,7 @@ int main(int argc, char** argv) } // GPG_Application app (system, maggie, startscenename); - app.SetGameEngineData(maggie, startscenename); + app.SetGameEngineData(maggie, scene); if (firstTimeRunning) { diff --git a/source/gameengine/GamePlayer/ghost/Makefile b/source/gameengine/GamePlayer/ghost/Makefile index 13940ac3fc8..0b187791734 100644 --- a/source/gameengine/GamePlayer/ghost/Makefile +++ b/source/gameengine/GamePlayer/ghost/Makefile @@ -69,6 +69,7 @@ CPPFLAGS += -I../../../blender/blenloader CPPFLAGS += -I../../../blender/imbuf CPPFLAGS += -I../../../blender/makesdna CPPFLAGS += -I../../../blender/readblenfile +CPPFLAGS += -I../../../blender/gpu CPPFLAGS += -I../../../gameengine/BlenderRoutines @@ -80,7 +81,3 @@ CPPFLAGS += -I$(NAN_STRING)/include CPPFLAGS += -I$(NAN_GHOST)/include CPPFLAGS += -I$(NAN_PYTHON)/include/python$(NAN_PYTHON_VERSION) -ifeq ($(WITH_BF_GLEXT),true) - CPPFLAGS += -DWITH_GLEXT -endif - diff --git a/source/gameengine/GamePlayer/ghost/SConscript b/source/gameengine/GamePlayer/ghost/SConscript index f3cce6c7443..33cf07b6211 100644 --- a/source/gameengine/GamePlayer/ghost/SConscript +++ b/source/gameengine/GamePlayer/ghost/SConscript @@ -40,6 +40,7 @@ incs = ['.', '#source/gameengine/GamePlayer/common', '#source/blender/misc', '#source/blender/blenloader', + '#source/blender/gpu', '#extern/glew/include'] incs += Split(env['BF_PYTHON_INC']) @@ -48,8 +49,5 @@ cflags = [] if env['OURPLATFORM']=='win32-vc': cflags = ['/GR'] -if env['WITH_BF_GLEXT'] == 1: - env['CPPFLAGS'].append('-DWITH_GLEXT') - env.BlenderLib (libname='gp_ghost', sources=source_files, includes = incs, defines = [], libtype='player',priority=0, compileflags=cflags) diff --git a/source/gameengine/Ketsji/BL_BlenderShader.cpp b/source/gameengine/Ketsji/BL_BlenderShader.cpp index a9a0771936c..13b8235687b 100644 --- a/source/gameengine/Ketsji/BL_BlenderShader.cpp +++ b/source/gameengine/Ketsji/BL_BlenderShader.cpp @@ -9,108 +9,64 @@ #include "BL_BlenderShader.h" #include "BL_Material.h" -#ifdef BLENDER_GLSL #include "GPU_extensions.h" #include "GPU_material.h" -#endif #include "RAS_BucketManager.h" #include "RAS_MeshObject.h" #include "RAS_IRasterizer.h" - /* this is evil, but we need the scene to create materials with - * lights from the correct scene .. */ -static struct Scene *GetSceneForName(const STR_String& scenename) -{ - Scene *sce; - - for (sce= (Scene*)G.main->scene.first; sce; sce= (Scene*)sce->id.next) - if (scenename == (sce->id.name+2)) - return sce; - - return (Scene*)G.main->scene.first; -} - -bool BL_BlenderShader::Ok() -{ -#ifdef BLENDER_GLSL - VerifyShader(); - - return (mMat && mMat->gpumaterial); -#else - return 0; -#endif -} - BL_BlenderShader::BL_BlenderShader(KX_Scene *scene, struct Material *ma, int lightlayer) : -#ifdef BLENDER_GLSL mScene(scene), mMat(ma), - mGPUMat(NULL), -#endif - mBound(false), mLightLayer(lightlayer) { -#ifdef BLENDER_GLSL - mBlenderScene = GetSceneForName(scene->GetName()); + mBlenderScene = scene->GetBlenderScene(); //GetSceneForName(scene->GetName()); mBlendMode = GPU_BLEND_SOLID; - if(mMat) { + if(mMat) GPU_material_from_blender(mBlenderScene, mMat); - mGPUMat = mMat->gpumaterial; - } -#endif } BL_BlenderShader::~BL_BlenderShader() { -#ifdef BLENDER_GLSL - if(mMat && mMat->gpumaterial) - GPU_material_unbind(mMat->gpumaterial); -#endif + if(mMat && GPU_material_from_blender(mBlenderScene, mMat)) + GPU_material_unbind(GPU_material_from_blender(mBlenderScene, mMat)); +} + +bool BL_BlenderShader::Ok() +{ + return VerifyShader(); } bool BL_BlenderShader::VerifyShader() { -#ifdef BLENDER_GLSL - if(mMat && !mMat->gpumaterial) - GPU_material_from_blender(mBlenderScene, mMat); - - mGPUMat = mMat->gpumaterial; - - return (mMat && mGPUMat); -#else - return false; -#endif + if(mMat) + return (GPU_material_from_blender(mBlenderScene, mMat) != 0); + else + return false; } -void BL_BlenderShader::SetProg(bool enable) +void BL_BlenderShader::SetProg(bool enable, double time) { -#ifdef BLENDER_GLSL if(VerifyShader()) { - if(enable) { - GPU_material_bind(mGPUMat, mLightLayer); - mBound = true; - } - else { - GPU_material_unbind(mGPUMat); - mBound = false; - } + if(enable) + GPU_material_bind(GPU_material_from_blender(mBlenderScene, mMat), mLightLayer, time); + else + GPU_material_unbind(GPU_material_from_blender(mBlenderScene, mMat)); } -#endif } int BL_BlenderShader::GetAttribNum() { -#ifdef BLENDER_GLSL GPUVertexAttribs attribs; int i, enabled = 0; if(!VerifyShader()) return enabled; - GPU_material_vertex_attributes(mGPUMat, &attribs); + GPU_material_vertex_attributes(GPU_material_from_blender(mBlenderScene, mMat), &attribs); for(i = 0; i < attribs.totlayer; i++) if(attribs.layer[i].glindex+1 > enabled) @@ -120,24 +76,23 @@ int BL_BlenderShader::GetAttribNum() enabled = BL_MAX_ATTRIB; return enabled; -#else - return 0; -#endif } void BL_BlenderShader::SetAttribs(RAS_IRasterizer* ras, const BL_Material *mat) { -#ifdef BLENDER_GLSL GPUVertexAttribs attribs; + GPUMaterial *gpumat; int i, attrib_num; ras->SetAttribNum(0); if(!VerifyShader()) return; + + gpumat = GPU_material_from_blender(mBlenderScene, mMat); if(ras->GetDrawingMode() == RAS_IRasterizer::KX_TEXTURED) { - GPU_material_vertex_attributes(mGPUMat, &attribs); + GPU_material_vertex_attributes(gpumat, &attribs); attrib_num = GetAttribNum(); ras->SetTexCoordNum(0); @@ -168,44 +123,37 @@ void BL_BlenderShader::SetAttribs(RAS_IRasterizer* ras, const BL_Material *mat) else ras->SetAttrib(RAS_IRasterizer::RAS_TEXCO_DISABLE, attribs.layer[i].glindex); } - - ras->EnableTextures(true); } - else - ras->EnableTextures(false); -#endif } -void BL_BlenderShader::Update( const KX_MeshSlot & ms, RAS_IRasterizer* rasty ) +void BL_BlenderShader::Update(const RAS_MeshSlot & ms, RAS_IRasterizer* rasty ) { -#ifdef BLENDER_GLSL float obmat[4][4], viewmat[4][4], viewinvmat[4][4], obcol[4]; + GPUMaterial *gpumat; - VerifyShader(); + gpumat = GPU_material_from_blender(mBlenderScene, mMat); - if(!mGPUMat) // || !mBound) + if(!gpumat || !GPU_material_bound(gpumat)) return; MT_Matrix4x4 model; model.setValue(ms.m_OpenGLMatrix); - MT_Matrix4x4 view; - rasty->GetViewMatrix(view); + const MT_Matrix4x4& view = rasty->GetViewMatrix(); + const MT_Matrix4x4& viewinv = rasty->GetViewInvMatrix(); + // note: getValue gives back column major as needed by OpenGL model.getValue((float*)obmat); view.getValue((float*)viewmat); - - view.invert(); - view.getValue((float*)viewinvmat); + viewinv.getValue((float*)viewinvmat); if(ms.m_bObjectColor) ms.m_RGBAcolor.getValue((float*)obcol); else obcol[0]= obcol[1]= obcol[2]= obcol[3]= 1.0f; - GPU_material_bind_uniforms(mGPUMat, obmat, viewmat, viewinvmat, obcol); + GPU_material_bind_uniforms(gpumat, obmat, viewmat, viewinvmat, obcol); - mBlendMode = GPU_material_blend_mode(mGPUMat, obcol); -#endif + mBlendMode = GPU_material_blend_mode(gpumat, obcol); } int BL_BlenderShader::GetBlendMode() @@ -215,12 +163,8 @@ int BL_BlenderShader::GetBlendMode() bool BL_BlenderShader::Equals(BL_BlenderShader *blshader) { -#ifdef BLENDER_GLSL /* to avoid unneeded state switches */ - return (blshader && mGPUMat == blshader->mGPUMat && mLightLayer == blshader->mLightLayer); -#else - return true; -#endif + return (blshader && mMat == blshader->mMat && mLightLayer == blshader->mLightLayer); } // eof diff --git a/source/gameengine/Ketsji/BL_BlenderShader.h b/source/gameengine/Ketsji/BL_BlenderShader.h index da9765dafa4..5c1f59f94ad 100644 --- a/source/gameengine/Ketsji/BL_BlenderShader.h +++ b/source/gameengine/Ketsji/BL_BlenderShader.h @@ -2,9 +2,7 @@ #ifndef __BL_GPUSHADER_H__ #define __BL_GPUSHADER_H__ -#ifdef BLENDER_GLSL #include "GPU_material.h" -#endif #include "MT_Matrix4x4.h" #include "MT_Matrix3x3.h" @@ -29,13 +27,9 @@ class BL_Material; class BL_BlenderShader { private: -#ifdef BLENDER_GLSL KX_Scene *mScene; struct Scene *mBlenderScene; struct Material *mMat; - GPUMaterial *mGPUMat; -#endif - bool mBound; int mLightLayer; int mBlendMode; @@ -46,11 +40,11 @@ public: virtual ~BL_BlenderShader(); bool Ok(); - void SetProg(bool enable); + void SetProg(bool enable, double time=0.0); int GetAttribNum(); void SetAttribs(class RAS_IRasterizer* ras, const BL_Material *mat); - void Update(const class KX_MeshSlot & ms, class RAS_IRasterizer* rasty); + void Update(const class RAS_MeshSlot & ms, class RAS_IRasterizer* rasty); int GetBlendMode(); bool Equals(BL_BlenderShader *blshader); diff --git a/source/gameengine/Ketsji/BL_Material.h b/source/gameengine/Ketsji/BL_Material.h index dcb66ea2579..0eaa234566c 100644 --- a/source/gameengine/Ketsji/BL_Material.h +++ b/source/gameengine/Ketsji/BL_Material.h @@ -18,9 +18,9 @@ struct EnvMap; this will default to users available units to build with more available, just increment this value although the more you add the slower the search time will be. - we will go for three, which should be enough + we will go for eight, which should be enough */ -#define MAXTEX 3 //match in RAS_TexVert & RAS_OpenGLRasterizer +#define MAXTEX 8 //match in RAS_TexVert & RAS_OpenGLRasterizer // different mapping modes class BL_Mapping @@ -139,7 +139,7 @@ enum BL_ras_mode COLLIDER=2, ZSORT=4, ALPHA=8, - TRIANGLE=16, + // TRIANGLE=16, USE_LIGHT=32, WIRE=64 }; diff --git a/source/gameengine/Ketsji/BL_Shader.cpp b/source/gameengine/Ketsji/BL_Shader.cpp index 57d0fe4140f..f28d3fa2912 100644 --- a/source/gameengine/Ketsji/BL_Shader.cpp +++ b/source/gameengine/Ketsji/BL_Shader.cpp @@ -433,7 +433,7 @@ void BL_Shader::SetProg(bool enable) } } -void BL_Shader::Update( const KX_MeshSlot & ms, RAS_IRasterizer* rasty ) +void BL_Shader::Update( const RAS_MeshSlot & ms, RAS_IRasterizer* rasty ) { if(!Ok() || !mPreDef.size()) return; @@ -445,8 +445,7 @@ void BL_Shader::Update( const KX_MeshSlot & ms, RAS_IRasterizer* rasty ) { MT_Matrix4x4 model; model.setValue(ms.m_OpenGLMatrix); - MT_Matrix4x4 view; - rasty->GetViewMatrix(view); + const MT_Matrix4x4& view = rasty->GetViewMatrix(); if(mAttr==SHD_TANGENT) ms.m_mesh->SetMeshModified(true); @@ -525,13 +524,15 @@ void BL_Shader::Update( const KX_MeshSlot & ms, RAS_IRasterizer* rasty ) } case VIEWMATRIX_INVERSE: { - view.invert(); + MT_Matrix4x4 viewinv = view; + viewinv.invert(); SetUniform(uni->mLoc, view); break; } case VIEWMATRIX_INVERSETRANSPOSE: { - view.invert(); + MT_Matrix4x4 viewinv = view; + viewinv.invert(); SetUniform(uni->mLoc, view, true); break; } @@ -670,6 +671,7 @@ void BL_Shader::SetUniform(int uniform, const MT_Matrix4x4& vec, bool transpose) ) { float value[16]; + // note: getValue gives back column major as needed by OpenGL vec.getValue(value); glUniformMatrix4fvARB(uniform, 1, transpose?GL_TRUE:GL_FALSE, value); } diff --git a/source/gameengine/Ketsji/BL_Shader.h b/source/gameengine/Ketsji/BL_Shader.h index 8f303454087..c7fae31ba03 100644 --- a/source/gameengine/Ketsji/BL_Shader.h +++ b/source/gameengine/Ketsji/BL_Shader.h @@ -177,7 +177,7 @@ public: void UnloadShader(); // Update predefined uniforms each render call - void Update(const class KX_MeshSlot & ms, class RAS_IRasterizer* rasty); + void Update(const class RAS_MeshSlot & ms, class RAS_IRasterizer* rasty); //// Set sampler units (copied) //void InitializeSampler(int unit, BL_Texture* texture ); diff --git a/source/gameengine/Ketsji/CMakeLists.txt b/source/gameengine/Ketsji/CMakeLists.txt index be009d94701..58411f6d25e 100644 --- a/source/gameengine/Ketsji/CMakeLists.txt +++ b/source/gameengine/Ketsji/CMakeLists.txt @@ -69,6 +69,7 @@ SET(INC ../../../intern/SoundSystem ../../../source/blender/misc ../../../source/blender/blenloader + ../../../source/blender/gpu ../../../extern/bullet2/src ../../../extern/solid ../../../extern/glew/include diff --git a/source/gameengine/Ketsji/KX_BlenderMaterial.cpp b/source/gameengine/Ketsji/KX_BlenderMaterial.cpp index a67e5b26667..f92200780d5 100644 --- a/source/gameengine/Ketsji/KX_BlenderMaterial.cpp +++ b/source/gameengine/Ketsji/KX_BlenderMaterial.cpp @@ -19,13 +19,12 @@ #include "MT_Vector4.h" #include "MT_Matrix4x4.h" +#include "RAS_BucketManager.h" #include "RAS_MeshObject.h" #include "RAS_IRasterizer.h" #include "RAS_OpenGLRasterizer/RAS_GLExtensionManager.h" -extern "C" { -#include "BDR_drawmesh.h" -} +#include "GPU_draw.h" #include "STR_HashedString.h" @@ -48,7 +47,6 @@ KX_BlenderMaterial::KX_BlenderMaterial( BL_Material *data, bool skin, int lightlayer, - void *clientobject, PyTypeObject *T ) : PyObjectPlus(T), @@ -62,9 +60,7 @@ KX_BlenderMaterial::KX_BlenderMaterial( data->transp, ((data->ras_mode &ALPHA)!=0), ((data->ras_mode &ZSORT)!=0), - lightlayer, - ((data->ras_mode &TRIANGLE)!=0), - clientobject + lightlayer ), mMaterial(data), mShader(0), @@ -78,9 +74,10 @@ KX_BlenderMaterial::KX_BlenderMaterial( { // -------------------------------- // RAS_IPolyMaterial variables... - m_flag |=RAS_BLENDERMAT; - m_flag |=(mMaterial->IdMode>=ONETEX)?RAS_MULTITEX:0; - m_flag |=(mMaterial->ras_mode & USE_LIGHT)!=0?RAS_MULTILIGHT:0; + m_flag |= RAS_BLENDERMAT; + m_flag |= (mMaterial->IdMode>=ONETEX)? RAS_MULTITEX: 0; + m_flag |= ((mMaterial->ras_mode & USE_LIGHT)!=0)? RAS_MULTILIGHT: 0; + m_flag |= (mMaterial->glslmat)? RAS_BLENDERGLSL: 0; // figure max int enabled = mMaterial->num_enabled; @@ -97,7 +94,7 @@ KX_BlenderMaterial::KX_BlenderMaterial( mMaterial->blend_mode[i] ); } - m_multimode += mMaterial->IdMode+mMaterial->ras_mode; + m_multimode += mMaterial->IdMode+ (mMaterial->ras_mode & ~(COLLIDER|USE_LIGHT)); } @@ -204,7 +201,7 @@ void KX_BlenderMaterial::OnExit() } if( mMaterial->tface ) - set_tpage(mMaterial->tface); + GPU_set_tpage(mMaterial->tface); } @@ -256,25 +253,28 @@ void KX_BlenderMaterial::setShaderData( bool enable, RAS_IRasterizer *ras) void KX_BlenderMaterial::setBlenderShaderData( bool enable, RAS_IRasterizer *ras) { if( !enable || !mBlenderShader->Ok() ) { + ras->SetBlendingMode(TF_SOLID); + // frame cleanup. if(mLastBlenderShader) { mLastBlenderShader->SetProg(false); mLastBlenderShader= NULL; } + else + BL_Texture::DisableAllTextures(); - ras->SetBlendingMode(TF_SOLID); - BL_Texture::DisableAllTextures(); return; } if(!mBlenderShader->Equals(mLastBlenderShader)) { ras->SetBlendingMode(mMaterial->transp); - BL_Texture::DisableAllTextures(); if(mLastBlenderShader) mLastBlenderShader->SetProg(false); + else + BL_Texture::DisableAllTextures(); - mBlenderShader->SetProg(true); + mBlenderShader->SetProg(true, ras->GetTime()); mLastBlenderShader= mBlenderShader; } } @@ -354,21 +354,22 @@ KX_BlenderMaterial::ActivatShaders( if (GetCachingInfo() != cachingInfo) { if (!cachingInfo) - tmp->setShaderData( false, rasty); + tmp->setShaderData(false, rasty); cachingInfo = GetCachingInfo(); if(rasty->GetDrawingMode() == RAS_IRasterizer::KX_TEXTURED) - tmp->setShaderData( true, rasty); + tmp->setShaderData(true, rasty); else - tmp->setShaderData( false, rasty); + tmp->setShaderData(false, rasty); if(mMaterial->mode & RAS_IRasterizer::KX_TWOSIDE) rasty->SetCullFace(false); else rasty->SetCullFace(true); - if (((mMaterial->ras_mode &WIRE)!=0) || mMaterial->mode & RAS_IRasterizer::KX_LINES) + if (((mMaterial->ras_mode &WIRE)!=0) || (mMaterial->mode & RAS_IRasterizer::KX_LINES) || + (rasty->GetDrawingMode() <= RAS_IRasterizer::KX_WIREFRAME)) { if((mMaterial->ras_mode &WIRE)!=0) rasty->SetCullFace(false); @@ -394,31 +395,24 @@ KX_BlenderMaterial::ActivateBlenderShaders( mLastShader= NULL; } - // reset... - if(tmp->mMaterial->IsShared()) - cachingInfo =0; - if (GetCachingInfo() != cachingInfo) { if (!cachingInfo) tmp->setBlenderShaderData(false, rasty); cachingInfo = GetCachingInfo(); - if(rasty->GetDrawingMode() == RAS_IRasterizer::KX_TEXTURED) { + if(rasty->GetDrawingMode() == RAS_IRasterizer::KX_TEXTURED) tmp->setBlenderShaderData(true, rasty); - rasty->EnableTextures(true); - } - else { + else tmp->setBlenderShaderData(false, rasty); - rasty->EnableTextures(false); - } if(mMaterial->mode & RAS_IRasterizer::KX_TWOSIDE) rasty->SetCullFace(false); else rasty->SetCullFace(true); - if (((mMaterial->ras_mode &WIRE)!=0) || mMaterial->mode & RAS_IRasterizer::KX_LINES) + if (((mMaterial->ras_mode & WIRE)!=0) || (mMaterial->mode & RAS_IRasterizer::KX_LINES) || + (rasty->GetDrawingMode() <= RAS_IRasterizer::KX_WIREFRAME)) { if((mMaterial->ras_mode &WIRE)!=0) rasty->SetCullFace(false); @@ -426,10 +420,10 @@ KX_BlenderMaterial::ActivateBlenderShaders( } else rasty->SetLines(false); - } - ActivatGLMaterials(rasty); - mBlenderShader->SetAttribs(rasty, mMaterial); + ActivatGLMaterials(rasty); + mBlenderShader->SetAttribs(rasty, mMaterial); + } } void @@ -466,7 +460,8 @@ KX_BlenderMaterial::ActivateMat( else rasty->SetCullFace(true); - if (((mMaterial->ras_mode &WIRE)!=0) || mMaterial->mode & RAS_IRasterizer::KX_LINES) + if (((mMaterial->ras_mode &WIRE)!=0) || (mMaterial->mode & RAS_IRasterizer::KX_LINES) || + (rasty->GetDrawingMode() <= RAS_IRasterizer::KX_WIREFRAME)) { if((mMaterial->ras_mode &WIRE)!=0) rasty->SetCullFace(false); @@ -486,12 +481,10 @@ KX_BlenderMaterial::Activate( TCachingInfo& cachingInfo )const { - bool dopass = false; - if( GLEW_ARB_shader_objects && ( mShader && mShader->Ok() ) ) { - if( (mPass++) < mShader->getNumPass() ) { + if(GLEW_ARB_shader_objects && (mShader && mShader->Ok())) { + if((mPass++) < mShader->getNumPass() ) { ActivatShaders(rasty, cachingInfo); - dopass = true; - return dopass; + return true; } else { if(mShader == mLastShader) { @@ -499,36 +492,29 @@ KX_BlenderMaterial::Activate( mLastShader = NULL; } mPass = 0; - dopass = false; - return dopass; + return false; } } - else if( GLEW_ARB_shader_objects && ( mBlenderShader && mBlenderShader->Ok() ) ) { - if( (mPass++) == 0 ) { + else if( GLEW_ARB_shader_objects && (mBlenderShader && mBlenderShader->Ok() ) ) { + if(mPass++ == 0) { ActivateBlenderShaders(rasty, cachingInfo); - dopass = true; - return dopass; + return true; } else { mPass = 0; - dopass = false; - return dopass; + return false; } } else { - switch (mPass++) - { - case 0: - ActivateMat(rasty, cachingInfo); - dopass = true; - break; - default: - mPass = 0; - dopass = false; - break; + if(mPass++ == 0) { + ActivateMat(rasty, cachingInfo); + return true; + } + else { + mPass = 0; + return false; } } - return dopass; } bool KX_BlenderMaterial::UsesLighting(RAS_IRasterizer *rasty) const @@ -536,14 +522,15 @@ bool KX_BlenderMaterial::UsesLighting(RAS_IRasterizer *rasty) const if(!RAS_IPolyMaterial::UsesLighting(rasty)) return false; - if(mShader && mShader->Ok()); + if(mShader && mShader->Ok()) + return true; else if(mBlenderShader && mBlenderShader->Ok()) return false; - - return true; + else + return true; } -void KX_BlenderMaterial::ActivateMeshSlot(const KX_MeshSlot & ms, RAS_IRasterizer* rasty) const +void KX_BlenderMaterial::ActivateMeshSlot(const RAS_MeshSlot & ms, RAS_IRasterizer* rasty) const { if(mShader && GLEW_ARB_shader_objects) { mShader->Update(ms, rasty); @@ -554,7 +541,7 @@ void KX_BlenderMaterial::ActivateMeshSlot(const KX_MeshSlot & ms, RAS_IRasterize mBlenderShader->Update(ms, rasty); /* we do blend modes here, because they can change per object - * with the same material due to obcolor */ + * with the same material due to obcolor/obalpha */ blendmode = mBlenderShader->GetBlendMode(); if((blendmode == TF_SOLID || blendmode == TF_ALPHA) && mMaterial->transp != TF_SOLID) blendmode = mMaterial->transp; @@ -633,11 +620,7 @@ void KX_BlenderMaterial::ActivateTexGen(RAS_IRasterizer *ras) const else ras->SetTexCoord(RAS_IRasterizer::RAS_TEXCO_DISABLE, i); } - - ras->EnableTextures(true); } - else - ras->EnableTextures(false); } void KX_BlenderMaterial::setTexMatrixData(int i) @@ -712,8 +695,7 @@ void KX_BlenderMaterial::setObjectMatrixData(int i, RAS_IRasterizer *ras) glEnable(GL_TEXTURE_GEN_T); glEnable(GL_TEXTURE_GEN_R); - MT_Matrix4x4 mvmat; - ras->GetViewMatrix(mvmat); + const MT_Matrix4x4& mvmat = ras->GetViewMatrix(); glMatrixMode(GL_TEXTURE); glLoadIdentity(); @@ -835,7 +817,9 @@ KX_PYMETHODDEF_DOC( KX_BlenderMaterial, getShader , "getShader()") } if(mShader && !mShader->GetError()) { + m_flag &= ~RAS_BLENDERGLSL; mMaterial->SetSharedMaterial(true); + mScene->GetBucketManager()->ReleaseDisplayLists(this); Py_INCREF(mShader); return mShader; }else @@ -870,8 +854,6 @@ void KX_BlenderMaterial::SetBlenderGLSLShader(void) delete mBlenderShader; mBlenderShader = 0; } - else - m_flag |= RAS_BLENDERGLSL; } KX_PYMETHODDEF_DOC( KX_BlenderMaterial, getMaterialIndex, "getMaterialIndex()") diff --git a/source/gameengine/Ketsji/KX_BlenderMaterial.h b/source/gameengine/Ketsji/KX_BlenderMaterial.h index 0d7657b8cdb..4ddf5a924df 100644 --- a/source/gameengine/Ketsji/KX_BlenderMaterial.h +++ b/source/gameengine/Ketsji/KX_BlenderMaterial.h @@ -28,7 +28,6 @@ public: BL_Material* mat, bool skin, int lightlayer, - void* clientobject, PyTypeObject* T=&Type ); @@ -47,7 +46,7 @@ public: virtual void ActivateMeshSlot( - const KX_MeshSlot & ms, + const RAS_MeshSlot & ms, RAS_IRasterizer* rasty ) const; diff --git a/source/gameengine/Ketsji/KX_ConvertPhysicsObjects.cpp b/source/gameengine/Ketsji/KX_ConvertPhysicsObjects.cpp index d6997ee29a8..9607489497d 100644 --- a/source/gameengine/Ketsji/KX_ConvertPhysicsObjects.cpp +++ b/source/gameengine/Ketsji/KX_ConvertPhysicsObjects.cpp @@ -76,16 +76,16 @@ struct KX_PhysicsInstance { DT_VertexBaseHandle m_vertexbase; - int m_vtxarray; + RAS_DisplayArray* m_darray; RAS_IPolyMaterial* m_material; - - KX_PhysicsInstance(DT_VertexBaseHandle vertex_base, int vtxarray, RAS_IPolyMaterial* mat) + + KX_PhysicsInstance(DT_VertexBaseHandle vertex_base, RAS_DisplayArray *darray, RAS_IPolyMaterial* mat) : m_vertexbase(vertex_base), - m_vtxarray(vtxarray), - m_material(mat) + m_darray(darray), + m_material(mat) { } - + ~KX_PhysicsInstance() { DT_DeleteVertexBase(m_vertexbase); @@ -100,11 +100,11 @@ static void BL_RegisterSumoObject(KX_GameObject* gameobj,class SM_Scene* sumoSce static DT_ShapeHandle CreateShapeFromMesh(RAS_MeshObject* meshobj, bool polytope); void KX_ConvertSumoObject( KX_GameObject* gameobj, - RAS_MeshObject* meshobj, - KX_Scene* kxscene, - PHY_ShapeProps* kxshapeprops, - PHY_MaterialProps* kxmaterial, - struct KX_ObjectProperties* objprop) + RAS_MeshObject* meshobj, + KX_Scene* kxscene, + PHY_ShapeProps* kxshapeprops, + PHY_MaterialProps* kxmaterial, + struct KX_ObjectProperties* objprop) { @@ -150,23 +150,23 @@ void KX_ConvertSumoObject( KX_GameObject* gameobj, objprop->m_boundobject.box.m_extends[1], objprop->m_boundobject.box.m_extends[2]); smprop->m_inertia.scale(objprop->m_boundobject.box.m_extends[0]*objprop->m_boundobject.box.m_extends[0], - objprop->m_boundobject.box.m_extends[1]*objprop->m_boundobject.box.m_extends[1], - objprop->m_boundobject.box.m_extends[2]*objprop->m_boundobject.box.m_extends[2]); + objprop->m_boundobject.box.m_extends[1]*objprop->m_boundobject.box.m_extends[1], + objprop->m_boundobject.box.m_extends[2]*objprop->m_boundobject.box.m_extends[2]); smprop->m_inertia *= smprop->m_mass/MT_Vector3(objprop->m_boundobject.box.m_extends).length(); break; case KX_BOUNDCYLINDER: shape = DT_NewCylinder(smprop->m_radius, objprop->m_boundobject.c.m_height); smprop->m_inertia.scale(smprop->m_mass*smprop->m_radius*smprop->m_radius, - smprop->m_mass*smprop->m_radius*smprop->m_radius, - smprop->m_mass*objprop->m_boundobject.c.m_height*objprop->m_boundobject.c.m_height); + smprop->m_mass*smprop->m_radius*smprop->m_radius, + smprop->m_mass*objprop->m_boundobject.c.m_height*objprop->m_boundobject.c.m_height); break; case KX_BOUNDCONE: shape = DT_NewCone(objprop->m_radius, objprop->m_boundobject.c.m_height); smprop->m_inertia.scale(smprop->m_mass*smprop->m_radius*smprop->m_radius, - smprop->m_mass*smprop->m_radius*smprop->m_radius, - smprop->m_mass*objprop->m_boundobject.c.m_height*objprop->m_boundobject.c.m_height); + smprop->m_mass*smprop->m_radius*smprop->m_radius, + smprop->m_mass*objprop->m_boundobject.c.m_height*objprop->m_boundobject.c.m_height); break; - /* Dynamic mesh objects. WARNING! slow. */ + /* Dynamic mesh objects. WARNING! slow. */ case KX_BOUNDPOLYTOPE: polytope = true; // fall through @@ -186,15 +186,15 @@ void KX_ConvertSumoObject( KX_GameObject* gameobj, shape = DT_NewSphere(objprop->m_radius); smprop->m_inertia *= smprop->m_mass*smprop->m_radius*smprop->m_radius; break; - + } - + sumoObj = new SM_Object(shape, !objprop->m_ghost?smmaterial:NULL,smprop,NULL); - + sumoObj->setRigidBody(objprop->m_angular_rigidbody?true:false); - + BL_RegisterSumoObject(gameobj,sceneptr,sumoObj,"",true, true); - + } else { // non physics object @@ -320,12 +320,11 @@ static void BL_RegisterSumoObject( physicscontroller->SetObject(gameobj->GetSGNode()); } -static DT_ShapeHandle InstancePhysicsComplex(RAS_MeshObject* meshobj, int vtxarray, RAS_IPolyMaterial *mat) +static DT_ShapeHandle InstancePhysicsComplex(RAS_MeshObject* meshobj, RAS_DisplayArray *darray, RAS_IPolyMaterial *mat) { // instance a mesh from a single vertex array & material - const RAS_TexVert *vertex_array = &((*meshobj->GetVertexCache(mat)[vtxarray])[0]); - //const KX_IndexArray &index_array = *meshobj->GetIndexCache(mat)[vtxarray]; - DT_VertexBaseHandle vertex_base = DT_NewVertexBase(vertex_array[0].getLocalXYZ(), sizeof(RAS_TexVert)); + const RAS_TexVert *vertex_array = &darray->m_vertex[0]; + DT_VertexBaseHandle vertex_base = DT_NewVertexBase(vertex_array[0].getXYZ(), sizeof(RAS_TexVert)); DT_ShapeHandle shape = DT_NewComplexShape(vertex_base); @@ -337,15 +336,19 @@ static DT_ShapeHandle InstancePhysicsComplex(RAS_MeshObject* meshobj, int vtxarr // only add polygons that have the collisionflag set if (poly->IsCollider()) { - DT_VertexIndices(3, poly->GetVertexIndexBase().m_indexarray); + DT_Begin(); + DT_VertexIndex(poly->GetVertexOffset(0)); + DT_VertexIndex(poly->GetVertexOffset(1)); + DT_VertexIndex(poly->GetVertexOffset(2)); + DT_End(); // tesselate if (poly->VertexCount() == 4) { DT_Begin(); - DT_VertexIndex(poly->GetVertexIndexBase().m_indexarray[0]); - DT_VertexIndex(poly->GetVertexIndexBase().m_indexarray[2]); - DT_VertexIndex(poly->GetVertexIndexBase().m_indexarray[3]); + DT_VertexIndex(poly->GetVertexOffset(0)); + DT_VertexIndex(poly->GetVertexOffset(2)); + DT_VertexIndex(poly->GetVertexOffset(3)); DT_End(); } } @@ -354,16 +357,15 @@ static DT_ShapeHandle InstancePhysicsComplex(RAS_MeshObject* meshobj, int vtxarr //DT_VertexIndices(indices.size(), &indices[0]); DT_EndComplexShape(); - map_gamemesh_to_instance.insert(GEN_HashedPtr(meshobj), new KX_PhysicsInstance(vertex_base, vtxarray, mat)); + map_gamemesh_to_instance.insert(GEN_HashedPtr(meshobj), new KX_PhysicsInstance(vertex_base, darray, mat)); return shape; } -static DT_ShapeHandle InstancePhysicsPolytope(RAS_MeshObject* meshobj, int vtxarray, RAS_IPolyMaterial *mat) +static DT_ShapeHandle InstancePhysicsPolytope(RAS_MeshObject* meshobj, RAS_DisplayArray *darray, RAS_IPolyMaterial *mat) { // instance a mesh from a single vertex array & material - const RAS_TexVert *vertex_array = &((*meshobj->GetVertexCache(mat)[vtxarray])[0]); - //const KX_IndexArray &index_array = *meshobj->GetIndexCache(mat)[vtxarray]; - DT_VertexBaseHandle vertex_base = DT_NewVertexBase(vertex_array[0].getLocalXYZ(), sizeof(RAS_TexVert)); + const RAS_TexVert *vertex_array = &darray->m_vertex[0]; + DT_VertexBaseHandle vertex_base = DT_NewVertexBase(vertex_array[0].getXYZ(), sizeof(RAS_TexVert)); std::vector indices; for (int p = 0; p < meshobj->NumPolygons(); p++) @@ -373,12 +375,12 @@ static DT_ShapeHandle InstancePhysicsPolytope(RAS_MeshObject* meshobj, int vtxar // only add polygons that have the collisionflag set if (poly->IsCollider()) { - indices.push_back(poly->GetVertexIndexBase().m_indexarray[0]); - indices.push_back(poly->GetVertexIndexBase().m_indexarray[1]); - indices.push_back(poly->GetVertexIndexBase().m_indexarray[2]); + indices.push_back(poly->GetVertexOffset(0)); + indices.push_back(poly->GetVertexOffset(1)); + indices.push_back(poly->GetVertexOffset(2)); if (poly->VertexCount() == 4) - indices.push_back(poly->GetVertexIndexBase().m_indexarray[3]); + indices.push_back(poly->GetVertexOffset(3)); } } @@ -386,7 +388,7 @@ static DT_ShapeHandle InstancePhysicsPolytope(RAS_MeshObject* meshobj, int vtxar DT_VertexIndices(indices.size(), &indices[0]); DT_EndPolytope(); - map_gamemesh_to_instance.insert(GEN_HashedPtr(meshobj), new KX_PhysicsInstance(vertex_base, vtxarray, mat)); + map_gamemesh_to_instance.insert(GEN_HashedPtr(meshobj), new KX_PhysicsInstance(vertex_base, darray, mat)); return shape; } @@ -398,8 +400,8 @@ bool KX_ReInstanceShapeFromMesh(RAS_MeshObject* meshobj) KX_PhysicsInstance *instance = *map_gamemesh_to_instance[GEN_HashedPtr(meshobj)]; if (instance) { - const RAS_TexVert *vertex_array = &((*meshobj->GetVertexCache(instance->m_material)[instance->m_vtxarray])[0]); - DT_ChangeVertexBase(instance->m_vertexbase, vertex_array[0].getLocalXYZ()); + const RAS_TexVert *vertex_array = &instance->m_darray->m_vertex[0]; + DT_ChangeVertexBase(instance->m_vertexbase, vertex_array[0].getXYZ()); return true; } return false; @@ -425,7 +427,7 @@ static DT_ShapeHandle CreateShapeFromMesh(RAS_MeshObject* meshobj, bool polytope // Count the number of collision polygons and check they all come from the same // vertex array int numvalidpolys = 0; - int vtxarray = -1; + RAS_DisplayArray *darray = NULL; RAS_IPolyMaterial *poly_material = NULL; bool reinstance = true; @@ -437,14 +439,14 @@ static DT_ShapeHandle CreateShapeFromMesh(RAS_MeshObject* meshobj, bool polytope if (poly->IsCollider()) { // check polygon is from the same vertex array - if (poly->GetVertexIndexBase().m_vtxarray != vtxarray) + if (poly->GetDisplayArray() != darray) { - if (vtxarray < 0) - vtxarray = poly->GetVertexIndexBase().m_vtxarray; + if (darray == NULL) + darray = poly->GetDisplayArray(); else { reinstance = false; - vtxarray = -1; + darray = NULL; } } @@ -478,9 +480,9 @@ static DT_ShapeHandle CreateShapeFromMesh(RAS_MeshObject* meshobj, bool polytope if (reinstance) { if (polytope) - shape = InstancePhysicsPolytope(meshobj, vtxarray, poly_material); + shape = InstancePhysicsPolytope(meshobj, darray, poly_material); else - shape = InstancePhysicsComplex(meshobj, vtxarray, poly_material); + shape = InstancePhysicsComplex(meshobj, darray, poly_material); } else { @@ -489,7 +491,7 @@ static DT_ShapeHandle CreateShapeFromMesh(RAS_MeshObject* meshobj, bool polytope std::cout << "CreateShapeFromMesh: " << meshobj->GetName() << " is not suitable for polytope." << std::endl; if (!poly_material) std::cout << " Check mesh materials." << std::endl; - if (vtxarray < 0) + if (darray == NULL) std::cout << " Check number of vertices." << std::endl; } @@ -505,18 +507,10 @@ static DT_ShapeHandle CreateShapeFromMesh(RAS_MeshObject* meshobj, bool polytope if (poly->IsCollider()) { /* We have to tesselate here because SOLID can only raycast triangles */ DT_Begin(); - /* V1 */ - DT_Vertex(meshobj->GetVertex(poly->GetVertexIndexBase().m_vtxarray, - poly->GetVertexIndexBase().m_indexarray[2], - poly->GetMaterial()->GetPolyMaterial())->getLocalXYZ()); - /* V2 */ - DT_Vertex(meshobj->GetVertex(poly->GetVertexIndexBase().m_vtxarray, - poly->GetVertexIndexBase().m_indexarray[1], - poly->GetMaterial()->GetPolyMaterial())->getLocalXYZ()); - /* V3 */ - DT_Vertex(meshobj->GetVertex(poly->GetVertexIndexBase().m_vtxarray, - poly->GetVertexIndexBase().m_indexarray[0], - poly->GetMaterial()->GetPolyMaterial())->getLocalXYZ()); + /* V1, V2, V3 */ + DT_Vertex(poly->GetVertex(2)->getXYZ()); + DT_Vertex(poly->GetVertex(1)->getXYZ()); + DT_Vertex(poly->GetVertex(0)->getXYZ()); numvalidpolys++; DT_End(); @@ -524,18 +518,10 @@ static DT_ShapeHandle CreateShapeFromMesh(RAS_MeshObject* meshobj, bool polytope if (poly->VertexCount() == 4) { DT_Begin(); - /* V1 */ - DT_Vertex(meshobj->GetVertex(poly->GetVertexIndexBase().m_vtxarray, - poly->GetVertexIndexBase().m_indexarray[3], - poly->GetMaterial()->GetPolyMaterial())->getLocalXYZ()); - /* V3 */ - DT_Vertex(meshobj->GetVertex(poly->GetVertexIndexBase().m_vtxarray, - poly->GetVertexIndexBase().m_indexarray[2], - poly->GetMaterial()->GetPolyMaterial())->getLocalXYZ()); - /* V4 */ - DT_Vertex(meshobj->GetVertex(poly->GetVertexIndexBase().m_vtxarray, - poly->GetVertexIndexBase().m_indexarray[0], - poly->GetMaterial()->GetPolyMaterial())->getLocalXYZ()); + /* V1, V3, V4 */ + DT_Vertex(poly->GetVertex(3)->getXYZ()); + DT_Vertex(poly->GetVertex(2)->getXYZ()); + DT_Vertex(poly->GetVertex(0)->getXYZ()); numvalidpolys++; DT_End(); diff --git a/source/gameengine/Ketsji/KX_GameObject.cpp b/source/gameengine/Ketsji/KX_GameObject.cpp index cc2956813c1..bec5d188f06 100644 --- a/source/gameengine/Ketsji/KX_GameObject.cpp +++ b/source/gameengine/Ketsji/KX_GameObject.cpp @@ -79,10 +79,12 @@ KX_GameObject::KX_GameObject( m_bDyna(false), m_layer(0), m_pBlenderObject(NULL), + m_pBlenderGroupObject(NULL), m_bSuspendDynamics(false), m_bUseObjectColor(false), m_bIsNegativeScaling(false), m_bVisible(true), + m_bCulled(true), m_pPhysicsController1(NULL), m_pPhysicsEnvironment(NULL), m_xray(false), @@ -101,8 +103,11 @@ KX_GameObject::KX_GameObject( }; + KX_GameObject::~KX_GameObject() { + RemoveMeshes(); + // is this delete somewhere ? //if (m_sumoObj) // delete m_sumoObj; @@ -164,7 +169,6 @@ STR_String KX_GameObject::GetName() void KX_GameObject::SetName(STR_String name) { m_name = name; - }; // Set the name of the value @@ -285,11 +289,11 @@ void KX_GameObject::ProcessReplica(KX_GameObject* replica) CValue* KX_GameObject::GetReplica() { KX_GameObject* replica = new KX_GameObject(*this); - + // this will copy properties and so on... CValue::AddDataToReplica(replica); ProcessReplica(replica); - + return replica; } @@ -355,24 +359,26 @@ double* KX_GameObject::GetOpenGLMatrix() return fl; } +void KX_GameObject::AddMeshUser() +{ + for (size_t i=0;iAddMeshUser(this); + + UpdateBuckets(); +} - -void KX_GameObject::Bucketize() +void KX_GameObject::UpdateBuckets() { double* fl = GetOpenGLMatrix(); for (size_t i=0;iBucketize(fl, this, m_bUseObjectColor, m_objectColor); + m_meshes[i]->UpdateBuckets(this, fl, m_bUseObjectColor, m_objectColor, m_bVisible, m_bCulled); } - - void KX_GameObject::RemoveMeshes() { - double* fl = GetOpenGLMatrix(); - for (size_t i=0;iRemoveFromBuckets(fl, this); + m_meshes[i]->RemoveFromBuckets(this); //note: meshes can be shared, and are deleted by KX_BlenderSceneConverter @@ -455,13 +461,14 @@ KX_GameObject::UpdateMaterialData( ) { int mesh = 0; - if (((unsigned int)mesh < m_meshes.size()) && mesh >= 0) { - RAS_MaterialBucket::Set::iterator mit = m_meshes[mesh]->GetFirstMaterial(); + list::iterator mit = m_meshes[mesh]->GetFirstMaterial(); + for(; mit != m_meshes[mesh]->GetLastMaterial(); ++mit) { - RAS_IPolyMaterial* poly = (*mit)->GetPolyMaterial(); - if(poly->GetFlag() & RAS_BLENDERMAT) + RAS_IPolyMaterial* poly = mit->m_bucket->GetPolyMaterial(); + + if(poly->GetFlag() & RAS_BLENDERMAT ) { KX_BlenderMaterial *m = static_cast(poly); @@ -469,8 +476,7 @@ KX_GameObject::UpdateMaterialData( { m->UpdateIPO(rgba, specrgb,hard,spec,ref,emit, alpha); // if mesh has only one material attached to it then use original hack with no need to edit vertices (better performance) - if(!(poly->GetFlag() & RAS_BLENDERGLSL)) - SetObjectColor(rgba); + SetObjectColor(rgba); } else { @@ -504,6 +510,23 @@ KX_GameObject::SetVisible( m_bVisible = v; } +bool +KX_GameObject::GetCulled( + void + ) +{ + return m_bCulled; +} + +void +KX_GameObject::SetCulled( + bool c + ) +{ + m_bCulled = c; +} + + void KX_GameObject::SetLayer( int l @@ -520,44 +543,6 @@ KX_GameObject::GetLayer( return m_layer; } -// used by Python, and the actuatorshould _not_ be misused by the -// scene! -void -KX_GameObject::MarkVisible( - bool visible - ) -{ - /* If explicit visibility settings are used, this is - * determined on this level. Maybe change this to mesh level - * later on? */ - - double* fl = GetOpenGLMatrixPtr()->getPointer(); - for (size_t i=0;iMarkVisible(fl,this,visible,m_bUseObjectColor,m_objectColor); - } -} - - -// Always use the flag? -void -KX_GameObject::MarkVisible( - void - ) -{ - double* fl = GetOpenGLMatrixPtr()->getPointer(); - for (size_t i=0;iMarkVisible(fl, - this, - m_bVisible, - m_bUseObjectColor, - m_objectColor - ); - } -} - - void KX_GameObject::addLinearVelocity(const MT_Vector3& lin_vel,bool local) { if (m_pPhysicsController1) @@ -1052,6 +1037,7 @@ int KX_GameObject::_setattr(const STR_String& attr, PyObject *value) // _setattr if (attr == "visible") { SetVisible(val != 0); + UpdateBuckets(); return 0; } } @@ -1221,8 +1207,8 @@ PyObject* KX_GameObject::PySetVisible(PyObject* self, PyObject* value) return NULL; } - MarkVisible(visible!=0); - m_bVisible = (visible!=0); + SetVisible(visible != 0); + UpdateBuckets(); Py_RETURN_NONE; } diff --git a/source/gameengine/Ketsji/KX_GameObject.h b/source/gameengine/Ketsji/KX_GameObject.h index 508bc7cdfd0..9dcf6526448 100644 --- a/source/gameengine/Ketsji/KX_GameObject.h +++ b/source/gameengine/Ketsji/KX_GameObject.h @@ -75,15 +75,17 @@ protected: int m_layer; std::vector m_meshes; struct Object* m_pBlenderObject; + struct Object* m_pBlenderGroupObject; bool m_bSuspendDynamics; bool m_bUseObjectColor; bool m_bIsNegativeScaling; MT_Vector4 m_objectColor; - // Is this object set to be visible? Only useful for the - // visibility subsystem right now. - bool m_bVisible; + // visible = user setting + // culled = while rendering, depending on camera + bool m_bVisible; + bool m_bCulled; KX_IPhysicsController* m_pPhysicsController1; // used for ray casting @@ -395,6 +397,16 @@ public: { m_pBlenderObject = obj; } + + struct Object* GetBlenderGroupObject( ) + { + return m_pBlenderGroupObject; + } + + void SetBlenderGroupObject( struct Object* obj) + { + m_pBlenderGroupObject = obj; + } bool IsDupliGroup() { @@ -538,18 +550,22 @@ public: /** * @section Mesh accessor functions. */ - + /** - * Run through the meshes associated with this - * object and bucketize them. See RAS_Mesh for - * more details on this function. Interesting to - * note that polygon bucketizing seems to happen on a per - * object basis. Which may explain why there is such - * a big performance gain when all static objects - * are joined into 1. + * Update buckets to indicate that there is a new + * user of this object's meshes. */ void - Bucketize( + AddMeshUser( + ); + + /** + * Update buckets with data about the mesh after + * creating or duplicating the object, changing + * visibility, object color, .. . + */ + void + UpdateBuckets( ); /** @@ -610,25 +626,8 @@ public: ResetDebugColor( ); - /** - * Set the visibility of the meshes associated with this - * object. - */ - void - MarkVisible( - bool visible - ); - - /** - * Set the visibility according to the visibility flag. - */ - void - MarkVisible( - void - ); - /** - * Was this object marked visible? (only for the ewxplicit + * Was this object marked visible? (only for the explicit * visibility system). */ bool @@ -644,6 +643,22 @@ public: bool b ); + /** + * Was this object culled? + */ + bool + GetCulled( + void + ); + + /** + * Set culled flag of this object + */ + void + SetCulled( + bool c + ); + /** * Change the layer of the object (when it is added in another layer * than the original layer) @@ -669,6 +684,14 @@ public: void ) { return m_bIsNegativeScaling; } + /** + * Is this a light? + */ + virtual bool + IsLight( + void + ) { return false; } + /** * @section Logic bubbling methods. */ diff --git a/source/gameengine/Ketsji/KX_ISceneConverter.h b/source/gameengine/Ketsji/KX_ISceneConverter.h index f069048cd3d..3709fa8c784 100644 --- a/source/gameengine/Ketsji/KX_ISceneConverter.h +++ b/source/gameengine/Ketsji/KX_ISceneConverter.h @@ -32,6 +32,8 @@ #include "STR_String.h" #include "KX_Python.h" +struct Scene; + class KX_ISceneConverter { @@ -77,6 +79,8 @@ public: // use blender glsl materials virtual void SetGLSLMaterials(bool val) =0; virtual bool GetGLSLMaterials()=0; + + virtual struct Scene* GetBlenderSceneForName(const STR_String& name)=0; }; #endif //__KX_ISCENECONVERTER_H diff --git a/source/gameengine/Ketsji/KX_KetsjiEngine.cpp b/source/gameengine/Ketsji/KX_KetsjiEngine.cpp index 1d6cc975ab5..cf98bb72601 100644 --- a/source/gameengine/Ketsji/KX_KetsjiEngine.cpp +++ b/source/gameengine/Ketsji/KX_KetsjiEngine.cpp @@ -96,6 +96,7 @@ double KX_KetsjiEngine::m_ticrate = DEFAULT_LOGIC_TIC_RATE; double KX_KetsjiEngine::m_anim_framerate = 25.0; double KX_KetsjiEngine::m_suspendedtime = 0.0; double KX_KetsjiEngine::m_suspendeddelta = 0.0; +double KX_KetsjiEngine::m_average_framerate = 0.0; /** @@ -310,6 +311,12 @@ void KX_KetsjiEngine::EndFrame() { RenderDebugProperties(); } + + m_average_framerate = m_logger->GetAverage(); + if (m_average_framerate < 1e-6) + m_average_framerate = 1e-6; + m_average_framerate = 1.0/m_average_framerate; + // Go to next profiling measurement, time spend after this call is shown in the next frame. m_logger->NextMeasurement(m_kxsystem->GetTimeInSeconds()); @@ -321,8 +328,6 @@ void KX_KetsjiEngine::EndFrame() m_canvas->EndDraw(); - - } //#include "PIL_time.h" @@ -897,11 +902,18 @@ void KX_KetsjiEngine::SetupRenderFrame(KX_Scene *scene, KX_Camera* cam) void KX_KetsjiEngine::RenderShadowBuffers(KX_Scene *scene) { - CListValue *lightlist = scene->GetLightList(); + CListValue *objectlist = scene->GetObjectList(); int i, drawmode; - for(i=0; iGetCount(); i++) { - KX_LightObject *light = (KX_LightObject*)lightlist->GetValue(i); + m_rendertools->SetAuxilaryClientInfo(scene); + + for(i=0; iGetCount(); i++) { + KX_GameObject *gameobj = (KX_GameObject*)objectlist->GetValue(i); + + if(!gameobj->IsLight()) + continue; + + KX_LightObject *light = (KX_LightObject*)gameobj; light->Update(); @@ -1281,12 +1293,13 @@ void KX_KetsjiEngine::RemoveScheduledScenes() KX_Scene* KX_KetsjiEngine::CreateScene(const STR_String& scenename) { - + Scene *scene = m_sceneconverter->GetBlenderSceneForName(scenename); KX_Scene* tmpscene = new KX_Scene(m_keyboarddevice, m_mousedevice, m_networkdevice, m_audiodevice, - scenename); + scenename, + scene); m_sceneconverter->ConvertScene(scenename, tmpscene, @@ -1442,6 +1455,11 @@ void KX_KetsjiEngine::SetAnimFrameRate(double framerate) m_anim_framerate = framerate; } +double KX_KetsjiEngine::GetAverageFrameRate() +{ + return m_average_framerate; +} + void KX_KetsjiEngine::SetTimingDisplay(bool frameRate, bool profile, bool properties) { m_show_framerate = frameRate; diff --git a/source/gameengine/Ketsji/KX_KetsjiEngine.h b/source/gameengine/Ketsji/KX_KetsjiEngine.h index 77b69ec2d9e..97458362f0f 100644 --- a/source/gameengine/Ketsji/KX_KetsjiEngine.h +++ b/source/gameengine/Ketsji/KX_KetsjiEngine.h @@ -149,6 +149,8 @@ private: /** Labels for profiling display. */ static const char m_profileLabels[tc_numCategories][15]; + /** Last estimated framerate */ + static double m_average_framerate; /** Show the framerate on the game display? */ bool m_show_framerate; /** Show profiling info on the game display? */ @@ -271,6 +273,11 @@ public: */ static void SetAnimFrameRate(double framerate); + /** + * Gets the last estimated average framerate + */ + static double GetAverageFrameRate(); + /** * Activates or deactivates timing information display. * @param frameRate Display for frame rate on or off. diff --git a/source/gameengine/Ketsji/KX_Light.cpp b/source/gameengine/Ketsji/KX_Light.cpp index 4e3d6180d22..6cfe5610863 100644 --- a/source/gameengine/Ketsji/KX_Light.cpp +++ b/source/gameengine/Ketsji/KX_Light.cpp @@ -42,14 +42,13 @@ #include "KX_PyMath.h" -#ifdef BLENDER_GLSL +#include "DNA_object_types.h" #include "GPU_material.h" -#endif KX_LightObject::KX_LightObject(void* sgReplicationInfo,SG_Callbacks callbacks, class RAS_IRenderTools* rendertools, const RAS_LightObject& lightobj, - struct GPULamp *gpulamp, + bool glsl, PyTypeObject* T ) : @@ -59,7 +58,8 @@ KX_LightObject::KX_LightObject(void* sgReplicationInfo,SG_Callbacks callbacks, m_lightobj = lightobj; m_lightobj.m_worldmatrix = GetOpenGLMatrixPtr(); m_rendertools->AddLight(&m_lightobj); - m_gpulamp = gpulamp; + m_glsl = glsl; + m_blenderscene = ((KX_Scene*)sgReplicationInfo)->GetBlenderScene(); }; @@ -73,7 +73,7 @@ CValue* KX_LightObject::GetReplica() { KX_LightObject* replica = new KX_LightObject(*this); - + // this will copy properties and so on... CValue::AddDataToReplica(replica); @@ -81,13 +81,23 @@ CValue* KX_LightObject::GetReplica() replica->m_lightobj.m_worldmatrix = replica->GetOpenGLMatrixPtr(); m_rendertools->AddLight(&replica->m_lightobj); + return replica; } +GPULamp *KX_LightObject::GetGPULamp() +{ + if(m_glsl) + return GPU_lamp_from_blender(m_blenderscene, GetBlenderObject(), GetBlenderGroupObject()); + else + return false; +} + void KX_LightObject::Update() { -#ifdef BLENDER_GLSL - if(m_gpulamp) { + GPULamp *lamp; + + if((lamp = GetGPULamp())) { float obmat[4][4]; double *dobmat = GetOpenGLMatrixPtr()->getPointer(); @@ -95,38 +105,39 @@ void KX_LightObject::Update() for(int j=0; j<4; j++, dobmat++) obmat[i][j] = (float)*dobmat; - GPU_lamp_update(m_gpulamp, obmat); + GPU_lamp_update(lamp, obmat); } -#endif } bool KX_LightObject::HasShadowBuffer() { -#ifdef BLENDER_GLSL - return (m_gpulamp && GPU_lamp_has_shadow_buffer(m_gpulamp)); -#else - return false; -#endif + GPULamp *lamp; + + if((lamp = GetGPULamp())) + return GPU_lamp_has_shadow_buffer(lamp); + else + return false; } int KX_LightObject::GetShadowLayer() { -#ifdef BLENDER_GLSL - if(m_gpulamp) - return GPU_lamp_shadow_layer(m_gpulamp); + GPULamp *lamp; + + if((lamp = GetGPULamp())) + return GPU_lamp_shadow_layer(lamp); else -#endif return 0; } void KX_LightObject::BindShadowBuffer(RAS_IRasterizer *ras, KX_Camera *cam, MT_Transform& camtrans) { -#ifdef BLENDER_GLSL + GPULamp *lamp; float viewmat[4][4], winmat[4][4]; int winsize; /* bind framebuffer */ - GPU_lamp_shadow_buffer_bind(m_gpulamp, viewmat, &winsize, winmat); + lamp = GetGPULamp(); + GPU_lamp_shadow_buffer_bind(lamp, viewmat, &winsize, winmat); /* setup camera transformation */ MT_Matrix4x4 modelviewmat((float*)viewmat); @@ -146,14 +157,12 @@ void KX_LightObject::BindShadowBuffer(RAS_IRasterizer *ras, KX_Camera *cam, MT_T ras->SetProjectionMatrix(projectionmat); ras->SetViewMatrix(modelviewmat, cam->NodeGetWorldPosition(), cam->GetCameraLocation(), cam->GetCameraOrientation()); -#endif } void KX_LightObject::UnbindShadowBuffer(RAS_IRasterizer *ras) { -#ifdef BLENDER_GLSL - GPU_lamp_shadow_buffer_unbind(m_gpulamp); -#endif + GPULamp *lamp = GetGPULamp(); + GPU_lamp_shadow_buffer_unbind(lamp); } PyObject* KX_LightObject::_getattr(const STR_String& attr) diff --git a/source/gameengine/Ketsji/KX_Light.h b/source/gameengine/Ketsji/KX_Light.h index 62eb26c61a8..e5dbf0b7f4a 100644 --- a/source/gameengine/Ketsji/KX_Light.h +++ b/source/gameengine/Ketsji/KX_Light.h @@ -33,6 +33,7 @@ #include "KX_GameObject.h" struct GPULamp; +struct Scene; class KX_Camera; class RAS_IRasterizer; class RAS_IRenderTools; @@ -44,16 +45,18 @@ class KX_LightObject : public KX_GameObject protected: RAS_LightObject m_lightobj; class RAS_IRenderTools* m_rendertools; //needed for registering and replication of lightobj - struct GPULamp *m_gpulamp; - static char doc[]; + bool m_glsl; + Scene* m_blenderscene; + static char doc[]; public: - KX_LightObject(void* sgReplicationInfo,SG_Callbacks callbacks,class RAS_IRenderTools* rendertools,const struct RAS_LightObject& lightobj, struct GPULamp *gpulamp, PyTypeObject *T = &Type); + KX_LightObject(void* sgReplicationInfo,SG_Callbacks callbacks,class RAS_IRenderTools* rendertools,const struct RAS_LightObject& lightobj, bool glsl, PyTypeObject *T = &Type); virtual ~KX_LightObject(); virtual CValue* GetReplica(); RAS_LightObject* GetLightData() { return &m_lightobj;} /* GLSL shadow */ + struct GPULamp *GetGPULamp(); bool HasShadowBuffer(); int GetShadowLayer(); void BindShadowBuffer(class RAS_IRasterizer *ras, class KX_Camera *cam, class MT_Transform& camtrans); @@ -62,6 +65,8 @@ public: virtual PyObject* _getattr(const STR_String& attr); /* lens, near, far, projection_matrix */ virtual int _setattr(const STR_String& attr, PyObject *pyvalue); + + virtual bool IsLight(void) { return true; } }; #endif //__KX_LIGHT diff --git a/source/gameengine/Ketsji/KX_MeshProxy.cpp b/source/gameengine/Ketsji/KX_MeshProxy.cpp index 29842af7fb6..5bfe8c70cba 100644 --- a/source/gameengine/Ketsji/KX_MeshProxy.cpp +++ b/source/gameengine/Ketsji/KX_MeshProxy.cpp @@ -96,10 +96,11 @@ KX_MeshProxy::_getattr(const STR_String& attr) if (attr == "materials") { PyObject *materials = PyList_New(0); - RAS_MaterialBucket::Set::iterator mit = m_meshobj->GetFirstMaterial(); + list::iterator mit = m_meshobj->GetFirstMaterial(); for(; mit != m_meshobj->GetLastMaterial(); ++mit) { - RAS_IPolyMaterial *polymat = (*mit)->GetPolyMaterial(); + RAS_IPolyMaterial *polymat = mit->m_bucket->GetPolyMaterial(); + if(polymat->GetFlag() & RAS_BLENDERMAT) { KX_BlenderMaterial *mat = static_cast(polymat); @@ -204,11 +205,11 @@ PyObject* KX_MeshProxy::PyGetVertexArrayLength(PyObject* self, if (PyArg_ParseTuple(args,"i",&matid)) { - RAS_IPolyMaterial* mat = m_meshobj->GetMaterialBucket(matid)->GetPolyMaterial(); + RAS_MeshMaterial *mmat = m_meshobj->GetMeshMaterial(matid); + RAS_IPolyMaterial* mat = mmat->m_bucket->GetPolyMaterial(); + if (mat) - { - length = m_meshobj->GetVertexArrayLength(mat); - } + length = m_meshobj->NumVertices(mat); } else { return NULL; diff --git a/source/gameengine/Ketsji/KX_PolyProxy.cpp b/source/gameengine/Ketsji/KX_PolyProxy.cpp index 658c8a98e4f..c6f6bc2db01 100644 --- a/source/gameengine/Ketsji/KX_PolyProxy.cpp +++ b/source/gameengine/Ketsji/KX_PolyProxy.cpp @@ -112,8 +112,8 @@ KX_PolyProxy::_getattr(const STR_String& attr) unsigned int matid; for (matid=0; matidNumMaterials(); matid++) { - RAS_MaterialBucket* meshBucket = m_mesh->GetMaterialBucket(matid); - if (meshBucket == polyBucket) + RAS_MeshMaterial* meshMat = m_mesh->GetMeshMaterial(matid); + if (meshMat->m_bucket == polyBucket) // found it break; } @@ -121,19 +121,19 @@ KX_PolyProxy::_getattr(const STR_String& attr) } if (attr == "v1") { - return PyInt_FromLong(m_polygon->GetVertexIndexBase().m_indexarray[0]); + return PyInt_FromLong(m_polygon->GetVertexOffset(0)); } if (attr == "v2") { - return PyInt_FromLong(m_polygon->GetVertexIndexBase().m_indexarray[1]); + return PyInt_FromLong(m_polygon->GetVertexOffset(1)); } if (attr == "v3") { - return PyInt_FromLong(m_polygon->GetVertexIndexBase().m_indexarray[2]); + return PyInt_FromLong(m_polygon->GetVertexOffset(2)); } if (attr == "v4") { - return PyInt_FromLong(((m_polygon->VertexCount()>3)?m_polygon->GetVertexIndexBase().m_indexarray[3]:0)); + return PyInt_FromLong(((m_polygon->VertexCount()>3)?m_polygon->GetVertexOffset(3):0)); } if (attr == "visible") { @@ -178,8 +178,8 @@ KX_PYMETHODDEF_DOC_NOARG(KX_PolyProxy, getMaterialIndex, unsigned int matid; for (matid=0; matidNumMaterials(); matid++) { - RAS_MaterialBucket* meshBucket = m_mesh->GetMaterialBucket(matid); - if (meshBucket == polyBucket) + RAS_MeshMaterial* meshMat = m_mesh->GetMeshMaterial(matid); + if (meshMat->m_bucket == polyBucket) // found it break; } @@ -234,7 +234,7 @@ KX_PYMETHODDEF_DOC(KX_PolyProxy, getVertexIndex, } if (index < m_polygon->VertexCount()) { - return PyInt_FromLong(m_polygon->GetVertexIndexBase().m_indexarray[index]); + return PyInt_FromLong(m_polygon->GetVertexOffset(index)); } return PyInt_FromLong(0); } diff --git a/source/gameengine/Ketsji/KX_PolygonMaterial.cpp b/source/gameengine/Ketsji/KX_PolygonMaterial.cpp index 144f74a1a4c..c9180bf3a80 100644 --- a/source/gameengine/Ketsji/KX_PolygonMaterial.cpp +++ b/source/gameengine/Ketsji/KX_PolygonMaterial.cpp @@ -35,10 +35,6 @@ #include "BKE_global.h" #include "BKE_image.h" -extern "C" { -#include "BDR_drawmesh.h" -} - #include "DNA_material_types.h" #include "DNA_texture_types.h" #include "DNA_image_types.h" @@ -46,6 +42,8 @@ extern "C" { #include "IMB_imbuf_types.h" +#include "GPU_draw.h" + #include "MEM_guardedalloc.h" #include "RAS_LightObject.h" @@ -63,8 +61,6 @@ KX_PolygonMaterial::KX_PolygonMaterial(const STR_String &texname, bool alpha, bool zsort, int lightlayer, - bool bIsTriangle, - void* clientobject, struct MTFace* tface, unsigned int* mcol, PyTypeObject *T) @@ -78,9 +74,7 @@ KX_PolygonMaterial::KX_PolygonMaterial(const STR_String &texname, transp, alpha, zsort, - lightlayer, - bIsTriangle, - clientobject), + lightlayer), m_tface(tface), m_mcol(mcol), m_material(material), @@ -140,38 +134,29 @@ void KX_PolygonMaterial::DefaultActivate(RAS_IRasterizer* rasty, TCachingInfo& c if (GetCachingInfo() != cachingInfo) { if (!cachingInfo) - { - set_tpage(NULL); - } + GPU_set_tpage(NULL); + cachingInfo = GetCachingInfo(); if ((m_drawingmode & 4)&& (rasty->GetDrawingMode() == RAS_IRasterizer::KX_TEXTURED)) { - update_realtime_texture((struct MTFace*) m_tface, rasty->GetTime()); - set_tpage(m_tface); - rasty->EnableTextures(true); + Image *ima = (Image*)m_tface->tpage; + GPU_update_image_time(ima, rasty->GetTime()); + GPU_set_tpage(m_tface); } else - { - set_tpage(NULL); - rasty->EnableTextures(false); - } + GPU_set_tpage(NULL); if(m_drawingmode & RAS_IRasterizer::KX_TWOSIDE) - { rasty->SetCullFace(false); - } else - { rasty->SetCullFace(true); - } - if (m_drawingmode & RAS_IRasterizer::KX_LINES) { + if ((m_drawingmode & RAS_IRasterizer::KX_LINES) || + (rasty->GetDrawingMode() <= RAS_IRasterizer::KX_WIREFRAME)) rasty->SetLines(true); - } - else { + else rasty->SetLines(false); - } } rasty->SetSpecularity(m_specular[0],m_specular[1],m_specular[2],m_specularity); @@ -253,7 +238,8 @@ PyObject* KX_PolygonMaterial::_getattr(const STR_String& attr) if (attr == "lightlayer") return PyInt_FromLong(m_lightlayer); if (attr == "triangle") - return PyInt_FromLong(m_bIsTriangle); + // deprecated, triangle/quads shouldn't have been a material property + return 0; if (attr == "diffuse") return PyObjectFrom(m_diffuse); @@ -333,7 +319,7 @@ int KX_PolygonMaterial::_setattr(const STR_String &attr, PyObject *pyvalue) // This probably won't work... if (attr == "triangle") { - m_bIsTriangle = value; + // deprecated, triangle/quads shouldn't have been a material property return 0; } } @@ -386,7 +372,9 @@ KX_PYMETHODDEF_DOC(KX_PolygonMaterial, updateTexture, "updateTexture(tface, rast { MTFace *tface = (MTFace*) PyCObject_AsVoidPtr(pytface); RAS_IRasterizer *rasty = (RAS_IRasterizer*) PyCObject_AsVoidPtr(pyrasty); - update_realtime_texture(tface, rasty->GetTime()); + Image *ima = (Image*)tface->tpage; + GPU_update_image_time(ima, rasty->GetTime()); + Py_Return; } @@ -399,7 +387,7 @@ KX_PYMETHODDEF_DOC(KX_PolygonMaterial, setTexture, "setTexture(tface)") if (PyArg_ParseTuple(args, "O!", &PyCObject_Type, &pytface)) { MTFace *tface = (MTFace*) PyCObject_AsVoidPtr(pytface); - set_tpage(tface); + GPU_set_tpage(tface); Py_Return; } diff --git a/source/gameengine/Ketsji/KX_PolygonMaterial.h b/source/gameengine/Ketsji/KX_PolygonMaterial.h index 11c8baa8b1f..fe116f757db 100644 --- a/source/gameengine/Ketsji/KX_PolygonMaterial.h +++ b/source/gameengine/Ketsji/KX_PolygonMaterial.h @@ -68,8 +68,6 @@ public: bool alpha, bool zsort, int lightlayer, - bool bIsTriangle, - void* clientobject, struct MTFace* tface, unsigned int* mcol, PyTypeObject *T = &Type); diff --git a/source/gameengine/Ketsji/KX_PythonInit.cpp b/source/gameengine/Ketsji/KX_PythonInit.cpp index 4b6a38f18c0..120311fb967 100644 --- a/source/gameengine/Ketsji/KX_PythonInit.cpp +++ b/source/gameengine/Ketsji/KX_PythonInit.cpp @@ -57,13 +57,13 @@ #include "BL_ActionActuator.h" #include "RAS_IRasterizer.h" #include "RAS_ICanvas.h" +#include "RAS_BucketManager.h" #include "MT_Vector3.h" #include "MT_Point3.h" #include "ListValue.h" #include "KX_Scene.h" #include "SND_DeviceManager.h" -#include "RAS_OpenGLRasterizer/RAS_GLExtensionManager.h" #include "BL_Shader.h" #include "KX_PyMath.h" @@ -83,6 +83,7 @@ extern "C" { #include "BKE_utildefines.h" #include "BKE_global.h" #include "BLI_blenlib.h" +#include "GPU_material.h" static void setSandbox(TPythonSecurityLevel level); @@ -90,6 +91,7 @@ static void setSandbox(TPythonSecurityLevel level); // 'local' copy of canvas ptr, for window height/width python scripts static RAS_ICanvas* gp_Canvas = NULL; static KX_Scene* gp_KetsjiScene = NULL; +static KX_KetsjiEngine* gp_KetsjiEngine = NULL; static RAS_IRasterizer* gp_Rasterizer = NULL; void KX_RasterizerDrawDebugLine(const MT_Vector3& from,const MT_Vector3& to,const MT_Vector3& color) @@ -270,6 +272,11 @@ static PyObject* gPyGetPhysicsTicRate(PyObject*) return PyFloat_FromDouble(PHY_GetActiveEnvironment()->getFixedTimeStep()); } +static PyObject* gPyGetAverageFrameRate(PyObject*) +{ + return PyFloat_FromDouble(KX_KetsjiEngine::GetAverageFrameRate()); +} + static PyObject* gPyGetBlendFileList(PyObject*, PyObject* args) { char cpath[sizeof(G.sce)]; @@ -409,6 +416,7 @@ static struct PyMethodDef game_methods[] = { {"setLogicTicRate", (PyCFunction) gPySetLogicTicRate, METH_VARARGS, "Sets the logic tic rate"}, {"getPhysicsTicRate", (PyCFunction) gPyGetPhysicsTicRate, METH_NOARGS, "Gets the physics tic rate"}, {"setPhysicsTicRate", (PyCFunction) gPySetPhysicsTicRate, METH_VARARGS, "Sets the physics tic rate"}, + {"getAverageFrameRate", (PyCFunction) gPyGetAverageFrameRate, METH_NOARGS, "Gets the estimated average frame rate"}, {"getBlendFileList", (PyCFunction)gPyGetBlendFileList, METH_VARARGS, "Gets a list of blend files in the same directory as the current blend file"}, {"PrintGLInfo", (PyCFunction)pyPrintExt, METH_NOARGS, "Prints GL Extension Info"}, {NULL, (PyCFunction) NULL, 0, NULL } @@ -670,6 +678,76 @@ static PyObject* gPyDisableMotionBlur(PyObject*, PyObject* args) Py_Return; } +int getGLSLSettingFlag(char *setting) +{ + if(strcmp(setting, "lights") == 0) + return G_FILE_GLSL_NO_LIGHTS; + else if(strcmp(setting, "shaders") == 0) + return G_FILE_GLSL_NO_SHADERS; + else if(strcmp(setting, "shadows") == 0) + return G_FILE_GLSL_NO_SHADOWS; + else if(strcmp(setting, "ramps") == 0) + return G_FILE_GLSL_NO_RAMPS; + else if(strcmp(setting, "nodes") == 0) + return G_FILE_GLSL_NO_NODES; + else if(strcmp(setting, "extra_textures") == 0) + return G_FILE_GLSL_NO_EXTRA_TEX; + else + return -1; +} + +static PyObject* gPySetGLSLMaterialSetting(PyObject*, + PyObject* args, + PyObject*) +{ + char *setting; + int enable, flag; + + if (PyArg_ParseTuple(args,"si",&setting,&enable)) + { + flag = getGLSLSettingFlag(setting); + + if(flag != -1) { + if (enable) + G.fileflags &= ~flag; + else + G.fileflags |= flag; + + /* display lists and GLSL materials need to be remade */ + if(gp_KetsjiEngine) { + KX_SceneList *scenes = gp_KetsjiEngine->CurrentScenes(); + KX_SceneList::iterator it; + + for(it=scenes->begin(); it!=scenes->end(); it++) + if((*it)->GetBucketManager()) + (*it)->GetBucketManager()->ReleaseDisplayLists(); + } + + GPU_materials_free(); + } + } + + Py_Return; +} + +static PyObject* gPyGetGLSLMaterialSetting(PyObject*, + PyObject* args, + PyObject*) +{ + char *setting; + int enabled = 0, flag; + + if (PyArg_ParseTuple(args,"s",&setting)) + { + flag = getGLSLSettingFlag(setting); + + if(flag != -1) + enabled = ((G.fileflags & flag) != 0); + } + + return PyInt_FromLong(enabled); +} + STR_String gPyGetWindowHeight__doc__="getWindowHeight doc"; STR_String gPyGetWindowWidth__doc__="getWindowWidth doc"; STR_String gPyEnableVisibility__doc__="enableVisibility doc"; @@ -703,11 +781,13 @@ static struct PyMethodDef rasterizer_methods[] = { {"getEyeSeparation", (PyCFunction) gPyGetEyeSeparation, METH_VARARGS, "get the eye separation for stereo mode"}, {"setFocalLength", (PyCFunction) gPySetFocalLength, METH_VARARGS, "set the focal length for stereo mode"}, {"getFocalLength", (PyCFunction) gPyGetFocalLength, METH_VARARGS, "get the focal length for stereo mode"}, + {"setGLSLMaterialSetting",(PyCFunction) gPySetGLSLMaterialSetting, + METH_VARARGS, "set the state of a GLSL material setting"}, + {"getGLSLMaterialSetting",(PyCFunction) gPyGetGLSLMaterialSetting, + METH_VARARGS, "get the state of a GLSL material setting"}, { NULL, (PyCFunction) NULL, 0, NULL } }; - - // Initialization function for the module (*must* be called initGameLogic) static char GameLogic_module_documentation[] = @@ -720,11 +800,12 @@ static char Rasterizer_module_documentation[] = -PyObject* initGameLogic(KX_Scene* scene) // quick hack to get gravity hook +PyObject* initGameLogic(KX_KetsjiEngine *engine, KX_Scene* scene) // quick hack to get gravity hook { PyObject* m; PyObject* d; + gp_KetsjiEngine = engine; gp_KetsjiScene = scene; gUseVisibilityTemp=false; diff --git a/source/gameengine/Ketsji/KX_PythonInit.h b/source/gameengine/Ketsji/KX_PythonInit.h index f094a1ca575..388d073c6db 100644 --- a/source/gameengine/Ketsji/KX_PythonInit.h +++ b/source/gameengine/Ketsji/KX_PythonInit.h @@ -40,7 +40,7 @@ typedef enum { extern bool gUseVisibilityTemp; -PyObject* initGameLogic(class KX_Scene* ketsjiscene); +PyObject* initGameLogic(class KX_KetsjiEngine *engine, class KX_Scene* ketsjiscene); PyObject* initGameKeys(); PyObject* initRasterizer(class RAS_IRasterizer* rasty,class RAS_ICanvas* canvas); PyObject* initGamePlayerPythonScripting(const STR_String& progname, TPythonSecurityLevel level); diff --git a/source/gameengine/Ketsji/KX_SG_BoneParentNodeRelationship.cpp b/source/gameengine/Ketsji/KX_SG_BoneParentNodeRelationship.cpp index f085ff435dc..d651373869a 100644 --- a/source/gameengine/Ketsji/KX_SG_BoneParentNodeRelationship.cpp +++ b/source/gameengine/Ketsji/KX_SG_BoneParentNodeRelationship.cpp @@ -78,7 +78,7 @@ UpdateChildCoordinates( if (parent) { - const BL_ArmatureObject *armature = (const BL_ArmatureObject*)(parent->GetSGClientObject()); + BL_ArmatureObject *armature = (BL_ArmatureObject*)(parent->GetSGClientObject()); if (armature) { MT_Matrix4x4 parent_matrix; diff --git a/source/gameengine/Ketsji/KX_Scene.cpp b/source/gameengine/Ketsji/KX_Scene.cpp index 1c37fcea77e..2ad0412f1bf 100644 --- a/source/gameengine/Ketsji/KX_Scene.cpp +++ b/source/gameengine/Ketsji/KX_Scene.cpp @@ -68,6 +68,7 @@ #include "SG_IObject.h" #include "SG_Tree.h" #include "DNA_group_types.h" +#include "DNA_scene_types.h" #include "BKE_anim.h" #include "KX_SG_NodeRelationships.h" @@ -116,7 +117,8 @@ KX_Scene::KX_Scene(class SCA_IInputDevice* keyboarddevice, class SCA_IInputDevice* mousedevice, class NG_NetworkDeviceInterface *ndi, class SND_IAudioDevice* adi, - const STR_String& sceneName): + const STR_String& sceneName, + Scene *scene): PyObjectPlus(&KX_Scene::Type), m_keyboardmgr(NULL), m_mousemgr(NULL), @@ -126,7 +128,8 @@ KX_Scene::KX_Scene(class SCA_IInputDevice* keyboarddevice, m_adi(adi), m_networkDeviceInterface(ndi), m_active_camera(NULL), - m_ueberExecutionPriority(0) + m_ueberExecutionPriority(0), + m_blenderScene(scene) { m_suspendedtime = 0.0; m_suspendeddelta = 0.0; @@ -453,7 +456,7 @@ KX_GameObject* KX_Scene::AddNodeReplicaObject(class SG_IObject* node, class CVal // this is the list of object that are send to the graphics pipeline m_objectlist->Add(newobj->AddRef()); - newobj->Bucketize(); + newobj->AddMeshUser(); // logic cannot be replicated, until the whole hierarchy is replicated. m_logicHierarchicalGameObjects.push_back(newobj); @@ -623,6 +626,7 @@ void KX_Scene::DupliGroupRecurse(CValue* obj, int level) if (blgroupobj == blenderobj) // this check is also in group_duplilist() continue; + gameobj = (KX_GameObject*)m_logicmgr->FindGameObjByBlendObj(blenderobj); if (gameobj == NULL) { @@ -630,6 +634,9 @@ void KX_Scene::DupliGroupRecurse(CValue* obj, int level) // Should not happen as dupli group are created automatically continue; } + + gameobj->SetBlenderGroupObject(blgroupobj); + if ((blenderobj->lay & group->layer)==0) { // object is not visible in the 3D view, will not be instantiated @@ -999,7 +1006,7 @@ void KX_Scene::ReplaceMesh(class CValue* obj,void* meshobj) newobj->m_pDeformer = NULL; } - if (mesh->m_class == 1) + if (mesh->IsDeformed()) { // we must create a new deformer but which one? KX_GameObject* parentobj = newobj->GetParent(); @@ -1073,7 +1080,8 @@ void KX_Scene::ReplaceMesh(class CValue* obj,void* meshobj) parentobj->Release(); } } - gameobj->Bucketize(); + + gameobj->AddMeshUser(); } @@ -1225,7 +1233,9 @@ void KX_Scene::MarkSubTreeVisible(SG_Tree *node, RAS_IRasterizer* rasty, bool vi for (int m=0;mGetMesh(m))->SchedulePolygons(rasty->GetDrawingMode()); } - gameobj->MarkVisible(visible); + + gameobj->SetCulled(!visible); + gameobj->UpdateBuckets(); } } if (node->Left()) @@ -1242,7 +1252,8 @@ void KX_Scene::MarkVisible(RAS_IRasterizer* rasty, KX_GameObject* gameobj,KX_Cam // Shadow lamp layers if(layer && !(gameobj->GetLayer() & layer)) { - gameobj->MarkVisible(false); + gameobj->SetCulled(true); + gameobj->UpdateBuckets(); return; } @@ -1288,9 +1299,11 @@ void KX_Scene::MarkVisible(RAS_IRasterizer* rasty, KX_GameObject* gameobj,KX_Cam } // Visibility/ non-visibility are marked // elsewhere now. - gameobj->MarkVisible(); + gameobj->SetCulled(false); + gameobj->UpdateBuckets(); } else { - gameobj->MarkVisible(false); + gameobj->SetCulled(true); + gameobj->UpdateBuckets(); } } diff --git a/source/gameengine/Ketsji/KX_Scene.h b/source/gameengine/Ketsji/KX_Scene.h index 1c56dd1ee55..5f7e1167e27 100644 --- a/source/gameengine/Ketsji/KX_Scene.h +++ b/source/gameengine/Ketsji/KX_Scene.h @@ -54,6 +54,7 @@ */ struct SM_MaterialProps; struct SM_ShapeProps; +struct Scene; class GEN_HashedPtr; class CListValue; @@ -277,12 +278,15 @@ protected: */ PyObject* m_attrlist; + struct Scene* m_blenderScene; + public: KX_Scene(class SCA_IInputDevice* keyboarddevice, class SCA_IInputDevice* mousedevice, class NG_NetworkDeviceInterface* ndi, class SND_IAudioDevice* adi, - const STR_String& scenename ); + const STR_String& scenename, + struct Scene* scene); virtual ~KX_Scene(); @@ -582,6 +586,10 @@ public: * was running and not suspended) and the "curtime" */ double getSuspendedDelta(); + /** + * Returns the Blender scene this was made from + */ + struct Scene *GetBlenderScene() { return m_blenderScene; } }; typedef std::vector KX_SceneList; diff --git a/source/gameengine/Ketsji/KX_VertexProxy.cpp b/source/gameengine/Ketsji/KX_VertexProxy.cpp index 5cec65dff1c..25205714308 100644 --- a/source/gameengine/Ketsji/KX_VertexProxy.cpp +++ b/source/gameengine/Ketsji/KX_VertexProxy.cpp @@ -82,7 +82,7 @@ PyObject* KX_VertexProxy::_getattr(const STR_String& attr) { if (attr == "XYZ") - return PyObjectFrom(MT_Vector3(m_vertex->getLocalXYZ())); + return PyObjectFrom(MT_Vector3(m_vertex->getXYZ())); if (attr == "UV") return PyObjectFrom(MT_Point2(m_vertex->getUV1())); @@ -102,11 +102,11 @@ KX_VertexProxy::_getattr(const STR_String& attr) // pos if (attr == "x") - return PyFloat_FromDouble(m_vertex->getLocalXYZ()[0]); + return PyFloat_FromDouble(m_vertex->getXYZ()[0]); if (attr == "y") - return PyFloat_FromDouble(m_vertex->getLocalXYZ()[1]); + return PyFloat_FromDouble(m_vertex->getXYZ()[1]); if (attr == "z") - return PyFloat_FromDouble(m_vertex->getLocalXYZ()[2]); + return PyFloat_FromDouble(m_vertex->getXYZ()[2]); // Col if (attr == "r") @@ -184,7 +184,7 @@ int KX_VertexProxy::_setattr(const STR_String& attr, PyObject *pyvalue) { float val = PyFloat_AsDouble(pyvalue); // pos - MT_Point3 pos(m_vertex->getLocalXYZ()); + MT_Point3 pos(m_vertex->getXYZ()); if (attr == "x") { pos.x() = val; @@ -312,7 +312,7 @@ PyObject* KX_VertexProxy::PyGetXYZ(PyObject*, PyObject*, PyObject*) { - return PyObjectFrom(MT_Point3(m_vertex->getLocalXYZ())); + return PyObjectFrom(MT_Point3(m_vertex->getXYZ())); } PyObject* KX_VertexProxy::PySetXYZ(PyObject*, @@ -426,7 +426,7 @@ PyObject* KX_VertexProxy::PySetUV2(PyObject*, { if (PyVecTo(list, vec)) { - m_vertex->SetFlag((m_vertex->getFlag()|TV_2NDUV)); + m_vertex->SetFlag((m_vertex->getFlag()|RAS_TexVert::SECOND_UV)); m_vertex->SetUnit(unit); m_vertex->SetUV2(vec); m_mesh->SetMeshModified(true); diff --git a/source/gameengine/Ketsji/KX_VisibilityActuator.cpp b/source/gameengine/Ketsji/KX_VisibilityActuator.cpp index b4693a7a7db..5a0cadcbcfe 100644 --- a/source/gameengine/Ketsji/KX_VisibilityActuator.cpp +++ b/source/gameengine/Ketsji/KX_VisibilityActuator.cpp @@ -76,7 +76,7 @@ KX_VisibilityActuator::Update() KX_GameObject *obj = (KX_GameObject*) GetParent(); obj->SetVisible(m_visible); - obj->MarkVisible(); + obj->UpdateBuckets(); return true; } diff --git a/source/gameengine/Ketsji/Makefile b/source/gameengine/Ketsji/Makefile index 995237adf2c..0b48ad8b8c3 100644 --- a/source/gameengine/Ketsji/Makefile +++ b/source/gameengine/Ketsji/Makefile @@ -64,13 +64,9 @@ CPPFLAGS += -I../../blender/blenlib CPPFLAGS += -I../../blender/include CPPFLAGS += -I../../blender/makesdna CPPFLAGS += -I../../blender/imbuf +CPPFLAGS += -I../../blender/gpu CPPFLAGS += -I$(NAN_GUARDEDALLOC)/include -ifeq ($(WITH_BF_GLEXT),true) - CPPFLAGS += -DWITH_GLEXT -endif - - ########################### SOURCEDIR = source/gameengine/Ketsji diff --git a/source/gameengine/Ketsji/SConscript b/source/gameengine/Ketsji/SConscript index f6f744b199a..02e7aed82a5 100644 --- a/source/gameengine/Ketsji/SConscript +++ b/source/gameengine/Ketsji/SConscript @@ -32,16 +32,13 @@ incs += ' #source/gameengine/SceneGraph #source/gameengine/Physics/common #sourc incs += ' #source/gameengine/Physics/BlOde #source/gameengine/Physics/Dummy' incs += ' #source/gameengine/Physics/Sumo #source/gameengine/Physics/Sumo/include' incs += ' #source/gameengine/Physics/Sumo/Fuzzics/include #source/gameengine/Network/LoopBackNetwork' -incs += ' #source/blender/misc #source/blender/blenloader #extern/glew/include' +incs += ' #source/blender/misc #source/blender/blenloader #extern/glew/include #source/blender/gpu' cflags = [] if env['OURPLATFORM'] == 'win32-vc': cflags.append('/GR') cflags.append('/Ox') -if env['WITH_BF_GLEXT'] == 1: - env['CPPFLAGS'].append('-DWITH_GLEXT') - incs += ' ' + env['BF_SOLID_INC'] incs += ' ' + env['BF_PYTHON_INC'] incs += ' ' + env['BF_SDL_INC'] diff --git a/source/gameengine/Physics/Bullet/CcdPhysicsController.cpp b/source/gameengine/Physics/Bullet/CcdPhysicsController.cpp index 2ec96c75a68..8fd89295b03 100644 --- a/source/gameengine/Physics/Bullet/CcdPhysicsController.cpp +++ b/source/gameengine/Physics/Bullet/CcdPhysicsController.cpp @@ -815,9 +815,7 @@ bool CcdShapeConstructionInfo::SetMesh(RAS_MeshObject* meshobj, bool polytope) { for (int i=0;iVertexCount();i++) { - const float* vtx = meshobj->GetVertex(poly->GetVertexIndexBase().m_vtxarray, - poly->GetVertexIndexBase().m_indexarray[i], - poly->GetMaterial()->GetPolyMaterial())->getLocalXYZ(); + const float* vtx = poly->GetVertex(i)->getXYZ(); btPoint3 point(vtx[0],vtx[1],vtx[2]); m_vertexArray.push_back(point); numvalidpolys++; @@ -825,18 +823,15 @@ bool CcdShapeConstructionInfo::SetMesh(RAS_MeshObject* meshobj, bool polytope) } else { { - const float* vtx = meshobj->GetVertex(poly->GetVertexIndexBase().m_vtxarray, - poly->GetVertexIndexBase().m_indexarray[2], - poly->GetMaterial()->GetPolyMaterial())->getLocalXYZ(); + const float* vtx = poly->GetVertex(2)->getXYZ(); btPoint3 vertex0(vtx[0],vtx[1],vtx[2]); - vtx = meshobj->GetVertex(poly->GetVertexIndexBase().m_vtxarray, - poly->GetVertexIndexBase().m_indexarray[1], - poly->GetMaterial()->GetPolyMaterial())->getLocalXYZ(); + + vtx = poly->GetVertex(1)->getXYZ(); btPoint3 vertex1(vtx[0],vtx[1],vtx[2]); - vtx = meshobj->GetVertex(poly->GetVertexIndexBase().m_vtxarray, - poly->GetVertexIndexBase().m_indexarray[0], - poly->GetMaterial()->GetPolyMaterial())->getLocalXYZ(); + + vtx = poly->GetVertex(0)->getXYZ(); btPoint3 vertex2(vtx[0],vtx[1],vtx[2]); + m_vertexArray.push_back(vertex0); m_vertexArray.push_back(vertex1); m_vertexArray.push_back(vertex2); @@ -845,18 +840,15 @@ bool CcdShapeConstructionInfo::SetMesh(RAS_MeshObject* meshobj, bool polytope) } if (poly->VertexCount() == 4) { - const float* vtx = meshobj->GetVertex(poly->GetVertexIndexBase().m_vtxarray, - poly->GetVertexIndexBase().m_indexarray[3], - poly->GetMaterial()->GetPolyMaterial())->getLocalXYZ(); + const float* vtx = poly->GetVertex(3)->getXYZ(); btPoint3 vertex0(vtx[0],vtx[1],vtx[2]); - vtx = meshobj->GetVertex(poly->GetVertexIndexBase().m_vtxarray, - poly->GetVertexIndexBase().m_indexarray[2], - poly->GetMaterial()->GetPolyMaterial())->getLocalXYZ(); + + vtx = poly->GetVertex(2)->getXYZ(); btPoint3 vertex1(vtx[0],vtx[1],vtx[2]); - vtx = meshobj->GetVertex(poly->GetVertexIndexBase().m_vtxarray, - poly->GetVertexIndexBase().m_indexarray[0], - poly->GetMaterial()->GetPolyMaterial())->getLocalXYZ(); + + vtx = poly->GetVertex(0)->getXYZ(); btPoint3 vertex2(vtx[0],vtx[1],vtx[2]); + m_vertexArray.push_back(vertex0); m_vertexArray.push_back(vertex1); m_vertexArray.push_back(vertex2); diff --git a/source/gameengine/Physics/Bullet/CcdPhysicsController.h b/source/gameengine/Physics/Bullet/CcdPhysicsController.h index 8a7f1062f53..a3fbb502c08 100644 --- a/source/gameengine/Physics/Bullet/CcdPhysicsController.h +++ b/source/gameengine/Physics/Bullet/CcdPhysicsController.h @@ -128,7 +128,8 @@ struct CcdConstructionInfo CcdConstructionInfo() - : m_gravity(0,0,0), + : m_localInertiaTensor(1.f, 1.f, 1.f), + m_gravity(0,0,0), m_scaling(1.f,1.f,1.f), m_mass(0.f), m_restitution(0.1f), diff --git a/source/gameengine/PyDoc/GameLogic.py b/source/gameengine/PyDoc/GameLogic.py index b65bc0f3ce8..af3d2810553 100644 --- a/source/gameengine/PyDoc/GameLogic.py +++ b/source/gameengine/PyDoc/GameLogic.py @@ -220,6 +220,13 @@ def setPhysicsTicRate(ticrate): @param ticrate: The new update frequency (in Hz). @type ticrate: float """ +def getAverageFrameRate(): + """ + Gets the estimated average framerate + + @return: The estimed average framerate in frames per second + @rtype: float + """ def expandPath(path): """ @@ -245,4 +252,4 @@ def getBlendFileList(path = "//"): @type path: string @return: A list of filenames, with no directory prefix @rtype: list - """ \ No newline at end of file + """ diff --git a/source/gameengine/PyDoc/Rasterizer.py b/source/gameengine/PyDoc/Rasterizer.py index 3711ac63b3e..7afdcf07f2e 100644 --- a/source/gameengine/PyDoc/Rasterizer.py +++ b/source/gameengine/PyDoc/Rasterizer.py @@ -146,3 +146,20 @@ def getFocalLength(): @rtype: float """ + +def setGLSLMaterialSetting(setting, enable): + """ + Enables or disables a GLSL material setting. + + @type setting: string (lights, shaders, shadows, ramps, nodes, extra_textures) + @type enable: boolean + """ + +def getGLSLMaterialSetting(setting, enable): + """ + Get the state of a GLSL material setting. + + @type setting: string (lights, shaders, shadows, ramps, nodes, extra_textures) + @rtype: boolean + """ + diff --git a/source/gameengine/Rasterizer/Makefile b/source/gameengine/Rasterizer/Makefile index e3b1f274ee5..917f70c7108 100644 --- a/source/gameengine/Rasterizer/Makefile +++ b/source/gameengine/Rasterizer/Makefile @@ -49,10 +49,6 @@ ifeq ($(OS),darwin) CPPFLAGS += -fpascal-strings endif -ifeq ($(WITH_BF_GLEXT),true) - CPPFLAGS += -DWITH_GLEXT -endif - ############### SOURCEDIR = source/gameengine/Rasterizer diff --git a/source/gameengine/Rasterizer/RAS_BucketManager.cpp b/source/gameengine/Rasterizer/RAS_BucketManager.cpp index 82bdce44519..9fb21a3c17b 100644 --- a/source/gameengine/Rasterizer/RAS_BucketManager.cpp +++ b/source/gameengine/Rasterizer/RAS_BucketManager.cpp @@ -26,10 +26,6 @@ * ***** END GPL LICENSE BLOCK ***** */ -#ifdef HAVE_CONFIG_H -#include -#endif - #ifdef WIN32 // don't show these anoying STL warnings #pragma warning (disable:4786) @@ -39,14 +35,54 @@ #include "RAS_MaterialBucket.h" #include "STR_HashedString.h" #include "RAS_MeshObject.h" -#define KX_NUM_MATERIALBUCKETS 100 #include "RAS_IRasterizer.h" #include "RAS_IRenderTools.h" #include "RAS_BucketManager.h" +#include #include +/* sorting */ + +struct RAS_BucketManager::sortedmeshslot +{ +public: + MT_Scalar m_z; /* depth */ + RAS_MeshSlot *m_ms; /* mesh slot */ + RAS_MaterialBucket *m_bucket; /* buck mesh slot came from */ + + sortedmeshslot() {} + + void set(RAS_MeshSlot *ms, RAS_MaterialBucket *bucket, const MT_Vector3& pnorm) + { + // would be good to use the actual bounding box center instead + MT_Point3 pos(ms->m_OpenGLMatrix[12], ms->m_OpenGLMatrix[13], ms->m_OpenGLMatrix[14]); + + m_z = MT_dot(pnorm, pos); + m_ms = ms; + m_bucket = bucket; + } +}; + +struct RAS_BucketManager::backtofront +{ + bool operator()(const sortedmeshslot &a, const sortedmeshslot &b) + { + return (a.m_z < b.m_z) || (a.m_z == b.m_z && a.m_ms < b.m_ms); + } +}; + +struct RAS_BucketManager::fronttoback +{ + bool operator()(const sortedmeshslot &a, const sortedmeshslot &b) + { + return (a.m_z > b.m_z) || (a.m_z == b.m_z && a.m_ms > b.m_ms); + } +}; + +/* bucket manager */ + RAS_BucketManager::RAS_BucketManager() { @@ -54,153 +90,188 @@ RAS_BucketManager::RAS_BucketManager() RAS_BucketManager::~RAS_BucketManager() { - RAS_BucketManagerClearAll(); + BucketList::iterator it; + + for (it = m_SolidBuckets.begin(); it != m_SolidBuckets.end(); it++) + delete (*it); + + for (it = m_AlphaBuckets.begin(); it != m_AlphaBuckets.end(); it++) + delete(*it); + + m_SolidBuckets.clear(); + m_AlphaBuckets.clear(); } -/** - * struct alphamesh holds a mesh, (m_ms) it's depth, (m_z) and the bucket it came from (m_bucket.) - */ -struct RAS_BucketManager::alphamesh +void RAS_BucketManager::OrderBuckets(const MT_Transform& cameratrans, BucketList& buckets, vector& slots, bool alpha) { -public: - MT_Scalar m_z; - RAS_MaterialBucket::T_MeshSlotList::iterator m_ms; - RAS_MaterialBucket *m_bucket; - alphamesh(MT_Scalar z, RAS_MaterialBucket::T_MeshSlotList::iterator &ms, RAS_MaterialBucket *bucket) : - m_z(z), - m_ms(ms), - m_bucket(bucket) - {} -}; + BucketList::iterator bit; + list::iterator mit; + size_t size = 0, i = 0; -struct RAS_BucketManager::backtofront -{ - bool operator()(const alphamesh &a, const alphamesh &b) - { - return a.m_z < b.m_z; - } -}; - + /* Camera's near plane equation: pnorm.dot(point) + pval, + * but we leave out pval since it's constant anyway */ + const MT_Vector3 pnorm(cameratrans.getBasis()[2]); + + for (bit = buckets.begin(); bit != buckets.end(); ++bit) + for (mit = (*bit)->msBegin(); mit != (*bit)->msEnd(); ++mit) + if (!mit->IsCulled()) + size++; + + slots.resize(size); + + for (bit = buckets.begin(); bit != buckets.end(); ++bit) + for (mit = (*bit)->msBegin(); mit != (*bit)->msEnd(); ++mit) + if (!mit->IsCulled()) + slots[i++].set(&*mit, *bit, pnorm); + + if(alpha) + sort(slots.begin(), slots.end(), backtofront()); + else + sort(slots.begin(), slots.end(), fronttoback()); +} + +//static int TOTASLOT = 0; +//static int TOTSLOT = 0; void RAS_BucketManager::RenderAlphaBuckets( const MT_Transform& cameratrans, RAS_IRasterizer* rasty, RAS_IRenderTools* rendertools) { - BucketList::iterator bit; - std::multiset alphameshset; - RAS_MaterialBucket::T_MeshSlotList::iterator mit; + vector slots; + vector::iterator sit; + + // Having depth masks disabled/enabled gives different artifacts in + // case no sorting is done or is done inexact. For compatibility, we + // disable it. + rasty->SetDepthMask(RAS_IRasterizer::KX_DEPTHMASK_DISABLED); + + OrderBuckets(cameratrans, m_AlphaBuckets, slots, true); - /* Camera's near plane equation: cam_norm.dot(point) + cam_origin */ - const MT_Vector3 cam_norm(cameratrans.getBasis()[2]); - const MT_Scalar cam_origin = cameratrans.getOrigin()[2]; - for (bit = m_AlphaBuckets.begin(); bit != m_AlphaBuckets.end(); ++bit) - { - for (mit = (*bit)->msBegin(); mit != (*bit)->msEnd(); ++mit) - { - if ((*mit).m_bVisible) - { - MT_Point3 pos((*mit).m_OpenGLMatrix[12], (*mit).m_OpenGLMatrix[13], (*mit).m_OpenGLMatrix[14]); - alphameshset.insert(alphamesh(MT_dot(cam_norm, pos) + cam_origin, mit, *bit)); + for(sit=slots.begin(); sit!=slots.end(); ++sit) { + rendertools->SetClientObject(rasty, sit->m_ms->m_clientObj); + + while(sit->m_bucket->ActivateMaterial(cameratrans, rasty, rendertools)) { + sit->m_bucket->RenderMeshSlot(cameratrans, rasty, rendertools, *(sit->m_ms)); + //TOTASLOT++; + } + } + + rasty->SetDepthMask(RAS_IRasterizer::KX_DEPTHMASK_ENABLED); +} + +void RAS_BucketManager::RenderSolidBuckets( + const MT_Transform& cameratrans, RAS_IRasterizer* rasty, RAS_IRenderTools* rendertools) +{ + BucketList::iterator bit; + list::iterator mit; + + rasty->SetDepthMask(RAS_IRasterizer::KX_DEPTHMASK_ENABLED); + + for (bit = m_SolidBuckets.begin(); bit != m_SolidBuckets.end(); ++bit) { + for (mit = (*bit)->msBegin(); mit != (*bit)->msEnd(); ++mit) { + if (mit->IsCulled()) + continue; + + rendertools->SetClientObject(rasty, mit->m_clientObj); + + while ((*bit)->ActivateMaterial(cameratrans, rasty, rendertools)) { + (*bit)->RenderMeshSlot(cameratrans, rasty, rendertools, *mit); + //TOTSLOT++; } } } - // It shouldn't be strictly necessary to disable depth writes; but - // it is needed for compatibility. - rasty->SetDepthMask(RAS_IRasterizer::KX_DEPTHMASK_DISABLED); +#if 0 + vector slots; + vector::iterator sit; - RAS_IRasterizer::DrawMode drawingmode; - std::multiset< alphamesh, backtofront>::iterator msit = alphameshset.begin(); - for (; msit != alphameshset.end(); ++msit) - { - rendertools->SetClientObject((*(*msit).m_ms).m_clientObj); - while ((*msit).m_bucket->ActivateMaterial(cameratrans, rasty, rendertools, drawingmode)) - (*msit).m_bucket->RenderMeshSlot(cameratrans, rasty, rendertools, *(*msit).m_ms, drawingmode); + OrderBuckets(cameratrans, m_SolidBuckets, slots, false); + + for(sit=slots.begin(); sit!=slots.end(); ++sit) { + rendertools->SetClientObject(rasty, sit->m_ms->m_clientObj); + + while(sit->m_bucket->ActivateMaterial(cameratrans, rasty, rendertools)) + sit->m_bucket->RenderMeshSlot(cameratrans, rasty, rendertools, *(sit->m_ms)); } - - rasty->SetDepthMask(RAS_IRasterizer::KX_DEPTHMASK_ENABLED); +#endif } void RAS_BucketManager::Renderbuckets( const MT_Transform& cameratrans, RAS_IRasterizer* rasty, RAS_IRenderTools* rendertools) { - BucketList::iterator bucket; - - rasty->EnableTextures(false); - rasty->SetDepthMask(RAS_IRasterizer::KX_DEPTHMASK_ENABLED); - // beginning each frame, clear (texture/material) caching information rasty->ClearCachingInfo(); - RAS_MaterialBucket::StartFrame(); - - for (bucket = m_MaterialBuckets.begin(); bucket != m_MaterialBuckets.end(); ++bucket) - (*bucket)->Render(cameratrans,rasty,rendertools); + //TOTASLOT = 0; + //TOTSLOT = 0; + RenderSolidBuckets(cameratrans, rasty, rendertools); RenderAlphaBuckets(cameratrans, rasty, rendertools); - RAS_MaterialBucket::EndFrame(); + + //printf("total slots = %d = %d + %d\n", TOTSLOT + TOTASLOT, TOTSLOT, TOTASLOT); + + rendertools->SetClientObject(rasty, NULL); } RAS_MaterialBucket* RAS_BucketManager::FindBucket(RAS_IPolyMaterial * material, bool &bucketCreated) { - bucketCreated = false; BucketList::iterator it; - for (it = m_MaterialBuckets.begin(); it != m_MaterialBuckets.end(); it++) - { + + bucketCreated = false; + + for (it = m_SolidBuckets.begin(); it != m_SolidBuckets.end(); it++) if (*(*it)->GetPolyMaterial() == *material) return *it; - } for (it = m_AlphaBuckets.begin(); it != m_AlphaBuckets.end(); it++) - { if (*(*it)->GetPolyMaterial() == *material) return *it; - } RAS_MaterialBucket *bucket = new RAS_MaterialBucket(material); bucketCreated = true; + if (bucket->IsAlpha()) m_AlphaBuckets.push_back(bucket); else - m_MaterialBuckets.push_back(bucket); + m_SolidBuckets.push_back(bucket); return bucket; } -void RAS_BucketManager::RAS_BucketManagerClearAll() -{ - BucketList::iterator it; - for (it = m_MaterialBuckets.begin(); it != m_MaterialBuckets.end(); it++) - { - delete (*it); - } - for (it = m_AlphaBuckets.begin(); it != m_AlphaBuckets.end(); it++) - { - delete(*it); - } - - m_MaterialBuckets.clear(); - m_AlphaBuckets.clear(); -} - -void RAS_BucketManager::ReleaseDisplayLists() +void RAS_BucketManager::OptimizeBuckets(MT_Scalar distance) { BucketList::iterator bit; - RAS_MaterialBucket::T_MeshSlotList::iterator mit; + + distance = 10.0; - for (bit = m_MaterialBuckets.begin(); bit != m_MaterialBuckets.end(); ++bit) { - for (mit = (*bit)->msBegin(); mit != (*bit)->msEnd(); ++mit) { - if(mit->m_DisplayList) { - mit->m_DisplayList->Release(); - mit->m_DisplayList = NULL; + for (bit = m_SolidBuckets.begin(); bit != m_SolidBuckets.end(); ++bit) + (*bit)->Optimize(distance); + for (bit = m_AlphaBuckets.begin(); bit != m_AlphaBuckets.end(); ++bit) + (*bit)->Optimize(distance); +} + +void RAS_BucketManager::ReleaseDisplayLists(RAS_IPolyMaterial *mat) +{ + BucketList::iterator bit; + list::iterator mit; + + for (bit = m_SolidBuckets.begin(); bit != m_SolidBuckets.end(); ++bit) { + if (mat == NULL || (mat == (*bit)->GetPolyMaterial())) { + for (mit = (*bit)->msBegin(); mit != (*bit)->msEnd(); ++mit) { + if(mit->m_DisplayList) { + mit->m_DisplayList->Release(); + mit->m_DisplayList = NULL; + } } } } for (bit = m_AlphaBuckets.begin(); bit != m_AlphaBuckets.end(); ++bit) { - for (mit = (*bit)->msBegin(); mit != (*bit)->msEnd(); ++mit) { - if(mit->m_DisplayList) { - mit->m_DisplayList->Release(); - mit->m_DisplayList = NULL; + if (mat == NULL || (mat == (*bit)->GetPolyMaterial())) { + for (mit = (*bit)->msBegin(); mit != (*bit)->msEnd(); ++mit) { + if(mit->m_DisplayList) { + mit->m_DisplayList->Release(); + mit->m_DisplayList = NULL; + } } } } diff --git a/source/gameengine/Rasterizer/RAS_BucketManager.h b/source/gameengine/Rasterizer/RAS_BucketManager.h index 08b67ed022f..74526f365a0 100644 --- a/source/gameengine/Rasterizer/RAS_BucketManager.h +++ b/source/gameengine/Rasterizer/RAS_BucketManager.h @@ -39,32 +39,33 @@ class RAS_BucketManager { - //GEN_Map m_MaterialBuckets; - typedef std::vector BucketList; - BucketList m_MaterialBuckets; + BucketList m_SolidBuckets; BucketList m_AlphaBuckets; - struct alphamesh; + struct sortedmeshslot; struct backtofront; + struct fronttoback; public: RAS_BucketManager(); virtual ~RAS_BucketManager(); - void RenderAlphaBuckets(const MT_Transform& cameratrans, - RAS_IRasterizer* rasty, RAS_IRenderTools* rendertools); void Renderbuckets(const MT_Transform & cameratrans, - RAS_IRasterizer* rasty, - class RAS_IRenderTools* rendertools); + RAS_IRasterizer* rasty, RAS_IRenderTools* rendertools); RAS_MaterialBucket* FindBucket(RAS_IPolyMaterial * material, bool &bucketCreated); + void OptimizeBuckets(MT_Scalar distance); - void ReleaseDisplayLists(); + void ReleaseDisplayLists(RAS_IPolyMaterial * material = NULL); private: - void RAS_BucketManagerClearAll(); + void OrderBuckets(const MT_Transform& cameratrans, BucketList& buckets, vector& slots, bool alpha); + void RenderSolidBuckets(const MT_Transform& cameratrans, + RAS_IRasterizer* rasty, RAS_IRenderTools* rendertools); + void RenderAlphaBuckets(const MT_Transform& cameratrans, + RAS_IRasterizer* rasty, RAS_IRenderTools* rendertools); }; #endif //__RAS_BUCKETMANAGER diff --git a/source/gameengine/Rasterizer/RAS_IPolygonMaterial.cpp b/source/gameengine/Rasterizer/RAS_IPolygonMaterial.cpp index 4ee06d96603..fb3607f89f4 100644 --- a/source/gameengine/Rasterizer/RAS_IPolygonMaterial.cpp +++ b/source/gameengine/Rasterizer/RAS_IPolygonMaterial.cpp @@ -42,11 +42,8 @@ RAS_IPolyMaterial::RAS_IPolyMaterial(const STR_String& texname, int transp, bool alpha, bool zsort, - int lightlayer, - bool bIsTriangle, - void* clientobject=NULL) : - - m_texturename(texname), + int lightlayer) + : m_texturename(texname), m_materialname(matname), m_tile(tile), m_tilexrep(tilexrep), @@ -56,7 +53,6 @@ RAS_IPolyMaterial::RAS_IPolyMaterial(const STR_String& texname, m_alpha(alpha), m_zsort(zsort), m_lightlayer(lightlayer), - m_bIsTriangle(bIsTriangle), m_polymatid(m_newpolymatid++), m_flag(0), m_multimode(0) @@ -72,15 +68,16 @@ bool RAS_IPolyMaterial::Equals(const RAS_IPolyMaterial& lhs) const { if(m_flag &RAS_BLENDERMAT) { - return ( + bool test = ( this->m_multimode == lhs.m_multimode && this->m_flag == lhs.m_flag && this->m_drawingmode == lhs.m_drawingmode && this->m_transp == lhs.m_transp && - this->m_lightlayer == lhs.m_lightlayer && this->m_texturename.hash() == lhs.m_texturename.hash() && this->m_materialname.hash() == lhs.m_materialname.hash() ); + + return test; } else { @@ -92,8 +89,6 @@ bool RAS_IPolyMaterial::Equals(const RAS_IPolyMaterial& lhs) const this->m_alpha == lhs.m_alpha && this->m_zsort == lhs.m_zsort && this->m_drawingmode == lhs.m_drawingmode && - this->m_bIsTriangle == lhs.m_bIsTriangle && - this->m_lightlayer == lhs.m_lightlayer && this->m_texturename.hash() == lhs.m_texturename.hash() && this->m_materialname.hash() == lhs.m_materialname.hash() ); @@ -123,11 +118,6 @@ bool RAS_IPolyMaterial::IsZSort() const return m_zsort; } -bool RAS_IPolyMaterial::UsesTriangles() const -{ - return m_bIsTriangle; -} - unsigned int RAS_IPolyMaterial::hash() const { return m_texturename.hash(); @@ -172,5 +162,10 @@ bool RAS_IPolyMaterial::UsesLighting(RAS_IRasterizer *rasty) const return dolights; } +bool RAS_IPolyMaterial::UsesObjectColor() const +{ + return !(m_flag & RAS_BLENDERGLSL); +} + unsigned int RAS_IPolyMaterial::m_newpolymatid = 0; diff --git a/source/gameengine/Rasterizer/RAS_IPolygonMaterial.h b/source/gameengine/Rasterizer/RAS_IPolygonMaterial.h index 8fc53e6b038..218dd91cb30 100644 --- a/source/gameengine/Rasterizer/RAS_IPolygonMaterial.h +++ b/source/gameengine/Rasterizer/RAS_IPolygonMaterial.h @@ -71,7 +71,6 @@ protected: bool m_alpha; bool m_zsort; int m_lightlayer; - bool m_bIsTriangle; unsigned int m_polymatid; static unsigned int m_newpolymatid; @@ -106,9 +105,7 @@ public: int transp, bool alpha, bool zsort, - int lightlayer, - bool bIsTriangle, - void* clientobject); + int lightlayer); virtual ~RAS_IPolyMaterial() {}; /** @@ -129,14 +126,13 @@ public: { return false; } - virtual void ActivateMeshSlot(const class KX_MeshSlot & ms, RAS_IRasterizer* rasty) const {} + virtual void ActivateMeshSlot(const class RAS_MeshSlot & ms, RAS_IRasterizer* rasty) const {} virtual bool Equals(const RAS_IPolyMaterial& lhs) const; bool Less(const RAS_IPolyMaterial& rhs) const; int GetLightLayer() const; bool IsAlpha() const; bool IsZSort() const; - bool UsesTriangles() const; unsigned int hash() const; int GetDrawingMode() const; const STR_String& GetMaterialName() const; @@ -145,6 +141,7 @@ public: const unsigned int GetFlag() const; virtual bool UsesLighting(RAS_IRasterizer *rasty) const; + virtual bool UsesObjectColor() const; /* * PreCalculate texture gen diff --git a/source/gameengine/Rasterizer/RAS_IRasterizer.h b/source/gameengine/Rasterizer/RAS_IRasterizer.h index 9e03212283e..1d18d02a583 100644 --- a/source/gameengine/Rasterizer/RAS_IRasterizer.h +++ b/source/gameengine/Rasterizer/RAS_IRasterizer.h @@ -217,39 +217,18 @@ public: // Drawing Functions /** - * IndexPrimitives: Renders primitives. - * @param vertexarrays is an array of vertex arrays - * @param indexarrays is an array of index arrays - * @param mode determines the type of primitive stored in the vertex/index arrays - * @param useObjectColor will render the object using @param rgbacolor instead of - * vertex colors. + * IndexPrimitives: Renders primitives from mesh slot. */ - virtual void IndexPrimitives( const vecVertexArray& vertexarrays, - const vecIndexArrays & indexarrays, - DrawMode mode, - bool useObjectColor, - const MT_Vector4& rgbacolor, - class KX_ListSlot** slot)=0; - - virtual void IndexPrimitivesMulti( - const vecVertexArray& vertexarrays, - const vecIndexArrays & indexarrays, - DrawMode mode, - bool useObjectColor, - const MT_Vector4& rgbacolor, - class KX_ListSlot** slot)=0; + virtual void IndexPrimitives(class RAS_MeshSlot& ms)=0; + virtual void IndexPrimitivesMulti(class RAS_MeshSlot& ms)=0; /** * IndexPrimitives_3DText will render text into the polygons. * The text to be rendered is from @param rendertools client object's text property. */ - virtual void IndexPrimitives_3DText( const vecVertexArray& vertexarrays, - const vecIndexArrays & indexarrays, - DrawMode mode, + virtual void IndexPrimitives_3DText(class RAS_MeshSlot& ms, class RAS_IPolyMaterial* polymat, - class RAS_IRenderTools* rendertools, - bool useObjectColor, - const MT_Vector4& rgbacolor)=0; + class RAS_IRenderTools* rendertools)=0; virtual void SetProjectionMatrix(MT_CmMatrix4x4 & mat)=0; /* This one should become our final version, methinks. */ @@ -269,9 +248,6 @@ public: /** */ virtual const MT_Point3& GetCameraPosition()=0; - /** - */ - virtual void LoadViewMatrix()=0; /** */ virtual void SetFog(float start, @@ -308,9 +284,6 @@ public: * @return the current drawing mode: KX_BOUNDINGBOX, KX_WIREFRAME, KX_SOLID, KX_SHADED or KX_TEXTURED. */ virtual int GetDrawingMode()=0; - /** - */ - virtual void EnableTextures(bool enable)=0; /** * Sets face culling */ @@ -385,7 +358,9 @@ public: virtual void SetAttribNum(int num) = 0; virtual void SetTexCoord(TexCoGen coords, int unit) = 0; virtual void SetAttrib(TexCoGen coords, int unit) = 0; - virtual void GetViewMatrix(MT_Matrix4x4 &mat) const = 0; + + virtual const MT_Matrix4x4& GetViewMatrix() const = 0; + virtual const MT_Matrix4x4& GetViewInvMatrix() const = 0; virtual bool QueryLists(){return false;} virtual bool QueryArrays(){return false;} @@ -398,6 +373,7 @@ public: virtual void SetMotionBlurState(int newstate)=0; virtual void SetBlendingMode(int blendmode)=0; + virtual void SetFrontFace(bool ccw)=0; }; #endif //__RAS_IRASTERIZER diff --git a/source/gameengine/Rasterizer/RAS_IRenderTools.cpp b/source/gameengine/Rasterizer/RAS_IRenderTools.cpp index 2be9bb75ebf..555a3520bb4 100644 --- a/source/gameengine/Rasterizer/RAS_IRenderTools.cpp +++ b/source/gameengine/Rasterizer/RAS_IRenderTools.cpp @@ -28,42 +28,22 @@ #include "RAS_IRenderTools.h" -#ifdef HAVE_CONFIG_H -#include -#endif - -void RAS_IRenderTools::SetViewMat(const MT_Transform& trans) -{ - trans.getValue(m_viewmat); -} - - - -void RAS_IRenderTools::SetClientObject(void* obj) +void RAS_IRenderTools::SetClientObject(RAS_IRasterizer* rasty, void *obj) { if (m_clientobject != obj) - { m_clientobject = obj; - m_modified = true; - } } - - void RAS_IRenderTools::SetAuxilaryClientInfo(void* inf) { m_auxilaryClientInfo = inf; } - - void RAS_IRenderTools::AddLight(struct RAS_LightObject* lightobject) { m_lights.push_back(lightobject); } - - void RAS_IRenderTools::RemoveLight(struct RAS_LightObject* lightobject) { std::vector::iterator lit = @@ -71,5 +51,5 @@ void RAS_IRenderTools::RemoveLight(struct RAS_LightObject* lightobject) if (!(lit==m_lights.end())) m_lights.erase(lit); - } + diff --git a/source/gameengine/Rasterizer/RAS_IRenderTools.h b/source/gameengine/Rasterizer/RAS_IRenderTools.h index 54a663ba111..57f331e64cb 100644 --- a/source/gameengine/Rasterizer/RAS_IRenderTools.h +++ b/source/gameengine/Rasterizer/RAS_IRenderTools.h @@ -44,12 +44,9 @@ class RAS_IRenderTools { protected: - float m_viewmat[16]; void* m_clientobject; void* m_auxilaryClientInfo; - bool m_modified; - std::vector m_lights; RAS_2DFilterManager m_filtermanager; @@ -68,8 +65,7 @@ public: RAS_IRenderTools( ) : - m_clientobject(NULL), - m_modified(true) + m_clientobject(NULL) { }; @@ -131,24 +127,21 @@ public: float v1[3], float v2[3], float v3[3], - float v4[3] + float v4[3], + int glattrib )=0; virtual - void - SetViewMat( - const MT_Transform& trans - ); - - virtual - int + void ProcessLighting( - int layer + int layer, + const MT_Transform& trans )=0; virtual void SetClientObject( + RAS_IRasterizer* rasty, void* obj ); @@ -190,24 +183,6 @@ public: virtual void Render2DFilters(RAS_ICanvas* canvas)=0; - - virtual - class RAS_IPolyMaterial* - CreateBlenderPolyMaterial( - const STR_String &texname, - bool ba, - const STR_String& matname, - int tile, - int tilexrep, - int tileyrep, - int mode, - bool transparant, - bool zsort, - int lightlayer, - bool bIsTriangle, - void* clientobject, - void* tface - )=0; }; #endif //__RAS_IRENDERTOOLS diff --git a/source/gameengine/Rasterizer/RAS_MaterialBucket.cpp b/source/gameengine/Rasterizer/RAS_MaterialBucket.cpp index 0015b6a251f..e003cdc9368 100644 --- a/source/gameengine/Rasterizer/RAS_MaterialBucket.cpp +++ b/source/gameengine/Rasterizer/RAS_MaterialBucket.cpp @@ -28,10 +28,6 @@ #include "RAS_MaterialBucket.h" -#ifdef HAVE_CONFIG_H -#include -#endif - #ifdef WIN32 #pragma warning (disable:4786) #include @@ -44,81 +40,410 @@ #include "RAS_MeshObject.h" #include "RAS_Deformer.h" // __NLA +/* mesh slot */ - -KX_VertexIndex::KX_VertexIndex(int size) +RAS_MeshSlot::RAS_MeshSlot() { - m_size = size; + m_clientObj = NULL; + m_pDeformer = NULL; + m_OpenGLMatrix = NULL; + m_mesh = NULL; + m_bucket = NULL; + m_bVisible = false; + m_bCulled = true; + m_bObjectColor = false; + m_RGBAcolor = MT_Vector4(0.0, 0.0, 0.0, 0.0); + m_DisplayList = NULL; + m_bDisplayList = true; + m_joinSlot = NULL; } - - -void KX_VertexIndex::SetIndex(short loc,unsigned int index) +RAS_MeshSlot::~RAS_MeshSlot() { - m_indexarray[loc]=index; -} + vector::iterator it; -bool KX_MeshSlot::Less(const KX_MeshSlot& lhs) const -{ - bool result = ((m_mesh < lhs.m_mesh ) || - ((m_mesh == lhs.m_mesh)&&(m_OpenGLMatrix < lhs.m_OpenGLMatrix))); - - return result; -} + Split(true); -KX_MeshSlot::~KX_MeshSlot() -{ - if (m_DisplayList) + while(m_joinedSlots.size()) + m_joinedSlots.front()->Split(true); + + for(it=m_displayArrays.begin(); it!=m_displayArrays.end(); it++) { + (*it)->m_users--; + if((*it)->m_users == 0) + delete *it; + } + + if (m_DisplayList) { m_DisplayList->Release(); + m_DisplayList = NULL; + } } +RAS_MeshSlot::RAS_MeshSlot(const RAS_MeshSlot& slot) +{ + vector::iterator it; + + m_clientObj = NULL; + m_pDeformer = NULL; + m_OpenGLMatrix = NULL; + m_mesh = slot.m_mesh; + m_bucket = slot.m_bucket; + m_bVisible = slot.m_bVisible; + m_bCulled = slot.m_bCulled; + m_bObjectColor = slot.m_bObjectColor; + m_RGBAcolor = slot.m_RGBAcolor; + m_DisplayList = NULL; + m_bDisplayList = slot.m_bDisplayList; + m_joinSlot = NULL; + m_currentArray = slot.m_currentArray; + m_displayArrays = slot.m_displayArrays; + m_joinedSlots = slot.m_joinedSlots; + + m_startarray = slot.m_startarray; + m_startvertex = slot.m_startvertex; + m_startindex = slot.m_startindex; + m_endarray = slot.m_endarray; + m_endvertex = slot.m_endvertex; + m_endindex = slot.m_endindex; + + for(it=m_displayArrays.begin(); it!=m_displayArrays.end(); it++) { + *it = new RAS_DisplayArray(**it); + (*it)->m_users = 1; + } +} + +void RAS_MeshSlot::init(RAS_MaterialBucket *bucket, int numverts) +{ + m_bucket = bucket; + + SetDisplayArray(numverts); + + m_startarray = 0; + m_startvertex = 0; + m_startindex = 0; + m_endarray = 0; + m_endvertex = 0; + m_endindex = 0; +} + +void RAS_MeshSlot::begin(RAS_MeshSlot::iterator& it) +{ + int startvertex, endvertex; + int startindex, endindex; + + it.array = m_displayArrays[m_startarray]; + + startvertex = m_startvertex; + endvertex = (m_startarray == m_endarray)? m_endvertex: it.array->m_vertex.size(); + startindex = m_startindex; + endindex = (m_startarray == m_endarray)? m_endindex: it.array->m_index.size(); + + it.vertex = &it.array->m_vertex[0]; + it.index = &it.array->m_index[startindex]; + it.startvertex = startvertex; + it.endvertex = endvertex; + it.totindex = endindex-startindex; + it.arraynum = m_startarray; +} + +void RAS_MeshSlot::next(RAS_MeshSlot::iterator& it) +{ + int startvertex, endvertex; + int startindex, endindex; + + if(it.arraynum == (size_t)m_endarray) { + it.array = NULL; + it.vertex = NULL; + it.index = NULL; + it.startvertex = 0; + it.endvertex = 0; + it.totindex = 0; + } + else { + it.arraynum++; + it.array = m_displayArrays[it.arraynum]; + + startindex = 0; + endindex = (it.arraynum == (size_t)m_endarray)? m_endindex: it.array->m_index.size(); + startvertex = 0; + endvertex = (it.arraynum == (size_t)m_endarray)? m_endvertex: it.array->m_vertex.size(); + + it.vertex = &it.array->m_vertex[0]; + it.index = &it.array->m_index[startindex]; + it.startvertex = startvertex; + it.endvertex = endvertex; + it.totindex = endindex-startindex; + } +} + +bool RAS_MeshSlot::end(RAS_MeshSlot::iterator& it) +{ + return (it.array == NULL); +} + +RAS_DisplayArray *RAS_MeshSlot::CurrentDisplayArray() +{ + return m_currentArray; +} + +void RAS_MeshSlot::SetDisplayArray(int numverts) +{ + vector::iterator it; + RAS_DisplayArray *darray = NULL; + + for(it=m_displayArrays.begin(); it!=m_displayArrays.end(); it++) { + darray = *it; + + if(darray->m_type == numverts) { + if(darray->m_index.size()+numverts >= RAS_DisplayArray::BUCKET_MAX_INDEX) + darray = NULL; + else if(darray->m_vertex.size()+numverts >= RAS_DisplayArray::BUCKET_MAX_VERTEX) + darray = NULL; + else + break; + } + else + darray = NULL; + } + + if(!darray) { + darray = new RAS_DisplayArray(); + darray->m_users = 1; + + if(numverts == 2) darray->m_type = RAS_DisplayArray::LINE; + else if(numverts == 3) darray->m_type = RAS_DisplayArray::TRIANGLE; + else darray->m_type = RAS_DisplayArray::QUAD; + + m_displayArrays.push_back(darray); + + if(numverts == 2) + darray->m_type = RAS_DisplayArray::LINE; + else if(numverts == 3) + darray->m_type = RAS_DisplayArray::TRIANGLE; + else if(numverts == 4) + darray->m_type = RAS_DisplayArray::QUAD; + + m_endarray = m_displayArrays.size()-1; + m_endvertex = 0; + m_endindex = 0; + } + + m_currentArray = darray; +} + +void RAS_MeshSlot::AddPolygon(int numverts) +{ + SetDisplayArray(numverts); +} + +int RAS_MeshSlot::AddVertex(const RAS_TexVert& tv) +{ + RAS_DisplayArray *darray; + int offset; + + darray = m_currentArray; + darray->m_vertex.push_back(tv); + offset = darray->m_vertex.size()-1; + + if(darray == m_displayArrays[m_endarray]) + m_endvertex++; + + return offset; +} + +void RAS_MeshSlot::AddPolygonVertex(int offset) +{ + RAS_DisplayArray *darray; + + darray = m_currentArray; + darray->m_index.push_back(offset); + + if(darray == m_displayArrays[m_endarray]) + m_endindex++; +} + +bool RAS_MeshSlot::Equals(RAS_MeshSlot *target) +{ + if(!m_OpenGLMatrix || !target->m_OpenGLMatrix) + return false; + if(m_pDeformer || target->m_pDeformer) + return false; + if(m_bVisible != target->m_bVisible) + return false; + if(m_bObjectColor != target->m_bObjectColor) + return false; + if(m_bObjectColor && !(m_RGBAcolor == target->m_RGBAcolor)) + return false; + + return true; +} + +bool RAS_MeshSlot::Join(RAS_MeshSlot *target, MT_Scalar distance) +{ + vector::iterator it; + iterator mit; + size_t i; + + // verify if we can join + if(m_joinSlot || m_joinedSlots.size() || target->m_joinSlot) + return false; + + if(!Equals(target)) + return false; + + MT_Vector3 co(&m_OpenGLMatrix[12]); + MT_Vector3 targetco(&target->m_OpenGLMatrix[12]); + + if((co - targetco).length() > distance) + return false; + + MT_Matrix4x4 mat(m_OpenGLMatrix); + MT_Matrix4x4 targetmat(target->m_OpenGLMatrix); + targetmat.invert(); + + MT_Matrix4x4 transform = targetmat*mat; + + // m_mesh, clientobj + m_joinSlot = target; + m_joinInvTransform = transform; + m_joinInvTransform.invert(); + target->m_joinedSlots.push_back(this); + + MT_Matrix4x4 ntransform = m_joinInvTransform.transposed(); + ntransform[0][3]= ntransform[1][3]= ntransform[2][3]= 0.0f; + + for(begin(mit); !end(mit); next(mit)) + for(i=mit.startvertex; im_displayArrays.push_back(*it); + target->m_endarray++; + target->m_endvertex = target->m_displayArrays.back()->m_vertex.size(); + target->m_endindex = target->m_displayArrays.back()->m_index.size(); + } + + if (m_DisplayList) { + m_DisplayList->Release(); + m_DisplayList = NULL; + } + if (target->m_DisplayList) { + target->m_DisplayList->Release(); + target->m_DisplayList = NULL; + } + + return true; +#if 0 + return false; +#endif +} + +bool RAS_MeshSlot::Split(bool force) +{ + list::iterator jit; + RAS_MeshSlot *target = m_joinSlot; + vector::iterator it, jt; + iterator mit; + size_t i, found0 = 0, found1 = 0; + + if(target && (force || !Equals(target))) { + m_joinSlot = NULL; + + for(jit=target->m_joinedSlots.begin(); jit!=target->m_joinedSlots.end(); jit++) { + if(*jit == this) { + target->m_joinedSlots.erase(jit); + found0 = 1; + break; + } + } + + if(!found0) + abort(); + + for(it=m_displayArrays.begin(); it!=m_displayArrays.end(); it++) { + found1 = 0; + for(jt=target->m_displayArrays.begin(); jt!=target->m_displayArrays.end(); jt++) { + if(*jt == *it) { + target->m_displayArrays.erase(jt); + target->m_endarray--; + found1 = 1; + break; + } + } + + if(!found1) + abort(); + } + + if(target->m_displayArrays.size()) { + target->m_endvertex = target->m_displayArrays.back()->m_vertex.size(); + target->m_endindex = target->m_displayArrays.back()->m_index.size(); + } + else { + target->m_endvertex = 0; + target->m_endindex = 0; + } + + MT_Matrix4x4 ntransform = m_joinInvTransform.inverse().transposed(); + ntransform[0][3]= ntransform[1][3]= ntransform[2][3]= 0.0f; + + for(begin(mit); !end(mit); next(mit)) + for(i=mit.startvertex; im_DisplayList) { + target->m_DisplayList->Release(); + target->m_DisplayList = NULL; + } + + return true; + } + + return false; +} + +bool RAS_MeshSlot::IsCulled() +{ + list::iterator it; + + if(m_joinSlot) + return true; + if(!m_bCulled) + return false; + + for(it=m_joinedSlots.begin(); it!=m_joinedSlots.end(); it++) + if(!(*it)->m_bCulled) + return false; + + return true; +} + +/* material bucket sorting */ + +struct RAS_MaterialBucket::less +{ + bool operator()(const RAS_MaterialBucket* x, const RAS_MaterialBucket* y) const + { + return *x->GetPolyMaterial() < *y->GetPolyMaterial(); + } +}; + +/* material bucket */ RAS_MaterialBucket::RAS_MaterialBucket(RAS_IPolyMaterial* mat) - :m_bModified(true) { m_material = mat; } - +RAS_MaterialBucket::~RAS_MaterialBucket() +{ +} RAS_IPolyMaterial* RAS_MaterialBucket::GetPolyMaterial() const { return m_material; } - - -void RAS_MaterialBucket::SetMeshSlot(KX_MeshSlot& ms) -{ - m_meshSlots.insert(ms); -} - - - -void RAS_MaterialBucket::RemoveMeshSlot(KX_MeshSlot& ms) -{ - T_MeshSlotList::iterator it = m_meshSlots.find(ms); - - if (!(it == m_meshSlots.end())) - m_meshSlots.erase(it); - -} - - - -void RAS_MaterialBucket::MarkVisibleMeshSlot(KX_MeshSlot& ms, - bool visible, - bool color, - const MT_Vector4& rgbavec) -{ - T_MeshSlotList::iterator it = m_meshSlots.find(ms); - - assert (!(it == m_meshSlots.end())); - (*it).m_bVisible = visible; - (*it).m_bObjectColor = color; - (*it).m_RGBAcolor= rgbavec; -} - bool RAS_MaterialBucket::IsAlpha() const { return (m_material->IsAlpha()); @@ -129,162 +454,129 @@ bool RAS_MaterialBucket::IsZSort() const return (m_material->IsZSort()); } - - -void RAS_MaterialBucket::StartFrame() +RAS_MeshSlot* RAS_MaterialBucket::AddMesh(int numverts) { + RAS_MeshSlot *ms; + + m_meshSlots.push_back(RAS_MeshSlot()); + + ms = &m_meshSlots.back(); + ms->init(this, numverts); + + return ms; } - - -void RAS_MaterialBucket::EndFrame() +RAS_MeshSlot* RAS_MaterialBucket::CopyMesh(RAS_MeshSlot *ms) { + m_meshSlots.push_back(RAS_MeshSlot(*ms)); + + return &m_meshSlots.back(); } -unsigned int RAS_MaterialBucket::NumMeshSlots() +void RAS_MaterialBucket::RemoveMesh(RAS_MeshSlot* ms) { - return m_meshSlots.size(); + list::iterator it; + + for(it=m_meshSlots.begin(); it!=m_meshSlots.end(); it++) { + if(&*it == ms) { + m_meshSlots.erase(it); + return; + } + } } -RAS_MaterialBucket::T_MeshSlotList::iterator RAS_MaterialBucket::msBegin() +list::iterator RAS_MaterialBucket::msBegin() { return m_meshSlots.begin(); } -RAS_MaterialBucket::T_MeshSlotList::iterator RAS_MaterialBucket::msEnd() +list::iterator RAS_MaterialBucket::msEnd() { return m_meshSlots.end(); } bool RAS_MaterialBucket::ActivateMaterial(const MT_Transform& cameratrans, RAS_IRasterizer* rasty, - RAS_IRenderTools *rendertools, RAS_IRasterizer::DrawMode &drawmode) + RAS_IRenderTools *rendertools) { - rendertools->SetViewMat(cameratrans); - if (!rasty->SetMaterial(*m_material)) return false; if (m_material->UsesLighting(rasty)) - rendertools->ProcessLighting(RAS_IRenderTools::RAS_LIGHT_OBJECT_LAYER/*m_material->GetLightLayer()*/); + rendertools->ProcessLighting(RAS_IRenderTools::RAS_LIGHT_OBJECT_LAYER, cameratrans); else - rendertools->ProcessLighting(-1); - - if(rasty->GetDrawingMode() < RAS_IRasterizer::KX_SOLID) - drawmode = RAS_IRasterizer::KX_MODE_LINES; - else if(m_material->UsesTriangles()) - drawmode = RAS_IRasterizer::KX_MODE_TRIANGLES; - else - drawmode = RAS_IRasterizer::KX_MODE_QUADS; + rendertools->ProcessLighting(-1, cameratrans); return true; } void RAS_MaterialBucket::RenderMeshSlot(const MT_Transform& cameratrans, RAS_IRasterizer* rasty, - RAS_IRenderTools* rendertools, const KX_MeshSlot &ms, RAS_IRasterizer::DrawMode drawmode) + RAS_IRenderTools* rendertools, RAS_MeshSlot &ms) { - if (!ms.m_bVisible) - return; - m_material->ActivateMeshSlot(ms, rasty); - /* __NLA Do the deformation */ if (ms.m_pDeformer) { ms.m_pDeformer->Apply(m_material); // KX_ReInstanceShapeFromMesh(ms.m_mesh); // Recompute the physics mesh. (Can't call KX_* from RAS_) } - /* End __NLA */ - if (rasty->GetDrawingMode() >= RAS_IRasterizer::KX_SOLID) - ms.m_mesh->SortPolygons(cameratrans*MT_Transform(ms.m_OpenGLMatrix)); + if(IsZSort() && rasty->GetDrawingMode() >= RAS_IRasterizer::KX_SOLID) + ms.m_mesh->SortPolygons(ms, cameratrans*MT_Transform(ms.m_OpenGLMatrix)); rendertools->PushMatrix(); rendertools->applyTransform(rasty,ms.m_OpenGLMatrix,m_material->GetDrawingMode()); if(rasty->QueryLists()) - { if(ms.m_DisplayList) ms.m_DisplayList->SetModified(ms.m_mesh->MeshModified()); - } // verify if we can use display list, not for deformed object, and // also don't create a new display list when drawing shadow buffers, - // then it won't have texture coordinates for actual drawing - KX_ListSlot **displaylist; + // then it won't have texture coordinates for actual drawing. also + // for zsort we can't make a display list, since the polygon order + // changes all the time. if(ms.m_pDeformer) - displaylist = 0; + ms.m_bDisplayList = false; else if(!ms.m_DisplayList && rasty->GetDrawingMode() == RAS_IRasterizer::KX_SHADOW) - displaylist = 0; + ms.m_bDisplayList = false; + else if (IsZSort()) + ms.m_bDisplayList = false; + else if(m_material->UsesObjectColor() && ms.m_bObjectColor) + ms.m_bDisplayList = false; else - displaylist = &ms.m_DisplayList; + ms.m_bDisplayList = true; - // Use the text-specific IndexPrimitives for text faces + // for text drawing using faces if (m_material->GetDrawingMode() & RAS_IRasterizer::RAS_RENDER_3DPOLYGON_TEXT) - { - rasty->IndexPrimitives_3DText( - ms.m_mesh->GetVertexCache(m_material), - ms.m_mesh->GetIndexCache(m_material), - drawmode, - m_material, - rendertools, // needed for textprinting on polys - ms.m_bObjectColor, - ms.m_RGBAcolor); - } - - // for using glMultiTexCoord + rasty->IndexPrimitives_3DText(ms, m_material, rendertools); + // for multitexturing else if((m_material->GetFlag() & RAS_MULTITEX)) - { - rasty->IndexPrimitivesMulti( - ms.m_mesh->GetVertexCache(m_material), - ms.m_mesh->GetIndexCache(m_material), - drawmode, - ms.m_bObjectColor, - ms.m_RGBAcolor, - displaylist); - } - - // Use the normal IndexPrimitives + rasty->IndexPrimitivesMulti(ms); + // use normal IndexPrimitives else - { - rasty->IndexPrimitives( - ms.m_mesh->GetVertexCache(m_material), - ms.m_mesh->GetIndexCache(m_material), - drawmode, - ms.m_bObjectColor, - ms.m_RGBAcolor, - displaylist); - } + rasty->IndexPrimitives(ms); - if(rasty->QueryLists()) { + if(rasty->QueryLists()) if(ms.m_DisplayList) ms.m_mesh->SetMeshModified(false); - } rendertools->PopMatrix(); } -void RAS_MaterialBucket::Render(const MT_Transform& cameratrans, - RAS_IRasterizer* rasty, - RAS_IRenderTools* rendertools) +void RAS_MaterialBucket::Optimize(MT_Scalar distance) { - if (m_meshSlots.begin()== m_meshSlots.end()) - return; - - //rendertools->SetViewMat(cameratrans); - - //rasty->SetMaterial(*m_material); + /* TODO: still have to check before this works correct: + * - lightlayer, frontface, text, billboard + * - make it work with physics */ - RAS_IRasterizer::DrawMode drawmode; - for (T_MeshSlotList::const_iterator it = m_meshSlots.begin(); - ! (it == m_meshSlots.end()); ++it) - { - rendertools->SetClientObject((*it).m_clientObj); - while (ActivateMaterial(cameratrans, rasty, rendertools, drawmode)) { - RenderMeshSlot(cameratrans, rasty, rendertools, *it, drawmode); - } - } - // to reset the eventual GL_CW mode - rendertools->SetClientObject(NULL); +#if 0 + list::iterator it; + list::iterator jt; + + // greed joining on all following buckets + for(it=m_meshSlots.begin(); it!=m_meshSlots.end(); it++) + for(jt=it, jt++; jt!=m_meshSlots.end(); jt++) + jt->Join(&*it, distance); +#endif } - diff --git a/source/gameengine/Rasterizer/RAS_MaterialBucket.h b/source/gameengine/Rasterizer/RAS_MaterialBucket.h index 4eef889c533..475f01d549a 100644 --- a/source/gameengine/Rasterizer/RAS_MaterialBucket.h +++ b/source/gameengine/Rasterizer/RAS_MaterialBucket.h @@ -36,30 +36,15 @@ #include "MT_Transform.h" #include "RAS_IPolygonMaterial.h" #include "RAS_IRasterizer.h" -#include "RAS_Deformer.h" // __NLA +#include "RAS_Deformer.h" + #include -#include #include +#include using namespace std; -/** - * KX_VertexIndex - */ -struct KX_VertexIndex { -public: - KX_VertexIndex(int size); - void SetIndex(short loc,unsigned int index); - - // The vertex array - short m_vtxarray; - // An index into the vertex array for up to 4 verticies - unsigned short m_indexarray[4]; - short m_size; -}; +/* Display List Slot */ -/** - * KX_ListSlot. - */ class KX_ListSlot { protected: @@ -80,91 +65,149 @@ public: virtual void SetModified(bool mod)=0; }; -/** - * KX_MeshSlot. - */ -class KX_MeshSlot +class RAS_DisplayArray; +class RAS_MeshSlot; +class RAS_MeshMaterial; +class RAS_MaterialBucket; + +/* An array with data used for OpenGL drawing */ + +class RAS_DisplayArray { public: - void* m_clientObj; - RAS_Deformer* m_pDeformer; // __NLA - double* m_OpenGLMatrix; - class RAS_MeshObject* m_mesh; - mutable bool m_bVisible; // for visibility - mutable bool m_bObjectColor; - mutable MT_Vector4 m_RGBAcolor; - mutable KX_ListSlot* m_DisplayList; // for lists - KX_MeshSlot() : - m_pDeformer(NULL), - m_bVisible(true), - m_DisplayList(0) - { - } - ~KX_MeshSlot(); - bool Less(const KX_MeshSlot& lhs) const; + vector m_vertex; + vector m_index; + enum { LINE = 2, TRIANGLE = 3, QUAD = 4 } m_type; + //RAS_MeshSlot *m_origSlot; + int m_users; + + enum { BUCKET_MAX_INDEX = 65535 }; + enum { BUCKET_MAX_VERTEX = 65535 }; }; +/* Entry of a RAS_MeshObject into RAS_MaterialBucket */ -inline bool operator <( const KX_MeshSlot& rhs,const KX_MeshSlot& lhs) +class RAS_MeshSlot { - return ( rhs.Less(lhs)); -} +private: + // indices into display arrays + int m_startarray; + int m_endarray; + int m_startindex; + int m_endindex; + int m_startvertex; + int m_endvertex; + vector m_displayArrays; + + // for construction only + RAS_DisplayArray* m_currentArray; + +public: + // for rendering + RAS_MaterialBucket* m_bucket; + RAS_MeshObject* m_mesh; + void* m_clientObj; + RAS_Deformer* m_pDeformer; + double* m_OpenGLMatrix; + // visibility + bool m_bVisible; + bool m_bCulled; + // object color + bool m_bObjectColor; + MT_Vector4 m_RGBAcolor; + // display lists + KX_ListSlot* m_DisplayList; + bool m_bDisplayList; + // joined mesh slots + RAS_MeshSlot* m_joinSlot; + MT_Matrix4x4 m_joinInvTransform; + list m_joinedSlots; + + RAS_MeshSlot(); + RAS_MeshSlot(const RAS_MeshSlot& slot); + virtual ~RAS_MeshSlot(); + + void init(RAS_MaterialBucket *bucket, int numverts); + + struct iterator { + RAS_DisplayArray *array; + RAS_TexVert *vertex; + unsigned short *index; + size_t startvertex; + size_t endvertex; + size_t totindex; + size_t arraynum; + }; + + void begin(iterator& it); + void next(iterator& it); + bool end(iterator& it); + + /* used during construction */ + void SetDisplayArray(int numverts); + RAS_DisplayArray *CurrentDisplayArray(); + + void AddPolygon(int numverts); + int AddVertex(const RAS_TexVert& tv); + void AddPolygonVertex(int offset); + + /* optimization */ + bool Split(bool force=false); + bool Join(RAS_MeshSlot *target, MT_Scalar distance); + bool Equals(RAS_MeshSlot *target); + bool IsCulled(); +}; + +/* Used by RAS_MeshObject, to point to it's slots in a bucket */ + +class RAS_MeshMaterial +{ +public: + RAS_MeshSlot *m_baseslot; + class RAS_MaterialBucket *m_bucket; + + GEN_Map m_slots; +}; + +/* Contains a list of display arrays with the same material, + * and a mesh slot for each mesh that uses display arrays in + * this bucket */ -/** - * Contains a list of meshs with the same material properties. - */ class RAS_MaterialBucket { public: - typedef std::set T_MeshSlotList; - RAS_MaterialBucket(RAS_IPolyMaterial* mat); - virtual ~RAS_MaterialBucket() {} - - void Render(const MT_Transform& cameratrans, - class RAS_IRasterizer* rasty, - class RAS_IRenderTools* rendertools); - - RAS_IPolyMaterial* GetPolyMaterial() const; - bool IsAlpha() const; - bool IsZSort() const; - - static void StartFrame(); - static void EndFrame(); - - void SetMeshSlot(KX_MeshSlot& ms); - void RemoveMeshSlot(KX_MeshSlot& ms); - void MarkVisibleMeshSlot(KX_MeshSlot& ms, - bool visible, - bool color, - const MT_Vector4& rgbavec); - - void RenderMeshSlot(const MT_Transform& cameratrans, RAS_IRasterizer* rasty, - RAS_IRenderTools* rendertools, const KX_MeshSlot &ms, RAS_IRasterizer::DrawMode drawmode); - bool ActivateMaterial(const MT_Transform& cameratrans, RAS_IRasterizer* rasty, - RAS_IRenderTools *rendertools, RAS_IRasterizer::DrawMode& drawmode); - - unsigned int NumMeshSlots(); - T_MeshSlotList::iterator msBegin(); - T_MeshSlotList::iterator msEnd(); - - struct less - { - bool operator()(const RAS_MaterialBucket* x, const RAS_MaterialBucket* y) const - { - return *x->GetPolyMaterial() < *y->GetPolyMaterial(); - } - }; + virtual ~RAS_MaterialBucket(); + /* Bucket Sorting */ + struct less; typedef set Set; -private: + + /* Material Properties */ + RAS_IPolyMaterial* GetPolyMaterial() const; + bool IsAlpha() const; + bool IsZSort() const; + + /* Rendering */ + bool ActivateMaterial(const MT_Transform& cameratrans, RAS_IRasterizer* rasty, + RAS_IRenderTools *rendertools); + void RenderMeshSlot(const MT_Transform& cameratrans, RAS_IRasterizer* rasty, + RAS_IRenderTools* rendertools, RAS_MeshSlot &ms); - T_MeshSlotList m_meshSlots; - bool m_bModified; + /* Mesh Slot Access */ + list::iterator msBegin(); + list::iterator msEnd(); + + class RAS_MeshSlot* AddMesh(int numverts); + class RAS_MeshSlot* CopyMesh(class RAS_MeshSlot *ms); + void RemoveMesh(class RAS_MeshSlot* ms); + void Optimize(MT_Scalar distance); + +private: + list m_meshSlots; RAS_IPolyMaterial* m_material; - double* m_pOGLMatrix; }; -#endif //__KX_BUCKET +#endif //__RAS_MATERIAL_BUCKET diff --git a/source/gameengine/Rasterizer/RAS_MeshObject.cpp b/source/gameengine/Rasterizer/RAS_MeshObject.cpp index a4f7f3f01dd..a907994bf57 100644 --- a/source/gameengine/Rasterizer/RAS_MeshObject.cpp +++ b/source/gameengine/Rasterizer/RAS_MeshObject.cpp @@ -26,10 +26,6 @@ * ***** END GPL LICENSE BLOCK ***** */ -#ifdef HAVE_CONFIG_H -#include -#endif - #include "RAS_MeshObject.h" #include "RAS_IRasterizer.h" #include "MT_MinMax.h" @@ -37,544 +33,7 @@ #include - -STR_String RAS_MeshObject::s_emptyname = ""; - - - -KX_ArrayOptimizer::~KX_ArrayOptimizer() -{ - for (vector::iterator itv = m_VertexArrayCache1.begin(); - !(itv == m_VertexArrayCache1.end());++itv) - { - delete (*itv); - } - - for (vector::iterator iti = m_IndexArrayCache1.begin(); - !(iti == m_IndexArrayCache1.end());++iti) - { - delete (*iti); - } - - m_TriangleArrayCount.clear(); - m_VertexArrayCache1.clear(); - m_IndexArrayCache1.clear(); - - -} - - - -RAS_MeshObject::RAS_MeshObject(Mesh* mesh, int lightlayer) - : m_bModified(true), - m_lightlayer(lightlayer), - m_zsort(false), - m_MeshMod(true), - m_mesh(mesh), - m_class(0) -{ -} - - -bool RAS_MeshObject::MeshModified() -{ - return m_MeshMod; -} - - -RAS_MeshObject::~RAS_MeshObject() -{ - for (vector::iterator it=m_Polygons.begin();!(it==m_Polygons.end());it++) - { - delete (*it); - } - - ClearArrayData(); -} - - - -unsigned int RAS_MeshObject::GetLightLayer() -{ - return m_lightlayer; -} - - - -int RAS_MeshObject::NumMaterials() -{ - return m_materials.size(); -} - -const STR_String& RAS_MeshObject::GetMaterialName(unsigned int matid) -{ - RAS_MaterialBucket* bucket = GetMaterialBucket(matid); - - return bucket?bucket->GetPolyMaterial()->GetMaterialName():s_emptyname; -} - -RAS_MaterialBucket* RAS_MeshObject::GetMaterialBucket(unsigned int matid) -{ - if (m_materials.size() > 0 && (matid < m_materials.size())) - { - RAS_MaterialBucket::Set::const_iterator it = m_materials.begin(); - while (matid--) ++it; - return *it; - } - - return NULL; -} - - - -int RAS_MeshObject::NumPolygons() -{ - return m_Polygons.size(); -} - - - -RAS_Polygon* RAS_MeshObject::GetPolygon(int num) const -{ - return m_Polygons[num]; -} - - - -RAS_MaterialBucket::Set::iterator RAS_MeshObject::GetFirstMaterial() -{ - return m_materials.begin(); -} - - - -RAS_MaterialBucket::Set::iterator RAS_MeshObject::GetLastMaterial() -{ - return m_materials.end(); -} - - - -void RAS_MeshObject::SetName(STR_String name) -{ - m_name = name; -} - - - -const STR_String& RAS_MeshObject::GetName() -{ - return m_name; -} - - - -const STR_String& RAS_MeshObject::GetTextureName(unsigned int matid) -{ - RAS_MaterialBucket* bucket = GetMaterialBucket(matid); - - return bucket?bucket->GetPolyMaterial()->GetTextureName():s_emptyname; -} - - - -void RAS_MeshObject::AddPolygon(RAS_Polygon* poly) -{ - m_Polygons.push_back(poly); -} - - - -void RAS_MeshObject::DebugColor(unsigned int abgr) -{ -/* - int numpolys = NumPolygons(); - for (int i=0;iVertexCount();v++) - { - RAS_TexVert* vtx = poly->GetVertex(v); - vtx->setDebugRGBA(abgr); - } - } - */ - - m_debugcolor = abgr; -} - -void RAS_MeshObject::SetVertexColor(RAS_IPolyMaterial* mat,MT_Vector4 rgba) -{ - const vecVertexArray & vertexvec = GetVertexCache(mat); - - for (vector::const_iterator it = vertexvec.begin(); it != vertexvec.end(); ++it) - { - KX_VertexArray::iterator vit; - for (vit=(*it)->begin(); vit != (*it)->end(); vit++) - { - vit->SetRGBA(rgba); - } - } -} - -void RAS_MeshObject::SchedulePoly(const KX_VertexIndex& idx, - int numverts, - RAS_IPolyMaterial* mat) -{ - KX_ArrayOptimizer* ao = GetArrayOptimizer(mat); - - ao->m_IndexArrayCache1[idx.m_vtxarray]->push_back(idx.m_indexarray[0]); - ao->m_IndexArrayCache1[idx.m_vtxarray]->push_back(idx.m_indexarray[1]); - ao->m_IndexArrayCache1[idx.m_vtxarray]->push_back(idx.m_indexarray[2]); - - if (!mat->UsesTriangles()) - ao->m_IndexArrayCache1[idx.m_vtxarray]->push_back(idx.m_indexarray[3]); -} - - -void RAS_MeshObject::ScheduleWireframePoly(const KX_VertexIndex& idx, - int numverts, - int edgecode, - RAS_IPolyMaterial* mat) -{ - //int indexpos = m_IndexArrayCount[idx.m_vtxarray]; - int edgetrace = 1<<(numverts-1); - bool drawedge = (edgecode & edgetrace)!=0; - edgetrace = 1; - int prevvert = idx.m_indexarray[numverts-1]; - KX_ArrayOptimizer* ao = GetArrayOptimizer(mat); - - for (int v = 0; v < numverts; v++) - { - unsigned int curvert = idx.m_indexarray[v]; - if (drawedge) - { - ao->m_IndexArrayCache1[idx.m_vtxarray]->push_back(prevvert); - ao->m_IndexArrayCache1[idx.m_vtxarray]->push_back(curvert); - } - prevvert = curvert; - drawedge = (edgecode & edgetrace)!=0; - edgetrace*=2; - } - //m_IndexArrayCount[idx.m_vtxarray] = indexpos; -} - -int RAS_MeshObject::FindOrAddVertex(int vtxarray, - const MT_Point3& xyz, - const MT_Point2& uv, - const MT_Point2& uv2, - const MT_Vector4& tangent, - const unsigned int rgbacolor, - const MT_Vector3& normal, - bool flat, - RAS_IPolyMaterial* mat, - int origindex) -{ - KX_ArrayOptimizer* ao = GetArrayOptimizer(mat); - - int numverts = ao->m_VertexArrayCache1[vtxarray]->size();//m_VertexArrayCount[vtxarray]; - RAS_TexVert newvert(xyz,uv,uv2,tangent,rgbacolor,normal, flat? TV_CALCFACENORMAL: 0,origindex); - -#define KX_FIND_SHARED_VERTICES -#ifdef KX_FIND_SHARED_VERTICES - if(!flat) { - for (std::vector::iterator it = m_xyz_index_to_vertex_index_mapping[origindex].begin(); - it != m_xyz_index_to_vertex_index_mapping[origindex].end(); - it++) - { - if ((*it).m_arrayindex1 == ao->m_index1 && - (*it).m_array == vtxarray && - *(*it).m_matid == *mat && - (*ao->m_VertexArrayCache1[vtxarray])[(*it).m_index].closeTo(&newvert) - ) - { - return (*it).m_index; - } - } - } -#endif // KX_FIND_SHARED_VERTICES - - // no vertex found, add one - ao->m_VertexArrayCache1[vtxarray]->push_back(newvert); - // printf("(%f,%f,%f) ",xyz[0],xyz[1],xyz[2]); - RAS_MatArrayIndex idx; - idx.m_arrayindex1 = ao->m_index1; - idx.m_array = vtxarray; - idx.m_index = numverts; - idx.m_matid = mat; - m_xyz_index_to_vertex_index_mapping[origindex].push_back(idx); - - return numverts; -} - -vecVertexArray& RAS_MeshObject::GetVertexCache (RAS_IPolyMaterial* mat) -{ - KX_ArrayOptimizer* ao = GetArrayOptimizer(mat); - - return ao->m_VertexArrayCache1; -} - -int RAS_MeshObject::GetVertexArrayLength(RAS_IPolyMaterial* mat) -{ - int len = 0; - - const vecVertexArray & vertexvec = GetVertexCache(mat); - vector::const_iterator it = vertexvec.begin(); - - for (; it != vertexvec.end(); ++it) - { - len += (*it)->size(); - } - - return len; -} - - - -RAS_TexVert* RAS_MeshObject::GetVertex(unsigned int matid, - unsigned int index) -{ - RAS_TexVert* vertex = NULL; - - RAS_MaterialBucket* bucket = GetMaterialBucket(matid); - if (bucket) - { - RAS_IPolyMaterial* mat = bucket->GetPolyMaterial(); - if (mat) - { - const vecVertexArray & vertexvec = GetVertexCache(mat); - vector::const_iterator it = vertexvec.begin(); - - for (unsigned int len = 0; it != vertexvec.end(); ++it) - { - if (index < len + (*it)->size()) - { - vertex = &(*(*it))[index-len]; - break; - } - else - { - len += (*it)->size(); - } - } - } - } - - return vertex; -} - - - -const vecIndexArrays& RAS_MeshObject::GetIndexCache (RAS_IPolyMaterial* mat) -{ - KX_ArrayOptimizer* ao = GetArrayOptimizer(mat); - - return ao->m_IndexArrayCache1; -} - - - -KX_ArrayOptimizer* RAS_MeshObject::GetArrayOptimizer(RAS_IPolyMaterial* polymat) -{ - KX_ArrayOptimizer** aop = m_matVertexArrayS[polymat]; - - if(aop) - return *aop; - - // didn't find array, but an array might already exist - // for a material equal to this one - for(int i=0;igetValue()); - if(*mat == *polymat) { - m_matVertexArrayS.insert(polymat, *m_matVertexArrayS.at(i)); - return *m_matVertexArrayS.at(i); - } - } - - // create new array - int numelements = m_matVertexArrayS.size(); - m_sortedMaterials.push_back(polymat); - - KX_ArrayOptimizer* ao = new KX_ArrayOptimizer(numelements); - m_matVertexArrayS.insert(polymat, ao); - - return ao; -} - - - -void RAS_MeshObject::Bucketize(double* oglmatrix, - void* clientobj, - bool useObjectColor, - const MT_Vector4& rgbavec) -{ - KX_MeshSlot ms; - ms.m_clientObj = clientobj; - ms.m_mesh = this; - ms.m_OpenGLMatrix = oglmatrix; - ms.m_bObjectColor = useObjectColor; - ms.m_RGBAcolor = rgbavec; - - for (RAS_MaterialBucket::Set::iterator it = m_materials.begin();it!=m_materials.end();++it) - { - RAS_MaterialBucket* bucket = *it; -// KX_ArrayOptimizer* oa = GetArrayOptimizer(bucket->GetPolyMaterial()); - bucket->SetMeshSlot(ms); - } - -} - - - -void RAS_MeshObject::MarkVisible(double* oglmatrix, - void* clientobj, - bool visible, - bool useObjectColor, - const MT_Vector4& rgbavec) -{ - KX_MeshSlot ms; - ms.m_clientObj = clientobj; - ms.m_mesh = this; - ms.m_OpenGLMatrix = oglmatrix; - ms.m_RGBAcolor = rgbavec; - ms.m_bObjectColor= useObjectColor; - - for (RAS_MaterialBucket::Set::iterator it = m_materials.begin();it!=m_materials.end();++it) - { - RAS_MaterialBucket* bucket = *it; -// KX_ArrayOptimizer* oa = GetArrayOptimizer(bucket->GetPolyMaterial()); - bucket->MarkVisibleMeshSlot(ms,visible,useObjectColor,rgbavec); - } -} - - -void RAS_MeshObject::RemoveFromBuckets(double* oglmatrix, - void* clientobj) -{ - KX_MeshSlot ms; - ms.m_clientObj = clientobj; - ms.m_mesh = this; - ms.m_OpenGLMatrix = oglmatrix; - - for (RAS_MaterialBucket::Set::iterator it = m_materials.begin();it!=m_materials.end();++it) - { - RAS_MaterialBucket* bucket = *it; -// RAS_IPolyMaterial* polymat = bucket->GetPolyMaterial(); - //KX_ArrayOptimizer* oa = GetArrayOptimizer(polymat); - bucket->RemoveMeshSlot(ms); - } - -} - - - -/* - * RAS_MeshObject::GetVertex returns the vertex located somewhere in the vertexpool - * it is the clients responsibility to make sure the array and index are valid - */ -RAS_TexVert* RAS_MeshObject::GetVertex(short array, - unsigned int index, - RAS_IPolyMaterial* polymat) -{ - KX_ArrayOptimizer* ao = GetArrayOptimizer(polymat); - return &((*(ao->m_VertexArrayCache1)[array])[index]); -} - - - -void RAS_MeshObject::ClearArrayData() -{ - for (int i=0;im_VertexArrayCache1.size();i++) - { - if ( (ao->m_TriangleArrayCount[i] + (numverts-2)) < BUCKET_MAX_TRIANGLES) - { - if((ao->m_VertexArrayCache1[i]->size()+numverts < BUCKET_MAX_INDICES)) - { - array = i; - ao->m_TriangleArrayCount[array]+=numverts-2; - break; - } - } - } - - if (array == -1) - { - array = ao->m_VertexArrayCache1.size(); - vector* va = new vector; - ao->m_VertexArrayCache1.push_back(va); - KX_IndexArray *ia = new KX_IndexArray(); - ao->m_IndexArrayCache1.push_back(ia); - ao->m_TriangleArrayCount.push_back(numverts-2); - } - - return array; -} - - - - -//void RAS_MeshObject::Transform(const MT_Transform& trans) -//{ - //m_trans.translate(MT_Vector3(0,0,1));//.operator *=(trans); - -// for (int i=0;iTransform(trans); -// } -//} - - -/* -void RAS_MeshObject::RelativeTransform(const MT_Vector3& vec) -{ - for (int i=0;iRelativeTransform(vec); - } -} -*/ - - - -void RAS_MeshObject::UpdateMaterialList() -{ - m_materials.clear(); - unsigned int numpolys = m_Polygons.size(); - // for all polygons, find out which material they use, and add it to the set of materials - for (unsigned int i=0;iGetMaterial()); - } -} +/* polygon sorting */ struct RAS_MeshObject::polygonSlot { @@ -585,7 +44,7 @@ struct RAS_MeshObject::polygonSlot /* pnorm is the normal from the plane equation that the distance from is * used to sort again. */ - void get(const KX_VertexArray& vertexarray, const KX_IndexArray& indexarray, + void get(const RAS_TexVert *vertexarray, const unsigned short *indexarray, int offset, int nvert, const MT_Vector3& pnorm) { MT_Vector3 center(0, 0, 0); @@ -593,7 +52,7 @@ struct RAS_MeshObject::polygonSlot for(i=0; i::iterator it; + + for(it=m_Polygons.begin(); it!=m_Polygons.end(); it++) + delete (*it); +} + +bool RAS_MeshObject::MeshModified() +{ + return m_bMeshModified; +} + +unsigned int RAS_MeshObject::GetLightLayer() +{ + return m_lightlayer; +} + + + +int RAS_MeshObject::NumMaterials() +{ + return m_materials.size(); +} + +const STR_String& RAS_MeshObject::GetMaterialName(unsigned int matid) +{ + RAS_MeshMaterial* mmat = GetMeshMaterial(matid); + + if(mmat) + return mmat->m_bucket->GetPolyMaterial()->GetMaterialName(); + + return s_emptyname; +} + +RAS_MeshMaterial* RAS_MeshObject::GetMeshMaterial(unsigned int matid) +{ + if (m_materials.size() > 0 && (matid < m_materials.size())) + { + list::iterator it = m_materials.begin(); + while (matid--) ++it; + return &*it; + } + + return NULL; +} + + + +int RAS_MeshObject::NumPolygons() +{ + return m_Polygons.size(); +} + + + +RAS_Polygon* RAS_MeshObject::GetPolygon(int num) const +{ + return m_Polygons[num]; +} + + + + + list::iterator GetFirstMaterial(); + list::iterator GetLastMaterial(); +list::iterator RAS_MeshObject::GetFirstMaterial() +{ + return m_materials.begin(); +} + + + +list::iterator RAS_MeshObject::GetLastMaterial() +{ + return m_materials.end(); +} + + + +void RAS_MeshObject::SetName(STR_String name) +{ + m_name = name; +} + + + +const STR_String& RAS_MeshObject::GetName() +{ + return m_name; +} + + + +const STR_String& RAS_MeshObject::GetTextureName(unsigned int matid) +{ + RAS_MeshMaterial* mmat = GetMeshMaterial(matid); + + if(mmat) + return mmat->m_bucket->GetPolyMaterial()->GetTextureName(); + + return s_emptyname; +} + +RAS_MeshMaterial *RAS_MeshObject::GetMeshMaterial(RAS_IPolyMaterial *mat) +{ + list::iterator mit; + + /* find a mesh material */ + for(mit = m_materials.begin(); mit != m_materials.end(); mit++) + if(mit->m_bucket->GetPolyMaterial() == mat) + return &*mit; + + return NULL; +} + +RAS_Polygon* RAS_MeshObject::AddPolygon(RAS_MaterialBucket *bucket, int numverts) +{ + RAS_MeshMaterial *mmat; + RAS_Polygon *poly; + RAS_MeshSlot *slot; + + /* find a mesh material */ + mmat = GetMeshMaterial(bucket->GetPolyMaterial()); + + /* none found, create a new one */ + if(!mmat) { + RAS_MeshMaterial meshmat; + meshmat.m_bucket = bucket; + meshmat.m_baseslot = meshmat.m_bucket->AddMesh(numverts); + m_materials.push_back(meshmat); + mmat = &m_materials.back(); + } + + /* add it to the bucket, this also adds new display arrays */ + slot = mmat->m_baseslot; + slot->AddPolygon(numverts); + + /* create a new polygon */ + RAS_DisplayArray *darray = slot->CurrentDisplayArray(); + poly = new RAS_Polygon(bucket, darray, numverts); + m_Polygons.push_back(poly); + + return poly; +} + +void RAS_MeshObject::DebugColor(unsigned int abgr) +{ + /*int numpolys = NumPolygons(); + + for (int i=0;iVertexCount();v++) + RAS_TexVert* vtx = poly->GetVertex(v)->setDebugRGBA(abgr); + } + */ + + /* m_debugcolor = abgr; */ +} + +void RAS_MeshObject::SetVertexColor(RAS_IPolyMaterial* mat,MT_Vector4 rgba) +{ + RAS_MeshMaterial *mmat = GetMeshMaterial(mat); + RAS_MeshSlot *slot = mmat->m_baseslot; + RAS_MeshSlot::iterator it; + size_t i; + + for(slot->begin(it); !slot->end(it); slot->next(it)) + for(i=it.startvertex; iGetMaterial()->GetPolyMaterial()); + slot = mmat->m_baseslot; + darray = slot->CurrentDisplayArray(); + + if(!flat) { + /* find vertices shared between faces, with the restriction + * that they exist in the same display array, and have the + * same uv coordinate etc */ + vector& sharedmap = m_sharedvertex_map[origindex]; + vector::iterator it; + + for(it = sharedmap.begin(); it != sharedmap.end(); it++) + { + if(it->m_darray != darray) + continue; + if(!it->m_darray->m_vertex[it->m_offset].closeTo(&texvert)) + continue; + + /* found one, add it and we're done */ + if(poly->IsVisible()) + slot->AddPolygonVertex(it->m_offset); + poly->SetVertexOffset(i, it->m_offset); + return; + } + } + + /* no shared vertex found, add a new one */ + offset = slot->AddVertex(texvert); + if(poly->IsVisible()) + slot->AddPolygonVertex(offset); + poly->SetVertexOffset(i, offset); + + if(!flat) { + SharedVertex shared; + shared.m_darray = darray; + shared.m_offset = offset; + m_sharedvertex_map[origindex].push_back(shared); + } +} + +int RAS_MeshObject::NumVertices(RAS_IPolyMaterial* mat) +{ + RAS_MeshMaterial *mmat; + RAS_MeshSlot *slot; + RAS_MeshSlot::iterator it; + size_t len = 0; + + mmat = GetMeshMaterial(mat); + slot = mmat->m_baseslot; + for(slot->begin(it); !slot->end(it); slot->next(it)) + len += it.endvertex - it.startvertex; + + return len; +} + + +RAS_TexVert* RAS_MeshObject::GetVertex(unsigned int matid, + unsigned int index) +{ + RAS_MeshMaterial *mmat; + RAS_MeshSlot *slot; + RAS_MeshSlot::iterator it; + size_t len; + + mmat = GetMeshMaterial(matid); + + if(!mmat) + return NULL; + + slot = mmat->m_baseslot; + len = 0; + for(slot->begin(it); !slot->end(it); slot->next(it)) { + if(index >= len + it.endvertex - it.startvertex) + len += it.endvertex - it.startvertex; + else + return &it.vertex[index - len]; + } + + return NULL; +} + +void RAS_MeshObject::AddMeshUser(void *clientobj) +{ + list::iterator it; + + for(it = m_materials.begin();it!=m_materials.end();++it) { + /* always copy from the base slot, which is never removed + * since new objects can be created with the same mesh data */ + RAS_MeshSlot *ms = it->m_bucket->CopyMesh(it->m_baseslot); + ms->m_clientObj = clientobj; + it->m_slots.insert(clientobj, ms); + } +} + +void RAS_MeshObject::UpdateBuckets(void* clientobj, + double* oglmatrix, + bool useObjectColor, + const MT_Vector4& rgbavec, + bool visible, + bool culled) +{ + list::iterator it; + + for(it = m_materials.begin();it!=m_materials.end();++it) { + RAS_MeshSlot **msp = it->m_slots[clientobj]; + + if(!msp) + continue; + + RAS_MeshSlot *ms = *msp; + + ms->m_mesh = this; + ms->m_OpenGLMatrix = oglmatrix; + ms->m_bObjectColor = useObjectColor; + ms->m_RGBAcolor = rgbavec; + ms->m_bVisible = visible; + ms->m_bCulled = culled || !visible; + + /* split if necessary */ + ms->Split(); + } +} + +void RAS_MeshObject::RemoveFromBuckets(void *clientobj) +{ + list::iterator it; + + for(it = m_materials.begin();it!=m_materials.end();++it) { + RAS_MeshSlot **msp = it->m_slots[clientobj]; + + if(!msp) + continue; + + RAS_MeshSlot *ms = *msp; + + it->m_bucket->RemoveMesh(ms); + it->m_slots.remove(clientobj); + } +} + +//void RAS_MeshObject::Transform(const MT_Transform& trans) +//{ + //m_trans.translate(MT_Vector3(0,0,1));//.operator *=(trans); + +// for (int i=0;iTransform(trans); +// } +//} + + +/* +void RAS_MeshObject::RelativeTransform(const MT_Vector3& vec) +{ + for (int i=0;iRelativeTransform(vec); + } +} +*/ + +void RAS_MeshObject::SortPolygons(RAS_MeshSlot& ms, const MT_Transform &transform) { // Limitations: sorting is quite simple, and handles many // cases wrong, partially due to polygons being sorted per @@ -645,43 +466,34 @@ void RAS_MeshObject::SortPolygons(const MT_Transform &transform) // to avoid excessive state changes while drawing. e) would // require splitting polygons. - if (!m_zsort) - return; + RAS_MeshSlot::iterator it; + size_t j; - // Extract camera Z plane... - const MT_Vector3 pnorm(transform.getBasis()[2]); - // unneeded: const MT_Scalar pval = transform.getOrigin()[2]; + for(ms.begin(it); !ms.end(it); ms.next(it)) { + unsigned int nvert = (int)it.array->m_type; + unsigned int totpoly = it.totindex/nvert; - for (RAS_MaterialBucket::Set::iterator it = m_materials.begin();it!=m_materials.end();++it) - { - if(!(*it)->IsZSort()) + if(totpoly <= 1) + continue; + if(it.array->m_type == RAS_DisplayArray::LINE) continue; - RAS_IPolyMaterial *mat = (*it)->GetPolyMaterial(); - KX_ArrayOptimizer* ao = GetArrayOptimizer(mat); + // Extract camera Z plane... + const MT_Vector3 pnorm(transform.getBasis()[2]); + // unneeded: const MT_Scalar pval = transform.getOrigin()[2]; - vecIndexArrays& indexarrays = ao->m_IndexArrayCache1; - vecVertexArray& vertexarrays = ao->m_VertexArrayCache1; - unsigned int i, j, nvert = (mat->UsesTriangles())? 3: 4; + vector slots(totpoly); - for(i=0; i slots(totpoly); + /* sort (stable_sort might be better, if flickering happens?) */ + std::sort(slots.begin(), slots.end(), backtofront()); - /* get indices and z into temporary array */ - for(j=0; jIsZSort()) - m_zsort = true; - - if (drawingmode == RAS_IRasterizer::KX_WIREFRAME) - { - for (i=0;iIsVisible()) - ScheduleWireframePoly(poly->GetVertexIndexBase(),poly->VertexCount(),poly->GetEdgeCode(), - poly->GetMaterial()->GetPolyMaterial()); - - } - m_zsort = false; - } - else - { - for (i=0;iIsVisible()) - SchedulePoly(poly->GetVertexIndexBase(),poly->VertexCount(), - poly->GetMaterial()->GetPolyMaterial()); - } - } - m_bModified = false; - m_MeshMod = true; + m_bMeshModified = true; } } diff --git a/source/gameengine/Rasterizer/RAS_MeshObject.h b/source/gameengine/Rasterizer/RAS_MeshObject.h index 9a46d89c393..0d35a2f402b 100644 --- a/source/gameengine/Rasterizer/RAS_MeshObject.h +++ b/source/gameengine/Rasterizer/RAS_MeshObject.h @@ -36,6 +36,7 @@ #include #include +#include #include "RAS_Polygon.h" #include "RAS_MaterialBucket.h" @@ -44,194 +45,71 @@ #include "GEN_HashedPtr.h" struct Mesh; -/** - * This class holds an array of vertices and indicies. - */ -class KX_ArrayOptimizer -{ -public: - KX_ArrayOptimizer(int index) - : m_index1(index) - {}; - virtual ~KX_ArrayOptimizer(); - - vector m_VertexArrayCache1; - vector m_TriangleArrayCount; - vector m_IndexArrayCache1; - /** - order in which they are stored into the mesh - */ - int m_index1; -}; +/* RAS_MeshObject is a mesh used for rendering. It stores polygons, + * but the actual vertices and index arrays are stored in material + * buckets, referenced by the list of RAS_MeshMaterials. */ -/** - * This struct holds a triangle. - */ -struct RAS_TriangleIndex -{ -public: - int m_index[3]; - int m_array; - RAS_IPolyMaterial* m_matid; - bool m_collider; -}; - -/** - * This class looks horribly broken. Only m_matid is used, and - * m_matid is a (int) RAS_IPolyMaterial*. - * --> m_matid == lhs.m_matid should be *m_matid == *lhs.m_matid - */ -class RAS_MatArrayIndex -{ -public: - - int m_arrayindex1; - RAS_IPolyMaterial* m_matid; - int m_array; - int m_index; - -/* - inline bool Less(const RAS_MatArrayIndex& lhs) const { - bool result = - ( (m_matid < lhs.m_matid) || - ((m_matid == lhs.m_matid)&&(m_array < lhs.m_array)) || - ((m_matid == lhs.m_matid) && (m_array == lhs.m_array) && - (m_index < lhs.m_index)) - - ); - return result; - - } -*/ - -}; -/* -inline bool operator <( const RAS_MatArrayIndex& rhs,const RAS_MatArrayIndex& lhs) -{ - return ( rhs.Less(lhs)); -}*/ - -/** - * RAS_MeshObject stores mesh data for the renderer. - */ class RAS_MeshObject { - - // GEN_Map m_matVertexArrayS; - //vector m_vertexArrays; - virtual KX_ArrayOptimizer* GetArrayOptimizer(RAS_IPolyMaterial* polymat); - //vector m_polygons; - +private: unsigned int m_debugcolor; - bool m_bModified; int m_lightlayer; - - vector m_Polygons; + + bool m_bModified; + bool m_bMeshModified; + STR_String m_name; static STR_String s_emptyname; - bool m_zsort; - bool m_MeshMod; + vector m_Polygons; + + /* polygon sorting */ struct polygonSlot; struct backtofront; struct fronttoback; - void SchedulePoly( - const KX_VertexIndex& idx, - int numverts, - RAS_IPolyMaterial* mat - ); - - void ScheduleWireframePoly( - const KX_VertexIndex& idx, - int numverts, - int edgecode, - RAS_IPolyMaterial* mat - ); - protected: - enum { BUCKET_MAX_INDICES = 65535 };//2048};//8192}; - enum { BUCKET_MAX_TRIANGLES = 65535 }; - - GEN_Map m_matVertexArrayS; - - RAS_MaterialBucket::Set m_materials; + list m_materials; Mesh* m_mesh; + bool m_bDeformed; + public: // for now, meshes need to be in a certain layer (to avoid sorting on lights in realtime) RAS_MeshObject(Mesh* mesh, int lightlayer); virtual ~RAS_MeshObject(); - vector m_sortedMaterials; - vector > m_xyz_index_to_vertex_index_mapping; - vector m_triangle_indices; - - int m_class; - unsigned int GetLightLayer(); + bool IsDeformed() { return m_bDeformed; } + + /* materials */ int NumMaterials(); const STR_String& GetMaterialName(unsigned int matid); - RAS_MaterialBucket* GetMaterialBucket(unsigned int matid); const STR_String& GetTextureName(unsigned int matid); - virtual void AddPolygon(RAS_Polygon* poly); - void UpdateMaterialList(); - - int NumPolygons(); - RAS_Polygon* GetPolygon(int num) const; - - virtual void Bucketize( - double* oglmatrix, - void* clientobj, - bool useObjectColor, - const MT_Vector4& rgbavec - ); - void RemoveFromBuckets( - double* oglmatrix, - void* clientobj - ); + RAS_MeshMaterial* GetMeshMaterial(unsigned int matid); + RAS_MeshMaterial* GetMeshMaterial(RAS_IPolyMaterial *mat); - void MarkVisible( - double* oglmatrix, - void* clientobj, - bool visible, - bool useObjectColor, - const MT_Vector4& rgbavec - ); + list::iterator GetFirstMaterial(); + list::iterator GetLastMaterial(); - void DebugColor(unsigned int abgr); - void SetVertexColor(RAS_IPolyMaterial* mat,MT_Vector4 rgba); - - /** - * Sorts the polygons by their transformed z values. - */ - void SortPolygons(const MT_Transform &transform); + unsigned int GetLightLayer(); - void SchedulePolygons(int drawingmode); + /* name */ + void SetName(STR_String name); + const STR_String& GetName(); - void ClearArrayData(); - - RAS_MaterialBucket::Set::iterator GetFirstMaterial(); - RAS_MaterialBucket::Set::iterator GetLastMaterial(); - - virtual RAS_TexVert* GetVertex( - short array, - unsigned int index, - RAS_IPolyMaterial* polymat - ); - - virtual int FindVertexArray( - int numverts, - RAS_IPolyMaterial* polymat - ); + /* modification state */ + bool MeshModified(); + void SetMeshModified(bool v){m_bMeshModified = v;} + /* original blender mesh */ + Mesh* GetMesh() { return m_mesh; } + + /* mesh construction */ - // find (and share) or add vertices - // for some speedup, only the last 20 added vertices are searched for equality - - virtual int FindOrAddVertex( - int vtxarray, + virtual RAS_Polygon* AddPolygon(RAS_MaterialBucket *bucket, int numverts); + virtual void AddVertex(RAS_Polygon *poly, int i, const MT_Point3& xyz, const MT_Point2& uv, const MT_Point2& uv2, @@ -239,27 +117,43 @@ public: const unsigned int rgbacolor, const MT_Vector3& normal, bool flat, - RAS_IPolyMaterial* mat, - int origindex - ); + int origindex); + + void SchedulePolygons(int drawingmode); + + /* vertex and polygon acces */ + int NumVertices(RAS_IPolyMaterial* mat); + RAS_TexVert* GetVertex(unsigned int matid, unsigned int index); + + int NumPolygons(); + RAS_Polygon* GetPolygon(int num) const; - vecVertexArray& GetVertexCache (RAS_IPolyMaterial* mat); + /* buckets */ + virtual void AddMeshUser(void *clientobj); + virtual void UpdateBuckets( + void* clientobj, + double* oglmatrix, + bool useObjectColor, + const MT_Vector4& rgbavec, + bool visible, + bool culled); + + void RemoveFromBuckets(void *clientobj); + + /* colors */ + void DebugColor(unsigned int abgr); + void SetVertexColor(RAS_IPolyMaterial* mat,MT_Vector4 rgba); - int GetVertexArrayLength(RAS_IPolyMaterial* mat); + /* polygon sorting by Z for alpha */ + void SortPolygons(RAS_MeshSlot& ms, const MT_Transform &transform); - RAS_TexVert* GetVertex( - unsigned int matid, - unsigned int index - ); - - const vecIndexArrays& GetIndexCache (RAS_IPolyMaterial* mat); - void SetName(STR_String name); - const STR_String& GetName(); - - bool MeshModified(); - void SetMeshModified(bool v){m_MeshMod = v;} - Mesh* GetMesh() { return m_mesh; } + /* for construction to find shared vertices */ + struct SharedVertex { + RAS_DisplayArray *m_darray; + int m_offset; + }; + vector > m_sharedvertex_map; }; #endif //__RAS_MESHOBJECT diff --git a/source/gameengine/Rasterizer/RAS_OpenGLRasterizer/CMakeLists.txt b/source/gameengine/Rasterizer/RAS_OpenGLRasterizer/CMakeLists.txt index 2a6d64ecc73..e4403ace69f 100644 --- a/source/gameengine/Rasterizer/RAS_OpenGLRasterizer/CMakeLists.txt +++ b/source/gameengine/Rasterizer/RAS_OpenGLRasterizer/CMakeLists.txt @@ -32,6 +32,7 @@ SET(INC ../../../../intern/moto/include ../../../../source/gameengine/Rasterizer ../../../../extern/glew/include + ../../../../source/blender/gpu ) BLENDERLIB(bf_oglrasterizer "${SRC}" "${INC}") diff --git a/source/gameengine/Rasterizer/RAS_OpenGLRasterizer/Makefile b/source/gameengine/Rasterizer/RAS_OpenGLRasterizer/Makefile index f01978b8eb1..aee485a22be 100644 --- a/source/gameengine/Rasterizer/RAS_OpenGLRasterizer/Makefile +++ b/source/gameengine/Rasterizer/RAS_OpenGLRasterizer/Makefile @@ -41,12 +41,11 @@ CPPFLAGS += -I$(OPENGL_HEADERS) CPPFLAGS += -I$(NAN_STRING)/include CPPFLAGS += -I$(NAN_MOTO)/include CPPFLAGS += -I../../../kernel/gen_system +CPPFLAGS += -I../../../blender/gpu CPPFLAGS += -I../../BlenderRoutines CPPFLAGS += -I.. + ifeq ($(OS),darwin) CPPFLAGS += -fpascal-strings endif -ifeq ($(WITH_BF_GLEXT),true) - CPPFLAGS += -DWITH_GLEXT -endif diff --git a/source/gameengine/Rasterizer/RAS_OpenGLRasterizer/RAS_ListRasterizer.cpp b/source/gameengine/Rasterizer/RAS_OpenGLRasterizer/RAS_ListRasterizer.cpp index c2687319717..2c4b55ff964 100644 --- a/source/gameengine/Rasterizer/RAS_OpenGLRasterizer/RAS_ListRasterizer.cpp +++ b/source/gameengine/Rasterizer/RAS_OpenGLRasterizer/RAS_ListRasterizer.cpp @@ -9,6 +9,7 @@ #include "GL/glew.h" +#include "RAS_MaterialBucket.h" #include "RAS_TexVert.h" #include "MT_assert.h" @@ -125,20 +126,20 @@ void RAS_ListRasterizer::RemoveListSlot(RAS_ListSlot* list) } } -RAS_ListSlot* RAS_ListRasterizer::FindOrAdd(const vecVertexArray& vertexarrays, KX_ListSlot** slot) +RAS_ListSlot* RAS_ListRasterizer::FindOrAdd(RAS_MeshSlot& ms) { /* Keep a copy of constant lists submitted for rendering, this guards against (replicated)new...delete every frame, and we can reuse lists! - :: sorted by vertex array + :: sorted by mesh slot */ - RAS_ListSlot* localSlot = (RAS_ListSlot*)*slot; + RAS_ListSlot* localSlot = (RAS_ListSlot*)ms.m_DisplayList; if(!localSlot) { - RAS_Lists::iterator it = mLists.find(vertexarrays); + RAS_Lists::iterator it = mLists.find(&ms); if(it == mLists.end()) { localSlot = new RAS_ListSlot(this); - mLists.insert(std::pair(vertexarrays, localSlot)); + mLists.insert(std::pair(&ms, localSlot)); } else { localSlot = static_cast(it->second->AddRef()); } @@ -157,69 +158,45 @@ void RAS_ListRasterizer::ReleaseAlloc() mLists.clear(); } - -void RAS_ListRasterizer::IndexPrimitives( - const vecVertexArray & vertexarrays, - const vecIndexArrays & indexarrays, - DrawMode mode, - bool useObjectColor, - const MT_Vector4& rgbacolor, - class KX_ListSlot** slot) +void RAS_ListRasterizer::IndexPrimitives(RAS_MeshSlot& ms) { RAS_ListSlot* localSlot =0; - // useObjectColor(are we updating every frame?) - if(!useObjectColor && slot) { - localSlot = FindOrAdd(vertexarrays, slot); + if(ms.m_bDisplayList) { + localSlot = FindOrAdd(ms); localSlot->DrawList(); if(localSlot->End()) { // save slot here too, needed for replicas and object using same mesh // => they have the same vertexarray but different mesh slot - *slot = localSlot; + ms.m_DisplayList = localSlot; return; } } - if (mUseVertexArrays) { - RAS_VAOpenGLRasterizer::IndexPrimitives( - vertexarrays, indexarrays, - mode, useObjectColor, - rgbacolor,slot - ); - } else { - RAS_OpenGLRasterizer::IndexPrimitives( - vertexarrays, indexarrays, - mode, useObjectColor, - rgbacolor,slot - ); - } + if (mUseVertexArrays) + RAS_VAOpenGLRasterizer::IndexPrimitives(ms); + else + RAS_OpenGLRasterizer::IndexPrimitives(ms); - if(!useObjectColor && slot) { + if(ms.m_bDisplayList) { localSlot->EndList(); - *slot = localSlot; + ms.m_DisplayList = localSlot; } } -void RAS_ListRasterizer::IndexPrimitivesMulti( - const vecVertexArray& vertexarrays, - const vecIndexArrays & indexarrays, - DrawMode mode, - bool useObjectColor, - const MT_Vector4& rgbacolor, - class KX_ListSlot** slot) +void RAS_ListRasterizer::IndexPrimitivesMulti(RAS_MeshSlot& ms) { RAS_ListSlot* localSlot =0; - // useObjectColor(are we updating every frame?) - if(!useObjectColor && slot) { - localSlot = FindOrAdd(vertexarrays, slot); + if(ms.m_bDisplayList) { + localSlot = FindOrAdd(ms); localSlot->DrawList(); if(localSlot->End()) { // save slot here too, needed for replicas and object using same mesh // => they have the same vertexarray but different mesh slot - *slot = localSlot; + ms.m_DisplayList = localSlot; return; } } @@ -227,23 +204,14 @@ void RAS_ListRasterizer::IndexPrimitivesMulti( // workaround: note how we do not use vertex arrays for making display // lists, since glVertexAttribPointerARB doesn't seem to work correct // in display lists on ATI? either a bug in the driver or in Blender .. - if (mUseVertexArrays && !localSlot) { - RAS_VAOpenGLRasterizer::IndexPrimitivesMulti( - vertexarrays, indexarrays, - mode, useObjectColor, - rgbacolor,slot - ); - } else { - RAS_OpenGLRasterizer::IndexPrimitivesMulti( - vertexarrays, indexarrays, - mode, useObjectColor, - rgbacolor,slot - ); - } + if (mUseVertexArrays && !localSlot) + RAS_VAOpenGLRasterizer::IndexPrimitivesMulti(ms); + else + RAS_OpenGLRasterizer::IndexPrimitivesMulti(ms); - if(!useObjectColor && slot) { + if(ms.m_bDisplayList) { localSlot->EndList(); - *slot = localSlot; + ms.m_DisplayList = localSlot; } } diff --git a/source/gameengine/Rasterizer/RAS_OpenGLRasterizer/RAS_ListRasterizer.h b/source/gameengine/Rasterizer/RAS_OpenGLRasterizer/RAS_ListRasterizer.h index b1b19144c12..96d6d2a995d 100644 --- a/source/gameengine/Rasterizer/RAS_OpenGLRasterizer/RAS_ListRasterizer.h +++ b/source/gameengine/Rasterizer/RAS_OpenGLRasterizer/RAS_ListRasterizer.h @@ -4,6 +4,7 @@ #include "RAS_MaterialBucket.h" #include "RAS_VAOpenGLRasterizer.h" #include +#include class RAS_ListRasterizer; class RAS_ListSlot : public KX_ListSlot @@ -34,14 +35,14 @@ enum RAS_ListSlotFlags { LIST_REGEN =64 }; -typedef std::map RAS_Lists; +typedef std::map RAS_Lists; class RAS_ListRasterizer : public RAS_VAOpenGLRasterizer { bool mUseVertexArrays; RAS_Lists mLists; - RAS_ListSlot* FindOrAdd(const vecVertexArray& vertexarrays, KX_ListSlot** slot); + RAS_ListSlot* FindOrAdd(class RAS_MeshSlot& ms); void ReleaseAlloc(); public: @@ -49,23 +50,8 @@ public: RAS_ListRasterizer(RAS_ICanvas* canvas, bool useVertexArrays=false, bool lock=false); virtual ~RAS_ListRasterizer(); - virtual void IndexPrimitives( - const vecVertexArray& vertexarrays, - const vecIndexArrays & indexarrays, - DrawMode mode, - bool useObjectColor, - const MT_Vector4& rgbacolor, - class KX_ListSlot** slot - ); - - virtual void IndexPrimitivesMulti( - const vecVertexArray& vertexarrays, - const vecIndexArrays & indexarrays, - DrawMode mode, - bool useObjectColor, - const MT_Vector4& rgbacolor, - class KX_ListSlot** slot - ); + virtual void IndexPrimitives(class RAS_MeshSlot& ms); + virtual void IndexPrimitivesMulti(class RAS_MeshSlot& ms); virtual bool Init(); virtual void Exit(); diff --git a/source/gameengine/Rasterizer/RAS_OpenGLRasterizer/RAS_OpenGLRasterizer.cpp b/source/gameengine/Rasterizer/RAS_OpenGLRasterizer/RAS_OpenGLRasterizer.cpp index 1dcc6e70934..62ee2edb731 100644 --- a/source/gameengine/Rasterizer/RAS_OpenGLRasterizer/RAS_OpenGLRasterizer.cpp +++ b/source/gameengine/Rasterizer/RAS_OpenGLRasterizer/RAS_OpenGLRasterizer.cpp @@ -38,6 +38,9 @@ #include "MT_CmMatrix4x4.h" #include "RAS_IRenderTools.h" // rendering text +#include "GPU_draw.h" +#include "GPU_material.h" + /** * 32x32 bit masks for vinterlace stereo mode */ @@ -67,10 +70,12 @@ RAS_OpenGLRasterizer::RAS_OpenGLRasterizer(RAS_ICanvas* canvas) m_motionblurvalue(-1.0), m_texco_num(0), m_attrib_num(0), - m_last_blendmode(0), + m_last_blendmode(GPU_BLEND_SOLID), + m_last_frontface(true), m_materialCachingInfo(0) { - m_viewmatrix.Identity(); + m_viewmatrix.setIdentity(); + m_viewinvmatrix.setIdentity(); for (int i = 0; i < 32; i++) { @@ -87,81 +92,9 @@ RAS_OpenGLRasterizer::~RAS_OpenGLRasterizer() { } - - -static void Myinit_gl_stuff(void) -{ - float mat_specular[] = { 0.5, 0.5, 0.5, 1.0 }; - float mat_shininess[] = { 35.0 }; -/* float one= 1.0; */ - int a, x, y; - GLubyte pat[32*32]; - const GLubyte *patc= pat; - - glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE, mat_specular); - glMaterialfv(GL_FRONT_AND_BACK, GL_SPECULAR, mat_specular); - glMaterialfv(GL_FRONT_AND_BACK, GL_SHININESS, mat_shininess); - - -#if defined(__FreeBSD) || defined(__linux__) - glDisable(GL_DITHER); /* op sgi/sun hardware && 12 bits */ -#endif - - /* no local viewer, looks ugly in ortho mode */ - /* glLightModelfv(GL_LIGHT_MODEL_LOCAL_VIEWER, &one); */ - - glDepthFunc(GL_LEQUAL); - /* scaling matrices */ - glEnable(GL_NORMALIZE); - - glShadeModel(GL_FLAT); - - glDisable(GL_ALPHA_TEST); - glDisable(GL_BLEND); - glDisable(GL_DEPTH_TEST); - glDisable(GL_FOG); - glDisable(GL_LIGHTING); - glDisable(GL_LOGIC_OP); - glDisable(GL_STENCIL_TEST); - glDisable(GL_TEXTURE_1D); - glDisable(GL_TEXTURE_2D); - - glEnableClientState(GL_VERTEX_ARRAY); - glEnableClientState(GL_NORMAL_ARRAY); - - glPixelTransferi(GL_MAP_COLOR, GL_FALSE); - glPixelTransferi(GL_RED_SCALE, 1); - glPixelTransferi(GL_RED_BIAS, 0); - glPixelTransferi(GL_GREEN_SCALE, 1); - glPixelTransferi(GL_GREEN_BIAS, 0); - glPixelTransferi(GL_BLUE_SCALE, 1); - glPixelTransferi(GL_BLUE_BIAS, 0); - glPixelTransferi(GL_ALPHA_SCALE, 1); - glPixelTransferi(GL_ALPHA_BIAS, 0); - - a = 0; - for(x=0; x<32; x++) - { - for(y=0; y<4; y++) - { - if( (x) & 1) pat[a++]= 0x88; - else pat[a++]= 0x22; - } - } - - glPolygonStipple(patc); - - glFrontFace(GL_CCW); - glCullFace(GL_BACK); - glEnable(GL_CULL_FACE); -} - - - bool RAS_OpenGLRasterizer::Init() { - - Myinit_gl_stuff(); + GPU_state_init(); m_redback = 0.4375; m_greenback = 0.4375; @@ -172,7 +105,8 @@ bool RAS_OpenGLRasterizer::Init() m_ambg = 0.0f; m_ambb = 0.0f; - SetBlendingMode(0); + SetBlendingMode(GPU_BLEND_SOLID); + SetFrontFace(true); glClearColor(m_redback,m_greenback,m_blueback,m_alphaback); glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE); @@ -344,7 +278,8 @@ bool RAS_OpenGLRasterizer::BeginFrame(int drawingmode, double time) glEnable (GL_CULL_FACE); } - SetBlendingMode(0); + SetBlendingMode(GPU_BLEND_SOLID); + SetFrontFace(true); glShadeModel(GL_SMOOTH); @@ -359,28 +294,16 @@ void RAS_OpenGLRasterizer::SetDrawingMode(int drawingmode) { m_drawingmode = drawingmode; - switch (m_drawingmode) - { - case KX_WIREFRAME: - { - glDisable (GL_CULL_FACE); - break; - } - default: - { - } - } + if(m_drawingmode == KX_WIREFRAME) + glDisable(GL_CULL_FACE); } - - int RAS_OpenGLRasterizer::GetDrawingMode() { return m_drawingmode; } - void RAS_OpenGLRasterizer::SetDepthMask(DepthMask depthmask) { glDepthMask(depthmask == KX_DEPTHMASK_DISABLED ? GL_FALSE : GL_TRUE); @@ -573,294 +496,84 @@ void RAS_OpenGLRasterizer::SwapBuffers() -void RAS_OpenGLRasterizer::GetViewMatrix(MT_Matrix4x4 &mat) const +const MT_Matrix4x4& RAS_OpenGLRasterizer::GetViewMatrix() const { - float viewmat[16]; - glGetFloatv(GL_MODELVIEW_MATRIX, viewmat); - mat.setValue(viewmat); + return m_viewmatrix; } - - -void RAS_OpenGLRasterizer::IndexPrimitives(const vecVertexArray & vertexarrays, - const vecIndexArrays & indexarrays, - DrawMode mode, - bool useObjectColor, - const MT_Vector4& rgbacolor, - class KX_ListSlot** slot - ) -{ - const RAS_TexVert* vertexarray; - unsigned int numindices, vt; - - for (vt=0;vtm_type; + + if(it.array->m_type == RAS_DisplayArray::LINE) { + // line drawing, no text + glBegin(GL_LINES); + + for(i=0; igetXYZ()); + + vertex = &it.vertex[it.index[i+1]]; + glVertex3fv(vertex->getXYZ()); + } + + glEnd(); + } + else { + // triangle and quad text drawing + for(i=0; igetXYZ()[0]; + v[j][1] = vertex->getXYZ()[1]; + v[j][2] = vertex->getXYZ()[2]; + } + + // find the right opengl attribute + glattrib = -1; + if(GLEW_ARB_vertex_program) + for(unit=0; unitRenderText(polymat->GetDrawingMode(), polymat, + v[0], v[1], v[2], (numvert == 4)? v[3]: NULL, glattrib); + + ClearCachingInfo(); + } + } } - - for (vt=0;vtRenderText(polymat->GetDrawingMode(),polymat,v1,v2,v3,v4); - ClearCachingInfo(); - } - break; - } - case KX_MODE_TRIANGLES: - { - glBegin(GL_TRIANGLES); - vindex=0; - for (unsigned int i=0;iRenderText(polymat->GetDrawingMode(),polymat,v1,v2,v3,NULL); - ClearCachingInfo(); - } - glEnd(); - break; - } - default: - { - } - } //switch - } //for each vertexarray + + glDisableClientState(GL_COLOR_ARRAY); } void RAS_OpenGLRasterizer::SetTexCoordNum(int num) @@ -897,14 +610,14 @@ void RAS_OpenGLRasterizer::TexCoord(const RAS_TexVert &tv) if(GLEW_ARB_multitexture) { for(unit=0; unitm_type; - for (vt=0;vtm_type == RAS_DisplayArray::LINE) { + // line drawing + glBegin(GL_LINES); - if (!numindices) - break; - - int vindex=0; - switch (mode) - { - case KX_MODE_LINES: + for(i=0; igetXYZ()); + + vertex = &it.vertex[it.index[i+1]]; + glVertex3fv(vertex->getXYZ()); } - break; - case KX_MODE_QUADS: - { - glBegin(GL_QUADS); - vindex=0; - if (useObjectColor) - { - for (unsigned int i=0;im_type == RAS_DisplayArray::TRIANGLE) glBegin(GL_TRIANGLES); - vindex=0; - if (useObjectColor) - { - for (unsigned int i=0;igetRGBA())); + + glNormal3fv(vertex->getNormal()); + + if(multi) + TexCoord(*vertex); + else + glTexCoord2fv(vertex->getUV1()); + } + + glVertex3fv(vertex->getXYZ()); + } } - } // switch - } // for each vertexarray + + glEnd(); + } + } } void RAS_OpenGLRasterizer::SetProjectionMatrix(MT_CmMatrix4x4 &mat) @@ -1232,7 +814,7 @@ MT_Matrix4x4 RAS_OpenGLRasterizer::GetFrustumMatrix( void RAS_OpenGLRasterizer::SetViewMatrix(const MT_Matrix4x4 &mat, const MT_Vector3& campos, const MT_Point3 &, const MT_Quaternion &camOrientQuat) { - MT_Matrix4x4 viewMat = mat; + m_viewmatrix = mat; // correction for stereo if(m_stereomode != RAS_STEREO_NOSTEREO) @@ -1259,7 +841,7 @@ void RAS_OpenGLRasterizer::SetViewMatrix(const MT_Matrix4x4 &mat, const MT_Vecto MT_Transform transform; transform.setIdentity(); transform.translate(-(eyeline * m_eyeseparation / 2.0)); - viewMat *= transform; + m_viewmatrix *= transform; } break; case RAS_STEREO_RIGHTEYE: @@ -1268,20 +850,21 @@ void RAS_OpenGLRasterizer::SetViewMatrix(const MT_Matrix4x4 &mat, const MT_Vecto MT_Transform transform; transform.setIdentity(); transform.translate(eyeline * m_eyeseparation / 2.0); - viewMat *= transform; + m_viewmatrix *= transform; } break; } } - // convert row major matrix 'viewMat' to column major for OpenGL - MT_Scalar cammat[16]; - viewMat.getValue(cammat); - MT_CmMatrix4x4 viewCmmat = cammat; + m_viewinvmatrix = m_viewmatrix; + m_viewinvmatrix.invert(); + + // note: getValue gives back column major as needed by OpenGL + MT_Scalar glviewmat[16]; + m_viewmatrix.getValue(glviewmat); glMatrixMode(GL_MODELVIEW); - m_viewmatrix = viewCmmat; - glLoadMatrixd(&m_viewmatrix(0,0)); + glLoadMatrixd(glviewmat); m_campos = campos; } @@ -1292,20 +875,6 @@ const MT_Point3& RAS_OpenGLRasterizer::GetCameraPosition() } - -void RAS_OpenGLRasterizer::LoadViewMatrix() -{ - glLoadMatrixd(&m_viewmatrix(0,0)); -} - - - -void RAS_OpenGLRasterizer::EnableTextures(bool enable) -{ -} - - - void RAS_OpenGLRasterizer::SetCullFace(bool enable) { if (enable) @@ -1388,23 +957,23 @@ void RAS_OpenGLRasterizer::SetBlendingMode(int blendmode) if(blendmode == m_last_blendmode) return; - if(blendmode == 0) { + if(blendmode == GPU_BLEND_SOLID) { glDisable(GL_BLEND); glDisable(GL_ALPHA_TEST); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); } - else if(blendmode == 1) { + else if(blendmode == GPU_BLEND_ADD) { glBlendFunc(GL_ONE, GL_ONE); glEnable(GL_BLEND); glDisable(GL_ALPHA_TEST); } - else if(blendmode == 2) { + else if(blendmode == GPU_BLEND_ALPHA) { glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glEnable(GL_BLEND); glEnable(GL_ALPHA_TEST); glAlphaFunc(GL_GREATER, 0.0f); } - else if(blendmode == 4) { + else if(blendmode == GPU_BLEND_CLIP) { glDisable(GL_BLEND); glEnable(GL_ALPHA_TEST); glAlphaFunc(GL_GREATER, 0.5f); @@ -1413,3 +982,16 @@ void RAS_OpenGLRasterizer::SetBlendingMode(int blendmode) m_last_blendmode = blendmode; } +void RAS_OpenGLRasterizer::SetFrontFace(bool ccw) +{ + if(m_last_frontface == ccw) + return; + + if(ccw) + glFrontFace(GL_CCW); + else + glFrontFace(GL_CW); + + m_last_frontface = ccw; +} + diff --git a/source/gameengine/Rasterizer/RAS_OpenGLRasterizer/RAS_OpenGLRasterizer.h b/source/gameengine/Rasterizer/RAS_OpenGLRasterizer/RAS_OpenGLRasterizer.h index 02056cce446..368bd4312ac 100644 --- a/source/gameengine/Rasterizer/RAS_OpenGLRasterizer/RAS_OpenGLRasterizer.h +++ b/source/gameengine/Rasterizer/RAS_OpenGLRasterizer/RAS_OpenGLRasterizer.h @@ -41,7 +41,7 @@ using namespace std; #include "RAS_MaterialBucket.h" #include "RAS_ICanvas.h" -#define RAS_MAX_TEXCO 3 // match in BL_Material +#define RAS_MAX_TEXCO 8 // match in BL_Material #define RAS_MAX_ATTRIB 16 // match in BL_BlenderShader struct OglDebugLine @@ -77,7 +77,8 @@ class RAS_OpenGLRasterizer : public RAS_IRasterizer float m_ambb; double m_time; - MT_CmMatrix4x4 m_viewmatrix; + MT_Matrix4x4 m_viewmatrix; + MT_Matrix4x4 m_viewinvmatrix; MT_Point3 m_campos; StereoMode m_stereomode; @@ -100,6 +101,7 @@ protected: int m_texco_num; int m_attrib_num; int m_last_blendmode; + bool m_last_frontface; /** Stores the caching information for the last material activated. */ RAS_IPolyMaterial::TCachingInfo m_materialCachingInfo; @@ -144,33 +146,15 @@ public: virtual float GetFocalLength(); virtual void SwapBuffers(); - virtual void IndexPrimitives( - const vecVertexArray& vertexarrays, - const vecIndexArrays & indexarrays, - DrawMode mode, - bool useObjectColor, - const MT_Vector4& rgbacolor, - class KX_ListSlot** slot - ); + virtual void IndexPrimitives(class RAS_MeshSlot& ms); + virtual void IndexPrimitivesMulti(class RAS_MeshSlot& ms); virtual void IndexPrimitives_3DText( - const vecVertexArray& vertexarrays, - const vecIndexArrays & indexarrays, - DrawMode mode, + class RAS_MeshSlot& ms, class RAS_IPolyMaterial* polymat, - class RAS_IRenderTools* rendertools, - bool useObjectColor, - const MT_Vector4& rgbacolor - ); - - virtual void IndexPrimitivesMulti( - const vecVertexArray& vertexarrays, - const vecIndexArrays & indexarrays, - DrawMode mode, - bool useObjectColor, - const MT_Vector4& rgbacolor, - class KX_ListSlot** slot); + class RAS_IRenderTools* rendertools); + void IndexPrimitivesInternal(RAS_MeshSlot& ms, bool multi); virtual void SetProjectionMatrix(MT_CmMatrix4x4 & mat); virtual void SetProjectionMatrix(const MT_Matrix4x4 & mat); @@ -182,7 +166,6 @@ public: ); virtual const MT_Point3& GetCameraPosition(); - virtual void LoadViewMatrix(); virtual void SetFog( float start, @@ -214,7 +197,6 @@ public: virtual void SetDrawingMode(int drawingmode); virtual int GetDrawingMode(); - virtual void EnableTextures(bool enable); virtual void SetCullFace(bool enable); virtual void SetLines(bool enable); @@ -270,13 +252,10 @@ public: virtual void SetTexCoord(TexCoGen coords, int unit); virtual void SetAttrib(TexCoGen coords, int unit); - void TexCoord(const RAS_TexVert &tv); - virtual void GetViewMatrix(MT_Matrix4x4 &mat) const; + void TexCoord(const RAS_TexVert &tv); - void Tangent(const RAS_TexVert& v1, - const RAS_TexVert& v2, - const RAS_TexVert& v3, - const MT_Vector3 &no); + const MT_Matrix4x4& GetViewMatrix() const; + const MT_Matrix4x4& GetViewInvMatrix() const; virtual void EnableMotionBlur(float motionblurvalue); virtual void DisableMotionBlur(); @@ -293,6 +272,7 @@ public: }; virtual void SetBlendingMode(int blendmode); + virtual void SetFrontFace(bool ccw); }; #endif //__RAS_OPENGLRASTERIZER diff --git a/source/gameengine/Rasterizer/RAS_OpenGLRasterizer/RAS_VAOpenGLRasterizer.cpp b/source/gameengine/Rasterizer/RAS_OpenGLRasterizer/RAS_VAOpenGLRasterizer.cpp index c78a97ad7be..2cb3b52adfb 100644 --- a/source/gameengine/Rasterizer/RAS_OpenGLRasterizer/RAS_VAOpenGLRasterizer.cpp +++ b/source/gameengine/Rasterizer/RAS_OpenGLRasterizer/RAS_VAOpenGLRasterizer.cpp @@ -33,6 +33,7 @@ #include #include "GL/glew.h" +#include "GPU_extensions.h" #include "STR_String.h" #include "RAS_TexVert.h" @@ -77,16 +78,16 @@ void RAS_VAOpenGLRasterizer::SetDrawingMode(int drawingmode) { case KX_BOUNDINGBOX: case KX_WIREFRAME: - glDisableClientState(GL_COLOR_ARRAY); - glDisable(GL_CULL_FACE); + //glDisableClientState(GL_COLOR_ARRAY); + //glDisable(GL_CULL_FACE); break; case KX_SOLID: - glDisableClientState(GL_COLOR_ARRAY); + //glDisableClientState(GL_COLOR_ARRAY); break; case KX_TEXTURED: case KX_SHADED: case KX_SHADOW: - glEnableClientState(GL_COLOR_ARRAY); + //glEnableClientState(GL_COLOR_ARRAY); default: break; } @@ -98,141 +99,121 @@ void RAS_VAOpenGLRasterizer::Exit() glEnableClientState(GL_NORMAL_ARRAY); glDisableClientState(GL_TEXTURE_COORD_ARRAY); glDisableClientState(GL_COLOR_ARRAY); - EnableTextures(false); RAS_OpenGLRasterizer::Exit(); } -void RAS_VAOpenGLRasterizer::IndexPrimitives( const vecVertexArray& vertexarrays, - const vecIndexArrays & indexarrays, - DrawMode mode, - bool useObjectColor, - const MT_Vector4& rgbacolor, - class KX_ListSlot** slot) +void RAS_VAOpenGLRasterizer::IndexPrimitives(RAS_MeshSlot& ms) { - static const GLsizei vtxstride = sizeof(RAS_TexVert); + static const GLsizei stride = sizeof(RAS_TexVert); + bool wireframe = m_drawingmode <= KX_WIREFRAME; + RAS_MeshSlot::iterator it; GLenum drawmode; - if(mode == KX_MODE_TRIANGLES) - drawmode = GL_TRIANGLES; - else if(mode == KX_MODE_QUADS) - drawmode = GL_QUADS; - else - drawmode = GL_LINES; - const RAS_TexVert* vertexarray; - unsigned int numindices, vt; - - if (drawmode != GL_LINES) - { - if (useObjectColor) - { - glDisableClientState(GL_COLOR_ARRAY); - glColor4d(rgbacolor[0], rgbacolor[1], rgbacolor[2], rgbacolor[3]); - } else - { - glColor4d(0,0,0,1.0); - glEnableClientState(GL_COLOR_ARRAY); - } - } - else - { - glColor3d(0,0,0); - } - - EnableTextures(false); - glEnableClientState(GL_TEXTURE_COORD_ARRAY); + if(!wireframe) + glEnableClientState(GL_TEXTURE_COORD_ARRAY); // use glDrawElements to draw each vertexarray - for (vt=0;vtgetLocalXYZ()); - glNormalPointer(GL_FLOAT,vtxstride,vertexarray->getNormal()); - glTexCoordPointer(2,GL_FLOAT,vtxstride,vertexarray->getUV1()); - if(glIsEnabled(GL_COLOR_ARRAY)) - glColorPointer(4,GL_UNSIGNED_BYTE,vtxstride,vertexarray->getRGBA()); - //if(m_Lock) - // local->Begin(vertexarrays[vt]->size()); + // drawing mode + if(it.array->m_type == RAS_DisplayArray::TRIANGLE) + drawmode = GL_TRIANGLES; + else if(it.array->m_type == RAS_DisplayArray::QUAD) + drawmode = GL_QUADS; + else + drawmode = GL_LINES; - // here the actual drawing takes places - glDrawElements(drawmode,numindices,GL_UNSIGNED_SHORT,&(indexarray[0])); + // colors + if (drawmode != GL_LINES && !wireframe) { + if (ms.m_bObjectColor) { + const MT_Vector4& rgba = ms.m_RGBAcolor; - //if(m_Lock) - // local->End(); - } - - glDisableClientState(GL_TEXTURE_COORD_ARRAY); -} - -void RAS_VAOpenGLRasterizer::IndexPrimitivesMulti( const vecVertexArray& vertexarrays, - const vecIndexArrays & indexarrays, - DrawMode mode, - bool useObjectColor, - const MT_Vector4& rgbacolor, - class KX_ListSlot** slot) -{ - static const GLsizei vtxstride = sizeof(RAS_TexVert); - - GLenum drawmode; - if(mode == KX_MODE_TRIANGLES) - drawmode = GL_TRIANGLES; - else if(mode == KX_MODE_QUADS) - drawmode = GL_QUADS; - else - drawmode = GL_LINES; - - const RAS_TexVert* vertexarray; - unsigned int numindices, vt; - - if (drawmode != GL_LINES) - { - if (useObjectColor) - { - glDisableClientState(GL_COLOR_ARRAY); - glColor4d(rgbacolor[0], rgbacolor[1], rgbacolor[2], rgbacolor[3]); + glDisableClientState(GL_COLOR_ARRAY); + glColor4d(rgba[0], rgba[1], rgba[2], rgba[3]); + } + else { + glColor4f(0.0f, 0.0f, 0.0f, 1.0f); + glEnableClientState(GL_COLOR_ARRAY); + } } else - { - glColor4d(0,0,0,1.0); - glEnableClientState(GL_COLOR_ARRAY); + glColor4f(0.0f, 0.0f, 0.0f, 1.0f); + + glVertexPointer(3, GL_FLOAT, stride, it.vertex->getXYZ()); + glNormalPointer(GL_FLOAT, stride, it.vertex->getNormal()); + if(!wireframe) { + glTexCoordPointer(2, GL_FLOAT, stride, it.vertex->getUV1()); + if(glIsEnabled(GL_COLOR_ARRAY)) + glColorPointer(4, GL_UNSIGNED_BYTE, stride, it.vertex->getRGBA()); } - } - else - { - glColor3d(0,0,0); - } - - // use glDrawElements to draw each vertexarray - for (vt=0;vtgetLocalXYZ()); - glNormalPointer(GL_FLOAT,vtxstride,vertexarray->getNormal()); - TexCoordPtr(vertexarray); - if(glIsEnabled(GL_COLOR_ARRAY)) - glColorPointer(4,GL_UNSIGNED_BYTE,vtxstride,vertexarray->getRGBA()); - - //if(m_Lock) - // local->Begin(vertexarrays[vt]->size()); // here the actual drawing takes places - glDrawElements(drawmode,numindices,GL_UNSIGNED_SHORT,&(indexarray[0])); - - //if(m_Lock) - // local->End(); + glDrawElements(drawmode, it.totindex, GL_UNSIGNED_SHORT, it.index); + } + + if(!wireframe) { + glDisableClientState(GL_TEXTURE_COORD_ARRAY); + glDisableClientState(GL_COLOR_ARRAY); + } +} + +void RAS_VAOpenGLRasterizer::IndexPrimitivesMulti(RAS_MeshSlot& ms) +{ + static const GLsizei stride = sizeof(RAS_TexVert); + bool wireframe = m_drawingmode <= KX_WIREFRAME; + RAS_MeshSlot::iterator it; + GLenum drawmode; + + if(!wireframe) + EnableTextures(true); + + // use glDrawElements to draw each vertexarray + for(ms.begin(it); !ms.end(it); ms.next(it)) { + if(it.totindex == 0) + continue; + + // drawing mode + if(it.array->m_type == RAS_DisplayArray::TRIANGLE) + drawmode = GL_TRIANGLES; + else if(it.array->m_type == RAS_DisplayArray::QUAD) + drawmode = GL_QUADS; + else + drawmode = GL_LINES; + + // colors + if (drawmode != GL_LINES && !wireframe) { + if (ms.m_bObjectColor) { + const MT_Vector4& rgba = ms.m_RGBAcolor; + + glDisableClientState(GL_COLOR_ARRAY); + glColor4d(rgba[0], rgba[1], rgba[2], rgba[3]); + } + else { + glColor4f(0.0f, 0.0f, 0.0f, 1.0f); + glEnableClientState(GL_COLOR_ARRAY); + } + } + else + glColor4f(0.0f, 0.0f, 0.0f, 1.0f); + + glVertexPointer(3, GL_FLOAT, stride, it.vertex->getXYZ()); + glNormalPointer(GL_FLOAT, stride, it.vertex->getNormal()); + if(!wireframe) { + TexCoordPtr(it.vertex); + if(glIsEnabled(GL_COLOR_ARRAY)) + glColorPointer(4, GL_UNSIGNED_BYTE, stride, it.vertex->getRGBA()); + } + + // here the actual drawing takes places + glDrawElements(drawmode, it.totindex, GL_UNSIGNED_SHORT, it.index); + } + + if(!wireframe) { + glDisableClientState(GL_COLOR_ARRAY); + EnableTextures(false); } } @@ -248,7 +229,7 @@ void RAS_VAOpenGLRasterizer::TexCoordPtr(const RAS_TexVert *tv) for(unit=0; unitgetFlag() & TV_2NDUV && (int)tv->getUnit() == unit) { + if(tv->getFlag() & RAS_TexVert::SECOND_UV && (int)tv->getUnit() == unit) { glEnableClientState(GL_TEXTURE_COORD_ARRAY); glTexCoordPointer(2, GL_FLOAT, sizeof(RAS_TexVert), tv->getUV2()); continue; @@ -257,7 +238,7 @@ void RAS_VAOpenGLRasterizer::TexCoordPtr(const RAS_TexVert *tv) { case RAS_TEXCO_ORCO: case RAS_TEXCO_GLOB: - glTexCoordPointer(3, GL_FLOAT, sizeof(RAS_TexVert),tv->getLocalXYZ()); + glTexCoordPointer(3, GL_FLOAT, sizeof(RAS_TexVert),tv->getXYZ()); break; case RAS_TEXCO_UV1: glTexCoordPointer(2, GL_FLOAT, sizeof(RAS_TexVert),tv->getUV1()); @@ -284,7 +265,7 @@ void RAS_VAOpenGLRasterizer::TexCoordPtr(const RAS_TexVert *tv) switch(m_attrib[unit]) { case RAS_TEXCO_ORCO: case RAS_TEXCO_GLOB: - glVertexAttribPointerARB(unit, 3, GL_FLOAT, GL_FALSE, sizeof(RAS_TexVert), tv->getLocalXYZ()); + glVertexAttribPointerARB(unit, 3, GL_FLOAT, GL_FALSE, sizeof(RAS_TexVert), tv->getXYZ()); break; case RAS_TEXCO_UV1: glVertexAttribPointerARB(unit, 2, GL_FLOAT, GL_FALSE, sizeof(RAS_TexVert), tv->getUV1()); @@ -313,11 +294,6 @@ void RAS_VAOpenGLRasterizer::EnableTextures(bool enable) TexCoGen *texco, *attrib; int unit, texco_num, attrib_num; - /* disable previously enabled texture coordinates and attributes. ideally - * this shouldn't be necessary .. */ - if(enable) - EnableTextures(false); - /* we cache last texcoords and attribs to ensure we disable the ones that * were actually last set */ if(enable) { diff --git a/source/gameengine/Rasterizer/RAS_OpenGLRasterizer/RAS_VAOpenGLRasterizer.h b/source/gameengine/Rasterizer/RAS_OpenGLRasterizer/RAS_VAOpenGLRasterizer.h index e4cc4ace0e8..766bbfbed0e 100644 --- a/source/gameengine/Rasterizer/RAS_OpenGLRasterizer/RAS_VAOpenGLRasterizer.h +++ b/source/gameengine/Rasterizer/RAS_OpenGLRasterizer/RAS_VAOpenGLRasterizer.h @@ -50,22 +50,10 @@ public: virtual void SetDrawingMode(int drawingmode); - virtual void IndexPrimitives( const vecVertexArray& vertexarrays, - const vecIndexArrays & indexarrays, - DrawMode mode, - bool useObjectColor, - const MT_Vector4& rgbacolor, - class KX_ListSlot** slot); - - virtual void IndexPrimitivesMulti( - const vecVertexArray& vertexarrays, - const vecIndexArrays & indexarrays, - DrawMode mode, - bool useObjectColor, - const MT_Vector4& rgbacolor, - class KX_ListSlot** slot); - + virtual void IndexPrimitives(class RAS_MeshSlot& ms); + virtual void IndexPrimitivesMulti(class RAS_MeshSlot& ms); +private: virtual void EnableTextures(bool enable); //virtual bool QueryArrays(){return true;} //virtual bool QueryLists(){return m_Lock;} diff --git a/source/gameengine/Rasterizer/RAS_OpenGLRasterizer/SConscript b/source/gameengine/Rasterizer/RAS_OpenGLRasterizer/SConscript index 0cf9c326370..8d46528f7f0 100644 --- a/source/gameengine/Rasterizer/RAS_OpenGLRasterizer/SConscript +++ b/source/gameengine/Rasterizer/RAS_OpenGLRasterizer/SConscript @@ -1,12 +1,9 @@ #!/usr/bin/python Import ('env') -if env['WITH_BF_GLEXT'] == 1: - env['CPPFLAGS'].append('-DWITH_GLEXT') - sources = env.Glob('*.cpp') incs = '. #source/kernel/gen_system #intern/string #intern/moto/include #source/gameengine/Rasterizer #source/gameengine/BlenderRoutines ' -incs += ' #extern/glew/include ' + env['BF_OPENGL_INC'] +incs += ' #source/blender/gpu #extern/glew/include ' + env['BF_OPENGL_INC'] env.BlenderLib ( 'bf_oglrasterizer', Split(sources), Split(incs), [], libtype=['game','player'], priority=[40, 120] ) diff --git a/source/gameengine/Rasterizer/RAS_Polygon.cpp b/source/gameengine/Rasterizer/RAS_Polygon.cpp index b74cb9cfcac..50331d7a664 100644 --- a/source/gameengine/Rasterizer/RAS_Polygon.cpp +++ b/source/gameengine/Rasterizer/RAS_Polygon.cpp @@ -26,99 +26,82 @@ * ***** END GPL LICENSE BLOCK ***** */ -#ifdef HAVE_CONFIG_H -#include -#endif - #ifdef WIN32 - #pragma warning (disable:4786) #endif #include "RAS_Polygon.h" -RAS_Polygon::RAS_Polygon(RAS_MaterialBucket* bucket, - bool visible, - int numverts, - int vtxarrayindex) - :m_bucket(bucket), - m_vertexindexbase(numverts), - m_numverts(numverts), - m_edgecode(65535) +RAS_Polygon::RAS_Polygon(RAS_MaterialBucket* bucket, RAS_DisplayArray *darray, int numvert) { - m_vertexindexbase.m_vtxarray = vtxarrayindex ;//m_bucket->FindVertexArray(numverts); - m_polyFlags.Visible = visible; + m_bucket = bucket; + m_darray = darray; + m_offset[0]= m_offset[1]= m_offset[2]= m_offset[3]= 0; + m_numvert = numvert; + + m_edgecode = 255; + m_polyflags = 0; } - - int RAS_Polygon::VertexCount() { - return m_numverts; + return m_numvert; } - - -void RAS_Polygon::SetVertex(int i, - unsigned int vertexindex ) //const MT_Point3& xyz,const MT_Point2& uv,const unsigned int rgbacolor,const MT_Vector3& normal) +void RAS_Polygon::SetVertexOffset(int i, unsigned short offset) { - m_vertexindexbase.SetIndex(i,vertexindex); //m_bucket->FindOrAddVertex(m_vertexindexbase.m_vtxarray, - //xyz,uv,rgbacolor,normal)); + m_offset[i] = offset; } - - -const KX_VertexIndex& RAS_Polygon::GetIndexBase() +RAS_TexVert *RAS_Polygon::GetVertex(int i) { - return m_vertexindexbase; + return &m_darray->m_vertex[m_offset[i]]; } - - -void RAS_Polygon::SetVisibleWireframeEdges(int edgecode) +int RAS_Polygon::GetVertexOffset(int i) { - m_edgecode = edgecode; + return m_offset[i]; } - - -// each bit is for a visible edge, starting with bit 1 for the first edge, bit 2 for second etc. int RAS_Polygon::GetEdgeCode() { return m_edgecode; } +void RAS_Polygon::SetEdgeCode(int edgecode) +{ + m_edgecode = edgecode; +} bool RAS_Polygon::IsVisible() { - return m_polyFlags.Visible; + return (m_polyflags & VISIBLE) != 0; } - +void RAS_Polygon::SetVisible(bool visible) +{ + if(visible) m_polyflags |= VISIBLE; + else m_polyflags &= ~VISIBLE; +} bool RAS_Polygon::IsCollider() { - return m_polyFlags.Collider; + return (m_polyflags & COLLIDER) != 0; } - - -void RAS_Polygon::SetCollider(bool col) +void RAS_Polygon::SetCollider(bool visible) { - m_polyFlags.Collider = col; + if(visible) m_polyflags |= COLLIDER; + else m_polyflags &= ~COLLIDER; } - - -KX_VertexIndex& RAS_Polygon::GetVertexIndexBase() -{ - return m_vertexindexbase; -} - - - -RAS_MaterialBucket* RAS_Polygon::GetMaterial() +RAS_MaterialBucket* RAS_Polygon::GetMaterial() { return m_bucket; } + +RAS_DisplayArray* RAS_Polygon::GetDisplayArray() +{ + return m_darray; +} diff --git a/source/gameengine/Rasterizer/RAS_Polygon.h b/source/gameengine/Rasterizer/RAS_Polygon.h index 7ce7926a816..18526ba45f7 100644 --- a/source/gameengine/Rasterizer/RAS_Polygon.h +++ b/source/gameengine/Rasterizer/RAS_Polygon.h @@ -35,55 +35,47 @@ #include using namespace std; - -// -// Bitfield that stores the flags for each CValue derived class -// -struct PolygonFlags { - PolygonFlags() : - Visible(true), - Collider(true) - { - } - unsigned char Visible : 1; - unsigned char Collider : 1; - //int Visible : 1; - //int Collider : 1; -}; +/* polygon flags */ class RAS_Polygon { + /* location */ RAS_MaterialBucket* m_bucket; - KX_VertexIndex m_vertexindexbase; - int m_numverts; - int m_edgecode; - PolygonFlags m_polyFlags; - + RAS_DisplayArray* m_darray; + unsigned short m_offset[4]; + unsigned short m_numvert; + + /* flags */ + unsigned char m_edgecode; + unsigned char m_polyflags; public: - RAS_Polygon(RAS_MaterialBucket* bucket, - bool visible, - int numverts, - int vtxarrayindex) ; + enum { + VISIBLE = 1, + COLLIDER = 2 + }; + + RAS_Polygon(RAS_MaterialBucket* bucket, RAS_DisplayArray* darray, int numvert); virtual ~RAS_Polygon() {}; -// RAS_TexVert* GetVertex(int index); int VertexCount(); - void SetVertex(int i, unsigned int vertexindex); //const MT_Point3& xyz,const MT_Point2& uv,const unsigned int rgbacolor,const MT_Vector3& normal) - - const KX_VertexIndex& GetIndexBase(); + RAS_TexVert* GetVertex(int i); - void SetVisibleWireframeEdges(int edgecode); + void SetVertexOffset(int i, unsigned short offset); + int GetVertexOffset(int i); + // each bit is for a visible edge, starting with bit 1 for the first edge, bit 2 for second etc. int GetEdgeCode(); + void SetEdgeCode(int edgecode); bool IsVisible(); + void SetVisible(bool visible); + bool IsCollider(); - void SetCollider(bool col); + void SetCollider(bool collider); - KX_VertexIndex& GetVertexIndexBase(); RAS_MaterialBucket* GetMaterial(); - + RAS_DisplayArray* GetDisplayArray(); }; #endif diff --git a/source/gameengine/Rasterizer/RAS_TexVert.cpp b/source/gameengine/Rasterizer/RAS_TexVert.cpp index 935633dc636..d6f1fe912be 100644 --- a/source/gameengine/Rasterizer/RAS_TexVert.cpp +++ b/source/gameengine/Rasterizer/RAS_TexVert.cpp @@ -27,12 +27,7 @@ */ #include "RAS_TexVert.h" - -#ifdef HAVE_CONFIG_H -#include -#endif - -#define SHORT(x) short(x*32767.0) +#include "MT_Matrix4x4.h" RAS_TexVert::RAS_TexVert(const MT_Point3& xyz, const MT_Point2& uv, @@ -40,7 +35,7 @@ RAS_TexVert::RAS_TexVert(const MT_Point3& xyz, const MT_Vector4& tangent, const unsigned int rgba, const MT_Vector3& normal, - const short flag, + const bool flat, const unsigned int origindex) { xyz.getValue(m_localxyz); @@ -49,7 +44,7 @@ RAS_TexVert::RAS_TexVert(const MT_Point3& xyz, SetRGBA(rgba); SetNormal(normal); tangent.getValue(m_tangent); - m_flag = flag; + m_flag = (flat)? FLAT: 0; m_origindex = origindex; m_unit = 2; } @@ -101,7 +96,7 @@ void RAS_TexVert::SetFlag(const short flag) void RAS_TexVert::SetUnit(const unsigned int u) { - m_unit = u<=TV_MAX?u:TV_MAX; + m_unit = u<=MAX_UNIT?u:MAX_UNIT; } void RAS_TexVert::SetNormal(const MT_Vector3& normal) @@ -109,12 +104,18 @@ void RAS_TexVert::SetNormal(const MT_Vector3& normal) normal.getValue(m_normal); } +void RAS_TexVert::SetTangent(const MT_Vector3& tangent) +{ + tangent.getValue(m_tangent); +} + // compare two vertices, and return TRUE if both are almost identical (they can be shared) bool RAS_TexVert::closeTo(const RAS_TexVert* other) { return (m_flag == other->m_flag && m_rgba == other->m_rgba && MT_fuzzyEqual(MT_Vector3(m_normal), MT_Vector3(other->m_normal)) && + MT_fuzzyEqual(MT_Vector3(m_tangent), MT_Vector3(other->m_tangent)) && MT_fuzzyEqual(MT_Vector2(m_uv1), MT_Vector2(other->m_uv1)) && MT_fuzzyEqual(MT_Vector2(m_uv2), MT_Vector2(other->m_uv2)) && // p -- MT_fuzzyEqual(MT_Vector3(m_localxyz), MT_Vector3(other->m_localxyz))) ; @@ -131,11 +132,10 @@ unsigned int RAS_TexVert::getUnit() const return m_unit; } - -void RAS_TexVert::getOffsets(void* &xyz, void* &uv1, void* &rgba, void* &normal) const +void RAS_TexVert::Transform(const MT_Matrix4x4& mat, const MT_Matrix4x4& nmat) { - xyz = (void *) m_localxyz; - uv1 = (void *) m_uv1; - rgba = (void *) &m_rgba; - normal = (void *) m_normal; + SetXYZ((mat*MT_Vector4(m_localxyz[0], m_localxyz[1], m_localxyz[2], 1.0)).getValue()); + SetNormal((nmat*MT_Vector4(m_normal[0], m_normal[1], m_normal[2], 1.0)).getValue()); + SetTangent((nmat*MT_Vector4(m_tangent[0], m_tangent[1], m_tangent[2], 1.0)).getValue()); } + diff --git a/source/gameengine/Rasterizer/RAS_TexVert.h b/source/gameengine/Rasterizer/RAS_TexVert.h index bf092b4b230..4ec4db19e53 100644 --- a/source/gameengine/Rasterizer/RAS_TexVert.h +++ b/source/gameengine/Rasterizer/RAS_TexVert.h @@ -37,11 +37,6 @@ static MT_Point3 g_pt3; static MT_Point2 g_pt2; -#define TV_CALCFACENORMAL 0x0001 -#define TV_2NDUV 0x0002 - -#define TV_MAX 3//match Def in BL_Material.h - class RAS_TexVert { @@ -59,6 +54,12 @@ class RAS_TexVert // 32 bytes total size, fits nice = 56 = not fit nice. // We'll go for 64 bytes total size - 24 bytes left. public: + enum { + FLAT = 1, + SECOND_UV = 2, + MAX_UNIT = 8 + }; + short getFlag() const; unsigned int getUnit() const; @@ -70,7 +71,7 @@ public: const MT_Vector4& tangent, const unsigned int rgba, const MT_Vector3& normal, - const short flag, + const bool flat, const unsigned int origindex); ~RAS_TexVert() {}; @@ -82,7 +83,7 @@ public: return m_uv2; }; - const float* getLocalXYZ() const { + const float* getXYZ() const { return m_localxyz; }; @@ -108,20 +109,19 @@ public: void SetRGBA(const unsigned int rgba); void SetNormal(const MT_Vector3& normal); + void SetTangent(const MT_Vector3& tangent); void SetFlag(const short flag); void SetUnit(const unsigned u); void SetRGBA(const MT_Vector4& rgba); const MT_Point3& xyz(); - // compare two vertices, and return TRUE if both are almost identical (they can be shared) - bool closeTo(const RAS_TexVert* other); + void Transform(const class MT_Matrix4x4& mat, + const class MT_Matrix4x4& nmat); - bool closeTo(const MT_Point3& otherxyz, - const MT_Point2& otheruv, - const unsigned int otherrgba, - short othernormal[3]) const; - void getOffsets(void*&xyz, void *&uv1, void *&rgba, void *&normal) const; + // compare two vertices, to test if they can be shared, used for + // splitting up based on uv's, colors, etc + bool closeTo(const RAS_TexVert* other); }; #endif //__RAS_TEXVERT diff --git a/source/gameengine/Rasterizer/SConscript b/source/gameengine/Rasterizer/SConscript index e6bc657ed6d..a024f7e0ee6 100644 --- a/source/gameengine/Rasterizer/SConscript +++ b/source/gameengine/Rasterizer/SConscript @@ -3,11 +3,8 @@ Import ('env') sources = env.Glob('*.cpp') -if env['WITH_BF_GLEXT'] == 1: - env['CPPFLAGS'].append('-DWITH_GLEXT') - -incs = '. #source/kernel/gen_system #intern/string #intern/moto/include #source/gameengine/BlenderRoutines #extern/glew/include #source/gameengine/Expressions' +incs = '. #source/kernel/gen_system #intern/string #intern/moto/include #source/gameengine/BlenderRoutines #extern/glew/include #source/gameengine/Expressions #source/blender/blenkernel #source/blender/makesdna' incs += ' ' + env['BF_PYTHON_INC'] if env['OURPLATFORM']=='win32-vc': diff --git a/source/kernel/gen_system/GEN_Map.h b/source/kernel/gen_system/GEN_Map.h index 37c75d8293a..88c79293223 100644 --- a/source/kernel/gen_system/GEN_Map.h +++ b/source/kernel/gen_system/GEN_Map.h @@ -50,6 +50,19 @@ public: m_buckets[i] = 0; } } + + GEN_Map(const GEN_Map& map) + { + m_num_buckets = map.m_num_buckets; + m_buckets = new Entry *[m_num_buckets]; + + for (int i = 0; i < m_num_buckets; ++i) { + m_buckets[i] = 0; + + for(Entry *entry = map.m_buckets[i]; entry; entry=entry->m_next) + insert(entry->m_key, entry->m_value); + } + } int size() { int count=0; diff --git a/source/nan_definitions.mk b/source/nan_definitions.mk index 6200d430dd4..424a7c558d7 100644 --- a/source/nan_definitions.mk +++ b/source/nan_definitions.mk @@ -56,9 +56,6 @@ all debug:: # Object Config_Guess DIRectory export OCGDIR = $(NAN_OBJDIR)/$(CONFIG_GUESS) - export WITH_GLEXT?=true - export WITH_BF_GLEXT?=$(WITH_GLEXT) - # Determines what targets are built export WITH_BF_DYNAMICOPENGL ?= true export WITH_BF_STATICOPENGL ?= false diff --git a/tools/btools.py b/tools/btools.py index a25120f6c4b..3974d582640 100755 --- a/tools/btools.py +++ b/tools/btools.py @@ -51,7 +51,6 @@ def validate_arguments(args, bc): 'WITH_BF_STATICOPENGL', 'BF_OPENGL', 'BF_OPENGL_INC', 'BF_OPENGL_LIB', 'BF_OPENGL_LIBPATH', 'BF_OPENGL_LIB_STATIC', 'BF_OPENGL_LINKFLAGS', 'WITH_BF_FTGL', 'BF_FTGL', 'BF_FTGL_INC', 'BF_FTGL_LIB', 'WITH_BF_PLAYER', - 'WITH_BF_GLEXT', 'WITH_BF_BINRELOC', 'CFLAGS', 'CCFLAGS', 'CPPFLAGS', 'REL_CFLAGS', 'REL_CCFLAGS', @@ -292,7 +291,6 @@ def read_opts(cfg, args): ('BF_FTGL_INC', 'FTGL include path', ''), ('BF_FTGL_LIB', 'FTGL libraries', ''), - (BoolOption('WITH_BF_GLEXT', 'Enable GL Extensions', 'true')), (BoolOption('WITH_BF_PLAYER', 'Build blenderplayer if true', 'false')), ('CFLAGS', 'C-compiler flags', ''),