/**
  * moves soft body nodes and restores shape to modeled shape in current location,rotation
  */
 public void ResetNodesAfterTeleportJump(Vector3 jumpOffset)
 {
     if (m_collisionObject != null)
     {
         if (physicsSimMesh == null)
         {
             Debug.LogError("MeshFilter was null trying ResetNodesAfterTeleportJump.");
             return;
         }
         SoftBody sb = (SoftBody)m_collisionObject;
         for (int i = 0; i < sb.Nodes.Count; i++)
         {
             sb.Nodes[i].Position += jumpOffset.ToBullet(); //verts[i].ToBullet();
             //sb.Nodes[i].Normal = norms[i].ToBullet();
             //TODO deal with rotation
         }
         //sb.Rotate(physicsSimMesh.transform.rotation.ToBullet());
         //sb.Translate(physicsSimMesh.transform.position.ToBullet());
     }
 }
Exemplo n.º 2
0
        /// <summary>
        /// Shifts the robot by a set position vector
        /// </summary>
        public void TranslateRobot(Vector3 transposition)
        {
            foreach (RigidNode n in RootNode.ListAllNodes())
            {
                BRigidBody br = n.MainObject.GetComponent <BRigidBody>();

                if (br == null)
                {
                    continue;
                }

                RigidBody r = (RigidBody)br.GetCollisionObject();

                BulletSharp.Math.Matrix newTransform = r.WorldTransform;
                newTransform.Origin += transposition.ToBullet();
                r.WorldTransform     = newTransform;
            }

            OnTransposeRobot(transposition);
        }
Exemplo n.º 3
0
 public override CollisionShape GetCollisionShape()
 {
     if (collisionShapePtr == null)
     {
         Vector3[] verts = hullMesh.vertices;
         int[]     tris  = hullMesh.triangles;
         //todo test for convex. Make convex if not.
         TriangleMesh tm = new TriangleMesh();
         for (int i = 0; i < tris.Length; i += 3)
         {
             tm.AddTriangle(verts[tris[i]].ToBullet(),
                            verts[tris[i + 1]].ToBullet(),
                            verts[tris[i + 2]].ToBullet(),
                            true);
         }
         collisionShapePtr = new ConvexTriangleMeshShape(tm);
         ((ConvexTriangleMeshShape)collisionShapePtr).LocalScaling = m_localScaling.ToBullet();
     }
     return(collisionShapePtr);
 }
        private ConvexHullShape _CreateConvexHullShape()
        {
            Vector3[] verts = hullMesh.vertices;
            //todo remove duplicate verts
            //todo use vertex reduction utility
            float[] points = new float[verts.Length * 3];
            for (int i = 0; i < verts.Length; i++)
            {
                int idx = i * 3;
                points[idx]     = verts[i].x;
                points[idx + 1] = verts[i].y;
                points[idx + 2] = verts[i].z;
            }

            ConvexHullShape cs = new ConvexHullShape(points);

            cs.LocalScaling = m_localScaling.ToBullet();

            return(cs);
        }
Exemplo n.º 5
0
        protected override void _InitializePhysicsWorld()
        {
            base._InitializePhysicsWorld();

            if (collisionType == CollisionConfType.DefaultDynamicsWorldCollisionConf)
            {
                CollisionConf = new DefaultCollisionConfiguration();
            }
            else if (collisionType == CollisionConfType.SoftBodyRigidBodyCollisionConf)
            {
                CollisionConf = new SoftBodyRigidBodyCollisionConfiguration();
            }

            Dispatcher = new CollisionDispatcher(CollisionConf);

            if (broadphaseType == BroadphaseType.DynamicAABBBroadphase)
            {
                Broadphase = new DbvtBroadphase();
            }
            else if (broadphaseType == BroadphaseType.Axis3SweepBroadphase)
            {
                Broadphase = new AxisSweep3(axis3SweepBroadphaseMin.ToBullet(), axis3SweepBroadphaseMax.ToBullet(), axis3SweepMaxProxies);
            }
            else if (broadphaseType == BroadphaseType.Axis3SweepBroadphase_32bit)
            {
                Broadphase = new AxisSweep3_32Bit(axis3SweepBroadphaseMin.ToBullet(), axis3SweepBroadphaseMax.ToBullet(), axis3SweepMaxProxies);
            }
            else
            {
                Broadphase = new SimpleBroadphase();
            }

            World         = new DiscreteDynamicsWorld(Dispatcher, Broadphase, null, CollisionConf);
            World.Gravity = gravity.ToBullet();
            if (_doDebugDraw)
            {
                DebugDrawUnity db = new DebugDrawUnity();
                db.DebugMode      = _debugDrawMode;
                World.DebugDrawer = db;
            }
        }
        private ConvexTriangleMeshShape _CreateConvexTriangleMeshShape()
        {
            Vector3[] verts = hullMesh.vertices;
            int[]     tris  = hullMesh.triangles;
            //todo test for convex. Make convex if not.
            TriangleMesh tm = new TriangleMesh();

            for (int i = 0; i < tris.Length; i += 3)
            {
                tm.AddTriangle(verts[tris[i]].ToBullet(),
                               verts[tris[i + 1]].ToBullet(),
                               verts[tris[i + 2]].ToBullet(),
                               true);
            }

            ConvexTriangleMeshShape ms = new ConvexTriangleMeshShape(tm);

            ms.LocalScaling = m_localScaling.ToBullet();

            return(ms);
        }
Exemplo n.º 7
0
        public static bool Raycast(Vector3 source, Vector3 direction, float maxDistance, out RaycastHitInfo info)
        {
            BulletVector3 Bdestination = (source + (direction * maxDistance)).ToBullet();

            BulletVector3 Bsource = source.ToBullet();

            using (var cb = new ClosestRayResultCallback(ref Bsource, ref Bdestination))
            {
                _contextWorld.RayTestRef(ref Bsource, ref Bdestination, cb);
                if (cb.HasHit)
                {
                    info = new RaycastHitInfo(cb.HitPointWorld.ToNumerics(), Vector3.Normalize(cb.HitNormalWorld.ToNumerics()), (RigidBodyComponent)cb.CollisionObject.UserObject);
                    return(true);
                }
                else
                {
                    info = new RaycastHitInfo(Bdestination.ToNumerics(), new Vector3(1.0f, 0.0f, 0.0f), null);
                    return(false);
                }
            }
        }
        //called by Physics World just before constraint is added to world.
        //the current constraint properties are used to rebuild the constraint.
        internal override bool _BuildConstraint()
        {
            BPhysicsWorld world = BPhysicsWorld.Get();

            if (constraintPtr != null)
            {
                if (isInWorld && world != null)
                {
                    isInWorld = false;
                    world.RemoveConstraint(constraintPtr);
                }
            }
            if (targetRigidBodyA == null)
            {
                Debug.LogError("Constraint target rigid body was not set.");
                return(false);
            }

            RigidBody rba = (RigidBody)targetRigidBodyA.GetCollisionObject();

            if (rba == null)
            {
                Debug.LogError("Constraint could not get bullet RigidBody from target rigid body");
                return(false);
            }

            RigidBody rbb = (RigidBody)targetRigidBodyB.GetCollisionObject();

            if (rbb == null)
            {
                Debug.LogError("Constraint could not get bullet RigidBody from target rigid body");
                return(false);
            }
            BulletSharp.Math.Matrix frameInA = BulletSharp.Math.Matrix.Translation(localPointInA.ToBullet());
            BulletSharp.Math.Matrix frameInB = BulletSharp.Math.Matrix.Translation(localPointInB.ToBullet());
            constraintPtr            = new FixedConstraint(rba, rbb, frameInA, frameInB);
            constraintPtr.Userobject = this;

            return(true);
        }
