예제 #1
0
        public void UpdateWheel(RigidBody chassis, RaycastInfo raycastInfo)
        {
            if (raycastInfo.IsInContact)
            {
                float project = Vector3.Dot(raycastInfo.ContactNormalWS, raycastInfo.WheelDirectionWS);
                Vector3 chassis_velocity_at_contactPoint;
                Vector3 relpos = raycastInfo.ContactPointWS - chassis.CenterOfMassPosition;
                chassis_velocity_at_contactPoint = chassis.GetVelocityInLocalPoint(relpos);
                float projVel = Vector3.Dot(raycastInfo.ContactNormalWS, chassis_velocity_at_contactPoint);
                if (project >= -0.1f)
                {
                    SuspensionRelativeVelocity = 0;
                    ClippedInvContactDotSuspension = 1.0f / 0.1f;
                }
                else
                {
                    float inv = -1.0f / project;
                    SuspensionRelativeVelocity = projVel * inv;
                    ClippedInvContactDotSuspension = inv;
                }

            }

            else    // Not in contact : position wheel in a nice (rest length) position
            {
                RaycastInfo.SuspensionLength = SuspensionRestLength;
                SuspensionRelativeVelocity = 0;
                RaycastInfo.ContactNormalWS = -raycastInfo.WheelDirectionWS;
                ClippedInvContactDotSuspension = 1.0f;
            }
        }
예제 #2
0
 public static Kart GetKartFromBody(RigidBody enteredBody)
 {
     if (enteredBody.UserObject is CollisionObjectDataHolder) {
         return (enteredBody.UserObject as CollisionObjectDataHolder).GetThingAsKart();
     }
     return null;
 }
예제 #3
0
파일: RigidBody.cs 프로젝트: raizam/GeonBit
        /// <summary>
        /// Create the physical entity.
        /// </summary>
        /// <param name="shape">Collision shape that define this body.</param>
        /// <param name="mass">Body mass (in kg), or 0 for static.</param>
        /// <param name="inertia">Body inertia, or 0 for static.</param>
        /// <param name="transformations">Starting transformations.</param>
        public RigidBody(CollisionShapes.ICollisionShape shape, float mass = 10f, float inertia = 1f, Matrix?transformations = null)
        {
            // store collision shape
            _shape = shape;

            // set default transformations
            transformations = transformations ?? Matrix.Identity;

            // create starting state
            _state = new DefaultMotionState(ToBullet.Matrix((Matrix)(transformations)));

            // create the rigid body construction info
            RigidBodyConstructionInfo info = new RigidBodyConstructionInfo(
                mass,
                _state,
                shape.BulletCollisionShape,
                shape.BulletCollisionShape.CalculateLocalInertia(mass) * inertia);

            // create the rigid body itself and attach self to UserObject
            BulletRigidBody            = new BulletSharp.RigidBody(info);
            BulletRigidBody.UserObject = this;

            // set default group and mask
            CollisionGroup = CollisionGroups.DynamicObjects;
            CollisionMask  = CollisionMasks.Targets;

            // set some defaults
            InvokeCollisionEvents = true;
            IsEthereal            = false;
        }
        /// <summary>
        /// Only applies friction and bounciness. Use a RigidBodyConstructionInfo if you want to set the damping.
        /// </summary>
        public void ApplyMaterial(RigidBody body, string material)
        {
            PhysicsMaterial mat = GetMaterial(material);

            body.Friction = mat.Friction;
            body.Restitution = mat.Bounciness;
        }
        protected override void OnInitializePhysics()
        {
            CollisionConf = new DefaultCollisionConfiguration();
            Dispatcher = new CollisionDispatcher(CollisionConf);

            Broadphase = new DbvtBroadphase();

            World = new DiscreteDynamicsWorld(Dispatcher, Broadphase, null, CollisionConf);
            World.Gravity = new Vector3(0, -10, 0);

            // ground
            CollisionShape groundShape = new BoxShape(50, 1, 50);
            CollisionShapes.Add(groundShape);
            CollisionObject ground = LocalCreateRigidBody(0, Matrix.Identity, groundShape);
            ground.UserObject = "Ground";

            // Objects
            //colShape = new BoxShape(1);
            Vector3[] points0 = {
                new Vector3(1, 0, 0), new Vector3(0, 1, 0), new Vector3(0, 0, 1)
            };
            Vector3[] points1 = {
                new Vector3(1, 0, 0), new Vector3(0, 1, 0), new Vector3(0, 0, 1), new Vector3(0,0,-1), new Vector3(-1,-1,0)
            };
            colShape0 = new ConvexHullShape(points0);
            colShape1 = new ConvexHullShape(points1);
            CollisionShapes.Add(colShape0);
            CollisionShapes.Add(colShape1);

            body2 = LocalCreateRigidBody(0, body2Position, colShape1);

            rotBody = LocalCreateRigidBody(0, rotBodyPosition, colShape0);
            rotBody.CollisionFlags |= CollisionFlags.KinematicObject;
            rotBody.ActivationState = ActivationState.DisableDeactivation;
        }
예제 #6
0
        //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()
        {
            BPhysicsWorld world = BPhysicsWorld.Get;

            if (m_rigidBody != null && isInWorld && world != null)
            {
                isInWorld = false;
                world.RemoveRigidBody(m_rigidBody);
            }
            m_collisionShape = this.GetParent <Unit>().GetComponent <BCollisionShape>().baseBCollisionShape;   //必须在这里另外赋值,这个是最重要的组件。基本都用到它。
            if (m_collisionShape == null)
            {
                Log.Warning("There was no collision shape component attached to this BRigidBody. {0}");
                return(false);
            }

            CollisionShape cs = this.GetParent <Unit>().GetComponent <BCollisionShape>().GetCollisionShape;

            if (m_motionState == null)
            {
                m_motionState = new BGameObjectMotionState(this._Unit, this._Unit.Position, this._Unit.Quaternion);//创建MotionState,没有就无法更新状态。
            }

            BulletSharp.RigidBody rb = (BulletSharp.RigidBody)m_collisionObject;
            CreateOrConfigureRigidBody(ref rb, ref _localInertia, cs, m_motionState);
            m_collisionObject            = rb;
            m_collisionObject.UserObject = this.GetParent <Unit>();//这里就是碰撞检测等传递的对象。如果想不用unit,可以在这里改。
            return(true);
        }
예제 #7
0
        public void SetUp()
        {
            conf = new DefaultCollisionConfiguration();
            dispatcher = new CollisionDispatcher(conf);
            broadphase = new AxisSweep3(new Vector3(-1000, -1000, -1000), new Vector3(1000, 1000, 1000));
            world = new DiscreteDynamicsWorld(dispatcher, broadphase, null, conf);

            // Initialize TriangleIndexVertexArray with float array
            indexVertexArray = new TriangleIndexVertexArray(TorusMesh.Indices, TorusMesh.Vertices);
            gImpactMeshShape = new GImpactMeshShape(indexVertexArray);
            gImpactMeshShape.CalculateLocalInertia(1.0f);
            gImpactMesh = CreateBody(1.0f, gImpactMeshShape, Vector3.Zero);


            // Initialize TriangleIndexVertexArray with Vector3 array
            Vector3[] torusVertices = new Vector3[TorusMesh.Vertices.Length / 3];
            for (int i = 0; i < torusVertices.Length; i++)
            {
                torusVertices[i] = new Vector3(
                    TorusMesh.Vertices[i * 3],
                    TorusMesh.Vertices[i * 3 + 1],
                    TorusMesh.Vertices[i * 3 + 2]);
            }
            indexVertexArray2 = new TriangleIndexVertexArray(TorusMesh.Indices, torusVertices);
            triangleMeshShape = new BvhTriangleMeshShape(indexVertexArray2, true);
            // CalculateLocalInertia must fail for static shapes (shapes based on TriangleMeshShape)
            //triangleMeshShape.CalculateLocalInertia(1.0f);
            triangleMesh = CreateBody(0.0f, triangleMeshShape, Vector3.Zero);
        }
