コード例 #1
0
        public void Init(TgcSimpleTerrain terrain)
        {
            collisionConfiguration = new DefaultCollisionConfiguration();
            dispatcher             = new CollisionDispatcher(collisionConfiguration);
            GImpactCollisionAlgorithm.RegisterAlgorithm(dispatcher);
            constraintSolver      = new SequentialImpulseConstraintSolver();
            broadphaseInterface   = new DbvtBroadphase();
            dynamicsWorld         = new DiscreteDynamicsWorld(dispatcher, broadphaseInterface, constraintSolver, collisionConfiguration);
            dynamicsWorld.Gravity = gravity;

            var ballShape     = new SphereShape(50);
            var ballTransform = TGCMatrix.Identity;

            ballTransform.Origin = initialPosition;
            var ballMotionState = new DefaultMotionState(ballTransform.ToBsMatrix);
            var ballInertia     = ballShape.CalculateLocalInertia(1f);
            var ballInfo        = new RigidBodyConstructionInfo(1, ballMotionState, ballShape, ballInertia);

            RigidCamera = new RigidBody(ballInfo);
            RigidCamera.SetDamping(0.9f, 0.9f);

            //esto es para que no le afecte la gravedad al inicio de la partida
            //RigidCamera.ActivationState = ActivationState.IslandSleeping;
            dynamicsWorld.AddRigidBody(RigidCamera);

            var heighmapRigid = BulletRigidBodyFactory.Instance.CreateSurfaceFromHeighMap(terrain.getData());

            dynamicsWorld.AddRigidBody(heighmapRigid);
        }
コード例 #2
0
ファイル: RigidBodyBone.cs プロジェクト: Romulion/GameEngine
        public RigidBodyBone(RigidContainer rcon)
        {
            bodyContainer = rcon;
            CollisionShape shape = null;

            switch (rcon.PrimitiveType)
            {
            case PhysPrimitiveType.Box:
                shape = new BoxShape(rcon.Size.Convert());
                break;

            case PhysPrimitiveType.Capsule:
                shape = new CapsuleShape(rcon.Size.X, rcon.Size.Y);
                break;

            case PhysPrimitiveType.Sphere:
                shape = new SphereShape(rcon.Size.X);
                break;
            }
            if (rcon.Phys == PhysType.FollowBone)
            {
                rcon.Mass = 0;
            }

            bool isDynamic = (rcon.Mass != 0.0f);

            Vector3 inertia = Vector3.Zero;

            if (isDynamic)
            {
                shape.CalculateLocalInertia(rcon.Mass, out inertia);
            }
            startTransform = Matrix.RotationYawPitchRoll(rcon.Rotation.Y, rcon.Rotation.X, rcon.Rotation.Z) * Matrix.Translation(rcon.Position.Convert());

            //Convert left to right coordinates
            var reverce = Matrix.Scaling(new Vector3(1, 1, -1));

            startTransform = reverce * startTransform * reverce;

            rbInfo = new RigidBodyConstructionInfo(rcon.Mass, new DefaultMotionState(startTransform), shape, inertia);
            Body   = new RigidBody(rbInfo);
            Body.ActivationState = ActivationState.DisableDeactivation;
            Body.Friction        = rcon.Friction;
            Body.SetDamping(rcon.MassAttenuation, rcon.RotationDamping);
            Body.Restitution = rcon.Restitution;
            if (rcon.Phys == PhysType.FollowBone)
            {
                //Body.SetCustomDebugColor(new Vector3(0, 1, 0));
                Body.CollisionFlags = Body.CollisionFlags | CollisionFlags.KinematicObject;
            }

            /*
             * else if (rcon.Phys == PhysType.Gravity)
             *  Body.SetCustomDebugColor(new Vector3(1, 0, 0));
             * else if (rcon.Phys == PhysType.GravityBone)
             *  Body.SetCustomDebugColor(new Vector3(0, 0, 1));
             */
            //Disabled debug color cause its freeze engine on 3rd model load
        }