Exemplo n.º 9
0
        public bool CreateFrame(Vector3 forward, Vector3 up, Vector3 constraintPoint, ref BM.Matrix m, ref string errorMsg)
        {
            BM.Vector4 x;
            BM.Vector4 y;
            BM.Vector4 z;
            if (forward == Vector3.zero)
            {
                errorMsg = "forward vector must not be zero";
                return(false);
            }

            forward.Normalize();
            if (up == Vector3.zero)
            {
                errorMsg = "up vector must not be zero";
                return(false);
            }

            Vector3 right = Vector3.Cross(forward, up);

            if (right == Vector3.zero)
            {
                errorMsg = "forward and up vector must not be colinear";
                return(false);
            }

            up = Vector3.Cross(right, forward);
            right.Normalize();
            up.Normalize();
            x.X      = forward.x; x.Y = forward.y; x.Z = forward.z; x.W = 0f;
            y.X      = up.x; y.Y = up.y; y.Z = up.z; y.W = 0f;
            z.X      = right.x; z.Y = right.y; z.Z = right.z; z.W = 0f;
            m.Row1   = x;
            m.Row2   = y;
            m.Row3   = z;
            m.Origin = constraintPoint.ToBullet();

            return(true);
        }
Exemplo n.º 10
0
        /// <summary>
        /// Called when the robot is moved.
        /// </summary>
        /// <param name="transposition"></param>
        protected override void OnTransposeRobot(Vector3 transposition)
        {
            if (!RobotHasManipulator)
            {
                return;
            }

            foreach (RigidNode n in manipulatorNode.ListAllNodes())
            {
                BRigidBody br = n.MainObject.GetComponent <BRigidBody>();

                if (br == null)
                {
                    continue;
                }

                RigidBody r = (RigidBody)br.GetCollisionObject();

                BulletSharp.Math.Matrix newTransform = r.WorldTransform;
                newTransform.Origin += transposition.ToBullet();
                r.WorldTransform     = newTransform;
            }
        }
Exemplo n.º 11
0
        CapsuleShape _CreateCapsuleShape()
        {
            CapsuleShape cs = null;

            if (upAxis == CapsuleAxis.x)
            {
                cs = new CapsuleShapeX(radius, height);
            }
            else if (upAxis == CapsuleAxis.y)
            {
                cs = new CapsuleShape(radius, height);
            }
            else if (upAxis == CapsuleAxis.z)
            {
                cs = new CapsuleShapeZ(radius, height);
            }
            else
            {
                Log.Warning("invalid axis value");
            }
            cs.LocalScaling = m_localScaling.ToBullet();
            return(cs);
        }
Exemplo n.º 12
0
        /// <summary>
        /// Apply these SoftBody settings to this SoftBody
        /// </summary>
        /// <param name="softBody"></param>
        public void ConfigureSoftBody(SoftBody softBody)
        {
            softBody.Scale(scale.ToBullet());

            BulletSharp.SoftBody.Material pm = softBody.Materials[0];

            sBMaterial.SetSBMaterial(pm);

            config.CopyToBulletSBConfig(softBody.Cfg);

            if (allNodeBendingConstraints)
            {
                for (int i = 0; i < softBody.Nodes.Count - 1; ++i)
                {
                    softBody.GenerateBendingConstraints(1 + i);
                }
            }
            else
            {
                softBody.GenerateBendingConstraints(bendingConstraintDistance, pm);
            }

            if (randomizeConstraints)
            {
                softBody.RandomizeConstraints();
            }

            if (generateClusters)
            {
                softBody.GenerateClusters(0);
            }

            softBody.SetTotalMass(totalMass, fromFaces);

            softBody.SetPose(bvolume, bframe);
        }
Exemplo n.º 13
0
        private CapsuleShape _CreateCapsuleShape()
        {
            CapsuleShape cs = null;

            switch (upAxis)
            {
            default:
            case CapsuleAxis.x:
                cs = new CapsuleShapeX(radius, height);
                break;

            case CapsuleAxis.y:
                cs = new CapsuleShape(radius, height);
                break;

            case CapsuleAxis.z:
                cs = new CapsuleShapeZ(radius, height);
                break;
            }

            cs.LocalScaling = m_localScaling.ToBullet();

            return(cs);
        }
Exemplo n.º 14
0
 public static void lua_SetGravity(float x, float y = 0, float z = 0)
 {
     var g = new Vector3(x, y, z);
     BtEngineDynamicsWorld.Gravity = g.ToBullet();
     ConsoleInfo.Instance.Printf("gravity = {0}", g.ToStringEx(round: 3));
 }
Exemplo n.º 15
0
        public static void lua_PushEntityBody(int id, int bodyNumber, float hForce, float vForce, bool resetFlag)
        {
            var ent = EngineWorld.GetEntityByID((uint)id);
            // TODO: Add warning if null
            // TODO: Check bodyNumber > 0
            if (ent != null && bodyNumber < ent.Bf.BoneTags.Count && ent.Bt.BtBody[bodyNumber] != null &&
                ent.TypeFlags.HasFlag(ENTITY_TYPE.Dynamic))
            {
                var t = ent.Angles.X * RadPerDeg;

                var ang1 = (float) Math.Sin(t);
                var ang2 = (float) Math.Cos(t);

                var angle = new Vector3(-ang1 * hForce, ang2 * hForce, vForce);

                if (resetFlag)
                    ent.Bt.BtBody[bodyNumber].ClearForces();

                ent.Bt.BtBody[bodyNumber].LinearVelocity = angle.ToBullet();
                ent.Bt.BtBody[bodyNumber].AngularVelocity = (angle / 1024.0f).ToBullet();
            }
            else
            {
                ConsoleInfo.Instance.Warning(SYSWARN_CANT_APPLY_FORCE, id);
            }
        }
 // Object A has the constraint compontent and is constrainted to object B
 // The constraint frame is defined relative to A by three vectors.
 // This method calculates the frames A and B that need to be passed to bullet
 public bool CreateFramesA_B(UnityEngine.Vector3 forwardInA, UnityEngine.Vector3 upInA, UnityEngine.Vector3 constraintPivotInA, out BM.Matrix frameInA, out BM.Matrix frameInB, ref string errorMsg)
 {
     frameInA = BM.Matrix.Identity;
     if (!CreateFrame(forwardInA, upInA, constraintPivotInA, ref frameInA, ref errorMsg))
     {
         frameInB = BM.Matrix.Identity;
         return false;
     }
     BM.Vector4 x = frameInA.Row1;
     BM.Vector4 y = frameInA.Row2;
     BM.Vector4 z = frameInA.Row3;
     Vector3 xx = new Vector3(x.X, x.Y, x.Z);
     Vector3 yy = new Vector3(y.X, y.Y, y.Z);
     Vector3 zz = new Vector3(z.X, z.Y, z.Z);
     Quaternion q = transform.localRotation * Quaternion.Inverse(m_otherRigidBody.transform.localRotation);
     xx = q * xx;
     yy = q * yy;
     zz = q * zz;
     frameInB = BM.Matrix.Identity;
     frameInB.Row1 = new BM.Vector4(xx.ToBullet(), 0f);
     frameInB.Row2 = new BM.Vector4(yy.ToBullet(), 0f);
     frameInB.Row3 = new BM.Vector4(zz.ToBullet(), 0f);
     frameInB.Origin = m_otherRigidBody.transform.InverseTransformPoint(transform.TransformPoint(constraintPivotInA)).ToBullet();
     return true;
 }