예제 #8
0
        /// <summary>
        /// Starts the component.
        /// </summary>
        protected override void OnStart(GameTime time)
        {
            if (this.rigidBody == null)
            {
                var shape = this.Node.Components.Get <Shape>();
                if (shape == null)
                {
                    throw new NullReferenceException("Could not find a shape component for the rigid body.");
                }

                var constructionInfo = new RigidBodyConstructionInfo(
                    this.Mass,
                    new SceneNodeMotionState(this.Node),
                    shape.GetShape());

                this.rigidBody            = new BulletSharp.RigidBody(constructionInfo);
                this.rigidBody.UserObject = this;
                this.IsKinematic          = this.isKinematic;        // Just make sure the body gets its correct rigid body state.
            }

            if (this.Node.Scene.PhysicsEnabled)
            {
                this.Node.Scene.World.AddRigidBody(this.rigidBody);
            }
        }
예제 #9
0
 public PhysicalBody(RigidBody rigidBody, CollisionShape shape, TransformationManager manager)
 {
     Body = rigidBody;
     Shape = shape;
     Transformation = manager;
     Enabled = false;
 }
예제 #10
0
        /// <summary>
        /// 剛体を生成する
        /// </summary>
        /// <param name="rigidBodyData_s">剛体データ</param>
        private void CreateRigid(List <RigidBodyData> rigidBodyData_s)
        {
            foreach (var r in rigidBodyData_s)
            {
                var tempRigidBodyData = new TempRigidBodyData(r);
                var init_matrix       = tempRigidBodyData.init_matrix;
                tempRigidBodyData_s.Add(tempRigidBodyData);
                BulletSharp.RigidBody rigidBody = null;
                CollisionShape        collisionShape;
                switch (r.Shape)
                {
                case RigidBodyShape.Sphere:     // 球体
                    collisionShape = new SphereShape(r.Size.X);
                    break;

                case RigidBodyShape.Box:            // ボックス
                    collisionShape = new BoxShape(r.Size.X, r.Size.Y, r.Size.Z);
                    break;

                case RigidBodyShape.Capsule:        // カプセル
                    collisionShape = new CapsuleShape(r.Size.X, r.Size.Y);
                    break;

                default:        //  例外処理
                    throw new System.Exception("Invalid rigid body data");
                }
                var rigidProperty = new RigidProperty(r.Mass, r.Repulsion, r.Friction, r.MoveAttenuation, r.RotationAttenuation);
                var superProperty = new SuperProperty(r.PhysicsCalcType == PhysicsCalcType.Static, (CollisionFilterGroups)(1 << r.RigidBodyGroup), (CollisionFilterGroups)r.UnCollisionGroupFlag);
                rigidBody = bulletManager.CreateRigidBody(collisionShape, init_matrix, rigidProperty, superProperty);
                rigidBodies.Add(rigidBody);
            }
        }
		public unsafe static float SolveAngularLimits(this RotationalLimitMotor obj, float timeStep, ref OpenTK.Vector3 axis, float jacDiagABInv, RigidBody body0, RigidBody body1)
		{
			fixed (OpenTK.Vector3* axisPtr = &axis)
			{
				return obj.SolveAngularLimits(timeStep, ref *(BulletSharp.Math.Vector3*)axisPtr, jacDiagABInv, body0, body1);
			}
		}
		public HingeConstraint(RigidBody rigidBodyA, Matrix rigidBodyAFrame, bool useReferenceFrameA = false)
			: base(btHingeConstraint_new8(rigidBodyA._native, ref rigidBodyAFrame,
				useReferenceFrameA))
		{
			_rigidBodyA = rigidBodyA;
            _rigidBodyB = GetFixedBody();
		}
예제 #13
0
        public Physics()
        {
            // collision configuration contains default setup for memory, collision setup
            collisionConf = new DefaultCollisionConfiguration();
            Dispatcher = new CollisionDispatcher(collisionConf);

            Broadphase = new DbvtBroadphase();

            World = new DiscreteDynamicsWorld(Dispatcher, Broadphase, null, collisionConf);
            World.Gravity = new Vector3(0, -10, 0);

            CollisionShapes = new List<CollisionShape>();

            // create the ground
            CollisionShape groundShape = new BoxShape(50, 1, 50);
            CollisionShapes.Add(groundShape);
            CollisionObject ground = LocalCreateRigidBody(0, Matrix.Identity, groundShape);
            ground.UserObject = "Ground";

            // create a few dynamic rigidbodies
            float mass = 1.0f;

            CollisionShape colShape = new BoxShape(1);
            CollisionShapes.Add(colShape);
            Vector3 localInertia = colShape.CalculateLocalInertia(mass);

            float start_x = StartPosX - ArraySizeX / 2;
            float start_y = StartPosY;
            float start_z = StartPosZ - ArraySizeZ / 2;

            int k, i, j;
            for (k = 0; k < ArraySizeY; k++)
            {
                for (i = 0; i < ArraySizeX; i++)
                {
                    for (j = 0; j < ArraySizeZ; j++)
                    {
                        Matrix startTransform = Matrix.CreateTranslation(
                            new Vector3(
                                2*i + start_x,
                                2*k + start_y,
                                2*j + start_z
                                )
                            );

                        // using motionstate is recommended, it provides interpolation capabilities
                        // and only synchronizes 'active' objects
                        DefaultMotionState myMotionState = new DefaultMotionState(startTransform);
                        RigidBodyConstructionInfo rbInfo =
                            new RigidBodyConstructionInfo(mass, myMotionState, colShape, localInertia);
                        RigidBody body = new RigidBody(rbInfo);

                        // make it drop from a height
                        body.Translate(new Vector3(0, 20, 0));

                        World.AddRigidBody(body);
                    }
                }
            }
        }
		public ConeTwistConstraint(RigidBody rigidBodyA, RigidBody rigidBodyB, Matrix rigidBodyAFrame,
			Matrix rigidBodyBFrame)
			: base(btConeTwistConstraint_new(rigidBodyA._native, rigidBodyB._native,
				ref rigidBodyAFrame, ref rigidBodyBFrame))
		{
			_rigidBodyA = rigidBodyA;
			_rigidBodyB = rigidBodyB;
		}
		public Point2PointConstraint(RigidBody rigidBodyA, RigidBody rigidBodyB,
			Vector3 pivotInA, Vector3 pivotInB)
			: base(btPoint2PointConstraint_new(rigidBodyA._native, rigidBodyB._native,
				ref pivotInA, ref pivotInB))
		{
			_rigidBodyA = rigidBodyA;
			_rigidBodyB = rigidBodyB;
		}
		public HingeConstraint(RigidBody rigidBodyA, RigidBody rigidBodyB, Vector3 pivotInA,
			Vector3 pivotInB, Vector3 axisInA, Vector3 axisInB, bool useReferenceFrameA = false)
			: base(btHingeConstraint_new2(rigidBodyA._native, rigidBodyB._native,
				ref pivotInA, ref pivotInB, ref axisInA, ref axisInB, useReferenceFrameA))
		{
			_rigidBodyA = rigidBodyA;
			_rigidBodyB = rigidBodyB;
		}
		public HingeConstraint(RigidBody rigidBodyA, Vector3 pivotInA, Vector3 axisInA,
			bool useReferenceFrameA = false)
			: base(btHingeConstraint_new4(rigidBodyA._native, ref pivotInA, ref axisInA,
				useReferenceFrameA))
		{
			_rigidBodyA = rigidBodyA;
            _rigidBodyB = GetFixedBody();
		}
		public HingeConstraint(RigidBody rigidBodyA, RigidBody rigidBodyB, Matrix rigidBodyAFrame,
			Matrix rigidBodyBFrame, bool useReferenceFrameA = false)
			: base(btHingeConstraint_new6(rigidBodyA._native, rigidBodyB._native,
				ref rigidBodyAFrame, ref rigidBodyBFrame, useReferenceFrameA))
		{
			_rigidBodyA = rigidBodyA;
			_rigidBodyB = rigidBodyB;
		}
		public GearConstraint(RigidBody rigidBodyA, RigidBody rigidBodyB, Vector3 axisInA,
			Vector3 axisInB)
			: base(btGearConstraint_new(rigidBodyA._native, rigidBodyB._native, ref axisInA,
				ref axisInB))
		{
			_rigidBodyA = rigidBodyA;
			_rigidBodyB = rigidBodyB;
		}
		public Generic6DofSpringConstraint(RigidBody rigidBodyB, Matrix frameInB,
			bool useLinearReferenceFrameB)
			: base(btGeneric6DofSpringConstraint_new2(rigidBodyB._native, ref frameInB,
				useLinearReferenceFrameB))
		{
            _rigidBodyA = GetFixedBody();
			_rigidBodyB = rigidBodyB;
		}