コード例 #3
0
        public override void Init(BulletExampleWall ctx)
        {
            base.Init(ctx);

            //Creamos shapes y bodies.

            //El piso es un plano estatico se dice que si tiene masa 0 es estatico.
            var floorShape       = new StaticPlaneShape(TGCVector3.Up.ToBulletVector3(), 0);
            var floorMotionState = new DefaultMotionState();
            var floorInfo        = new RigidBodyConstructionInfo(0, floorMotionState, floorShape);

            floorBody = new RigidBody(floorInfo);
            dynamicsWorld.AddRigidBody(floorBody);

            //Se crea una caja de tamaño 20 con rotaciones y origien en 10,100,10 y 1kg de masa.
            var boxShape     = new BoxShape(10, 10, 10);
            var boxTransform = TGCMatrix.RotationYawPitchRoll(MathUtil.SIMD_HALF_PI, MathUtil.SIMD_QUARTER_PI, MathUtil.SIMD_2_PI).ToBsMatrix;

            boxTransform.Origin = new TGCVector3(10, 100, 10).ToBulletVector3();
            DefaultMotionState boxMotionState = new DefaultMotionState(boxTransform);
            //Es importante calcular la inercia caso contrario el objeto no rotara.
            var boxLocalInertia = boxShape.CalculateLocalInertia(1f);
            var boxInfo         = new RigidBodyConstructionInfo(1f, boxMotionState, boxShape, boxLocalInertia);

            boxBody = new RigidBody(boxInfo);
            dynamicsWorld.AddRigidBody(boxBody);

            //Crea una bola de radio 10 origen 50 de 1 kg.
            var ballShape     = new SphereShape(10);
            var ballTransform = TGCMatrix.Identity;

            ballTransform.Origin = new TGCVector3(0, 50, 0);
            var ballMotionState = new DefaultMotionState(ballTransform.ToBsMatrix);
            //Podriamos no calcular la inercia para que no rote, pero es correcto que rote tambien.
            var ballLocalInertia = ballShape.CalculateLocalInertia(1f);
            var ballInfo         = new RigidBodyConstructionInfo(1, ballMotionState, ballShape, ballLocalInertia);

            ballBody = new RigidBody(ballInfo);
            dynamicsWorld.AddRigidBody(ballBody);

            //Cargamos objetos de render del framework.
            var floorTexture = TgcTexture.createTexture(D3DDevice.Instance.Device, Ctx.MediaDir + @"Texturas\granito.jpg");

            floorMesh = new TgcPlane(new TGCVector3(-200, 0, -200), new TGCVector3(400, 0f, 400), TgcPlane.Orientations.XZplane, floorTexture);

            var texture = TgcTexture.createTexture(D3DDevice.Instance.Device, Ctx.MediaDir + @"Texturas\madera.jpg");

            //Es importante crear todos los mesh con centro en el 0,0,0 y que este coincida con el centro de masa definido caso contrario rotaria de otra forma diferente a la dada por el motor de fisica.
            boxMesh = TGCBox.fromSize(new TGCVector3(20, 20, 20), texture);
            //Se crea una esfera de tamaño 1 para escalarla luego (en render)
            sphereMesh = new TGCSphere(1, texture.Clone(), TGCVector3.Empty);
            //Tgc no crea el vertex buffer hasta invocar a update values.
            sphereMesh.updateValues();
        }
コード例 #4
0
        public static RigidBody crearBodyEsferico(TGCVector3 origen, float radio, float masa)
        {
            #region BOLA

            var ballShape     = new SphereShape(radio);
            var ballTransform = TGCMatrix.Identity;
            ballTransform.Origin = origen;
            var ballMotionState  = new DefaultMotionState(ballTransform.ToBsMatrix);
            var ballLocalInertia = ballShape.CalculateLocalInertia(masa);
            var ballInfo         = new RigidBodyConstructionInfo(masa, ballMotionState, ballShape, ballLocalInertia);
            return(new RigidBody(ballInfo));

            #endregion
        }