Exemplo n.º 17
0
        /// <summary>
        /// Builds the constraint.
        /// </summary>
        /// <returns></returns>
        internal override bool _BuildConstraint()
        {
            BPhysicsWorld world = BPhysicsWorld.Get();

            if (m_constraintPtr != null)
            {
                if (m_isInWorld && world != null)
                {
                    m_isInWorld = false;
                    world.RemoveConstraint(m_constraintPtr);
                }
            }
            BRigidBody targetRigidBodyA = GetComponent <BRigidBody>();

            if (targetRigidBodyA == null)
            {
                Debug.LogError("BHingedConstraint needs to be added to a component with a BRigidBody.");
                return(false);
            }
            if (!targetRigidBodyA.isInWorld)
            {
                world.AddRigidBody(targetRigidBodyA);
            }
            if (m_localConstraintAxisX == Vector3.zero)
            {
                Debug.LogError("Constaint axis cannot be zero vector");
                return(false);
            }
            RigidBody rba = (RigidBody)targetRigidBodyA.GetCollisionObject();

            if (rba == null)
            {
                Debug.LogError("Constraint could not get bullet RigidBody from target rigid body");
                return(false);
            }
            if (m_constraintType == ConstraintType.constrainToAnotherBody)
            {
                if (m_otherRigidBody == null)
                {
                    Debug.LogError("Other rigid body must not be null");
                    return(false);
                }
                if (!m_otherRigidBody.isInWorld)
                {
                    world.AddRigidBody(m_otherRigidBody);
                }
                RigidBody rbb = (RigidBody)m_otherRigidBody.GetCollisionObject();
                if (rbb == null)
                {
                    Debug.LogError("Constraint could not get bullet RigidBody from target rigid body");
                    return(false);
                }

                m_constraintPtr = new HingeConstraint(rba, rbb, m_localConstraintPoint.ToBullet(),
                                                      m_otherRigidBody.transform.InverseTransformPoint(transform.TransformPoint(m_localConstraintPoint)).ToBullet(),
                                                      m_axisInA.ToBullet(), m_axisInB.ToBullet());
            }
            else
            {
                m_constraintPtr = new HingeConstraint(rba, m_localConstraintPoint.ToBullet(), m_axisInA.ToBullet(), false);
            }
            if (m_enableMotor)
            {
                ((HingeConstraint)m_constraintPtr).EnableAngularMotor(true, m_targetMotorAngularVelocity, m_maxMotorImpulse);
            }
            if (m_setLimit)
            {
                ((HingeConstraint)m_constraintPtr).SetLimit(m_lowLimitAngleRadians, m_highLimitAngleRadians, m_limitSoftness, m_limitBiasFactor);
            }
            m_constraintPtr.Userobject                  = this;
            m_constraintPtr.DebugDrawSize               = m_debugDrawSize;
            m_constraintPtr.BreakingImpulseThreshold    = m_breakingImpulseThreshold;
            m_constraintPtr.OverrideNumSolverIterations = m_overrideNumSolverIterations;
            return(true);
        }
Exemplo n.º 18
0
        //called by Physics World just before constraint is added to world.
        //the current constraint properties are used to rebuild the constraint.
        internal override bool _BuildConstraint()
        {
            BPhysicsWorld world = BPhysicsWorld.Get();

            if (constraintPtr != null)
            {
                if (isInWorld && world != null)
                {
                    isInWorld = false;
                    world.RemoveConstraint(constraintPtr);
                }
            }
            if (targetRigidBodyA == null)
            {
                Debug.LogError("Constraint target rigid body was not set.");
                return(false);
            }

            RigidBody rba = targetRigidBodyA.GetRigidBody();

            if (rba == null)
            {
                Debug.LogError("Constraint could not get bullet RigidBody from target rigid body");
                return(false);
            }
            if (constraintType == ConstraintType.constrainToAnotherBody)
            {
                RigidBody rbb = targetRigidBodyB.GetRigidBody();
                if (rbb == null)
                {
                    Debug.LogError("Constraint could not get bullet RigidBody from target rigid body");
                    return(false);
                }

                BulletSharp.Math.Matrix frameInA = BulletSharp.Math.Matrix.AffineTransformation(1f, Quaternion.LookRotation(localForwardInA, localUpInA).ToBullet(), localPointInA.ToBullet());
                BulletSharp.Math.Matrix frameInB = BulletSharp.Math.Matrix.AffineTransformation(1f, Quaternion.LookRotation(localForwardInB, localUpInB).ToBullet(), localPointInB.ToBullet());
                constraintPtr = new Generic6DofConstraint(rba, rbb, frameInA, frameInB, false);
            }
            else
            {
                BulletSharp.Math.Matrix frameInA = BulletSharp.Math.Matrix.AffineTransformation(1f, Quaternion.LookRotation(localForwardInA, localUpInA).ToBullet(), localPointInA.ToBullet());
                constraintPtr = new Generic6DofConstraint(rba, frameInA, false);
            }
            Generic6DofConstraint sl = (Generic6DofConstraint)constraintPtr;

            sl.LinearLowerLimit  = linearLimitLower.ToBullet();
            sl.LinearUpperLimit  = linearLimitUpper.ToBullet();
            sl.AngularLowerLimit = angularLimitLower.ToBullet();
            sl.AngularUpperLimit = angularLimitUpper.ToBullet();
            sl.TranslationalLimitMotor.TargetVelocity = motorLinearTargetVelocity.ToBullet();
            sl.TranslationalLimitMotor.MaxMotorForce  = motorLinearMaxMotorForce.ToBullet();
            return(true);
        }
    public override void SetupLink(BulletSharp.Math.Vector3 linkInertia)
    {
        Quaternion parentToThisRotation = parentTransform.rotation * Quaternion.Inverse(transform.rotation);
        Vector3    linkPointInParent    = parentTransform.InverseTransformPoint(transform.position);
        Vector3    linkPointInPivot     = Pivot.transform.InverseTransformPoint(transform.position);

        MultiBody.MultiBody.SetupFixed(LinkId, Mass, linkInertia, ParentLinkId, parentToThisRotation.ToBullet(),
                                       (linkPointInParent - linkPointInPivot).ToBullet(), linkPointInPivot.ToBullet());
    }