예제 #21
0
        protected override void Apply(RigidBody obj, int slice)
        {
            Vector3D pos = this.FPosition[slice];
            Vector3D force = this.FImpulse[slice];

            obj.ApplyImpulse(new Vector3((float)force.x, (float)force.y, (float)force.z),
                new Vector3((float)pos.x, (float)pos.y, (float)pos.z));
        }
		public UniversalConstraint(RigidBody rigidBodyA, RigidBody rigidBodyB, Vector3 anchor,
			Vector3 axis1, Vector3 axis2)
			: base(btUniversalConstraint_new(rigidBodyA._native, rigidBodyB._native,
				ref anchor, ref axis1, ref axis2))
		{
			_rigidBodyA = rigidBodyA;
			_rigidBodyB = rigidBodyB;
		}
예제 #23
0
        public void SetUpBulletPhysicsBody(float mass, BulletSharp.MotionState motionState, BulletSharp.CollisionShape collisionShape, Vector3 localInertia)
        {
            BulletSharpPhysics.RigidBodyConstructionInfo rbInfo =
                new BulletSharpPhysics.RigidBodyConstructionInfo(mass, motionState, collisionShape, localInertia);
            RigidBody = new BulletSharpPhysics.RigidBody(rbInfo);

            bulletPhysics.World.AddRigidBody(RigidBody, GetCollisionFlags(), GetCollisionMask());
        }
 public void RemoveRigidBody(BulletSharp.RigidBody rb)
 {
     if (!_isDisposed)
     {
         Debug.LogFormat("Removing rigidbody {0} from world", rb);
         World.RemoveRigidBody(rb);
     }
 }
		public Generic6DofSpringConstraint(RigidBody rigidBodyA, RigidBody rigidBodyB,
			Matrix frameInA, Matrix frameInB, bool useLinearReferenceFrameA)
			: base(btGeneric6DofSpringConstraint_new(rigidBodyA._native, rigidBodyB._native,
				ref frameInA, ref frameInB, useLinearReferenceFrameA))
		{
			_rigidBodyA = rigidBodyA;
			_rigidBodyB = rigidBodyB;
		}
		public FixedConstraint(RigidBody rigidBodyA, RigidBody rigidBodyB, Matrix frameInA,
			Matrix frameInB)
			: base(btFixedConstraint_new(rigidBodyA._native, rigidBodyB._native,
				ref frameInA, ref frameInB))
		{
			_rigidBodyA = rigidBodyA;
			_rigidBodyB = rigidBodyB;
		}
        public void SetUpBulletPhysicsBody(float mass, BulletSharp.MotionState motionState, BulletSharp.CollisionShape collisionShape, Vector3 localInertia)
        {
            BulletSharpPhysics.RigidBodyConstructionInfo rbInfo =
                            new BulletSharpPhysics.RigidBodyConstructionInfo(mass, motionState, collisionShape, localInertia);
            RigidBody = new BulletSharpPhysics.RigidBody(rbInfo);

            bulletPhysics.World.AddRigidBody(RigidBody,GetCollisionFlags(),GetCollisionMask());
           
        }
        //public void Test()
        //{
        //    BulletSharp.Point2PointConstraint pt;
        //    /BulletSharp.Generic6DofConstraint sdof = new Generic6DofConstraint(
        //    pt.Setting.
        //sdof.sett
        //}
        public override TypedConstraint GetConstraint(RigidBody body)
        {
            Point2PointConstraint cst = new Point2PointConstraint(body, this.Pivot);
            cst.Setting.Damping = this.Damping;
            cst.Setting.ImpulseClamp = this.ImpulseClamp;
            cst.Setting.Tau = this.Tau;

            return cst;
        }
예제 #29
0
 public RigidBody(GameObject Object)
 {
     gameObject      = Object;
     _Mass           = 1;
     _Static         = false;
     _Shape          = new CapsuleShape(0.5f, 1);
     rigidBodyObject = LocalCreateRigidBody(_Mass, Matrix4.CreateTranslation(gameObject._transform.Position), _Shape);
     rigidBodyObject.CollisionFlags = CollisionFlags.CharacterObject;
     rigidBodyObject.Friction       = 0.1f;
     rigidBodyObject.SetDamping(0, 0);
 }
예제 #30
0
        public RigidBody(CollisionShape shape, float mass, OpenTK.Matrix4 transform)
        {
            DefaultMotionState state = new DefaultMotionState(transform);

            inertia = shape.BulletShape.CalculateLocalInertia(mass);
            var info = new RigidBodyConstructionInfo(mass, state, shape.BulletShape, inertia);

            BulletRigidBody                   = new BulletSharp.RigidBody(info);
            BulletRigidBody.UserObject        = this;
            BulletCollisionObject.Restitution = 0.5f;
        }
예제 #31
0
 /// <summary>
 /// output some text, show/hide a dialogue, and change the color of the region
 /// </summary>
 void doSomething(TriggerRegion region, RigidBody otherBody, TriggerReportFlags flags, CollisionReportInfo info)
 {
     if (flags.HasFlag(TriggerReportFlags.Enter)) {
         Console.WriteLine(otherBody.GetName() + " has entered trigger area \"" + region.Name + "\"");
         // cycle through the balloon colors
         region.CycleToNextColor();
     }
     else {
         Console.WriteLine(otherBody.GetName() + " has left trigger area \"" + region.Name + "\"");
         region.CycleToNextColor();
     }
 }
예제 #32
0
파일: Prop.cs 프로젝트: copygirl/Blocky
        public Prop(CollisionShape shape, float mass, Matrix4 start)
        {
            Physics physics = Game.Instance.Physics;

            Shape = shape;
            IsDynamic = (mass != 0.0f);
            physics.Props.Add(this);
            Vector3 inertia = Vector3.Zero;
            if (IsDynamic) shape.CalculateLocalInertia(mass, out inertia);
            DefaultMotionState motionState = new DefaultMotionState(start);
            RigidBody.RigidBodyConstructionInfo info = new RigidBody.RigidBodyConstructionInfo(mass, motionState, shape, inertia);
            Body = new RigidBody(info);
            physics.World.AddRigidBody(Body);
        }
예제 #33
0
        void TestContactTest(RigidBody testBody, RigidBody testBody2)
        {
            object context = "your context";
            ContactSensorCallback contactCallback = new ContactSensorCallback(testBody, context);
            world.ContactTest(testBody, contactCallback);

            testBody.CollisionFlags |= CollisionFlags.CustomMaterialCallback;
            testBody2.CollisionFlags |= CollisionFlags.CustomMaterialCallback;
            world.ContactPairTest(testBody, testBody2, contactCallback);
            testBody.CollisionFlags &= ~CollisionFlags.CustomMaterialCallback;
            testBody2.CollisionFlags &= ~CollisionFlags.CustomMaterialCallback;

            AddToDisposeQueue(contactCallback);
        }
예제 #34
0
 public void RemoveRigidBody(BulletSharp.RigidBody rb)
 {
     if (!_isDisposed)
     {
         if (m_worldType < WorldType.RigidBodyDynamics)
         {
             Log.Warning("World type must not be collision only");
         }
         ((DiscreteDynamicsWorld)m_world).RemoveRigidBody(rb);
         if (rb.UserObject is BCollisionObject)
         {
             ((BCollisionObject)rb.UserObject).isInWorld = false;
         }
     }
 }
        protected RigidBody LocalCreateRigidBody(float mass, Matrix startTransform, CollisionShape shape)
        {
            bool isDynamic = (mass != 0.0f);

            Vector3 localInertia = Vector3.Zero;
            if (isDynamic)
                shape.CalculateLocalInertia(mass, out localInertia);

            DefaultMotionState myMotionState = new DefaultMotionState(startTransform);

            RigidBodyConstructionInfo rbInfo = new RigidBodyConstructionInfo(mass, myMotionState, shape, localInertia);
            body = new RigidBody(rbInfo);
            
            return body;
        }
예제 #36
0
 public void RemoveRigidBody(BulletSharp.RigidBody rb)
 {
     if (!_isDisposed)
     {
         if (m_worldType < WorldType.RigidBodyDynamics)
         {
             BDebug.LogError(debugType, "World type must not be collision only");
         }
         BDebug.Log(debugType, "Removing rigidbody {0} from world", rb.UserObject);
         ((DiscreteDynamicsWorld)m_world).RemoveRigidBody(rb);
         if (rb.UserObject is BCollisionObject)
         {
             ((BCollisionObject)rb.UserObject).isInWorld = false;
         }
     }
 }