コード例 #5
0
ファイル: BulletTest.cs プロジェクト: hiroshi-nz/GLManager
        public RigidBody AddFallingRigidBody()
        {
            CollisionShape fallShape = new SphereShape(1);

            BulletSharp.Math.Vector3 fallInertia = new BulletSharp.Math.Vector3(0, 0, 0);
            float mass = 1;

            fallShape.CalculateLocalInertia(mass, out fallInertia);

            RigidBodyConstructionInfo fallRigidBodyCI = new RigidBodyConstructionInfo(mass, new DefaultMotionState(), fallShape, BulletSharp.Math.Vector3.Zero);
            RigidBody fallRigidBody = new RigidBody(fallRigidBodyCI);

            fallRigidBody.Translate(new BulletSharp.Math.Vector3(0, 100, 0));
            dynamicsWorld.AddRigidBody(fallRigidBody);

            return(fallRigidBody);
        }
コード例 #6
0
        /// <summary>
        ///     Se crea una esfera a partir de un radio, masa y posicion devolviendo el cuerpo rigido de una
        ///     esfera.
        /// </summary>
        /// <param name="radius">Radio de una esfera</param>
        /// <param name="mass">Masa de la esfera</param>
        /// <param name="position">Posicion de la Esfera</param>
        /// <returns>Rigid Body de la Esfera</returns>
        public static RigidBody CreateBall(float radius, float mass, TGCVector3 position)
        {
            //Creamos la forma de la esfera a partir de un radio
            var ballShape = new SphereShape(radius);

            //Armamos las matrices de transformacion de la esfera a partir de la posicion con la que queremos ubicarla
            //y el estado de movimiento de la misma.
            var ballTransform = TGCMatrix.Identity;

            ballTransform.Origin = position;
            var ballMotionState = new DefaultMotionState(ballTransform.ToBsMatrix);

            //Se calcula el momento de inercia de la esfera a partir de la masa.
            var ballLocalInertia = ballShape.CalculateLocalInertia(mass);
            var ballInfo         = new RigidBodyConstructionInfo(mass, ballMotionState, ballShape, ballLocalInertia);

            //Creamos el cuerpo rigido de la esfera a partir de la info.
            var ballBody = new RigidBody(ballInfo);

            ballBody.LinearFactor = TGCVector3.One.ToBsVector;
            return(ballBody);
        }