Exemplo n.º 20
0
        protected virtual void _InitializePhysicsWorld()
        {
            _isDisposed = false;
            if (m_worldType == WorldType.SoftBodyAndRigidBody && m_collisionType == CollisionConfType.DefaultDynamicsWorldCollisionConf)
            {
                BDebug.LogError(debugType, "For World Type = SoftBodyAndRigidBody collisionType must be collisionType=SoftBodyRigidBodyCollisionConf. Switching");
                m_collisionType = CollisionConfType.SoftBodyRigidBodyCollisionConf;
            }

            if (m_collisionType == CollisionConfType.DefaultDynamicsWorldCollisionConf)
            {
                CollisionConf = new DefaultCollisionConfiguration();
            }
            else if (m_collisionType == CollisionConfType.SoftBodyRigidBodyCollisionConf)
            {
                CollisionConf = new SoftBodyRigidBodyCollisionConfiguration();
            }

            Dispatcher = new CollisionDispatcher(CollisionConf);

            if (m_broadphaseType == BroadphaseType.DynamicAABBBroadphase)
            {
                Broadphase = new DbvtBroadphase();
            }
            else if (m_broadphaseType == BroadphaseType.Axis3SweepBroadphase)
            {
                Broadphase = new AxisSweep3(m_axis3SweepBroadphaseMin.ToBullet(), m_axis3SweepBroadphaseMax.ToBullet(), axis3SweepMaxProxies);
            }
            else if (m_broadphaseType == BroadphaseType.Axis3SweepBroadphase_32bit)
            {
                Broadphase = new AxisSweep3_32Bit(m_axis3SweepBroadphaseMin.ToBullet(), m_axis3SweepBroadphaseMax.ToBullet(), axis3SweepMaxProxies);
            }
            else
            {
                Broadphase = null;
            }

            if (m_worldType == WorldType.CollisionOnly)
            {
                m_world  = new CollisionWorld(Dispatcher, Broadphase, CollisionConf);
                _ddWorld = null;
            }
            else if (m_worldType == WorldType.RigidBodyDynamics)
            {
                m_world  = new DiscreteDynamicsWorld(Dispatcher, Broadphase, null, CollisionConf);
                _ddWorld = (DiscreteDynamicsWorld)m_world;
            }
            else if (m_worldType == WorldType.MultiBodyWorld)
            {
                m_world  = new MultiBodyDynamicsWorld(Dispatcher, Broadphase, null, CollisionConf);
                _ddWorld = (DiscreteDynamicsWorld)m_world;
            }
            else if (m_worldType == WorldType.SoftBodyAndRigidBody)
            {
                Solver            = new SequentialImpulseConstraintSolver();
                Solver.RandSeed   = sequentialImpulseConstraintSolverRandomSeed;
                softBodyWorldInfo = new SoftBodyWorldInfo
                {
                    AirDensity   = 1.2f,
                    WaterDensity = 0,
                    WaterOffset  = 0,
                    WaterNormal  = BulletSharp.Math.Vector3.Zero,
                    Gravity      = UnityEngine.Physics.gravity.ToBullet(),
                    Dispatcher   = Dispatcher,
                    Broadphase   = Broadphase
                };
                softBodyWorldInfo.SparseSdf.Initialize();

                m_world  = new SoftRigidDynamicsWorld(Dispatcher, Broadphase, Solver, CollisionConf);
                _ddWorld = (DiscreteDynamicsWorld)m_world;

                m_world.DispatchInfo.EnableSpu = true;
                softBodyWorldInfo.SparseSdf.Reset();
                softBodyWorldInfo.AirDensity   = 1.2f;
                softBodyWorldInfo.WaterDensity = 0;
                softBodyWorldInfo.WaterOffset  = 0;
                softBodyWorldInfo.WaterNormal  = BulletSharp.Math.Vector3.Zero;
                softBodyWorldInfo.Gravity      = m_gravity.ToBullet();
            }
            if (_ddWorld != null)
            {
                _ddWorld.Gravity = m_gravity.ToBullet();
            }
            if (_doDebugDraw)
            {
                DebugDrawUnity db = new DebugDrawUnity();
                db.DebugMode        = _debugDrawMode;
                m_world.DebugDrawer = db;
            }
        }
        //called by Physics World just before constraint is added to world.
        //the current constraint properties are used to rebuild the constraint.
        internal override bool _BuildConstraint()
        {
            BPhysicsWorld world = BPhysicsWorld.Get();

            if (m_constraintPtr != null)
            {
                if (m_isInWorld && world != null)
                {
                    m_isInWorld = false;
                    world.RemoveConstraint(m_constraintPtr);
                }
            }
            BRigidBody targetRigidBodyA = GetComponent <BRigidBody>();

            if (targetRigidBodyA == null)
            {
                Debug.LogError("B6DOFConstraint needs to be added to a component with a BRigidBody.");
                return(false);
            }
            if (!targetRigidBodyA.isInWorld)
            {
                world.AddRigidBody(targetRigidBodyA);
            }

            RigidBody rba = (RigidBody)targetRigidBodyA.GetCollisionObject();

            if (rba == null)
            {
                Debug.LogError("Constraint could not get bullet RigidBody from target rigid body");
                return(false);
            }
            if (m_constraintType == ConstraintType.constrainToAnotherBody)
            {
                if (m_otherRigidBody == null)
                {
                    Debug.LogError("Other Rigid Body is not set.");
                    return(false);
                }
                if (!m_otherRigidBody.isInWorld)
                {
                    world.AddRigidBody(m_otherRigidBody);
                    return(false);
                }
                RigidBody rbb = (RigidBody)m_otherRigidBody.GetCollisionObject();
                if (rbb == null)
                {
                    Debug.LogError("Constraint could not get bullet RigidBody from target rigid body");
                    return(false);
                }

                BM.Matrix frameInA, frameInOther;
                string    errormsg = "";
                if (CreateFramesA_B(m_localConstraintAxisX, m_localConstraintAxisY, m_localConstraintPoint, out frameInA, out frameInOther, ref errormsg))
                {
                    m_constraintPtr = new Generic6DofConstraint(rbb, rba, frameInOther, frameInA, true);
                }
                else
                {
                    Debug.LogError(errormsg);
                    return(false);
                }
            }
            else
            {
                //TODO think about this
                BM.Matrix frameInA = BulletSharp.Math.Matrix.Identity;
                m_constraintPtr = new Generic6DofConstraint(rba, frameInA, false);
            }
            m_constraintPtr.Userobject = this;
            Generic6DofConstraint sl = (Generic6DofConstraint)m_constraintPtr;

            sl.LinearLowerLimit  = m_linearLimitLower.ToBullet();
            sl.LinearUpperLimit  = m_linearLimitUpper.ToBullet();
            sl.AngularLowerLimit = m_angularLimitLowerRadians.ToBullet();
            sl.AngularUpperLimit = m_angularLimitUpperRadians.ToBullet();
            sl.TranslationalLimitMotor.TargetVelocity = m_motorLinearTargetVelocity.ToBullet();
            sl.TranslationalLimitMotor.MaxMotorForce  = m_motorLinearMaxMotorForce.ToBullet();
            sl.BreakingImpulseThreshold = m_breakingImpulseThreshold;
            sl.DebugDrawSize            = m_debugDrawSize;
            return(true);
        }
        //called by Physics World just before constraint is added to world.
        //the current constraint properties are used to rebuild the constraint.
        internal override bool _BuildConstraint()
        {
            BPhysicsWorld world = BPhysicsWorld.Get();

            if (constraintPtr != null)
            {
                if (isInWorld && world != null)
                {
                    isInWorld = false;
                    world.RemoveConstraint(constraintPtr);
                }
            }
            if (targetRigidBodyA == null)
            {
                Debug.LogError("Constraint target rigid body was not set.");
                return(false);
            }
            if (localPivotAxisA == Vector3.zero)
            {
                Debug.LogError("Constaint axis cannot be zero vector");
                return(false);
            }
            RigidBody rba = (RigidBody)targetRigidBodyA.GetCollisionObject();

            if (rba == null)
            {
                Debug.LogError("Constraint could not get bullet RigidBody from target rigid body");
                return(false);
            }
            if (constraintType == ConstraintType.constrainToAnotherBody)
            {
                RigidBody rbb = (RigidBody)targetRigidBodyB.GetCollisionObject();
                if (rbb == null)
                {
                    Debug.LogError("Constraint could not get bullet RigidBody from target rigid body");
                    return(false);
                }
                constraintPtr = new HingeConstraint(rba, rbb, localPointOnHingeOffsetA.ToBullet(), localPointOnHingeOffsetB.ToBullet(), localPivotAxisA.ToBullet(), localPivotAxisB.ToBullet());
            }
            else
            {
                constraintPtr = new HingeConstraint(rba, localPointOnHingeOffsetA.ToBullet(), localPivotAxisA.ToBullet());
            }
            if (enableMotor)
            {
                ((HingeConstraint)constraintPtr).EnableAngularMotor(true, targetMotorAngularVelocity, maxMotorImpulse);
            }
            if (setLimit)
            {
                ((HingeConstraint)constraintPtr).SetLimit(lowLimitAngleRadians, highLimitAngleRadians, limitSoftness, limitBiasFactor);
            }
            constraintPtr.Userobject = this;
            return(true);
        }