예제 #37
0
파일: FreeCamera.cs 프로젝트: yanko/vengine
 public FreeCamera(float aspectRatio, float fov)
 {
     Cam = new Camera(new Vector3(20, 20, 20), new Vector3(0, 2, 0), aspectRatio, fov, 1.0f, 10000.0f);
     collisionShape = new SphereShape(0.8f);
     //collisionShape.LinearDamping = 0.5f;
     rigidBody = World.Root.CreateRigidBody(0.01f, Matrix4.CreateTranslation(Cam.Transformation.GetPosition()), collisionShape, null);
     rigidBody.SetSleepingThresholds(0, 0);
     rigidBody.ContactProcessingThreshold = 0;
     rigidBody.CcdMotionThreshold = 0;
     World.Root.PhysicalWorld.AddRigidBody(rigidBody);
     rigidBody.Gravity = Vector3.Zero;
     rigidBody.ApplyGravity();
     rigidBody.SetDamping(0.5f, 0.01f);
     GLThread.OnUpdate += UpdateSterring;
     GLThread.OnMouseMove += OnMouseMove;
 }
예제 #38
0
        public Person(Vector3 StartPosition)
        {
            CameraDefinition defaultCameraDefinition = new CameraDefinition()
            {
                Distance = 10,
                FPV = true,
                Offset = Vector3.UnitY,
                ViewAngle = Vector2.One,
                Style = DrawingStyle.Normal
            };

            CameraList = new Camera[] { new FirstPersonCamera(defaultCameraDefinition), new ThirdPersonCamera(defaultCameraDefinition) };
            CurrentCamera = 0;
            SphereShape body = new SphereShape(0.5f);
            CharacterBody = World.CreateRigidBody(80, Matrix4.CreateTranslation(StartPosition), body);
        }
예제 #39
0
        public void SetUp()
        {
            conf = new DefaultCollisionConfiguration();
            dispatcher = new CollisionDispatcher(conf);
            broadphase = new AxisSweep3(new Vector3(-1000, -1000, -1000), new Vector3(1000, 1000, 1000));
            world = new DiscreteDynamicsWorld(dispatcher, broadphase, null, conf);

            indexVertexArray = new TriangleIndexVertexArray(TorusMesh.Indices, TorusMesh.Vertices);

            gImpactMeshShape = new GImpactMeshShape(indexVertexArray);

            triangleMeshShape = new BvhTriangleMeshShape(indexVertexArray, true);
            triangleMeshShape.CalculateLocalInertia(1.0f);

            gImpactMesh = CreateBody(1.0f, gImpactMeshShape, Vector3.Zero);
            triangleMesh = CreateBody(1.0f, triangleMeshShape, Vector3.Zero);
        }
예제 #40
0
        static RigidBody CreateBody(float mass, CollisionShape shape, Vector3 offset)
        {
            var constInfo = new RigidBodyConstructionInfo(mass, new DefaultMotionState(), shape, Vector3.Zero);
            if (mass != 0.0f)
            {
                constInfo.LocalInertia = constInfo.CollisionShape.CalculateLocalInertia(mass);
            }
            var collisionObject = new RigidBody(constInfo);
            collisionObject.Translate(offset);
            world.AddRigidBody(collisionObject);

            AddToDisposeQueue(constInfo);
            AddToDisposeQueue(constInfo.MotionState);
            AddToDisposeQueue(collisionObject);
            AddToDisposeQueue(shape);

            return collisionObject;
        }
예제 #41
0
        //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()
        {
            BPhysicsWorld world = BPhysicsWorld.Get();

            if (m_rigidBody != null && isInWorld && world != null)
            {
                isInWorld = false;
                world.RemoveRigidBody(m_rigidBody);
            }

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

            m_collisionShape = GetComponent <BCollisionShape>();
            if (m_collisionShape == null)
            {
                Debug.LogErrorFormat("There was no collision shape component attached to this BRigidBody. {0}", name);
                return(false);
            }

            CollisionShape cs = m_collisionShape.GetCollisionShape();

            if (m_motionState == null)
            {
                m_motionState = new BGameObjectMotionState(transform);
            }

            BulletSharp.RigidBody rb = (BulletSharp.RigidBody)m_collisionObject;
            CreateOrConfigureRigidBody(ref rb, ref _localInertia, cs, m_motionState);
            m_collisionObject            = rb;
            m_collisionObject.UserObject = this;

            // gRally
            //if (!isDynamic())
            {
                transform.position   = Native.UtoB(transform.position);
                transform.rotation   = Native.UtoB(transform.rotation);
                transform.localScale = Native.UtoB(transform.localScale);
            }

            return(true);
        }