コード例 #7
0
        protected override void OnInitializePhysics()
        {
            // collision configuration contains default setup for memory, collision setup
            CollisionConf = new DefaultCollisionConfiguration();
            Dispatcher    = new CollisionDispatcher(CollisionConf);

            Broadphase = new DbvtBroadphase();
            Solver     = new MultiBodyConstraintSolver();

            World         = new MultiBodyDynamicsWorld(Dispatcher, Broadphase, Solver as MultiBodyConstraintSolver, CollisionConf);
            World.Gravity = new Vector3(0, -9.81f, 0);

            const bool floating        = false;
            const bool gyro            = false;
            const int  numLinks        = 1;
            const bool canSleep        = false;
            const bool selfCollide     = false;
            Vector3    linkHalfExtents = new Vector3(0.05f, 0.5f, 0.1f);
            //Vector3 baseHalfExtents = new Vector3(0.05f, 0.5f, 0.1f);

            Vector3     baseInertiaDiag = Vector3.Zero;
            const float baseMass        = 0;

            multiBody = new MultiBody(numLinks, baseMass, baseInertiaDiag, !floating, canSleep);
            //multiBody.UseRK4Integration = true;
            //multiBody.BaseWorldTransform = Matrix.Identity;

            //init the links
            Vector3 hingeJointAxis = new Vector3(1, 0, 0);

            //y-axis assumed up
            Vector3 parentComToCurrentCom    = new Vector3(0, -linkHalfExtents[1], 0);
            Vector3 currentPivotToCurrentCom = new Vector3(0, -linkHalfExtents[1], 0);
            Vector3 parentComToCurrentPivot  = parentComToCurrentCom - currentPivotToCurrentCom;

            for (int i = 0; i < numLinks; i++)
            {
                const float linkMass        = 10;
                Vector3     linkInertiaDiag = Vector3.Zero;
                using (var shape = new SphereShape(radius))
                {
                    shape.CalculateLocalInertia(linkMass, out linkInertiaDiag);
                }

                multiBody.SetupRevolute(i, linkMass, linkInertiaDiag, i - 1, Quaternion.Identity,
                                        hingeJointAxis, parentComToCurrentPivot, currentPivotToCurrentCom, false);
            }

            multiBody.FinalizeMultiDof();

            (World as MultiBodyDynamicsWorld).AddMultiBody(multiBody);
            multiBody.CanSleep         = canSleep;
            multiBody.HasSelfCollision = selfCollide;
            multiBody.UseGyroTerm      = gyro;

#if PENDULUM_DAMPING
            multiBody.LinearDamping  = 0.1f;
            multiBody.AngularDamping = 0.9f;
#else
            multiBody.LinearDamping  = 0;
            multiBody.AngularDamping = 0;
#endif

            for (int i = 0; i < numLinks; i++)
            {
                var shape = new SphereShape(radius);
                CollisionShapes.Add(shape);
                var col = new MultiBodyLinkCollider(multiBody, i);
                col.CollisionShape = shape;
                //const bool isDynamic = true;
                CollisionFilterGroups collisionFilterGroup = CollisionFilterGroups.DefaultFilter; // : CollisionFilterGroups.StaticFilter;
                CollisionFilterGroups collisionFilterMask  = CollisionFilterGroups.AllFilter;     // : CollisionFilterGroups.AllFilter & ~CollisionFilterGroups.StaticFilter;
                World.AddCollisionObject(col, collisionFilterGroup, collisionFilterMask);
                multiBody.GetLink(i).Collider = col;
            }
        }
コード例 #8
0
        public void Init()
        {
            #region MUNDO_FISICO //Creamos el mundo fisico por defecto.
            collisionConfiguration = new DefaultCollisionConfiguration();
            dispatcher             = new CollisionDispatcher(collisionConfiguration);

            GImpactCollisionAlgorithm.RegisterAlgorithm(dispatcher);
            constraintSolver     = new SequentialImpulseConstraintSolver();
            overlappingPairCache = new DbvtBroadphase();
            dynamicsWorld        = new DiscreteDynamicsWorld(dispatcher, overlappingPairCache, constraintSolver, collisionConfiguration)
            {
                Gravity = new TGCVector3(0, -20f, 0).ToBsVector
            };
            #endregion

            var texture = TgcTexture.createTexture(D3DDevice.Instance.Device, GameModel.mediaDir + "texturas\\terrain\\NormalMapMar.png");
            //Creamos shapes y bodies.

            #region PISO
            //El piso es un plano estatico se dice que si tiene masa 0 es estatico.
            var floorShape       = new StaticPlaneShape(TGCVector3.Up.ToBsVector, 0);
            var floorMotionState = new DefaultMotionState();
            var floorInfo        = new RigidBodyConstructionInfo(0, floorMotionState, floorShape);
            floorBody = new RigidBody(floorInfo);
            dynamicsWorld.AddRigidBody(floorBody);

            //Cargamos objetos de render del framework.
            var floorTexture = TgcTexture.createTexture(D3DDevice.Instance.Device, GameModel.mediaDir + "modelos\\Textures\\Canionero.jpg");
            floorMesh = new TgcPlane(new TGCVector3(0, 500, 0), new TGCVector3(400, 0f, 400), TgcPlane.Orientations.XZplane, floorTexture);
            #endregion

            #region CAJA
            //Se crea una caja de tamaño 20 con rotaciones y origien en 10,100,10 y 1kg de masa.
            var boxShape     = new BoxShape(10, 10, 10);
            var boxTransform = TGCMatrix.RotationYawPitchRoll(MathUtil.SIMD_HALF_PI, MathUtil.SIMD_QUARTER_PI, MathUtil.SIMD_2_PI).ToBsMatrix;
            boxTransform.Origin = new TGCVector3(0, 600, 0).ToBsVector;
            DefaultMotionState boxMotionState = new DefaultMotionState(boxTransform);
            //Es importante calcular la inercia caso contrario el objeto no rotara.
            var boxLocalInertia = boxShape.CalculateLocalInertia(1f);
            var boxInfo         = new RigidBodyConstructionInfo(1f, boxMotionState, boxShape, boxLocalInertia);
            boxBody = new RigidBody(boxInfo);
            dynamicsWorld.AddRigidBody(boxBody);

            //Es importante crear todos los mesh con centro en el 0,0,0 y que este coincida con el centro de masa definido caso contrario rotaria de otra forma diferente a la dada por el motor de fisica.
            boxMesh = TGCBox.fromSize(new TGCVector3(20, 20, 20), texture);

            #endregion

            #region BOLA
            //Se crea una esfera de tamaño 1 para escalarla luego (en render)
            //Crea una bola de radio 10 origen 50 de 1 kg.
            var ballShape     = new SphereShape(10);
            var ballTransform = TGCMatrix.Identity;
            ballTransform.Origin = new TGCVector3(0, 200, 0);
            var ballMotionState = new DefaultMotionState(ballTransform.ToBsMatrix);
            //Podriamos no calcular la inercia para que no rote, pero es correcto que rote tambien.
            var ballLocalInertia = ballShape.CalculateLocalInertia(1f);
            var ballInfo         = new RigidBodyConstructionInfo(1, ballMotionState, ballShape, ballLocalInertia);
            ballBody = new RigidBody(ballInfo);
            dynamicsWorld.AddRigidBody(ballBody);

            sphereMesh = new TGCSphere(1, texture.Clone(), TGCVector3.Empty);
            //Tgc no crea el vertex buffer hasta invocar a update values.
            sphereMesh.updateValues();

            #endregion

            callback = new MyContactResultCallback(dispatcher, dynamicsWorld, floorBody);// boxBody);
        }