Exemplo n.º 23
0
 public BulletSharp.Math.Matrix CreateBSMatrix()
 {
     return(BulletSharp.Math.Matrix.AffineTransformation(1f, Quaternion.LookRotation(forward, up).ToBullet(), pivotPoint.ToBullet()));
 }
Exemplo n.º 24
0
 public void Move(Vector3 displacement)
 {
     m_characterController.SetWalkDirection(displacement.ToBullet());
 }
        internal override bool _BuildConstraint()
        {
            BPhysicsWorld world = BPhysicsWorld.Get();

            if (m_constraintPtr != null)
            {
                if (m_isInWorld && world != null)
                {
                    m_isInWorld = false;
                    world.RemoveConstraint(m_constraintPtr);
                }
            }
            BRigidBody targetRigidBodyA = GetComponent <BRigidBody>();

            if (targetRigidBodyA == null)
            {
                Debug.LogError("BGeneric6DofSpringConstraint needs to be added to a component with a BRigidBody.");
                return(false);
            }
            if (!targetRigidBodyA.isInWorld)
            {
                world.AddRigidBody(targetRigidBodyA);
            }
            if (m_localConstraintAxisX == Vector3.zero)
            {
                Debug.LogError("Constaint axis cannot be zero vector");
                return(false);
            }
            RigidBody rba = (RigidBody)targetRigidBodyA.GetCollisionObject();

            if (rba == null)
            {
                Debug.LogError("Constraint could not get bullet RigidBody from target rigid body");
                return(false);
            }
            if (m_constraintType == ConstraintType.constrainToAnotherBody)
            {
                if (m_otherRigidBody == null)
                {
                    Debug.LogError("Other rigid body must not be null");
                    return(false);
                }
                if (!m_otherRigidBody.isInWorld)
                {
                    world.AddRigidBody(m_otherRigidBody);
                }
                RigidBody rbb = (RigidBody)m_otherRigidBody.GetCollisionObject();
                if (rbb == null)
                {
                    Debug.LogError("Constraint could not get bullet RigidBody from target rigid body");
                    return(false);
                }
                BM.Matrix frameInA, frameInOther;
                string    errormsg = "";
                if (CreateFramesA_B(m_localConstraintAxisX, m_localConstraintAxisY, m_localConstraintPoint, out frameInA, out frameInOther, ref errormsg))
                {
                    m_constraintPtr = new Generic6DofSpring2Constraint(rba, rbb, frameInA, frameInOther);
                }
                else
                {
                    Debug.LogError(errormsg);
                    return(false);
                }
            }
            else
            {
                // TODO
                //   m_constraintPtr = new Generic6DofSpringConstraint(rba, m_localConstraintPoint.ToBullet(), m_localConstraintAxisX.ToBullet(), false);
            }
            if (m_setLimit)
            {
                ((Generic6DofSpring2Constraint)m_constraintPtr).SetLimit((int)m_springAxis, m_lowLimit, m_highLimit);
            }
            ((Generic6DofSpring2Constraint)m_constraintPtr).EnableSpring((int)m_springAxis, true);
            ((Generic6DofSpring2Constraint)m_constraintPtr).SetStiffness((int)m_springAxis, m_stiffness);
            ((Generic6DofSpring2Constraint)m_constraintPtr).SetDamping((int)m_springAxis, m_damping);
            ((Generic6DofSpring2Constraint)m_constraintPtr).SetBounce((int)m_springAxis, m_bounce);
            ((Generic6DofSpring2Constraint)m_constraintPtr).SetEquilibriumPoint();
            ((Generic6DofSpring2Constraint)m_constraintPtr).LinearLowerLimit  = m_linearLimitLower.ToBullet();
            ((Generic6DofSpring2Constraint)m_constraintPtr).LinearUpperLimit  = m_linearLimitUpper.ToBullet();
            ((Generic6DofSpring2Constraint)m_constraintPtr).AngularLowerLimit = m_angularLimitLowerRadians.ToBullet();
            ((Generic6DofSpring2Constraint)m_constraintPtr).AngularUpperLimit = m_angularLimitUpperRadians.ToBullet();
            m_constraintPtr.Userobject                  = this;
            m_constraintPtr.DebugDrawSize               = m_debugDrawSize;
            m_constraintPtr.BreakingImpulseThreshold    = m_breakingImpulseThreshold;
            m_constraintPtr.OverrideNumSolverIterations = m_overrideNumSolverIterations;
            return(true);
        }
Exemplo n.º 26
0
    public override void SetupLink(BulletSharp.Math.Vector3 linkInertia)
    {
        Quaternion parentToThisRotation = parentTransform.rotation * Quaternion.Inverse(transform.rotation);
        Vector3    linkPointInParent    = parentTransform.InverseTransformPoint(transform.position);

        MultiBody.MultiBody.SetupPlanar(LinkId, Mass, linkInertia, ParentLinkId, parentToThisRotation.ToBullet(), RotationAxis.ToBullet(),
                                        linkPointInParent.ToBullet(), DisableParentCollision);
    }