예제 #42
0
        public BulletSharp.RigidBody LocalCreateRigidBody(float mass, Matrix4 startTransform, CollisionShape shape)
        {
            bool isDynamic = (mass != 0.0f);

            Vector3 localInertia = Vector3.Zero;

            if (isDynamic || _Static == false)
            {
                shape.CalculateLocalInertia(mass, out localInertia);
            }

            DefaultMotionState myMotionState = new DefaultMotionState(startTransform);

            RigidBodyConstructionInfo rbInfo = new RigidBodyConstructionInfo(mass, myMotionState, shape, localInertia);

            BulletSharp.RigidBody body = new BulletSharp.RigidBody(rbInfo);

            Physics.AddRigidBody(body);

            return(body);
        }
        public override void Run()
        {
            #region Create renderers

            // Note: the renderers take care of creating their own
            // device resources and listen for DeviceManager.OnInitialize

            // Create a axis-grid renderer
            var axisGrid = ToDispose(new AxisGridRenderer());
            axisGrid.Initialize(this);

            // Create and initialize the mesh renderer
            var loadedMesh             = Common.Mesh.LoadFromFile("PhysicsScene1.cmo");
            List <MeshRenderer> meshes = new List <MeshRenderer>();
            meshes.AddRange(from mesh in loadedMesh
                            select ToDispose(new MeshRenderer(mesh)));
            foreach (var m in meshes)
            {
                m.Initialize(this);
                m.World = Matrix.Identity;
            }


            // Set the first animation as the current animation and start clock
            foreach (var m in meshes)
            {
                if (m.Mesh.Animations != null && m.Mesh.Animations.Any())
                {
                    m.CurrentAnimation = m.Mesh.Animations.First().Value;
                }
                m.Clock.Start();
            }


            loadedMesh = Common.Mesh.LoadFromFile("SubdividedPlane.cmo");
            var waterMesh = ToDispose(new MeshRenderer(loadedMesh.First()));
            waterMesh.Initialize(this);

            loadedMesh = Common.Mesh.LoadFromFile("Bataux.cmo");
            List <MeshRenderer> shipMeshes = new List <MeshRenderer>();
            shipMeshes.AddRange((from mesh in loadedMesh
                                 select ToDispose(new MeshRenderer(mesh))));
            foreach (var m in shipMeshes)
            {
                m.Initialize(this);
                m.World = Matrix.Scaling(3) * Matrix.RotationAxis(Vector3.UnitY, -1.57079f);
            }

            //var anchor = new SphereRenderer(0.05f);
            //anchor.Initialize(this);
            //var anchorWorld = Matrix.Identity;

            //var sphere = new SphereRenderer();
            //sphere.Initialize(this);
            //var sphereWorld = Matrix.Identity;

            // Create and initialize a Direct2D FPS text renderer
            var fps = ToDispose(new Common.FpsRenderer("Calibri", Color.CornflowerBlue, new Point(8, 8), 16));
            fps.Initialize(this);

            // Create and initialize a general purpose Direct2D text renderer
            // This will display some instructions and the current view and rotation offsets
            var textRenderer = ToDispose(new Common.TextRenderer("Calibri", Color.CornflowerBlue, new Point(8, 40), 12));
            textRenderer.Initialize(this);

            #endregion

            #region Initialize physics engine

            CollisionConfiguration defaultConfig = new DefaultCollisionConfiguration();
            ConstraintSolver       solver        = new SequentialImpulseConstraintSolver();
            BulletSharp.Dispatcher dispatcher    = new CollisionDispatcher(defaultConfig);
            BroadphaseInterface    broadphase    = new DbvtBroadphase();
            DynamicsWorld          world         = null;
            Action initializePhysics             = () =>
            {
                RemoveAndDispose(ref world);
                world         = ToDispose(new BulletSharp.DiscreteDynamicsWorld(dispatcher, broadphase, solver, defaultConfig));
                world.Gravity = new Vector3(0, -10, 0);

                // For each mesh, create a RigidBody and add to "world" for simulation
                meshes.ForEach(m =>
                {
                    // We use the name of the mesh to determine the correct body
                    if (String.IsNullOrEmpty(m.Mesh.Name))
                    {
                        return;
                    }

                    var name   = m.Mesh.Name.ToLower();
                    var extent = m.Mesh.Extent;

                    BulletSharp.CollisionShape shape;

                    #region Create collision shape
                    if (name.Contains("box") || name.Contains("cube"))
                    {
                        // Assumes the box/cube has an axis-aligned neutral orientation
                        shape = new BulletSharp.BoxShape(
                            Math.Abs(extent.Max.Z - extent.Min.Z) / 2.0f,
                            Math.Abs(extent.Max.Y - extent.Min.Y) / 2.0f,
                            Math.Abs(extent.Max.X - extent.Min.X) / 2.0f);
                    }
                    else if (name.Contains("sphere"))
                    {
                        shape = new BulletSharp.SphereShape(extent.Radius);
                    }
                    else // use mesh vertices directly
                    {
                        // for each SubMesh, retrieve the vertex and index buffers
                        // to create a TriangleMeshShape for collision detection.
                        List <Vector3> vertices = new List <Vector3>();
                        List <int> indices      = new List <int>();
                        int vertexOffset        = 0;
                        foreach (var sm in m.Mesh.SubMeshes)
                        {
                            vertexOffset += vertices.Count;
                            indices.AddRange(
                                (from indx in m.Mesh.IndexBuffers[(int)sm.IndexBufferIndex]
                                 select vertexOffset + (int)indx));
                            vertices.AddRange(
                                (from v in m.Mesh
                                 .VertexBuffers[(int)sm.VertexBufferIndex]
                                 select v.Position - extent.Center));
                        }
                        // Create the collision shape
                        var iva = new BulletSharp.TriangleIndexVertexArray(indices.ToArray(), vertices.ToArray());
                        shape   = new BulletSharp.BvhTriangleMeshShape(iva, true);
                    }
                    #endregion

                    m.World = Matrix.Identity; // Reset mesh location
                    float mass; Vector3 vec;
                    shape.GetBoundingSphere(out vec, out mass);
                    var body = new BulletSharp.RigidBody(
                        new BulletSharp.RigidBodyConstructionInfo(name.Contains("static") ? 0 : mass,
                                                                  new MeshMotionState(m),
                                                                  shape, shape.CalculateLocalInertia(mass)));
                    if (body.IsStaticObject)
                    {
                        body.Restitution = 1f;
                        body.Friction    = 0.4f;
                    }
                    // Add to the simulation
                    world.AddRigidBody(body);
                });

#if DEBUG
                world.DebugDrawer           = ToDispose(new PhysicsDebugDraw(this.DeviceManager));
                world.DebugDrawer.DebugMode = DebugDrawModes.DrawAabb | DebugDrawModes.DrawWireframe;
#endif
            };
            initializePhysics();


            // Newton's Cradle

            //var box = new Jitter.Dynamics.RigidBody(new Jitter.Collision.Shapes.BoxShape(7, 1, 2));
            //box.Position = new Jitter.LinearMath.JVector(0, 8, 0);
            //world.AddBody(box);
            //box.IsStatic = true;

            //var anchorBody = new Jitter.Dynamics.RigidBody(new Jitter.Collision.Shapes.SphereShape(0.05f));
            //anchorBody.Position = new Jitter.LinearMath.JVector(0, 4, 0);
            //world.AddBody(anchorBody);
            //anchorBody.IsStatic = true;

            //for (var bodyCount = -3; bodyCount < 4; bodyCount++)
            //{
            //    var testBody = new Jitter.Dynamics.RigidBody(new Jitter.Collision.Shapes.SphereShape(0.501f));
            //    testBody.Position = new Jitter.LinearMath.JVector(bodyCount, 0, 0);

            //    world.AddBody(testBody);

            //    world.AddConstraint(new Jitter.Dynamics.Constraints.PointPointDistance(box, testBody,
            //        testBody.Position + Jitter.LinearMath.JVector.Up * 8f + Jitter.LinearMath.JVector.Forward * 3f + Jitter.LinearMath.JVector.Down * 0.5f,
            //        testBody.Position) { Softness = 1.0f, BiasFactor = 0.8f });

            //    world.AddConstraint(new Jitter.Dynamics.Constraints.PointPointDistance(box, testBody,
            //        testBody.Position + Jitter.LinearMath.JVector.Up * 8f + Jitter.LinearMath.JVector.Backward * 3f + Jitter.LinearMath.JVector.Down * 0.5f,
            //        testBody.Position) { Softness = 1.0f, BiasFactor = 0.8f });

            //    testBody.Material.Restitution = 1.0f;
            //    testBody.Material.StaticFriction = 1.0f;
            //}

            #endregion

            // Initialize the world matrix
            var worldMatrix = Matrix.Identity;

            // Set the camera position slightly behind (z)
            var cameraPosition = new Vector3(0, 1, 10);
            var cameraTarget   = Vector3.Zero;  // Looking at the origin 0,0,0
            var cameraUp       = Vector3.UnitY; // Y+ is Up

            // Prepare matrices
            // Create the view matrix from our camera position, look target and up direction
            var viewMatrix = Matrix.LookAtRH(cameraPosition, cameraTarget, cameraUp);
            viewMatrix.TranslationVector += new Vector3(0, -0.98f, 0);

            // Create the projection matrix
            /* FoV 60degrees = Pi/3 radians */
            // Aspect ratio (based on window size), Near clip, Far clip
            var projectionMatrix = Matrix.PerspectiveFovRH((float)Math.PI / 3f, Width / (float)Height, 0.1f, 100f);

            // Maintain the correct aspect ratio on resize
            Window.Resize += (s, e) =>
            {
                projectionMatrix = Matrix.PerspectiveFovRH((float)Math.PI / 3f, Width / (float)Height, 0.1f, 100f);
            };

            bool debugDraw = false;
            bool paused    = false;

            var simTime = new System.Diagnostics.Stopwatch();
            simTime.Start();
            float time     = 0.0f;
            float timeStep = 0.0f;

            #region Rotation and window event handlers

            // Create a rotation vector to keep track of the rotation
            // around each of the axes
            var rotation = new Vector3(0.0f, 0.0f, 0.0f);

            // We will call this action to update text
            // for the text renderer
            Action updateText = () =>
            {
                textRenderer.Text =
                    String.Format("Rotation ({0}) (Up/Down Left/Right Wheel+-)\nView ({1}) (A/D, W/S, Shift+Wheel+-)"
                                  //+ "\nPress 1,2,3,4,5,6,7,8 to switch shaders"
                                  + "\nTime: {2:0.00} (P to toggle, R to reset scene)"
                                  + "\nPhysics debug draw: {3} (E to toggle)"
                                  + "\nBackspace: toggle between Physics and Waves",
                                  rotation,
                                  viewMatrix.TranslationVector,
                                  simTime.Elapsed.TotalSeconds,
                                  debugDraw);
            };

            Dictionary <Keys, bool> keyToggles = new Dictionary <Keys, bool>();
            keyToggles[Keys.Z]    = false;
            keyToggles[Keys.F]    = false;
            keyToggles[Keys.Back] = false;

            // Support keyboard/mouse input to rotate or move camera view
            var moveFactor      = 0.02f; // how much to change on each keypress
            var shiftKey        = false;
            var ctrlKey         = false;
            var background      = Color.White;
            var showNormals     = false;
            var enableNormalMap = true;
            Window.KeyDown += (s, e) =>
            {
                var context = DeviceManager.Direct3DContext;

                shiftKey = e.Shift;
                ctrlKey  = e.Control;

                switch (e.KeyCode)
                {
                // WASD -> pans view
                case Keys.A:
                    viewMatrix.TranslationVector += new Vector3(moveFactor * 2, 0f, 0f);
                    break;

                case Keys.D:
                    viewMatrix.TranslationVector -= new Vector3(moveFactor * 2, 0f, 0f);
                    break;

                case Keys.S:
                    if (shiftKey)
                    {
                        viewMatrix.TranslationVector += new Vector3(0f, moveFactor * 2, 0f);
                    }
                    else
                    {
                        viewMatrix.TranslationVector -= new Vector3(0f, 0f, 1) * moveFactor * 2;
                    }
                    break;

                case Keys.W:
                    if (shiftKey)
                    {
                        viewMatrix.TranslationVector -= new Vector3(0f, moveFactor * 2, 0f);
                    }
                    else
                    {
                        viewMatrix.TranslationVector += new Vector3(0f, 0f, 1) * moveFactor * 2;
                    }
                    break;

                // Up/Down and Left/Right - rotates around X / Y respectively
                // (Mouse wheel rotates around Z)
                case Keys.Down:
                    worldMatrix *= Matrix.RotationX(moveFactor);
                    rotation    += new Vector3(moveFactor, 0f, 0f);
                    break;

                case Keys.Up:
                    worldMatrix *= Matrix.RotationX(-moveFactor);
                    rotation    -= new Vector3(moveFactor, 0f, 0f);
                    break;

                case Keys.Left:
                    worldMatrix *= Matrix.RotationY(moveFactor);
                    rotation    += new Vector3(0f, moveFactor, 0f);
                    break;

                case Keys.Right:
                    worldMatrix *= Matrix.RotationY(-moveFactor);
                    rotation    -= new Vector3(0f, moveFactor, 0f);
                    break;

                case Keys.T:
                    fps.Show          = !fps.Show;
                    textRenderer.Show = !textRenderer.Show;
                    break;

                case Keys.B:
                    if (background == Color.White)
                    {
                        background = new Color(30, 30, 34);
                    }
                    else
                    {
                        background = Color.White;
                    }
                    break;

                case Keys.G:
                    axisGrid.Show = !axisGrid.Show;
                    break;

                case Keys.P:
                    paused = !paused;
                    if (paused)
                    {
                        simTime.Stop();
                    }
                    else
                    {
                        simTime.Start();
                    }

                    // Pause or resume mesh animation
                    meshes.ForEach(m => {
                        if (m.Clock.IsRunning)
                        {
                            m.Clock.Stop();
                        }
                        else
                        {
                            m.Clock.Start();
                        }
                    });
                    updateText();
                    break;

                case Keys.X:
                    // To test for correct resource recreation
                    // Simulate device reset or lost.
                    System.Diagnostics.Debug.WriteLine(SharpDX.Diagnostics.ObjectTracker.ReportActiveObjects());
                    DeviceManager.Initialize(DeviceManager.Dpi);
                    System.Diagnostics.Debug.WriteLine(SharpDX.Diagnostics.ObjectTracker.ReportActiveObjects());
                    break;

                case Keys.Z:
                    keyToggles[Keys.Z] = !keyToggles[Keys.Z];
                    if (keyToggles[Keys.Z])
                    {
                        context.PixelShader.Set(depthPixelShader);
                    }
                    else
                    {
                        context.PixelShader.Set(pixelShader);
                    }
                    break;

                case Keys.F:
                    keyToggles[Keys.F] = !keyToggles[Keys.F];
                    RasterizerStateDescription rasterDesc;
                    if (context.Rasterizer.State != null)
                    {
                        rasterDesc = context.Rasterizer.State.Description;
                    }
                    else
                    {
                        rasterDesc = new RasterizerStateDescription()
                        {
                            CullMode = CullMode.None,
                            FillMode = FillMode.Solid
                        }
                    };
                    if (keyToggles[Keys.F])
                    {
                        rasterDesc.FillMode      = FillMode.Wireframe;
                        context.Rasterizer.State = ToDispose(new RasterizerState(context.Device, rasterDesc));
                    }
                    else
                    {
                        rasterDesc.FillMode      = FillMode.Solid;
                        context.Rasterizer.State = ToDispose(new RasterizerState(context.Device, rasterDesc));
                    }
                    break;

                case Keys.N:
                    if (!shiftKey)
                    {
                        showNormals = !showNormals;
                    }
                    else
                    {
                        enableNormalMap = !enableNormalMap;
                    }
                    break;

                case Keys.E:
                    debugDraw = !debugDraw;
                    break;

                case Keys.R:

                    //world = new Jitter.World(new Jitter.Collision.CollisionSystemSAP());
                    initializePhysics();
                    if (simTime.IsRunning)
                    {
                        simTime.Restart();
                    }
                    else
                    {
                        simTime.Reset();
                    }
                    break;

                case Keys.D1:
                    context.PixelShader.Set(pixelShader);
                    break;

                case Keys.D2:
                    context.PixelShader.Set(lambertShader);
                    break;

                case Keys.D3:
                    context.PixelShader.Set(phongShader);
                    break;

                case Keys.D4:
                    context.PixelShader.Set(blinnPhongShader);
                    break;

                case Keys.Back:
                    keyToggles[Keys.Back] = !keyToggles[Keys.Back];
                    break;
                }

                updateText();
            };
            Window.KeyUp += (s, e) =>
            {
                // Clear the shift/ctrl keys so they aren't sticky
                if (e.KeyCode == Keys.ShiftKey)
                {
                    shiftKey = false;
                }
                if (e.KeyCode == Keys.ControlKey)
                {
                    ctrlKey = false;
                }
            };
            Window.MouseWheel += (s, e) =>
            {
                if (shiftKey)
                {
                    // Zoom in/out
                    viewMatrix.TranslationVector += new Vector3(0f, 0f, (e.Delta / 120f) * moveFactor * 2);
                }
                else
                {
                    // rotate around Z-axis
                    viewMatrix *= Matrix.RotationZ((e.Delta / 120f) * moveFactor);
                    rotation   += new Vector3(0f, 0f, (e.Delta / 120f) * moveFactor);
                }
                updateText();
            };

            var lastX = 0;
            var lastY = 0;

            Window.MouseDown += (s, e) =>
            {
                if (e.Button == MouseButtons.Left)
                {
                    lastX = e.X;
                    lastY = e.Y;
                }
            };

            Window.MouseMove += (s, e) =>
            {
                if (e.Button == MouseButtons.Left)
                {
                    var yRotate = lastX - e.X;
                    var xRotate = lastY - e.Y;
                    lastY = e.Y;
                    lastX = e.X;

                    // Mouse move changes
                    viewMatrix *= Matrix.RotationX(-xRotate * moveFactor);
                    viewMatrix *= Matrix.RotationY(-yRotate * moveFactor);

                    updateText();
                }
            };

            // Display instructions with initial values
            updateText();

            #endregion

            var clock = new System.Diagnostics.Stopwatch();
            clock.Start();

            #region Render loop

            // Create and run the render loop
            RenderLoop.Run(Window, () =>
            {
                // Update simulation, at 60fps
                if (!paused)
                {
                    if ((float)simTime.Elapsed.TotalSeconds < time)
                    {
                        time     = 0;
                        timeStep = 0;
                    }
                    timeStep = ((float)simTime.Elapsed.TotalSeconds - time);
                    time     = (float)simTime.Elapsed.TotalSeconds;
                    world.StepSimulation(timeStep, 7);
                    // For how to choose the maxSubSteps see:
                    // http://www.bulletphysics.org/mediawiki-1.5.8/index.php/Stepping_The_World
                }

                updateText();
                // Start of frame:

                // Retrieve immediate context
                var context = DeviceManager.Direct3DContext;

                // Clear depth stencil view
                context.ClearDepthStencilView(DepthStencilView, DepthStencilClearFlags.Depth | DepthStencilClearFlags.Stencil, 1.0f, 0);
                // Clear render target view
                context.ClearRenderTargetView(RenderTargetView, background);

                // Create viewProjection matrix
                var viewProjection = Matrix.Multiply(viewMatrix, projectionMatrix);

                // Extract camera position from view
                var camPosition = Matrix.Transpose(Matrix.Invert(viewMatrix)).Column4;
                cameraPosition  = new Vector3(camPosition.X, camPosition.Y, camPosition.Z);

                var perFrame             = new ConstantBuffers.PerFrame();
                perFrame.Light.Color     = new Color(0.8f, 0.8f, 0.8f, 1.0f);
                var lightDir             = Vector3.Transform(new Vector3(1f, -1f, -1f), worldMatrix);
                perFrame.Light.Direction = new Vector3(lightDir.X, lightDir.Y, lightDir.Z);
                perFrame.CameraPosition  = cameraPosition;
                perFrame.Time            = (float)simTime.Elapsed.TotalSeconds; // Provide simulation time to shader
                context.UpdateSubresource(ref perFrame, perFrameBuffer);

                // Render each object

                var perMaterial           = new ConstantBuffers.PerMaterial();
                perMaterial.Ambient       = new Color4(0.2f);
                perMaterial.Diffuse       = Color.White;
                perMaterial.Emissive      = new Color4(0);
                perMaterial.Specular      = Color.White;
                perMaterial.SpecularPower = 20f;
                perMaterial.HasTexture    = 0;
                perMaterial.UVTransform   = Matrix.Identity;
                context.UpdateSubresource(ref perMaterial, perMaterialBuffer);

                var perObject = new ConstantBuffers.PerObject();

                // MESH

                if (!keyToggles[Keys.Back])
                {
                    meshes.ForEach((m) =>
                    {
                        perObject.World = m.World * worldMatrix;
                        // Provide the material constant buffer to the mesh renderer
                        perObject.WorldInverseTranspose = Matrix.Transpose(Matrix.Invert(perObject.World));
                        perObject.WorldViewProjection   = perObject.World * viewProjection;
                        perObject.ViewProjection        = viewProjection;
                        perObject.Transpose();
                        context.UpdateSubresource(ref perObject, perObjectBuffer);

                        m.PerMaterialBuffer = perMaterialBuffer;
                        m.PerArmatureBuffer = perArmatureBuffer;
                        m.Render();

                        if (showNormals)
                        {
                            using (var prevPixelShader = context.PixelShader.Get())
                            {
                                perMaterial.HasTexture  = 0;
                                perMaterial.UVTransform = Matrix.Identity;
                                context.UpdateSubresource(ref perMaterial, perMaterialBuffer);
                                context.PixelShader.Set(pixelShader);

                                context.GeometryShader.Set(debugNormals);

                                m.Render();

                                context.PixelShader.Set(prevPixelShader);
                                context.GeometryShader.Set(null);
                            }
                        }
                    });

                    if (debugDraw)
                    {
                        perObject.World = Matrix.Identity;
                        perObject.WorldInverseTranspose = Matrix.Transpose(Matrix.Invert(perObject.World));
                        perObject.WorldViewProjection   = perObject.World * viewProjection;
                        perObject.ViewProjection        = viewProjection;
                        perObject.Transpose();
                        context.UpdateSubresource(ref perObject, perObjectBuffer);

                        (world.DebugDrawer as PhysicsDebugDraw).DrawDebugWorld(world);
                        context.VertexShader.Set(vertexShader);
                        context.PixelShader.Set(pixelShader);
                        context.InputAssembler.InputLayout = vertexLayout;
                    }
                }
                else
                {
                    perObject.World = waterMesh.World * worldMatrix;
                    perObject.WorldInverseTranspose = Matrix.Transpose(Matrix.Invert(perObject.World));
                    perObject.WorldViewProjection   = perObject.World * viewProjection;
                    perObject.ViewProjection        = viewProjection;
                    perObject.Transpose();
                    context.UpdateSubresource(ref perObject, perObjectBuffer);

                    waterMesh.EnableNormalMap   = enableNormalMap;
                    waterMesh.PerMaterialBuffer = perMaterialBuffer;
                    waterMesh.PerArmatureBuffer = perArmatureBuffer;

                    context.VertexShader.Set(waterVertexShader);
                    waterMesh.Render();

                    if (showNormals)
                    {
                        using (var prevPixelShader = context.PixelShader.Get())
                        {
                            perMaterial.HasTexture  = 0;
                            perMaterial.UVTransform = Matrix.Identity;
                            context.UpdateSubresource(ref perMaterial, perMaterialBuffer);
                            context.PixelShader.Set(pixelShader);

                            context.GeometryShader.Set(debugNormals);

                            waterMesh.Render();

                            context.PixelShader.Set(prevPixelShader);
                            context.GeometryShader.Set(null);
                        }
                    }

                    context.VertexShader.Set(vertexShader);

                    foreach (var m in shipMeshes)
                    {
                        perObject.World = m.World * worldMatrix;
                        perObject.WorldInverseTranspose = Matrix.Transpose(Matrix.Invert(perObject.World));
                        perObject.WorldViewProjection   = perObject.World * viewProjection;
                        perObject.Transpose();
                        context.UpdateSubresource(ref perObject, perObjectBuffer);
                        // Provide the material constant buffer to the mesh renderer
                        perObject.WorldInverseTranspose = Matrix.Transpose(Matrix.Invert(perObject.World));
                        perObject.WorldViewProjection   = perObject.World * viewProjection;
                        perObject.ViewProjection        = viewProjection;
                        perObject.Transpose();
                        context.UpdateSubresource(ref perObject, perObjectBuffer);

                        m.PerMaterialBuffer = perMaterialBuffer;
                        m.PerArmatureBuffer = perArmatureBuffer;
                        m.Render();

                        if (showNormals)
                        {
                            using (var prevPixelShader = context.PixelShader.Get())
                            {
                                perMaterial.HasTexture  = 0;
                                perMaterial.UVTransform = Matrix.Identity;
                                context.UpdateSubresource(ref perMaterial, perMaterialBuffer);
                                context.PixelShader.Set(pixelShader);

                                context.GeometryShader.Set(debugNormals);

                                m.Render();

                                context.PixelShader.Set(prevPixelShader);
                                context.GeometryShader.Set(null);
                            }
                        }
                    }
                }

                perMaterial.Ambient       = new Color4(0.2f);
                perMaterial.Diffuse       = Color.White;
                perMaterial.Emissive      = new Color4(0);
                perMaterial.Specular      = Color.White;
                perMaterial.SpecularPower = 20f;
                perMaterial.UVTransform   = Matrix.Identity;
                context.UpdateSubresource(ref perMaterial, perMaterialBuffer);

                // AXIS GRID
                context.HullShader.Set(null);
                context.DomainShader.Set(null);
                context.GeometryShader.Set(null);

                using (var prevPixelShader = context.PixelShader.Get())
                    using (var prevVertexShader = context.VertexShader.Get())
                    {
                        context.VertexShader.Set(vertexShader);
                        context.PixelShader.Set(pixelShader);
                        perObject.World = worldMatrix;
                        perObject.WorldInverseTranspose = Matrix.Transpose(Matrix.Invert(perObject.World));
                        perObject.WorldViewProjection   = perObject.World * viewProjection;
                        perObject.ViewProjection        = viewProjection;
                        perObject.Transpose();
                        context.UpdateSubresource(ref perObject, perObjectBuffer);
                        axisGrid.Render();
                        context.PixelShader.Set(prevPixelShader);
                        context.VertexShader.Set(prevVertexShader);
                    }

                // Render FPS
                fps.Render();

                // Render instructions + position changes
                textRenderer.Render();

                // Present the frame
                Present();
            });
            #endregion
        }
 public SliderConstraint(RigidBody rigidBodyB, Matrix frameInB, bool useLinearReferenceFrameA)
     : base(btSliderConstraint_new2(rigidBodyB._native, ref frameInB, useLinearReferenceFrameA))
 {
     _rigidBodyA = GetFixedBody();
     _rigidBodyB = rigidBodyB;
 }