コード例 #9
0
ファイル: Program.cs プロジェクト: HaKDMoDz/InVision
		private static void Main(string[] args)
		{
			var collisionConfig = new DefaultCollisionConfiguration();
			var dispatcher = new CollisionDispatcher(collisionConfig);
			var pairCache = new DbvtBroadphase();
			var solver = new SequentialImpulseConstraintSolver();

			var dynamicsWorld = new DiscreteDynamicsWorld(dispatcher, pairCache, solver, collisionConfig);
			dynamicsWorld.Gravity = new Vector3(0, -10, 0);

			var groundShape = new BoxShape(new Vector3(50, 50, 50));
			var groundTransform = Matrix.CreateTranslation(0, -56, 0);

			{
				float mass = 0;
				bool isDynamic = mass != 0;
				Vector3 localInertia = Vector3.Zero;

				if (isDynamic)
					localInertia = groundShape.CalculateLocalInertia(mass);

				var motionState = new DefaultMotionState(groundTransform);
				var rbinfo = new RigidBodyConstructionInfo(mass, motionState, groundShape, localInertia);
				var body = new RigidBody(rbinfo);

				dynamicsWorld.AddRigidBody(body);
			}

			{
				var collisionShape = new SphereShape(1);
				var transform = Matrix.Identity;
				float mass = 1;
				bool isDynamic = mass != 0;
				Vector3 localInertia = Vector3.Zero;

				if (isDynamic)
					localInertia = collisionShape.CalculateLocalInertia(mass);

				transform.Translation = new Vector3(2, 10, 0);

				var motionState = new DefaultMotionState(transform);
				var rbinfo = new RigidBodyConstructionInfo(mass, motionState, collisionShape, localInertia);
				var body = new RigidBody(rbinfo);

				dynamicsWorld.AddRigidBody(body);
			}

			Console.WriteLine("Starting simulation");

			for (int i = 0; i < 100; i++)
			{
				dynamicsWorld.StepSimulation(1f / 60f, 10);

				for (int j = dynamicsWorld.GetNumCollisionObjects() - 1; j >= 0; j--)
				{
					var obj = dynamicsWorld.GetCollisionObjectArray()[j];
					var body = (RigidBody)obj;

					if (body != null && body.GetMotionState() != null)
					{
						Matrix transform = Matrix.Identity;

						body.GetMotionState().GetWorldTransform(ref transform);

						Console.WriteLine("Object@{0} Position={1}", body.GetHashCode(), transform.Translation);
					}
				}
			}

			Console.Read();
		}