Exemplo n.º 27
0
        public static int Sector_AllowTraverse(RoomSector rs, float floor, EngineContainer container)
        {
            var f0 = rs.FloorCorners[0][2];
            if (rs.FloorCorners[1][2] != f0 || rs.FloorCorners[2][2] != f0 || rs.FloorCorners[3][2] != f0)
            {
                return 0x00;
            }

            if (Math.Abs(floor - f0) < 1.1f && rs.Ceiling - rs.Floor >= TR_METERING_SECTORSIZE)
            {
                return 0x01;
            }

            var cb = new BtEngineClosestRayResultCallback(container);
            var from = new Vector3(rs.Position.X, rs.Position.Y, floor + TR_METERING_SECTORSIZE * 0.5f);
            var to = new Vector3(rs.Position.X, rs.Position.Y, floor - TR_METERING_SECTORSIZE * 0.5f);
            BtEngineDynamicsWorld.RayTest(from.ToBullet(), to.ToBullet(), cb);
            if (cb.HasHit)
            {
                Vector3 v;
                Helper.SetInterpolate3(out v, from, to, cb.ClosestHitFraction);
                if (Math.Abs(v.Z - floor) < 1.1f)
                {
                    var cont = (EngineContainer) cb.CollisionObject.UserObject;
                    if (cont != null && cont.ObjectType == OBJECT_TYPE.Entity &&
                        ((Entity) cont.Object).TypeFlags.HasFlag(ENTITY_TYPE.TraverseFloor))
                    {
                        return 0x01;
                    }
                }
            }

            return 0x00;
        }
    //IMPORTANT Time.fixedTime must match the timestep being used here.
    public static List <Vector3> SimulateBall(BRigidBody ballRb, Vector3 ballThrowForce, int numberOfSimulationSteps, bool reverseOrder)
    {
        List <Vector3> ballPositions = new List <Vector3>(numberOfSimulationSteps);

        //Create a World
        Debug.Log("Initialize physics");

        CollisionConfiguration CollisionConf;
        CollisionDispatcher    Dispatcher;
        BroadphaseInterface    Broadphase;
        CollisionWorld         cw;
        ConstraintSolver       Solver;

        BulletSharp.SoftBody.SoftBodyWorldInfo softBodyWorldInfo;

        //This should create a copy of the BPhysicsWorld with the same settings
        WorldController bw = WorldsManager.WorldController;

        bw.CreatePhysicsWorld(out cw, out CollisionConf, out Dispatcher, out Broadphase, out Solver, out softBodyWorldInfo);
        World = (DiscreteDynamicsWorld)cw;

        //Copy all existing rigidbodies in scene
        // IMPORTANT rigidbodies must be added to the offline world in the same order that they are in the source world
        // this is because collisions must be resolved in the same order for the sim to be deterministic
        DiscreteDynamicsWorld sourceWorld  = bw.DDWorld;
        RigidBody             bulletBallRb = null;

        BulletSharp.Math.Matrix mm = BulletSharp.Math.Matrix.Identity;
        for (int i = 0; i < sourceWorld.NumCollisionObjects; i++)
        {
            CollisionObject co = sourceWorld.CollisionObjectArray[i];
            if (co != null && co.UserObject is BRigidBody)
            {
                BRigidBody      rb            = (BRigidBody)co.UserObject;
                BCollisionShape existingShape = rb.GetComponent <BCollisionShape>();
                CollisionShape  shape         = null;
                if (existingShape is BSphereShape)
                {
                    shape = ((BSphereShape)existingShape).CopyCollisionShape();
                }
                else if (existingShape is BBoxShape)
                {
                    shape = ((BBoxShape)existingShape).CopyCollisionShape();
                }

                RigidBody bulletRB = null;
                BulletSharp.Math.Vector3 localInertia = new BulletSharp.Math.Vector3();
                rb.CreateOrConfigureRigidBody(ref bulletRB, ref localInertia, shape, null);
                BulletSharp.Math.Vector3    pos = rb.GetCollisionObject().WorldTransform.Origin;
                BulletSharp.Math.Quaternion rot = rb.GetCollisionObject().WorldTransform.GetOrientation();
                BulletSharp.Math.Matrix.AffineTransformation(1f, ref rot, ref pos, out mm);
                bulletRB.WorldTransform = mm;
                World.AddRigidBody(bulletRB, rb.groupsIBelongTo, rb.collisionMask);
                if (rb == ballRb)
                {
                    bulletBallRb = bulletRB;
                    bulletRB.ApplyCentralImpulse(ballThrowForce.ToBullet());
                }
            }
        }

        //Step the simulation numberOfSimulationSteps times
        for (int i = 0; i < numberOfSimulationSteps; i++)
        {
            World.StepSimulation(1f / 60f, 10, 1f / 60f);
            ballPositions.Add(bulletBallRb.WorldTransform.Origin.ToUnity());
        }

        Debug.Log("ExitPhysics");
        if (World != null)
        {
            //remove/dispose constraints
            int i;
            for (i = World.NumConstraints - 1; i >= 0; i--)
            {
                TypedConstraint constraint = World.GetConstraint(i);
                World.RemoveConstraint(constraint);
                constraint.Dispose();
            }

            //remove the rigidbodies from the dynamics world and delete them
            for (i = World.NumCollisionObjects - 1; i >= 0; i--)
            {
                CollisionObject obj  = World.CollisionObjectArray[i];
                RigidBody       body = obj as RigidBody;
                if (body != null && body.MotionState != null)
                {
                    body.MotionState.Dispose();
                }

                World.RemoveCollisionObject(obj);
                obj.Dispose();
            }

            World.Dispose();
        }

        if (Broadphase != null)
        {
            Broadphase.Dispose();
        }

        if (Dispatcher != null)
        {
            Dispatcher.Dispose();
        }

        if (CollisionConf != null)
        {
            CollisionConf.Dispose();
        }

        return(ballPositions);
    }
 public virtual void SetPosition(Vector3 position)
 {
     if (isInWorld)
     {
         BulletSharp.Math.Matrix newTrans = m_collisionObject.WorldTransform;
         newTrans.Origin = position.ToBullet();
         m_collisionObject.WorldTransform = newTrans;
         transform.position = position;
     } else
     {
         transform.position = position;
     }
 }
        //called by Physics World just before constraint is added to world.
        //the current constraint properties are used to rebuild the constraint.
        internal override bool _BuildConstraint()
        {
            BPhysicsWorld world = BPhysicsWorld.Get();

            if (constraintPtr != null)
            {
                if (isInWorld && world != null)
                {
                    isInWorld = false;
                    world.RemoveConstraint(constraintPtr);
                }
            }
            if (targetRigidBodyA == null)
            {
                Debug.LogError("Constraint target rigid body was not set.");
                return(false);
            }

            RigidBody rba = (RigidBody)targetRigidBodyA.GetCollisionObject();

            if (rba == null)
            {
                Debug.LogError("Constraint could not get bullet RigidBody from target rigid body");
                return(false);
            }
            if (constraintType == ConstraintType.constrainToAnotherBody)
            {
                RigidBody rbb = (RigidBody)targetRigidBodyB.GetCollisionObject();
                if (rbb == null)
                {
                    Debug.LogError("Constraint could not get bullet RigidBody from target rigid body");
                    return(false);
                }

                BulletSharp.Math.Matrix frameInA = BulletSharp.Math.Matrix.AffineTransformation(1f, Quaternion.LookRotation(localForwardInA, localUpInA).ToBullet(), localPointInA.ToBullet());
                BulletSharp.Math.Matrix frameInB = BulletSharp.Math.Matrix.AffineTransformation(1f, Quaternion.LookRotation(localForwardInB, localUpInB).ToBullet(), localPointInB.ToBullet());
                constraintPtr            = new SliderConstraint(rba, rbb, frameInA, frameInB, false);
                constraintPtr.Userobject = this;
            }
            else
            {
                BulletSharp.Math.Matrix frameInA = BulletSharp.Math.Matrix.AffineTransformation(1f, Quaternion.LookRotation(localForwardInA, localUpInA).ToBullet(), localPointInA.ToBullet());
                constraintPtr            = new SliderConstraint(rba, frameInA, false);
                constraintPtr.Userobject = this;
            }
            SliderConstraint sl = (SliderConstraint)constraintPtr;

            sl.LowerLinearLimit = lowerLinearLimit;
            sl.UpperLinearLimit = upperLinearLimit;

            sl.LowerAngularLimit     = lowerAngularLimit;
            sl.UpperAngularLimit     = upperAngularLimit;
            constraintPtr.Userobject = this;
            return(true);
        }