예제 #45
0
 public static void AddRigidBody(BulletSharp.RigidBody obj)
 {
     _Main._World.AddRigidBody(obj);
 }
예제 #46
0
 public float SolveAngularLimits(float timeStep, Vector3 axis, float jacDiagABInv,
                                 RigidBody body0, RigidBody body1)
 {
     return(btRotationalLimitMotor_solveAngularLimits(_native, timeStep, ref axis,
                                                      jacDiagABInv, body0._native, body1._native));
 }
예제 #47
0
 public MultiBodySliderConstraint(MultiBody body, int link, RigidBody bodyB,
                                  Vector3 pivotInA, Vector3 pivotInB, Matrix frameInA, Matrix frameInB, Vector3 jointAxis)
     : base(btMultiBodySliderConstraint_new(body._native, link, bodyB._native,
                                            ref pivotInA, ref pivotInB, ref frameInA, ref frameInB, ref jointAxis))
 {
 }
 public MultiBodyPoint2Point(MultiBody body, int link, RigidBody bodyB, Vector3 pivotInA, Vector3 pivotInB)
     : base(btMultiBodyPoint2Point_new(body._native, link, bodyB._native, ref pivotInA, ref pivotInB))
 {
     _multiBodyA = body;
 }
예제 #49
0
 public MultiBodyFixedConstraint(MultiBody body, int link, RigidBody bodyB,
                                 Vector3 pivotInA, Vector3 pivotInB, Matrix frameInA, Matrix frameInB)
     : base(btMultiBodyFixedConstraint_new(body._native, link, bodyB._native,
                                           ref pivotInA, ref pivotInB, ref frameInA, ref frameInB))
 {
 }