コード例 #10
0
        public PendulumDemoSimulation()
        {
            CollisionConfiguration = new DefaultCollisionConfiguration();
            Dispatcher             = new CollisionDispatcher(CollisionConfiguration);

            Broadphase = new DbvtBroadphase();
            _solver    = new MultiBodyConstraintSolver();

            MultiBodyWorld = new MultiBodyDynamicsWorld(Dispatcher, Broadphase, _solver, CollisionConfiguration);
            World.SetInternalTickCallback(TickCallback, null, true);

            const bool floating        = false;
            const bool gyro            = false;
            const int  numLinks        = 1;
            const bool canSleep        = false;
            const bool selfCollide     = false;
            var        linkHalfExtents = new Vector3(0.05f, 0.5f, 0.1f);
            var        baseHalfExtents = new Vector3(0.05f, 0.5f, 0.1f);

            var         baseInertiaDiag = Vector3.Zero;
            const float baseMass        = 0;

            MultiBody = new MultiBody(numLinks, baseMass, baseInertiaDiag, !floating, canSleep);
            //MultiBody.UseRK4Integration = true;
            //MultiBody.BaseWorldTransform = Matrix.Identity;

            //init the links
            var hingeJointAxis = new Vector3(1, 0, 0);

            //y-axis assumed up
            Vector3 parentComToCurrentCom    = new Vector3(0, -linkHalfExtents[1], 0);
            Vector3 currentPivotToCurrentCom = new Vector3(0, -linkHalfExtents[1], 0);
            Vector3 parentComToCurrentPivot  = parentComToCurrentCom - currentPivotToCurrentCom;

            for (int i = 0; i < numLinks; i++)
            {
                const float linkMass        = 10;
                Vector3     linkInertiaDiag = Vector3.Zero;
                using (var shape = new SphereShape(radius))
                {
                    shape.CalculateLocalInertia(linkMass, out linkInertiaDiag);
                }

                MultiBody.SetupRevolute(i, linkMass, linkInertiaDiag, i - 1, Quaternion.Identity,
                                        hingeJointAxis, parentComToCurrentPivot, currentPivotToCurrentCom, false);
            }

            MultiBody.FinalizeMultiDof();

            MultiBodyWorld.AddMultiBody(MultiBody);
            MultiBody.CanSleep         = canSleep;
            MultiBody.HasSelfCollision = selfCollide;
            MultiBody.UseGyroTerm      = gyro;

#if PENDULUM_DAMPING
            MultiBody.LinearDamping  = 0.1f;
            MultiBody.AngularDamping = 0.9f;
#else
            MultiBody.LinearDamping  = 0;
            MultiBody.AngularDamping = 0;
#endif

            for (int i = 0; i < numLinks; i++)
            {
                var shape = new SphereShape(radius);
                var col   = new MultiBodyLinkCollider(MultiBody, i);
                col.CollisionShape = shape;
                const bool            isDynamic            = true;
                CollisionFilterGroups collisionFilterGroup = isDynamic ? CollisionFilterGroups.DefaultFilter : CollisionFilterGroups.StaticFilter;
                CollisionFilterGroups collisionFilterMask  = isDynamic ? CollisionFilterGroups.AllFilter : CollisionFilterGroups.AllFilter & ~CollisionFilterGroups.StaticFilter;
                World.AddCollisionObject(col, collisionFilterGroup, collisionFilterMask);
                MultiBody.GetLink(i).Collider = col;
            }
        }