Exemplo n.º 31
0
        CompoundShape _CreateCompoundShape(bool copyChildren)
        {
            BCollisionShape[] css = GetComponentsInChildren <BCollisionShape>();
            colliders = new BCollisionShape[css.Length - 1];
            int ii = 0;

            for (int i = 0; i < css.Length; i++)
            {
                if (css[i] == this)
                {
                    //skip
                }
                else
                {
                    colliders[ii] = css[i];
                    ii++;
                }
            }
            if (colliders.Length == 0)
            {
                Debug.LogError("Compound collider");
            }

            //TODO
            // some of the collider types (non-finite and other compound colliders) are probably not
            // can only be added to game object with rigid body attached.
            // allowed should check for these.
            // what about scaling not sure if it is handled correctly
            CompoundShape cs = new CompoundShape();

            for (int i = 0; i < colliders.Length; i++)
            {
                CollisionShape chcs;
                if (copyChildren == true)
                {
                    chcs = colliders[i].CopyCollisionShape();
                }
                else
                {
                    chcs = colliders[i].GetCollisionShape();
                }

                Vector3 up      = Vector3.up;
                Vector3 origin  = Vector3.zero;
                Vector3 forward = Vector3.forward;
                //to world
                up      = colliders[i].transform.TransformDirection(up);
                origin  = colliders[i].transform.TransformPoint(origin);
                forward = colliders[i].transform.TransformDirection(forward);
                //to compound collider
                up      = transform.InverseTransformDirection(up);
                origin  = transform.InverseTransformPoint(origin);
                forward = transform.InverseTransformDirection(forward);
                Quaternion q = Quaternion.LookRotation(forward, up);

                /*
                 * Some collision shapes can have local scaling applied. Use
                 * btCollisionShape::setScaling(vector3).Non uniform scaling with different scaling
                 * values for each axis, can be used for btBoxShape, btMultiSphereShape,
                 * btConvexShape, btTriangleMeshShape.Note that a non - uniform scaled
                 * sphere can be created by using a btMultiSphereShape with 1 sphere.
                 */

                BulletSharp.Math.Matrix m = BulletSharp.Math.Matrix.AffineTransformation(1f, q.ToBullet(), origin.ToBullet());

                cs.AddChildShape(m, chcs);
            }
            cs.LocalScaling = m_localScaling.ToBullet();
            return(cs);
        }
Exemplo n.º 32
0
        // public BDebug.DebugType debugType;

        /**
         * Creates or configures a RigidBody based on the current settings. Does not alter the internal state of this component in any way.
         * Can be used to create copies of this BRigidBody for use in other physics simulations.
         */
        public bool CreateOrConfigureRigidBody(ref RigidBody rb, ref BulletSharp.Math.Vector3 localInertia, CollisionShape cs, MotionState motionState)
        {
            //rigidbody is dynamic if and only if mass is non zero, otherwise static
            localInertia = BulletSharp.Math.Vector3.Zero;
            if (isDynamic())
            {
                cs.CalculateLocalInertia(_mass, out localInertia);
            }

            if (rb == null)
            {
                float bulletMass = _mass;
                if (!isDynamic())
                {
                    bulletMass = 0f;
                }
                RigidBodyConstructionInfo rbInfo = new RigidBodyConstructionInfo(bulletMass, motionState, cs, localInertia);
                rbInfo.Friction                             = _friction;
                rbInfo.RollingFriction                      = _rollingFriction;
                rbInfo.LinearDamping                        = _linearDamping;
                rbInfo.AngularDamping                       = _angularDamping;
                rbInfo.Restitution                          = _restitution;
                rbInfo.LinearSleepingThreshold              = _linearSleepingThreshold;
                rbInfo.AngularSleepingThreshold             = _angularSleepingThreshold;
                rbInfo.AdditionalDamping                    = _additionalDamping;
                rbInfo.AdditionalAngularDampingFactor       = _additionalAngularDampingFactor;
                rbInfo.AdditionalAngularDampingThresholdSqr = _additionalAngularDampingThresholdSqr;
                rbInfo.AdditionalDampingFactor              = _additionalDampingFactor;
                rbInfo.AdditionalLinearDampingThresholdSqr  = _additionalLinearDampingThresholdSqr;
                rb = new RigidBody(rbInfo);
                rbInfo.Dispose();
            }
            else
            {
                float usedMass = 0f;
                if (isDynamic())
                {
                    usedMass = _mass;
                }
                rb.SetMassProps(usedMass, localInertia);
                rb.Friction        = _friction;
                rb.RollingFriction = _rollingFriction;
                rb.SetDamping(_linearDamping, _angularDamping);
                rb.Restitution = _restitution;
                rb.SetSleepingThresholds(_linearSleepingThreshold, _angularSleepingThreshold);
                rb.CollisionShape = cs;
            }

            rb.AngularVelocity = angularVelocity.ToBullet();
            rb.LinearVelocity  = velocity.ToBullet();

            rb.CollisionFlags = m_collisionFlags;
            rb.LinearFactor   = _linearFactor.ToBullet();
            rb.AngularFactor  = _angularFactor.ToBullet();
            if (m_rigidBody != null)
            {
                rb.DeactivationTime             = m_rigidBody.DeactivationTime;
                rb.InterpolationLinearVelocity  = m_rigidBody.InterpolationLinearVelocity;
                rb.InterpolationAngularVelocity = m_rigidBody.InterpolationAngularVelocity;
                rb.InterpolationWorldTransform  = m_rigidBody.InterpolationWorldTransform;
            }

            //if kinematic then disable deactivation
            if ((m_collisionFlags & BulletSharp.CollisionFlags.KinematicObject) != 0)
            {
                rb.ActivationState = ActivationState.DisableDeactivation;
            }
            return(true);
        }
        //called by Physics World just before constraint is added to world.
        //the current constraint properties are used to rebuild the constraint.
        internal override bool _BuildConstraint()
        {
            BPhysicsWorld world = BPhysicsWorld.Get();

            if (constraintPtr != null)
            {
                if (isInWorld && world != null)
                {
                    isInWorld = false;
                    world.RemoveConstraint(constraintPtr);
                }
            }
            if (targetRigidBodyA == null)
            {
                Debug.LogError("Constraint target rigid body was not set.");
                return(false);
            }
            RigidBody rba = (RigidBody)targetRigidBodyA.GetCollisionObject();

            if (rba == null)
            {
                Debug.LogError("Constraint could not get bullet RigidBody from target rigid body A");
                return(false);
            }
            if (constraintType == ConstraintType.constrainToAnotherBody)
            {
                RigidBody rbb = (RigidBody)targetRigidBodyB.GetCollisionObject();
                if (rbb == null)
                {
                    Debug.LogError("Constraint could not get bullet RigidBody from target rigid body B");
                    return(false);
                }
                constraintPtr = new Point2PointConstraint(rba, rbb, pivotInA.ToBullet(), pivotInB.ToBullet());
            }
            else
            {
                constraintPtr = new Point2PointConstraint(rba, pivotInA.ToBullet());
            }
            constraintPtr.Userobject = this;
            return(true);
        }