예제 #50
0
 public static void RemoveRigidBody(BulletSharp.RigidBody obj)
 {
     _Main._World.RemoveRigidBody(obj);
 }
예제 #51
0
 public static RigidBody Upcast(CollisionObject colObj)
 {
     return(RigidBody.GetManaged(btRigidBody_upcast(colObj._native)) as RigidBody);
 }
 public void SynchronizeSingleMotionState(RigidBody body)
 {
     btDiscreteDynamicsWorld_synchronizeSingleMotionState(_native, body._native);
 }
예제 #53
0
    //IMPORTANT Time.fixedTime must match the timestep being used here.
    public static List <UnityEngine.Vector3> SimulateBall(BRigidBody ballRb, UnityEngine.Vector3 ballThrowForce, int numberOfSimulationSteps, bool reverseOrder)
    {
        var ballPositions = new List <UnityEngine.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
        BPhysicsWorld bw = BPhysicsWorld.Get();

        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 = (DiscreteDynamicsWorld)bw.world;

        BulletSharp.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;
                float           mass          = rb.isDynamic() ? rb.mass : 0f;
                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++)
        {
            int numSteps = World.StepSimulation(1f / 60f, 10, 1f / 60f);
            ballPositions.Add(bulletBallRb.WorldTransform.Origin.ToUnity());
        }

        UnityEngine.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();
            Broadphase.Dispose();
            Dispatcher.Dispose();
            CollisionConf.Dispose();
        }

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

        return(ballPositions);
    }