Exemplo n.º 34
0
        /*
         * Does not set any local variables. Is safe to use to create duplicate physics worlds for independant simulation.
         */
        public bool CreatePhysicsWorld(out CollisionWorld world,
                                       out CollisionConfiguration collisionConfig,
                                       out CollisionDispatcher dispatcher,
                                       out BroadphaseInterface broadphase,
                                       out ConstraintSolver solver,
                                       out SoftBodyWorldInfo softBodyWorldInfo)
        {
            bool success = true;

            if (m_worldType == WorldType.SoftBodyAndRigidBody && m_collisionType == CollisionConfType.DefaultDynamicsWorldCollisionConf)
            {
                Debug.LogError("For World Type = SoftBodyAndRigidBody collisionType must be collisionType=SoftBodyRigidBodyCollisionConf. Switching");
                m_collisionType = CollisionConfType.SoftBodyRigidBodyCollisionConf;
                success         = false;
            }

            collisionConfig = null;
            if (m_collisionType == CollisionConfType.DefaultDynamicsWorldCollisionConf)
            {
                collisionConfig = new DefaultCollisionConfiguration();
            }
            else if (m_collisionType == CollisionConfType.SoftBodyRigidBodyCollisionConf)
            {
                collisionConfig = new SoftBodyRigidBodyCollisionConfiguration();
            }

            dispatcher = new CollisionDispatcher(collisionConfig);

            if (m_broadphaseType == BroadphaseType.DynamicAABBBroadphase)
            {
                broadphase = new DbvtBroadphase();
            }
            else if (m_broadphaseType == BroadphaseType.Axis3SweepBroadphase)
            {
                broadphase = new AxisSweep3(m_axis3SweepBroadphaseMin.ToBullet(), m_axis3SweepBroadphaseMax.ToBullet(), axis3SweepMaxProxies);
            }
            else if (m_broadphaseType == BroadphaseType.Axis3SweepBroadphase_32bit)
            {
                broadphase = new AxisSweep3_32Bit(m_axis3SweepBroadphaseMin.ToBullet(), m_axis3SweepBroadphaseMax.ToBullet(), axis3SweepMaxProxies);
            }
            else
            {
                broadphase = null;
            }
            world             = null;
            softBodyWorldInfo = null;
            solver            = null;
            if (m_worldType == WorldType.CollisionOnly)
            {
                world = new CollisionWorld(dispatcher, broadphase, collisionConfig);
            }
            else if (m_worldType == WorldType.RigidBodyDynamics)
            {
                switch (solverType)
                {
                case SolverType.MLCP:
                    DantzigSolver dtsolver = new DantzigSolver();
                    solver = new MlcpSolver(dtsolver);
                    break;

                default:
                    break;
                }
                world = new DiscreteDynamicsWorld(dispatcher, broadphase, solver, collisionConfig);
            }
            else if (m_worldType == WorldType.MultiBodyWorld)
            {
                MultiBodyConstraintSolver mbConstraintSolver = null;
                switch (solverType)
                {
                /* case SolverType.MLCP:
                 *   DantzigSolver dtsolver = new DantzigSolver();
                 *   mbConstraintSolver = new MultiBodyMLCPConstraintSolver(dtsolver);
                 *   break;*/
                default:
                    mbConstraintSolver = new MultiBodyConstraintSolver();
                    break;
                }
                world = new MultiBodyDynamicsWorld(dispatcher, broadphase, mbConstraintSolver, collisionConfig);
            }
            else if (m_worldType == WorldType.SoftBodyAndRigidBody)
            {
                SequentialImpulseConstraintSolver siConstraintSolver = new SequentialImpulseConstraintSolver();
                constraintSolver            = siConstraintSolver;
                siConstraintSolver.RandSeed = sequentialImpulseConstraintSolverRandomSeed;
                m_world  = new SoftRigidDynamicsWorld(Dispatcher, Broadphase, siConstraintSolver, CollisionConf);
                _ddWorld = (DiscreteDynamicsWorld)m_world;;

                SoftRigidDynamicsWorld _sworld = (SoftRigidDynamicsWorld)m_world;
                m_world.DispatchInfo.EnableSpu = true;
                _sworld.WorldInfo.SparseSdf.Initialize();
                _sworld.WorldInfo.SparseSdf.Reset();
                _sworld.WorldInfo.AirDensity   = 1.2f;
                _sworld.WorldInfo.WaterDensity = 0;
                _sworld.WorldInfo.WaterOffset  = 0;
                _sworld.WorldInfo.WaterNormal  = BulletSharp.Math.Vector3.Zero;
                _sworld.WorldInfo.Gravity      = m_gravity.ToBullet();
            }

            if (world is DiscreteDynamicsWorld)
            {
                ((DiscreteDynamicsWorld)world).Gravity = m_gravity.ToBullet();
            }
            if (_doDebugDraw)
            {
                DebugDrawUnity db = new DebugDrawUnity();
                db.DebugMode      = _debugDrawMode;
                world.DebugDrawer = db;
            }
            return(success);
        }
        //called by Physics World just before rigid body is added to world.
        //the current rigid body properties are used to rebuild the rigid body.
        internal override bool _BuildCollisionObject()
        {
            if (td == null)
            {
                Debug.LogError("Must be attached to an object with a terrain ");
                return(false);
            }
            BPhysicsWorld world = BPhysicsWorld.Get();

            if (m_collisionObject != null)
            {
                if (isInWorld && world != null)
                {
                    isInWorld = false;
                    world.RemoveCollisionObject(m_collisionObject);
                }
            }

            if (transform.localScale != UnityEngine.Vector3.one)
            {
                Debug.LogError("The local scale on this collision shape is not one. Bullet physics does not support scaling on a rigid body world transform. Instead alter the dimensions of the CollisionShape.");
            }

            m_collisionShape = GetComponent <BCollisionShape>();
            if (m_collisionShape == null)
            {
                Debug.LogError("There was no collision shape component attached to this BRigidBody. " + name);
                return(false);
            }
            if (!(m_collisionShape is BHeightfieldTerrainShape))
            {
                Debug.LogError("The collision shape needs to be a BHeightfieldTerrainShape. " + name);
                return(false);
            }

            CollisionShape cs = m_collisionShape.GetCollisionShape();

            //rigidbody is dynamic if and only if mass is non zero, otherwise static

            if (m_collisionObject == null)
            {
                m_collisionObject = new CollisionObject();
                m_collisionObject.CollisionShape = cs;
                m_collisionObject.UserObject     = this;

                BulletSharp.Math.Matrix worldTrans = BulletSharp.Math.Matrix.Identity;
                Vector3 pos = transform.position + new Vector3(td.size.x * .5f, td.size.y * .5f, td.size.z * .5f);
                worldTrans.Origin = pos.ToBullet();
                m_collisionObject.WorldTransform = worldTrans;
                m_collisionObject.CollisionFlags = m_collisionFlags;
            }
            else
            {
                m_collisionObject.CollisionShape = cs;
                BulletSharp.Math.Matrix worldTrans = BulletSharp.Math.Matrix.Identity;
                Vector3 pos = transform.position + new Vector3(td.size.x * .5f, td.size.y * .5f, td.size.z * .5f);
                worldTrans.Origin = pos.ToBullet();
                m_collisionObject.WorldTransform = worldTrans;
                m_collisionObject.CollisionFlags = m_collisionFlags;
            }
            return(true);
        }