예제 #54
0
 public RaycastVehicle(VehicleTuning tuning, RigidBody chassis, IVehicleRaycaster raycaster)
 {
     chassisBody      = chassis;
     vehicleRaycaster = raycaster;
 }
예제 #55
0
        public void UpdateFriction(float timeStep)
        {
            //calculate the impulse, so that the wheels don't move sidewards
            int numWheel = NumWheels;

            if (numWheel == 0)
            {
                return;
            }

            Array.Resize(ref forwardWS, numWheel);
            Array.Resize(ref axle, numWheel);
            Array.Resize(ref forwardImpulse, numWheel);
            Array.Resize(ref sideImpulse, numWheel);

            int numWheelsOnGround = 0;

            //collapse all those loops into one!
            for (int i = 0; i < NumWheels; i++)
            {
                RigidBody groundObject = wheelInfo[i].RaycastInfo.GroundObject as RigidBody;
                if (groundObject != null)
                {
                    numWheelsOnGround++;
                }
                sideImpulse[i]    = 0;
                forwardImpulse[i] = 0;
            }

            for (int i = 0; i < NumWheels; i++)
            {
                WheelInfo wheel = wheelInfo[i];

                RigidBody groundObject = wheel.RaycastInfo.GroundObject as RigidBody;
                if (groundObject != null)
                {
                    Matrix wheelTrans = GetWheelTransformWS(i);

                    axle[i] = new Vector3(
                        wheelTrans[0, indexRightAxis],
                        wheelTrans[1, indexRightAxis],
                        wheelTrans[2, indexRightAxis]);

                    Vector3 surfNormalWS = wheel.RaycastInfo.ContactNormalWS;
                    float   proj;
                    Vector3.Dot(ref axle[i], ref surfNormalWS, out proj);
                    axle[i] -= surfNormalWS * proj;
                    axle[i].Normalize();

                    Vector3.Cross(ref surfNormalWS, ref axle[i], out forwardWS[i]);
                    forwardWS[i].Normalize();

                    ResolveSingleBilateral(chassisBody, wheel.RaycastInfo.ContactPointWS,
                                           groundObject, wheel.RaycastInfo.ContactPointWS,
                                           0, axle[i], ref sideImpulse[i], timeStep);

                    sideImpulse[i] *= sideFrictionStiffness2;
                }
            }

            const float sideFactor = 1.0f;
            const float fwdFactor  = 0.5f;

            bool sliding = false;

            for (int i = 0; i < NumWheels; i++)
            {
                WheelInfo wheel        = wheelInfo[i];
                RigidBody groundObject = wheel.RaycastInfo.GroundObject as RigidBody;

                float rollingFriction = 0.0f;

                if (groundObject != null)
                {
                    if (wheel.EngineForce != 0.0f)
                    {
                        rollingFriction = wheel.EngineForce * timeStep;
                    }
                    else
                    {
                        float defaultRollingFrictionImpulse = 0.0f;
                        float maxImpulse = (wheel.Brake != 0) ? wheel.Brake : defaultRollingFrictionImpulse;
                        rollingFriction = CalcRollingFriction(chassisBody, groundObject, wheel.RaycastInfo.ContactPointWS, forwardWS[i], maxImpulse);
                    }
                }

                //switch between active rolling (throttle), braking and non-active rolling friction (no throttle/break)

                forwardImpulse[i]     = 0;
                wheelInfo[i].SkidInfo = 1.0f;

                if (groundObject != null)
                {
                    wheelInfo[i].SkidInfo = 1.0f;

                    float maximp     = wheel.WheelsSuspensionForce * timeStep * wheel.FrictionSlip;
                    float maximpSide = maximp;

                    float maximpSquared = maximp * maximpSide;


                    forwardImpulse[i] = rollingFriction;//wheel.EngineForce* timeStep;

                    float x = forwardImpulse[i] * fwdFactor;
                    float y = sideImpulse[i] * sideFactor;

                    float impulseSquared = (x * x + y * y);

                    if (impulseSquared > maximpSquared)
                    {
                        sliding = true;

                        float factor = maximp / (float)System.Math.Sqrt(impulseSquared);

                        wheelInfo[i].SkidInfo *= factor;
                    }
                }
            }

            if (sliding)
            {
                for (int wheel = 0; wheel < NumWheels; wheel++)
                {
                    if (sideImpulse[wheel] != 0)
                    {
                        if (wheelInfo[wheel].SkidInfo < 1.0f)
                        {
                            forwardImpulse[wheel] *= wheelInfo[wheel].SkidInfo;
                            sideImpulse[wheel]    *= wheelInfo[wheel].SkidInfo;
                        }
                    }
                }
            }

            // apply the impulses
            for (int i = 0; i < NumWheels; i++)
            {
                WheelInfo wheel = wheelInfo[i];

                Vector3 rel_pos = wheel.RaycastInfo.ContactPointWS -
                                  chassisBody.CenterOfMassPosition;

                if (forwardImpulse[i] != 0)
                {
                    chassisBody.ApplyImpulse(forwardWS[i] * forwardImpulse[i], rel_pos);
                }
                if (sideImpulse[i] != 0)
                {
                    RigidBody groundObject = wheel.RaycastInfo.GroundObject as RigidBody;

                    Vector3 rel_pos2 = wheel.RaycastInfo.ContactPointWS -
                                       groundObject.CenterOfMassPosition;


                    Vector3 sideImp = axle[i] * sideImpulse[i];

#if ROLLING_INFLUENCE_FIX // fix. It only worked if car's up was along Y - VT.
                    //Vector4 vChassisWorldUp = RigidBody.CenterOfMassTransform.get_Columns(indexUpAxis);
                    Vector3 vChassisWorldUp = new Vector3(
                        RigidBody.CenterOfMassTransform.Row1[indexUpAxis],
                        RigidBody.CenterOfMassTransform.Row2[indexUpAxis],
                        RigidBody.CenterOfMassTransform.Row3[indexUpAxis]);
                    float dot;
                    Vector3.Dot(ref vChassisWorldUp, ref rel_pos, out dot);
                    rel_pos -= vChassisWorldUp * (dot * (1.0f - wheel.RollInfluence));
#else
                    rel_pos[indexUpAxis] *= wheel.RollInfluence;
#endif
                    chassisBody.ApplyImpulse(sideImp, rel_pos);

                    //apply friction impulse on the ground
                    groundObject.ApplyImpulse(-sideImp, rel_pos2);
                }
            }
        }