示例#1
0
        public override void InitializeDemo()
        {
            //maxiterations = 10;
            SetCameraDistance(SCALING * 50f);

            //string filename = @"E:\users\man\bullet\xna-basic-output-1.txt";
            //FileStream filestream = File.Open(filename, FileMode.Create, FileAccess.Write, FileShare.Read);
            //BulletGlobals.g_streamWriter = new StreamWriter(filestream);

	        ///collision configuration contains default setup for memory, collision setup
	        m_collisionConfiguration = new DefaultCollisionConfiguration();

	        ///use the default collision dispatcher. For parallel processing you can use a diffent dispatcher (see Extras/BulletMultiThreaded)
	        m_dispatcher = new CollisionDispatcher(m_collisionConfiguration);


            IndexedVector3 worldMin = new IndexedVector3(-1000, -1000, -1000);
            IndexedVector3 worldMax = -worldMin;
            m_broadphase = new AxisSweep3Internal(ref worldMin, ref worldMax, 0xfffe, 0xffff, 16384, null, false);

            //m_broadphase = new DbvtBroadphase();
            IOverlappingPairCache pairCache = null;
            //pairCache = new SortedOverlappingPairCache();

            //m_broadphase = new SimpleBroadphase(1000, pairCache);

	        ///the default constraint solver. For parallel processing you can use a different solver (see Extras/BulletMultiThreaded)
	        SequentialImpulseConstraintSolver sol = new SequentialImpulseConstraintSolver();
            m_constraintSolver = sol;

            m_dynamicsWorld = new DiscreteDynamicsWorld(m_dispatcher, m_broadphase, m_constraintSolver, m_collisionConfiguration);

            IndexedVector3 gravity = new IndexedVector3(0, -10, 0);
	        m_dynamicsWorld.SetGravity(ref gravity);

	        ///create a few basic rigid bodies
            IndexedVector3 halfExtents = new IndexedVector3(50, 50, 50);
            //IndexedVector3 halfExtents = new IndexedVector3(10, 10, 10);
            CollisionShape groundShape = new BoxShape(ref halfExtents);
            //CollisionShape groundShape = new StaticPlaneShape(new IndexedVector3(0,1,0), 50);
        	
	        m_collisionShapes.Add(groundShape);

            IndexedMatrix groundTransform = IndexedMatrix.CreateTranslation(new IndexedVector3(0, -50, 0));
            //IndexedMatrix groundTransform = IndexedMatrix.CreateTranslation(new IndexedVector3(0,-10,0));
	        float mass = 0f;
            LocalCreateRigidBody(mass, ref groundTransform, groundShape);
	        {
		        //create a few dynamic rigidbodies
                CollisionShape colShape = new BoxShape(new IndexedVector3(SCALING, SCALING, SCALING));
                //CollisionShape colShape = BuildCorner();
		        //btCollisionShape* colShape = new btSphereShape(btScalar(1.));
                //CollisionShape colShape = new CylinderShape(new IndexedVector3(1f, 1, 1f));
		        m_collisionShapes.Add(colShape);

		        /// Create Dynamic Objects
		        IndexedMatrix startTransform = IndexedMatrix.Identity;

		        mass = 1f;

		        //rigidbody is dynamic if and only if mass is non zero, otherwise static
		        bool isDynamic = mass != 0f;

		        IndexedVector3 localInertia = IndexedVector3.Zero;
		        if (isDynamic)
                {
			        colShape.CalculateLocalInertia(mass, out localInertia);
                }
		        float start_x = START_POS_X - ARRAY_SIZE_X/2;
		        float start_y = START_POS_Y;
		        float start_z = START_POS_Z - ARRAY_SIZE_Z/2;

		        for (int k=0;k<ARRAY_SIZE_Y;k++)
		        {
			        for (int i=0;i<ARRAY_SIZE_X;i++)
			        {
				        for(int j = 0;j<ARRAY_SIZE_Z;j++)
				        {
                            startTransform._origin = (new IndexedVector3(2.0f * i + start_x, 20 + 2.0f * k + start_y, 2.0f * j + start_z) * SCALING);

                            //using motionstate is recommended, it provides interpolation capabilities, and only synchronizes 'active' objects
                            DefaultMotionState myMotionState = new DefaultMotionState(startTransform, IndexedMatrix.Identity);
                            RigidBodyConstructionInfo rbInfo = new RigidBodyConstructionInfo(mass, myMotionState, colShape, localInertia);
                            RigidBody body = new RigidBody(rbInfo);
                            //body->setContactProcessingThreshold(colShape->getContactBreakingThreshold());
                            //body.SetActivationState(ActivationState.ISLAND_SLEEPING);

                            m_dynamicsWorld.AddRigidBody(body);
                            //body.SetActivationState(ActivationState.ISLAND_SLEEPING);
                            body.SetUserPointer(String.Format("Box X{0} Y{1} Z{2}", k, i, j));
				        }
			        }
		        }
	        }

            //ClientResetScene();
        }
示例#2
0
        //----------------------------------------------------------------------------------------------

        public RigidBody LocalCreateRigidBodyMultiWorld(float mass, ref IndexedMatrix startTransform, CollisionShape shape, DiscreteDynamicsWorld world)
        {

            Debug.Assert((shape == null || shape.GetShapeType() != BroadphaseNativeTypes.INVALID_SHAPE_PROXYTYPE));

            //rigidbody is dynamic if and only if mass is non zero, otherwise static
            bool isDynamic = !MathUtil.CompareFloat(mass, 0f);

            IndexedVector3 localInertia = IndexedVector3.Zero;
            if (isDynamic)
            {
                shape.CalculateLocalInertia(mass, out localInertia);
            }
            //using motionstate is recommended, it provides interpolation capabilities, and only synchronizes 'active' objects

            //#define USE_MOTIONSTATE 1
            //#ifdef USE_MOTIONSTATE
            DefaultMotionState myMotionState = new DefaultMotionState(startTransform, IndexedMatrix.Identity);

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

            RigidBody body = new RigidBody(cInfo);

            if (BulletGlobals.g_streamWriter != null && true)
            {
                BulletGlobals.g_streamWriter.WriteLine("localCreateRigidBody [{0}] startTransform", body.m_debugBodyId);
                MathUtil.PrintMatrix(BulletGlobals.g_streamWriter, startTransform);
                BulletGlobals.g_streamWriter.WriteLine("");
            }

            world.AddRigidBody(body);

            return body;
        }
示例#3
0
        protected override void Initialize()
        {
            base.Initialize();
            SetCameraDistance(50.0f);

            ///collision configuration contains default setup for memory, collision setup
            m_collisionConfiguration = new DefaultCollisionConfiguration();
            //m_collisionConfiguration.setConvexConvexMultipointIterations();

            ///use the default collision dispatcher. For parallel processing you can use a diffent dispatcher (see Extras/BulletMultiThreaded)
            m_dispatcher = new CollisionDispatcher(m_collisionConfiguration);

            m_broadphase = new DbvtBroadphase();

            ///the default constraint solver. For parallel processing you can use a different solver (see Extras/BulletMultiThreaded)
            m_constraintSolver = new SequentialImpulseConstraintSolver();

            m_dynamicsWorld = new DiscreteDynamicsWorld(m_dispatcher, m_broadphase, m_constraintSolver, m_collisionConfiguration);

            IndexedVector3 gravity = new IndexedVector3(0, -10, 0);
            m_dynamicsWorld.SetGravity(ref gravity);


            // NEW => btGhostPairCallback =================================
            m_ghostPairCallback = new GhostPairCallback();
            m_dynamicsWorld.GetBroadphase().GetOverlappingPairCache().SetInternalGhostPairCallback(m_ghostPairCallback);	// Needed once to enable ghost objects inside Bullet

            // NEW => btGhostObject =======================================
            m_ghostObject = new GhostObject();
            CollisionShape shape = new BoxShape(new IndexedVector3(5f));	// As far as I know only the world aabb of the shape will be used (i.e. a box always parallel to the x,y,z axis of variable size)
            m_collisionShapes.Add(shape);
            m_ghostObject.SetCollisionShape(shape);
            m_ghostObject.SetCollisionFlags(CollisionFlags.CF_NO_CONTACT_RESPONSE);		// We can choose to make it "solid" if we want...
            m_dynamicsWorld.AddCollisionObject(m_ghostObject, CollisionFilterGroups.SensorTrigger, CollisionFilterGroups.AllFilter & ~CollisionFilterGroups.SensorTrigger);
            //m_ghostObject.setWorldTransform(btTransform(btQuaternion::getIdentity(),btVector3(0,5,-15)));
            IndexedMatrix im = IndexedMatrix.CreateFromQuaternion(quatDeg45Y);
            im._origin = new IndexedVector3(0, 5, -15);
            m_ghostObject.SetWorldTransform(im);

            // NEW => btPairCachingGhostObject ============================
            m_pairCachingGhostObject = new PairCachingGhostObject();
            shape = new ConeShape(7.0f, 14.0f);
            m_collisionShapes.Add(shape);
            m_pairCachingGhostObject.SetCollisionShape(shape);
            m_pairCachingGhostObject.SetCollisionFlags(CollisionFlags.CF_NO_CONTACT_RESPONSE);	// We can choose to make it "solid" if we want...
            m_dynamicsWorld.AddCollisionObject(m_pairCachingGhostObject, CollisionFilterGroups.SensorTrigger, CollisionFilterGroups.AllFilter & ~CollisionFilterGroups.SensorTrigger);
            //m_pairCachingGhostObject.setWorldTransform(btTransform(btQuaternion::getIdentity(),btVector3(0,5,15)));
            im._origin = new IndexedVector3(0, 7, 15);
            m_pairCachingGhostObject.SetWorldTransform(im);
            //=============================================================

            ///create a few basic rigid bodies
            CollisionShape groundShape = new BoxShape(new IndexedVector3(50));

            m_collisionShapes.Add(groundShape);

            IndexedMatrix groundTransform = IndexedMatrix.Identity;
            groundTransform._origin = new IndexedVector3(0, -50, 0);

            float mass = 0.0f;
            LocalCreateRigidBody(mass, groundTransform, groundShape);

            // spawn some cubes (code pasted from appBasicDemo...)
            if(true)
            {
                //create a few dynamic rigidbodies
                CollisionShape colShape = new BoxShape(new IndexedVector3(SCALING, SCALING, SCALING));
                //btCollisionShape* colShape = new btSphereShape(btScalar(1.));
                //CollisionShape colShape = new CylinderShape(new IndexedVector3(1f, 1, 1f));
                m_collisionShapes.Add(colShape);

                /// Create Dynamic Objects
                IndexedMatrix startTransform = IndexedMatrix.Identity;

                mass = 1f;

                //rigidbody is dynamic if and only if mass is non zero, otherwise static
                bool isDynamic = mass != 0f;

                IndexedVector3 localInertia = IndexedVector3.Zero;
                if (isDynamic)
                {
                    colShape.CalculateLocalInertia(mass, out localInertia);
                }
                float start_x = START_POS_X - ARRAY_SIZE_X / 2;
                float start_y = START_POS_Y;
                float start_z = START_POS_Z - ARRAY_SIZE_Z / 2;

                for (int k = 0; k < ARRAY_SIZE_Y; k++)
                {
                    for (int i = 0; i < ARRAY_SIZE_X; i++)
                    {
                        for (int j = 0; j < ARRAY_SIZE_Z; j++)
                        {
                            startTransform._origin = (new IndexedVector3(2.0f * i + start_x, 20 + 2.0f * k + start_y, 2.0f * j + start_z) * SCALING);

                            //using motionstate is recommended, it provides interpolation capabilities, and only synchronizes 'active' objects
                            DefaultMotionState myMotionState = new DefaultMotionState(startTransform, IndexedMatrix.Identity);
                            RigidBodyConstructionInfo rbInfo = new RigidBodyConstructionInfo(mass, myMotionState, colShape, localInertia);
                            RigidBody body = new RigidBody(rbInfo);
                            //body.setContactProcessingThreshold(colShape.getContactBreakingThreshold());
                            body.SetActivationState(ActivationState.ISLAND_SLEEPING);

                            m_dynamicsWorld.AddRigidBody(body);
                            body.SetActivationState(ActivationState.ISLAND_SLEEPING);
                            body.SetUserPointer(String.Format("Box X{0} Y{1} Z{2}", k, i, j));
                        }
                    }
                }
            }

            ClientResetScene();

        }
示例#4
0
文件: Physics.cs 项目: diqost/bullet
        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);

            GImpactCollisionAlgorithm.RegisterAlgorithm(Dispatcher);


            BulletWorldImporter fileLoader = new CustomBulletWorldImporter(World);

            if (!fileLoader.LoadFile("testFile.bullet"))
            {
                CollisionShape groundShape = new BoxShape(50);
                CollisionShapes.Add(groundShape);
                RigidBody ground = LocalCreateRigidBody(0, Matrix.Translation(0, -50, 0), groundShape);
                ground.UserObject = "Ground";

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

                Vector3[] positions = new Vector3[2] {
                    new Vector3(0.1f, 0.2f, 0.3f), new Vector3(0.4f, 0.5f, 0.6f)
                };
                float[] radi = new float[2] {
                    0.3f, 0.4f
                };

                CollisionShape colShape = new MultiSphereShape(positions, radi);

                //CollisionShape colShape = new CapsuleShapeZ(1, 1);
                //CollisionShape colShape = new CylinderShapeZ(1, 1, 1);
                //CollisionShape colShape = new BoxShape(1);
                //CollisionShape colShape = new SphereShape(1);
                CollisionShapes.Add(colShape);

                Vector3 localInertia = colShape.CalculateLocalInertia(mass);

                var rbInfo = new RigidBodyConstructionInfo(mass, null, colShape, localInertia);

                const float startX = StartPosX - ArraySizeX / 2;
                const float startY = StartPosY;
                const float startZ = StartPosZ - ArraySizeZ / 2;

                for (int k = 0; k < ArraySizeY; k++)
                {
                    for (int i = 0; i < ArraySizeX; i++)
                    {
                        for (int j = 0; j < ArraySizeZ; j++)
                        {
                            Matrix startTransform = Matrix.Translation(
                                2 * i + startX,
                                2 * k + startY,
                                2 * j + startZ
                                );

                            // using motionstate is recommended, it provides interpolation capabilities
                            // and only synchronizes 'active' objects
                            rbInfo.MotionState = new DefaultMotionState(startTransform);
                            RigidBody body = new RigidBody(rbInfo);

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

                            World.AddRigidBody(body);
                        }
                    }
                }

                DefaultSerializer serializer = new DefaultSerializer();

                serializer.RegisterNameForObject(ground, "GroundName");

                for (int i = 0; i < CollisionShapes.Count; i++)
                {
                    serializer.RegisterNameForObject(CollisionShapes[i], "name" + i.ToString());
                }

                Point2PointConstraint p2p = new Point2PointConstraint((RigidBody)World.CollisionObjectArray[2], new Vector3(0, 1, 0));
                World.AddConstraint(p2p);

                serializer.RegisterNameForObject(p2p, "constraintje");

                World.Serialize(serializer);

                BulletSharp.DataStream data = serializer.LockBuffer();
                byte[] dataBytes            = new byte[data.Length];
                data.Read(dataBytes, 0, dataBytes.Length);

                FileStream file = new FileStream("testFile.bullet", FileMode.Create);
                file.Write(dataBytes, 0, dataBytes.Length);
                file.Close();
            }
        }
示例#5
0
        public override void InitializeDemo()
        {
            //string filename = @"E:\users\man\bullet\xna-constraint-output.txt";
            //FileStream filestream = File.Open(filename, FileMode.Create, FileAccess.Write, FileShare.Read);
            //BulletGlobals.g_streamWriter = new StreamWriter(filestream);

            //maxiterations = 100;

	        m_collisionConfiguration = new DefaultCollisionConfiguration();
	        m_dispatcher = new CollisionDispatcher(m_collisionConfiguration);
	        IndexedVector3 worldMin = new IndexedVector3(-1000,-1000,-1000);
	        IndexedVector3 worldMax = new IndexedVector3(1000,1000,1000);
            m_broadphase = new AxisSweep3Internal(ref worldMin, ref worldMax, 0xfffe, 0xffff, 16384, null, false);
	        m_constraintSolver = new SequentialImpulseConstraintSolver();
	        m_dynamicsWorld = new DiscreteDynamicsWorld(m_dispatcher,m_broadphase,m_constraintSolver,m_collisionConfiguration);
            m_dynamicsWorld.SetDebugDrawer(m_debugDraw);

            SetCameraDistance(26f);

            //CollisionShape groundShape = new BoxShape(new IndexedVector3(50f, 40f, 50f));
            CollisionShape groundShape = new StaticPlaneShape(new IndexedVector3(0, 1, 0), 40);

            m_collisionShapes.Add(groundShape);
            IndexedMatrix groundTransform = IndexedMatrix.Identity;
            groundTransform._origin = new IndexedVector3(0, -56, 0);
            RigidBody groundBody = LocalCreateRigidBody(0, ref groundTransform, groundShape);

            CollisionShape shape = new BoxShape(new IndexedVector3(CUBE_HALF_EXTENTS, CUBE_HALF_EXTENTS, CUBE_HALF_EXTENTS));
            m_collisionShapes.Add(shape);
            IndexedMatrix trans = IndexedMatrix.Identity;
            trans._origin = new IndexedVector3(0, 20, 0);

	        float mass = 1f;

#if true
	    //point to point constraint with a breaking threshold
	    {
		    trans = IndexedMatrix.Identity;
		    trans._origin = new IndexedVector3(1,30,-5);
		    LocalCreateRigidBody( mass,trans,shape);
		    trans._origin = new IndexedVector3(0,0,-5);

		    RigidBody body0 = LocalCreateRigidBody( mass,trans,shape);
		    
            trans._origin = new IndexedVector3(2*CUBE_HALF_EXTENTS,20,0);
		    mass = 1.0f;
		    RigidBody body1 = null;//localCreateRigidBody( mass,trans,shape);
		    IndexedVector3 pivotInA = new IndexedVector3(CUBE_HALF_EXTENTS,CUBE_HALF_EXTENTS,0);
		    TypedConstraint p2p = new Point2PointConstraint(body0,ref pivotInA);
		    m_dynamicsWorld.AddConstraint(p2p);
		    p2p.SetBreakingImpulseThreshold(10.2f);
		    p2p.SetDbgDrawSize(5.0f);
	    }
#endif



#if true
        //point to point constraint (ball socket)
			//SEEMS OK
	        {
                //trans = IndexedMatrix.Identity;
		        RigidBody body0 = LocalCreateRigidBody( mass,ref trans,shape);
		        trans._origin = new IndexedVector3(2*CUBE_HALF_EXTENTS,20,0);

		        mass = 1f;
		        RigidBody body1 = null;//localCreateRigidBody( mass,trans,shape);

		        IndexedVector3 pivotInA = new IndexedVector3(CUBE_HALF_EXTENTS,-CUBE_HALF_EXTENTS,-CUBE_HALF_EXTENTS);
		        IndexedVector3 axisInA = new IndexedVector3(0,0,1);

                IndexedVector3 pivotInB = body1 != null ? body1.GetCenterOfMassTransform().Inverse() * (body0.GetCenterOfMassTransform() * (pivotInA)) : pivotInA;
                IndexedVector3 axisInB = body1 != null ? (body1.GetCenterOfMassTransform()._basis.Inverse() * (body1.GetCenterOfMassTransform()._basis * axisInA)) :
                body0.GetCenterOfMassTransform()._basis * axisInA;
#if P2P
		TypedConstraint p2p = new Point2PointConstraint(body0,ref pivotInA);
		//btTypedConstraint* p2p = new btPoint2PointConstraint(*body0,*body1,pivotInA,pivotInB);
		//btTypedConstraint* hinge = new btHingeConstraint(*body0,*body1,pivotInA,pivotInB,axisInA,axisInB);
		m_dynamicsWorld.AddConstraint(p2p);
		p2p.SetDbgDrawSize(5.0f);
#else

		        HingeConstraint hinge = new HingeConstraint(body0,ref pivotInA,ref axisInA,false);
        		
		        float	targetVelocity = 1f;
		        float	maxMotorImpulse = 1.0f;
		        hinge.EnableAngularMotor(true,targetVelocity,maxMotorImpulse);

		        m_dynamicsWorld.AddConstraint(hinge);//p2p);
		        hinge.SetDbgDrawSize(5f);
        #endif
	        }
#endif

#if true
            //create a slider, using the generic D6 constraint
			// SEEMS OK
	        {
		        mass = 1f;
		        IndexedVector3 sliderWorldPos = new IndexedVector3(0,10,0);
		        IndexedVector3 sliderAxis = new IndexedVector3(1,0,0);
		        float angle=0f;//SIMD_RADS_PER_DEG * 10.f;
		        IndexedBasisMatrix sliderOrientation = new IndexedBasisMatrix(new IndexedQuaternion(sliderAxis,angle));
		        trans = IndexedMatrix.Identity;
		        trans._origin = sliderWorldPos;
		        //trans.setBasis(sliderOrientation);
		        sliderTransform = trans;

		        d6body0 = LocalCreateRigidBody( mass,ref trans,shape);
		        d6body0.SetActivationState(ActivationState.DISABLE_DEACTIVATION);
		        RigidBody fixedBody1 = LocalCreateRigidBody(0,ref trans,null);
		        m_dynamicsWorld.AddRigidBody(fixedBody1);

		        IndexedMatrix frameInA, frameInB;
		        frameInA = IndexedMatrix.Identity;
		        frameInB = IndexedMatrix.Identity;
                frameInA._origin = new IndexedVector3(0, 5, 0);
                frameInB._origin = new IndexedVector3(0, 5, 0);

        //		bool useLinearReferenceFrameA = false;//use fixed frame B for linear llimits
		        bool useLinearReferenceFrameA = true;//use fixed frame A for linear llimits
		        spSlider6Dof = new Generic6DofConstraint(fixedBody1, d6body0,ref frameInA,ref frameInB,useLinearReferenceFrameA);
                spSlider6Dof.SetLinearLowerLimit(ref lowerSliderLimit);
                spSlider6Dof.SetLinearUpperLimit(ref hiSliderLimit);

		        //range should be small, otherwise singularities will 'explode' the constraint
                IndexedVector3 angularLower = new IndexedVector3(-1.5f,0,0);
                IndexedVector3 angularUpper = -angularLower;
                spSlider6Dof.SetAngularLowerLimit(ref angularLower);
                spSlider6Dof.SetAngularUpperLimit(ref angularUpper);
        //		slider.setAngularLowerLimit(IndexedVector3(0,0,0));
        //		slider.setAngularUpperLimit(IndexedVector3(0,0,0));
                spSlider6Dof.SetAngularLowerLimit(new IndexedVector3(-MathUtil.SIMD_PI, 0, 0));
                spSlider6Dof.SetAngularUpperLimit(new IndexedVector3(1.5f, 0, 0));

                spSlider6Dof.GetTranslationalLimitMotor().m_enableMotor[0] = true;
                spSlider6Dof.GetTranslationalLimitMotor().m_targetVelocity.X = -5.0f;
                spSlider6Dof.GetTranslationalLimitMotor().m_maxMotorForce.X = 0.1f;


                m_dynamicsWorld.AddConstraint(spSlider6Dof);
                spSlider6Dof.SetDbgDrawSize(5f);

	        }
#endif
#if true
	        { // create a door using hinge constraint attached to the world
		        CollisionShape pDoorShape = new BoxShape(new IndexedVector3(2.0f, 5.0f, 0.2f));
		        m_collisionShapes.Add(pDoorShape);
		        IndexedMatrix doorTrans = IndexedMatrix.Identity;
		        doorTrans._origin = new IndexedVector3(-5.0f, -2.0f, 0.0f);
		        RigidBody pDoorBody = LocalCreateRigidBody( 1.0f, ref doorTrans, pDoorShape);
		        pDoorBody.SetActivationState(ActivationState.DISABLE_DEACTIVATION);
		        IndexedVector3 btPivotA = new IndexedVector3( 10f+2.1f, -2.0f, 0.0f ); // right next to the door slightly outside
		        IndexedVector3 btAxisA = new IndexedVector3( 0.0f, 1.0f, 0.0f ); // pointing upwards, aka Y-axis

		        spDoorHinge = new HingeConstraint( pDoorBody, ref btPivotA, ref btAxisA,false );

                spDoorHinge.SetLimit(-MathUtil.SIMD_PI * 0.25f, MathUtil.SIMD_PI * 0.25f);
		        m_dynamicsWorld.AddConstraint(spDoorHinge);
		        spDoorHinge.SetDbgDrawSize(5.0f);

	        }
#endif
#if true
            { // create a generic 6DOF constraint
				// SEEMS OK - But debug draw a bit wrong?
		        IndexedMatrix tr = IndexedMatrix.Identity;
		        tr._origin = new IndexedVector3(10f, 6f, 0f);
                //tr.getBasis().setEulerZYX(0,0,0);
        //		RigidBody pBodyA = localCreateRigidBody( mass, tr, shape);
		        RigidBody pBodyA = LocalCreateRigidBody( 0.0f, ref tr, shape);
        //		RigidBody pBodyA = localCreateRigidBody( 0.0, tr, 0);
		        pBodyA.SetActivationState(ActivationState.DISABLE_DEACTIVATION);

                tr = IndexedMatrix.Identity;
		        tr._origin = new IndexedVector3(0f, 6f, 0f);		        
                //tr.getBasis().setEulerZYX(0,0,0);
		        RigidBody pBodyB = LocalCreateRigidBody(mass, ref tr, shape);
		        pBodyB.SetActivationState(ActivationState.DISABLE_DEACTIVATION);

		        IndexedMatrix frameInA, frameInB;
		        frameInA = IndexedMatrix.CreateTranslation(-5,0,0);
		        frameInB = IndexedMatrix.CreateTranslation(5,0,0);

		        Generic6DofConstraint pGen6DOF = new Generic6DofConstraint(pBodyA, pBodyB, ref frameInA, ref frameInB, true);
        //		btGeneric6DofConstraint* pGen6DOF = new btGeneric6DofConstraint(*pBodyA, *pBodyB, frameInA, frameInB, false);
		        IndexedVector3 linearLower = new IndexedVector3(-10, -2, -1);
                pGen6DOF.SetLinearLowerLimit(ref linearLower);
                IndexedVector3 linearUpper = new IndexedVector3(10,2,1);
		        pGen6DOF.SetLinearUpperLimit(ref linearUpper);
                // ? why again?
                //linearLower = new IndexedVector3(-10,0,0);
                //pGen6DOF.setLinearLowerLimit(ref linearLower);
        //		pGen6DOF.setLinearUpperLimit(IndexedVector3(10., 0., 0.));
        //		pGen6DOF.setLinearLowerLimit(IndexedVector3(0., 0., 0.));
        //		pGen6DOF.setLinearUpperLimit(IndexedVector3(0., 0., 0.));

        //		pGen6DOF.getTranslationalLimitMotor().m_enableMotor[0] = true;
        //		pGen6DOF.getTranslationalLimitMotor().m_targetVelocity[0] = 5.0f;
        //		pGen6DOF.getTranslationalLimitMotor().m_maxMotorForce[0] = 0.1f;


        //		pGen6DOF.setAngularLowerLimit(IndexedVector3(0., SIMD_HALF_PI*0.9, 0.));
        //		pGen6DOF.setAngularUpperLimit(IndexedVector3(0., -SIMD_HALF_PI*0.9, 0.));
        //		pGen6DOF.setAngularLowerLimit(IndexedVector3(0., 0., -SIMD_HALF_PI));
        //		pGen6DOF.setAngularUpperLimit(IndexedVector3(0., 0., SIMD_HALF_PI));

                IndexedVector3 angularLower = new IndexedVector3(-MathUtil.SIMD_HALF_PI * 0.5f, -0.75f, -MathUtil.SIMD_HALF_PI * 0.8f);
                IndexedVector3 angularUpper = -angularLower;
		        pGen6DOF.SetAngularLowerLimit(ref angularLower);
		        pGen6DOF.SetAngularUpperLimit(ref angularUpper);
        //		pGen6DOF.setAngularLowerLimit(IndexedVector3(0.f, -0.75, SIMD_HALF_PI * 0.8f));
        //		pGen6DOF.setAngularUpperLimit(IndexedVector3(0.f, 0.75, -SIMD_HALF_PI * 0.8f));
        //		pGen6DOF.setAngularLowerLimit(IndexedVector3(0.f, -SIMD_HALF_PI * 0.8f, SIMD_HALF_PI * 1.98f));
        //		pGen6DOF.setAngularUpperLimit(IndexedVector3(0.f, SIMD_HALF_PI * 0.8f,  -SIMD_HALF_PI * 1.98f));

        		
        		
        //		pGen6DOF.setAngularLowerLimit(IndexedVector3(-0.75,-0.5, -0.5));
        //		pGen6DOF.setAngularUpperLimit(IndexedVector3(0.75,0.5, 0.5));
        //		pGen6DOF.setAngularLowerLimit(IndexedVector3(-0.75,0., 0.));
        //		pGen6DOF.setAngularUpperLimit(IndexedVector3(0.75,0., 0.));

		        m_dynamicsWorld.AddConstraint(pGen6DOF, true);
		        pGen6DOF.SetDbgDrawSize(5.0f);
	        }
#endif
#if true
            { // create a ConeTwist constraint

		        IndexedMatrix tr = IndexedMatrix.CreateTranslation(-10,5,0);

		        RigidBody pBodyA = LocalCreateRigidBody( 1.0f, ref tr, shape);
		        pBodyA.SetActivationState(ActivationState.DISABLE_DEACTIVATION);

		        tr = IndexedMatrix.CreateTranslation(-10,-5,0);

		        RigidBody pBodyB = LocalCreateRigidBody(0.0f, ref tr, shape);

		        IndexedMatrix frameInA, frameInB;
                frameInA = MathUtil.SetEulerZYX(0, 0, MathUtil.SIMD_HALF_PI);
                frameInA._origin = new IndexedVector3(0, -5, 0);
				frameInB = MathUtil.SetEulerZYX(0, 0, MathUtil.SIMD_HALF_PI);
                frameInB._origin = new IndexedVector3(0, 5, 0);

		        ConeTwistConstraint pCT = new ConeTwistConstraint(pBodyA, pBodyB, ref frameInA, ref frameInB);
		        pCT.SetLimit(MathUtil.SIMD_QUARTER_PI * 0.6f, MathUtil.SIMD_QUARTER_PI, MathUtil.SIMD_PI * 0.8f, 0.5f); // soft limit == hard limit
		        m_dynamicsWorld.AddConstraint(pCT, true);
		        pCT.SetDbgDrawSize(5.0f);
	        }
#endif
#if true
            { // Hinge connected to the world, with motor (to hinge motor with new and old constraint solver)
				// WORKS OK
		        IndexedMatrix tr = IndexedMatrix.Identity;
		        RigidBody pBody = LocalCreateRigidBody( 1.0f, ref tr, shape);
		        pBody.SetActivationState(ActivationState.DISABLE_DEACTIVATION);
		        IndexedVector3 btPivotA = new IndexedVector3( 10.0f, 0.0f, 0.0f );
		        IndexedVector3 btAxisA = new IndexedVector3( 0.0f, 0.0f, 1.0f );

		        HingeConstraint pHinge = new HingeConstraint(pBody, ref btPivotA, ref btAxisA,false);
        //		pHinge.enableAngularMotor(true, -1.0, 0.165); // use for the old solver
		        pHinge.EnableAngularMotor(true, -1.0f, 1.65f); // use for the new SIMD solver
		        m_dynamicsWorld.AddConstraint(pHinge);
		        pHinge.SetDbgDrawSize(5.0f);
	        }
#endif
#if true
            {
		// WORKS OK
		// create a universal joint using generic 6DOF constraint
		// create two rigid bodies
		// static bodyA (parent) on top:
		IndexedMatrix tr = IndexedMatrix.CreateTranslation(20,4,0);
		RigidBody pBodyA = LocalCreateRigidBody( 0.0f, ref tr, shape);
		pBodyA.SetActivationState(ActivationState.DISABLE_DEACTIVATION);
		// dynamic bodyB (child) below it :
		tr = IndexedMatrix.CreateTranslation(20,0,0);
		RigidBody pBodyB = LocalCreateRigidBody(1.0f, ref tr, shape);
		pBodyB.SetActivationState(ActivationState.DISABLE_DEACTIVATION);
		// add some (arbitrary) data to build constraint frames
		IndexedVector3 parentAxis = new IndexedVector3(1.0f, 0.0f, 0.0f); 
		IndexedVector3 childAxis = new IndexedVector3(0.0f, 0.0f, 1.0f);
        IndexedVector3 anchor = new IndexedVector3(20.0f, 2.0f, 0.0f);

		UniversalConstraint pUniv = new UniversalConstraint(pBodyA, pBodyB, ref anchor, ref parentAxis, ref childAxis);
        pUniv.SetLowerLimit(-MathUtil.SIMD_HALF_PI * 0.5f, -MathUtil.SIMD_HALF_PI * 0.5f);
        pUniv.SetUpperLimit(MathUtil.SIMD_HALF_PI * 0.5f, MathUtil.SIMD_HALF_PI * 0.5f);
		// add constraint to world
		m_dynamicsWorld.AddConstraint(pUniv, true);
		// draw constraint frames and limits for debugging
		pUniv.SetDbgDrawSize(5.0f);
	}
#endif

#if true
            // WORKS OK
	{ // create a generic 6DOF constraint with springs 

		IndexedMatrix tr = IndexedMatrix.CreateTranslation(-20f,16f,0f);
        //tr.setIdentity();
        //tr.setOrigin(btVector3(btScalar(-20.), btScalar(16.), btScalar(0.)));
        //tr.getBasis().setEulerZYX(0,0,0);
		RigidBody pBodyA = LocalCreateRigidBody( 0.0f, ref tr, shape);
		pBodyA.SetActivationState(ActivationState.DISABLE_DEACTIVATION);

        //tr.setIdentity();
        //tr.setOrigin(btVector3(btScalar(-10.), btScalar(16.), btScalar(0.)));
        //tr.getBasis().setEulerZYX(0,0,0);
        tr = IndexedMatrix.CreateTranslation(-10,16,0);
		RigidBody pBodyB = LocalCreateRigidBody(1.0f, ref tr, shape);
		pBodyB.SetActivationState(ActivationState.DISABLE_DEACTIVATION);

        IndexedMatrix frameInA = IndexedMatrix.CreateTranslation(10f,0f,0f);
        IndexedMatrix frameInB = IndexedMatrix.CreateTranslation(0f,0f,0f);

		Generic6DofSpringConstraint pGen6DOFSpring = new Generic6DofSpringConstraint(pBodyA, pBodyB, ref frameInA, ref frameInB, true);
		pGen6DOFSpring.SetLinearUpperLimit(new IndexedVector3(5f, 0f, 0f));
		pGen6DOFSpring.SetLinearLowerLimit(new IndexedVector3(-5f, 0f, 0f));

		pGen6DOFSpring.SetAngularLowerLimit(new IndexedVector3(0f, 0f, -1.5f));
		pGen6DOFSpring.SetAngularUpperLimit(new IndexedVector3(0f, 0f, 1.5f));

		m_dynamicsWorld.AddConstraint(pGen6DOFSpring, true);
		pGen6DOFSpring.SetDbgDrawSize(5.0f);
		
		pGen6DOFSpring.EnableSpring(0, true);
		pGen6DOFSpring.SetStiffness(0, 39.478f);
		pGen6DOFSpring.SetDamping(0, 0.5f);
		pGen6DOFSpring.EnableSpring(5, true);
		pGen6DOFSpring.SetStiffness(5, 39.478f);
		pGen6DOFSpring.SetDamping(0, 0.3f);
		pGen6DOFSpring.SetEquilibriumPoint();
	}
#endif
#if true
    {
		// WORKS OK
		// create a Hinge2 joint
		// create two rigid bodies
		// static bodyA (parent) on top:
		IndexedMatrix tr = IndexedMatrix.CreateTranslation(-20f,4f,0f);
        
        RigidBody pBodyA = LocalCreateRigidBody( 0.0f, ref tr, shape);
		pBodyA.SetActivationState(ActivationState.DISABLE_DEACTIVATION);
		// dynamic bodyB (child) below it :
		tr = IndexedMatrix.CreateTranslation(-20f,0f,0f);
        RigidBody pBodyB = LocalCreateRigidBody(1.0f, ref tr, shape);
		pBodyB.SetActivationState(ActivationState.DISABLE_DEACTIVATION);
		// add some data to build constraint frames
		IndexedVector3 parentAxis = new IndexedVector3(0.0f, 1.0f, 0.0f); 
		IndexedVector3 childAxis = new IndexedVector3(1.0f, 0.0f, 0.0f);
        IndexedVector3 anchor = new IndexedVector3(-20.0f, 0.0f, 0.0f);
		Hinge2Constraint pHinge2 = new Hinge2Constraint(pBodyA, pBodyB, ref anchor, ref parentAxis, ref childAxis);
		pHinge2.SetLowerLimit(-MathUtil.SIMD_HALF_PI * 0.5f);
        pHinge2.SetUpperLimit(MathUtil.SIMD_HALF_PI * 0.5f);
		// add constraint to world
		m_dynamicsWorld.AddConstraint(pHinge2, true);
		// draw constraint frames and limits for debugging
		pHinge2.SetDbgDrawSize(5.0f);
	}
#endif
#if true
    { 
			// WORKS OK
		// create a Hinge joint between two dynamic bodies
		// create two rigid bodies
		// static bodyA (parent) on top:
		IndexedMatrix tr = IndexedMatrix.CreateTranslation(-20f,-2f,0f);
		RigidBody pBodyA = LocalCreateRigidBody( 1.0f, ref tr, shape);
		pBodyA.SetActivationState(ActivationState.DISABLE_DEACTIVATION);
		// dynamic bodyB:
		tr = IndexedMatrix.CreateTranslation(-30f,-2f,0f);
		RigidBody pBodyB = LocalCreateRigidBody(10.0f, ref tr, shape);
		pBodyB.SetActivationState(ActivationState.DISABLE_DEACTIVATION);
		// add some data to build constraint frames
		IndexedVector3 axisA = new IndexedVector3(0.0f, 1.0f, 0.0f); 
		IndexedVector3 axisB = new IndexedVector3(0.0f, 1.0f, 0.0f); 
		IndexedVector3 pivotA = new IndexedVector3(-5.0f, 0.0f, 0.0f);
        IndexedVector3 pivotB = new IndexedVector3(5.0f, 0.0f, 0.0f);
		
        spHingeDynAB = new HingeConstraint(pBodyA, pBodyB, ref pivotA, ref pivotB, ref axisA, ref axisB);
        spHingeDynAB.SetLimit(-MathUtil.SIMD_HALF_PI * 0.5f, MathUtil.SIMD_HALF_PI * 0.5f);
		// add constraint to world
		m_dynamicsWorld.AddConstraint(spHingeDynAB, true);
		// draw constraint frames and limits for debugging
		spHingeDynAB.SetDbgDrawSize(5.0f);
	}
#endif

#if true
    { // 6DOF connected to the world, with motor
		IndexedMatrix tr = IndexedMatrix.CreateTranslation(10,-15,0);
		RigidBody pBody = LocalCreateRigidBody( 1.0f, ref tr, shape);
		pBody.SetActivationState(ActivationState.DISABLE_DEACTIVATION);
		IndexedMatrix frameB = IndexedMatrix.Identity;
		Generic6DofConstraint pGen6Dof = new Generic6DofConstraint(pBody, ref frameB, false );
		m_dynamicsWorld.AddConstraint(pGen6Dof);
		pGen6Dof.SetDbgDrawSize(5.0f);

		pGen6Dof.SetAngularLowerLimit(new IndexedVector3(0,0,0));
		pGen6Dof.SetAngularUpperLimit(new IndexedVector3(0,0,0));
		pGen6Dof.SetLinearLowerLimit(new IndexedVector3(-10.0f, 0, 0));
		pGen6Dof.SetLinearUpperLimit(new IndexedVector3(10.0f, 0, 0));

		pGen6Dof.GetTranslationalLimitMotor().m_enableMotor[0] = true;
		pGen6Dof.GetTranslationalLimitMotor().m_targetVelocity[0] = 5.0f;
		pGen6Dof.GetTranslationalLimitMotor().m_maxMotorForce[0] = 0.1f;
	}
#endif
        }
示例#6
0
        protected override void OnInitializePhysics()
        {
            // collision configuration contains default setup for memory, collision setup
            CollisionConf = new DefaultCollisionConfiguration();

            // Use the default collision dispatcher. For parallel processing you can use a diffent dispatcher.
            Dispatcher = new CollisionDispatcher(CollisionConf);

            VoronoiSimplexSolver            simplex  = new VoronoiSimplexSolver();
            MinkowskiPenetrationDepthSolver pdSolver = new MinkowskiPenetrationDepthSolver();

            Convex2DConvex2DAlgorithm.CreateFunc convexAlgo2d = new Convex2DConvex2DAlgorithm.CreateFunc(simplex, pdSolver);

            Dispatcher.RegisterCollisionCreateFunc(BroadphaseNativeType.Convex2DShape, BroadphaseNativeType.Convex2DShape, convexAlgo2d);
            Dispatcher.RegisterCollisionCreateFunc(BroadphaseNativeType.Box2DShape, BroadphaseNativeType.Convex2DShape, convexAlgo2d);
            Dispatcher.RegisterCollisionCreateFunc(BroadphaseNativeType.Convex2DShape, BroadphaseNativeType.Box2DShape, convexAlgo2d);
            Dispatcher.RegisterCollisionCreateFunc(BroadphaseNativeType.Box2DShape, BroadphaseNativeType.Box2DShape, new Box2DBox2DCollisionAlgorithm.CreateFunc());

            Broadphase = new DbvtBroadphase();

            // the default constraint solver.
            Solver = new SequentialImpulseConstraintSolver();

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

            // create a few basic rigid bodies
            CollisionShape groundShape = new BoxShape(150, 7, 150);

            CollisionShapes.Add(groundShape);
            RigidBody ground = LocalCreateRigidBody(0, Matrix.Identity, groundShape);

            ground.UserObject = "Ground";

            // create a few dynamic rigidbodies
            // Re-using the same collision is better for memory usage and performance
            float u = 0.96f;

            Vector3[]   points      = { new Vector3(0, u, 0), new Vector3(-u, -u, 0), new Vector3(u, -u, 0) };
            ConvexShape childShape0 = new BoxShape(1, 1, Depth);
            ConvexShape colShape    = new Convex2DShape(childShape0);
            ConvexShape childShape1 = new ConvexHullShape(points);
            ConvexShape colShape2   = new Convex2DShape(childShape1);
            ConvexShape childShape2 = new CylinderShapeZ(1, 1, Depth);
            ConvexShape colShape3   = new Convex2DShape(childShape2);

            CollisionShapes.Add(colShape);
            CollisionShapes.Add(colShape2);
            CollisionShapes.Add(colShape3);

            CollisionShapes.Add(childShape0);
            CollisionShapes.Add(childShape1);
            CollisionShapes.Add(childShape2);

            colShape.Margin = 0.03f;

            float   mass         = 1.0f;
            Vector3 localInertia = colShape.CalculateLocalInertia(mass);

            Matrix startTransform;

            Vector3 x      = new Vector3(-ArraySizeX, 8, -20);
            Vector3 y      = Vector3.Zero;
            Vector3 deltaX = new Vector3(1, 2, 0);
            Vector3 deltaY = new Vector3(2, 0, 0);

            int i, j;

            for (i = 0; i < ArraySizeY; i++)
            {
                y = x;
                for (j = 0; j < ArraySizeX; j++)
                {
                    startTransform = Matrix.Translation(y - new Vector3(-10, 0, 0));

                    //using motionstate is recommended, it provides interpolation capabilities, and only synchronizes 'active' objects
                    DefaultMotionState myMotionState = new DefaultMotionState(startTransform);

                    RigidBodyConstructionInfo rbInfo;
                    switch (j % 3)
                    {
                    case 0:
                        rbInfo = new RigidBodyConstructionInfo(mass, myMotionState, colShape, localInertia);
                        break;

                    case 1:
                        rbInfo = new RigidBodyConstructionInfo(mass, myMotionState, colShape3, localInertia);
                        break;

                    default:
                        rbInfo = new RigidBodyConstructionInfo(mass, myMotionState, colShape2, localInertia);
                        break;
                    }
                    RigidBody body = new RigidBody(rbInfo);
                    rbInfo.Dispose();
                    //body.ActivationState = ActivationState.IslandSleeping;
                    body.LinearFactor  = new Vector3(1, 1, 0);
                    body.AngularFactor = new Vector3(0, 0, 1);

                    World.AddRigidBody(body);

                    y += deltaY;
                }
                x += deltaX;
            }
        }
        protected override void OnInitializePhysics()
        {
            // 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);

            // create the ground
            CollisionShape groundShape = new BoxShape(20, 50, 10);

            CollisionShapes.Add(groundShape);
            CollisionObject ground = LocalCreateRigidBody(0,
                                                          Matrix.RotationAxis(new Vector3(0, 0, 1), (float)Math.PI * 0.03f) * Matrix.Translation(0, -50, 0),
                                                          groundShape);

            ground.Friction        = 1;
            ground.RollingFriction = 1;
            ground.UserObject      = "Ground";

            groundShape = new BoxShape(100, 50, 100);
            CollisionShapes.Add(groundShape);
            ground                 = LocalCreateRigidBody(0, Matrix.Translation(0, -54, 0), groundShape);
            ground.Friction        = 1;
            ground.RollingFriction = 1;
            ground.UserObject      = "Ground";

            // create a few dynamic rigidbodies
            CollisionShape[] colShapes =
            {
                new SphereShape(1),
                new CapsuleShape(0.5f,                 1),
                new CapsuleShapeX(0.5f,                1),
                new CapsuleShapeZ(0.5f,                1),
                new ConeShape(0.5f,                    1),
                new ConeShapeX(0.5f,                   1),
                new ConeShapeZ(0.5f,                   1),
                new CylinderShape(new Vector3(0.5f,     1, 0.5f)),
                new CylinderShapeX(new Vector3(1,    0.5f, 0.5f)),
                new CylinderShapeZ(new Vector3(0.5f, 0.5f,    1)),
            };
            foreach (var collisionShape in colShapes)
            {
                CollisionShapes.Add(collisionShape);
            }

            const float mass = 1.0f;

            CollisionShape colShape = new BoxShape(1);

            CollisionShapes.Add(colShape);
            Vector3 localInertia = colShape.CalculateLocalInertia(mass);

            var rbInfo = new RigidBodyConstructionInfo(mass, null, null, localInertia);

            const float startX = StartPosX - ArraySizeX / 2;
            const float startY = StartPosY;
            const float startZ = StartPosZ - ArraySizeZ / 2;

            int shapeIndex = 0;

            for (int k = 0; k < ArraySizeY; k++)
            {
                for (int i = 0; i < ArraySizeX; i++)
                {
                    for (int j = 0; j < ArraySizeZ; j++)
                    {
                        Matrix startTransform = Matrix.Translation(
                            2 * i + startX,
                            2 * k + startY + 20,
                            2 * j + startZ
                            );
                        shapeIndex++;

                        // using motionstate is recommended, it provides interpolation capabilities
                        // and only synchronizes 'active' objects
                        rbInfo.MotionState    = new DefaultMotionState(startTransform);
                        rbInfo.CollisionShape = colShapes[shapeIndex % colShapes.Length];

                        RigidBody body = new RigidBody(rbInfo);
                        body.Friction        = 1;
                        body.RollingFriction = 0.3f;
                        body.SetAnisotropicFriction(colShape.AnisotropicRollingFrictionDirection, AnisotropicFrictionFlags.RollingFriction);

                        World.AddRigidBody(body);
                    }
                }
            }

            rbInfo.Dispose();
        }
示例#8
0
        protected override void OnInitializePhysics()
        {
            // 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);

            // create the ground
            BoxShape groundShape = new BoxShape(50, 1, 50);

            //groundShape.InitializePolyhedralFeatures();
            //CollisionShape groundShape = new StaticPlaneShape(new Vector3(0,1,0), 50);

            CollisionShapes.Add(groundShape);
            CollisionObject ground = LocalCreateRigidBody(0, Matrix.Identity, groundShape);

            ground.UserObject = "Ground";

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

            BoxShape colShape = new BoxShape(1);

            CollisionShapes.Add(colShape);
            Vector3 localInertia = colShape.CalculateLocalInertia(mass);

            const float startX = StartPosX - ArraySizeX / 2;
            const float startY = StartPosY;
            const float startZ = StartPosZ - ArraySizeZ / 2;

            RigidBodyConstructionInfo rbInfo =
                new RigidBodyConstructionInfo(mass, null, colShape, localInertia);

            for (int k = 0; k < ArraySizeY; k++)
            {
                for (int i = 0; i < ArraySizeX; i++)
                {
                    for (int j = 0; j < ArraySizeZ; j++)
                    {
                        Matrix startTransform = Matrix.Translation(
                            2 * i + startX,
                            2 * k + startY,
                            2 * j + startZ
                            );

                        // using motionstate is recommended, it provides interpolation capabilities
                        // and only synchronizes 'active' objects
                        rbInfo.MotionState = new DefaultMotionState(startTransform);
                        RigidBody body = new RigidBody(rbInfo);

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

                        World.AddRigidBody(body);
                    }
                }
            }

            rbInfo.Dispose();
        }
示例#9
0
        public override void InitializeDemo()
        {
            SetTexturing(true);
            SetShadows(true);

            SetCameraDistance(SCALING * 50.0f);
            m_cameraTargetPosition = IndexedVector3.Zero;

            //string filename = @"E:\users\man\bullet\xna-box2d-output.txt";
            //FileStream filestream = File.Open(filename, FileMode.Create, FileAccess.Write, FileShare.Read);
            //BulletGlobals.g_streamWriter = new StreamWriter(filestream);


            ///collision configuration contains default setup for memory, collision setup
            m_collisionConfiguration = new DefaultCollisionConfiguration();
            //m_collisionConfiguration.setConvexConvexMultipointIterations();

            ///use the default collision dispatcher. For parallel processing you can use a diffent dispatcher (see Extras/BulletMultiThreaded)
            m_dispatcher = new CollisionDispatcher(m_collisionConfiguration);

            VoronoiSimplexSolver            simplex  = new VoronoiSimplexSolver();
            MinkowskiPenetrationDepthSolver pdSolver = new MinkowskiPenetrationDepthSolver();

            CollisionAlgorithmCreateFunc convexAlgo2d = new Convex2dConvex2dCreateFunc(simplex, pdSolver);

            m_dispatcher.RegisterCollisionCreateFunc((int)BroadphaseNativeTypes.CONVEX_2D_SHAPE_PROXYTYPE, (int)BroadphaseNativeTypes.CONVEX_2D_SHAPE_PROXYTYPE, convexAlgo2d);
            m_dispatcher.RegisterCollisionCreateFunc((int)BroadphaseNativeTypes.BOX_2D_SHAPE_PROXYTYPE, (int)BroadphaseNativeTypes.CONVEX_2D_SHAPE_PROXYTYPE, convexAlgo2d);
            m_dispatcher.RegisterCollisionCreateFunc((int)BroadphaseNativeTypes.CONVEX_2D_SHAPE_PROXYTYPE, (int)BroadphaseNativeTypes.BOX_2D_SHAPE_PROXYTYPE, convexAlgo2d);
            m_dispatcher.RegisterCollisionCreateFunc((int)BroadphaseNativeTypes.BOX_2D_SHAPE_PROXYTYPE, (int)BroadphaseNativeTypes.BOX_2D_SHAPE_PROXYTYPE, new Box2dBox2dCreateFunc());

            //m_broadphase = new DbvtBroadphase();
            m_broadphase = new SimpleBroadphase(1000, null);

            ///the default constraint solver. For parallel processing you can use a different solver (see Extras/BulletMultiThreaded)
            m_constraintSolver = new SequentialImpulseConstraintSolver();

            m_dynamicsWorld = new DiscreteDynamicsWorld(m_dispatcher, m_broadphase, m_constraintSolver, m_collisionConfiguration);
            //m_dynamicsWorld.getSolverInfo().m_erp = 1.f;
            //m_dynamicsWorld.getSolverInfo().m_numIterations = 4;

            //m_dynamicsWorld.setGravity(new IndexedVector3(0,-10,0));

            ///create a few basic rigid bodies
            CollisionShape groundShape = new BoxShape(new IndexedVector3(150, 50, 150));

            //	btCollisionShape* groundShape = new btStaticPlaneShape(IndexedVector3(0,1,0),50);

            m_collisionShapes.Add(groundShape);

            IndexedMatrix groundTransform = IndexedMatrix.CreateTranslation(0, -43, 0);

            LocalCreateRigidBody(0, groundTransform, groundShape);

            {
                //create a few dynamic rigidbodies
                // Re-using the same collision is better for memory usage and performance

                float u = 1 * SCALING - 0.04f;
                IList <IndexedVector3> points = new List <IndexedVector3>();
                points.Add(new IndexedVector3(0, u, 0));
                points.Add(new IndexedVector3(-u, -u, 0));
                points.Add(new IndexedVector3(u, -u, 0));
                ConvexShape boxShape = new Convex2dShape(new BoxShape(new IndexedVector3(SCALING, SCALING, 0.04f)));
                //btCollisionShape* colShape = new btBox2dShape(IndexedVector3(SCALING*1,SCALING*1,0.04));


                ConvexShape    triangleShape = new Convex2dShape(new ConvexHullShape(points, 3));
                IndexedVector3 extents       = new IndexedVector3(SCALING, SCALING, 0.04f);
                ConvexShape    cylinderShape = new Convex2dShape(new CylinderShapeZ(ref extents));


                //btUniformScalingShape* colShape = new btUniformScalingShape(convexColShape,1.f);
                boxShape.SetMargin(0.03f);
                //btCollisionShape* colShape = new btSphereShape(float(1.));
                m_collisionShapes.Add(boxShape);
                m_collisionShapes.Add(triangleShape);

                /// Create Dynamic Objects
                IndexedMatrix startTransform = IndexedMatrix.Identity;

                float mass = 1.0f;;

                //rigidbody is dynamic if and only if mass is non zero, otherwise static
                bool isDynamic = (mass != 0.9f);

                IndexedVector3 localInertia = IndexedVector3.Zero;
                if (isDynamic)
                {
                    boxShape.CalculateLocalInertia(mass, out localInertia);
                }

                //		float start_x = START_POS_X - ARRAY_SIZE_X/2;
                //		float start_y = START_POS_Y;
                //		float start_z = START_POS_Z - ARRAY_SIZE_Z/2;

                IndexedVector3 x = new IndexedVector3(-ARRAY_SIZE_X, 8f, -20f);
                //IndexedVector3 y = IndexedVector3.Zero;
                IndexedVector3 y      = new IndexedVector3(0, 0, 0);
                IndexedVector3 deltaX = new IndexedVector3(SCALING * 1, SCALING * 2, 0f);
                IndexedVector3 deltaY = new IndexedVector3(SCALING * 2, 0.0f, 0f);

                for (int i = 0; i < ARRAY_SIZE_X; ++i)
                {
                    y = x;

                    for (int j = i; j < ARRAY_SIZE_Y; ++j)
                    {
                        startTransform._origin = (y - new IndexedVector3(-10, 0, 0));


                        //using motionstate is recommended, it provides interpolation capabilities, and only synchronizes 'active' objects
                        DefaultMotionState        myMotionState = new DefaultMotionState(startTransform, IndexedMatrix.Identity);
                        RigidBodyConstructionInfo rbInfo;
                        switch (j % 3)
                        {
#if true
                        case 0:
                            rbInfo = new RigidBodyConstructionInfo(mass, myMotionState, boxShape, localInertia);
                            //rbInfo = new RigidBodyConstructionInfo(mass, myMotionState, triangleShape, localInertia);
                            break;

                        case 1:
                            rbInfo = new RigidBodyConstructionInfo(mass, myMotionState, triangleShape, localInertia);
                            break;
#endif
                        default:
                            rbInfo = new RigidBodyConstructionInfo(mass, myMotionState, cylinderShape, localInertia);
                            break;
                        }
                        RigidBody body = new RigidBody(rbInfo);
                        //body.setContactProcessingThreshold(colShape.getContactBreakingThreshold());
                        body.SetActivationState(ActivationState.ISLAND_SLEEPING);
                        body.SetLinearFactor(new IndexedVector3(1, 1, 0));
                        body.SetAngularFactor(new IndexedVector3(0, 0, 1));

                        m_dynamicsWorld.AddRigidBody(body);
                        body.SetActivationState(ActivationState.ISLAND_SLEEPING);
                        //if (BulletGlobals.g_streamWriter != null)
                        //{
                        //    BulletGlobals.g_streamWriter.WriteLine("localCreateRigidBody [{0}] startTransform", body.m_debugBodyId);
                        //    MathUtil.PrintMatrix(BulletGlobals.g_streamWriter, startTransform);
                        //    BulletGlobals.g_streamWriter.WriteLine("");
                        //}


                        //	y += -0.8*deltaY;
                        y += deltaY;
                    }

                    x += deltaX;
                }
            }


            ClientResetScene();
        }
    void Start()
    {
        //Create a World
        Debug.Log("Initialize physics");
        List <CollisionShape> CollisionShapes = new List <CollisionShape>();

        DefaultCollisionConfiguration CollisionConf = new DefaultCollisionConfiguration();
        CollisionDispatcher           Dispatcher    = new CollisionDispatcher(CollisionConf);

        DbvtBroadphase Broadphase = new DbvtBroadphase();

        DiscreteDynamicsWorld World = new DiscreteDynamicsWorld(Dispatcher, Broadphase, null, CollisionConf);

        World.Gravity = new BulletSharp.Math.Vector3(0, -10, 0);


        // create a few dynamic rigidbodies
        const float mass = 1.0f;
        //Add a single cube
        RigidBody fallRigidBody;
        BoxShape  shape = new BoxShape(1f, 1f, 1f);

        BulletSharp.Math.Vector3 localInertia = BulletSharp.Math.Vector3.Zero;
        shape.CalculateLocalInertia(mass, out localInertia);
        RigidBodyConstructionInfo rbInfo = new RigidBodyConstructionInfo(mass, null, shape, localInertia);

        fallRigidBody = new RigidBody(rbInfo);
        rbInfo.Dispose();
        Matrix st = Matrix.Translation(new BulletSharp.Math.Vector3(0f, 10f, 0f));

        fallRigidBody.WorldTransform = st;
        World.AddRigidBody(fallRigidBody);

        //Step the simulation 300 steps
        for (int i = 0; i < 300; i++)
        {
            World.StepSimulation(1f / 60f, 10);

            Matrix trans;
            fallRigidBody.GetWorldTransform(out trans);

            Debug.Log("box height: " + trans.Origin);
        }

        //Clean up.
        World.RemoveRigidBody(fallRigidBody);
        fallRigidBody.Dispose();

        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();
            }

            //delete collision shapes
            foreach (CollisionShape ss in CollisionShapes)
            {
                ss.Dispose();
            }
            CollisionShapes.Clear();

            World.Dispose();
            Broadphase.Dispose();
            Dispatcher.Dispose();
            CollisionConf.Dispose();
        }

        if (Broadphase != null)
        {
            Broadphase.Dispose();
        }
        if (Dispatcher != null)
        {
            Dispatcher.Dispose();
        }
        if (CollisionConf != null)
        {
            CollisionConf.Dispose();
        }
    }
示例#11
0
        public override void InitializeDemo()
        {
            //string filename = @"E:\users\man\bullet\xna-constraint-output.txt";
            //FileStream filestream = File.Open(filename, FileMode.Create, FileAccess.Write, FileShare.Read);
            //BulletGlobals.g_streamWriter = new StreamWriter(filestream);

            //maxiterations = 100;

            m_collisionConfiguration = new DefaultCollisionConfiguration();
            m_dispatcher             = new CollisionDispatcher(m_collisionConfiguration);
            IndexedVector3 worldMin = new IndexedVector3(-1000, -1000, -1000);
            IndexedVector3 worldMax = new IndexedVector3(1000, 1000, 1000);

            m_broadphase       = new AxisSweep3Internal(ref worldMin, ref worldMax, 0xfffe, 0xffff, 16384, null, false);
            m_constraintSolver = new SequentialImpulseConstraintSolver();
            m_dynamicsWorld    = new DiscreteDynamicsWorld(m_dispatcher, m_broadphase, m_constraintSolver, m_collisionConfiguration);
            m_dynamicsWorld.SetDebugDrawer(m_debugDraw);

            SetCameraDistance(26f);

            //CollisionShape groundShape = new BoxShape(new IndexedVector3(50f, 40f, 50f));
            CollisionShape groundShape = new StaticPlaneShape(new IndexedVector3(0, 1, 0), 40);

            m_collisionShapes.Add(groundShape);
            IndexedMatrix groundTransform = IndexedMatrix.Identity;

            groundTransform._origin = new IndexedVector3(0, -56, 0);
            RigidBody groundBody = LocalCreateRigidBody(0, ref groundTransform, groundShape);

            CollisionShape shape = new BoxShape(new IndexedVector3(CUBE_HALF_EXTENTS, CUBE_HALF_EXTENTS, CUBE_HALF_EXTENTS));

            m_collisionShapes.Add(shape);
            IndexedMatrix trans = IndexedMatrix.Identity;

            trans._origin = new IndexedVector3(0, 20, 0);

            float mass = 1f;

#if true
            //point to point constraint with a breaking threshold
            {
                trans         = IndexedMatrix.Identity;
                trans._origin = new IndexedVector3(1, 30, -5);
                LocalCreateRigidBody(mass, trans, shape);
                trans._origin = new IndexedVector3(0, 0, -5);

                RigidBody body0 = LocalCreateRigidBody(mass, trans, shape);

                trans._origin = new IndexedVector3(2 * CUBE_HALF_EXTENTS, 20, 0);
                mass          = 1.0f;
                RigidBody       body1    = null;//localCreateRigidBody( mass,trans,shape);
                IndexedVector3  pivotInA = new IndexedVector3(CUBE_HALF_EXTENTS, CUBE_HALF_EXTENTS, 0);
                TypedConstraint p2p      = new Point2PointConstraint(body0, ref pivotInA);
                m_dynamicsWorld.AddConstraint(p2p);
                p2p.SetBreakingImpulseThreshold(10.2f);
                p2p.SetDbgDrawSize(5.0f);
            }
#endif



#if true
            //point to point constraint (ball socket)
            //SEEMS OK
            {
                //trans = IndexedMatrix.Identity;
                RigidBody body0 = LocalCreateRigidBody(mass, ref trans, shape);
                trans._origin = new IndexedVector3(2 * CUBE_HALF_EXTENTS, 20, 0);

                mass = 1f;
                RigidBody body1 = null;        //localCreateRigidBody( mass,trans,shape);

                IndexedVector3 pivotInA = new IndexedVector3(CUBE_HALF_EXTENTS, -CUBE_HALF_EXTENTS, -CUBE_HALF_EXTENTS);
                IndexedVector3 axisInA  = new IndexedVector3(0, 0, 1);

                IndexedVector3 pivotInB = body1 != null?body1.GetCenterOfMassTransform().Inverse() * (body0.GetCenterOfMassTransform() * (pivotInA)) : pivotInA;

                IndexedVector3 axisInB = body1 != null ? (body1.GetCenterOfMassTransform()._basis.Inverse() * (body1.GetCenterOfMassTransform()._basis *axisInA)) :
                                         body0.GetCenterOfMassTransform()._basis *axisInA;
#if P2P
                TypedConstraint p2p = new Point2PointConstraint(body0, ref pivotInA);
                //btTypedConstraint* p2p = new btPoint2PointConstraint(*body0,*body1,pivotInA,pivotInB);
                //btTypedConstraint* hinge = new btHingeConstraint(*body0,*body1,pivotInA,pivotInB,axisInA,axisInB);
                m_dynamicsWorld.AddConstraint(p2p);
                p2p.SetDbgDrawSize(5.0f);
#else
                HingeConstraint hinge = new HingeConstraint(body0, ref pivotInA, ref axisInA, false);

                float targetVelocity  = 1f;
                float maxMotorImpulse = 1.0f;
                hinge.EnableAngularMotor(true, targetVelocity, maxMotorImpulse);

                m_dynamicsWorld.AddConstraint(hinge);        //p2p);
                hinge.SetDbgDrawSize(5f);
        #endif
            }
#endif

#if true
            //create a slider, using the generic D6 constraint
            // SEEMS OK
            {
                mass = 1f;
                IndexedVector3     sliderWorldPos    = new IndexedVector3(0, 10, 0);
                IndexedVector3     sliderAxis        = new IndexedVector3(1, 0, 0);
                float              angle             = 0f;//SIMD_RADS_PER_DEG * 10.f;
                IndexedBasisMatrix sliderOrientation = new IndexedBasisMatrix(new IndexedQuaternion(sliderAxis, angle));
                trans         = IndexedMatrix.Identity;
                trans._origin = sliderWorldPos;
                //trans.setBasis(sliderOrientation);
                sliderTransform = trans;

                d6body0 = LocalCreateRigidBody(mass, ref trans, shape);
                d6body0.SetActivationState(ActivationState.DISABLE_DEACTIVATION);
                RigidBody fixedBody1 = LocalCreateRigidBody(0, ref trans, null);
                m_dynamicsWorld.AddRigidBody(fixedBody1);

                IndexedMatrix frameInA, frameInB;
                frameInA         = IndexedMatrix.Identity;
                frameInB         = IndexedMatrix.Identity;
                frameInA._origin = new IndexedVector3(0, 5, 0);
                frameInB._origin = new IndexedVector3(0, 5, 0);

                //		bool useLinearReferenceFrameA = false;//use fixed frame B for linear llimits
                bool useLinearReferenceFrameA = true;        //use fixed frame A for linear llimits
                spSlider6Dof = new Generic6DofConstraint(fixedBody1, d6body0, ref frameInA, ref frameInB, useLinearReferenceFrameA);
                spSlider6Dof.SetLinearLowerLimit(ref lowerSliderLimit);
                spSlider6Dof.SetLinearUpperLimit(ref hiSliderLimit);

                //range should be small, otherwise singularities will 'explode' the constraint
                IndexedVector3 angularLower = new IndexedVector3(-1.5f, 0, 0);
                IndexedVector3 angularUpper = -angularLower;
                spSlider6Dof.SetAngularLowerLimit(ref angularLower);
                spSlider6Dof.SetAngularUpperLimit(ref angularUpper);
                //		slider.setAngularLowerLimit(IndexedVector3(0,0,0));
                //		slider.setAngularUpperLimit(IndexedVector3(0,0,0));
                spSlider6Dof.SetAngularLowerLimit(new IndexedVector3(-MathUtil.SIMD_PI, 0, 0));
                spSlider6Dof.SetAngularUpperLimit(new IndexedVector3(1.5f, 0, 0));

                spSlider6Dof.GetTranslationalLimitMotor().m_enableMotor[0] = true;
                spSlider6Dof.GetTranslationalLimitMotor().m_targetVelocity.X = -5.0f;
                spSlider6Dof.GetTranslationalLimitMotor().m_maxMotorForce.X = 0.1f;


                m_dynamicsWorld.AddConstraint(spSlider6Dof);
                spSlider6Dof.SetDbgDrawSize(5f);
            }
#endif
#if true
            {     // create a door using hinge constraint attached to the world
                CollisionShape pDoorShape = new BoxShape(new IndexedVector3(2.0f, 5.0f, 0.2f));
                m_collisionShapes.Add(pDoorShape);
                IndexedMatrix doorTrans = IndexedMatrix.Identity;
                doorTrans._origin = new IndexedVector3(-5.0f, -2.0f, 0.0f);
                RigidBody pDoorBody = LocalCreateRigidBody(1.0f, ref doorTrans, pDoorShape);
                pDoorBody.SetActivationState(ActivationState.DISABLE_DEACTIVATION);
                IndexedVector3 btPivotA = new IndexedVector3(10f + 2.1f, -2.0f, 0.0f);   // right next to the door slightly outside
                IndexedVector3 btAxisA  = new IndexedVector3(0.0f, 1.0f, 0.0f);          // pointing upwards, aka Y-axis

                spDoorHinge = new HingeConstraint(pDoorBody, ref btPivotA, ref btAxisA, false);

                spDoorHinge.SetLimit(-MathUtil.SIMD_PI * 0.25f, MathUtil.SIMD_PI * 0.25f);
                m_dynamicsWorld.AddConstraint(spDoorHinge);
                spDoorHinge.SetDbgDrawSize(5.0f);
            }
#endif
#if true
            { // create a generic 6DOF constraint
                // SEEMS OK - But debug draw a bit wrong?
                IndexedMatrix tr = IndexedMatrix.Identity;
                tr._origin = new IndexedVector3(10f, 6f, 0f);
                //tr.getBasis().setEulerZYX(0,0,0);
                //		RigidBody pBodyA = localCreateRigidBody( mass, tr, shape);
                RigidBody pBodyA = LocalCreateRigidBody(0.0f, ref tr, shape);
                //		RigidBody pBodyA = localCreateRigidBody( 0.0, tr, 0);
                pBodyA.SetActivationState(ActivationState.DISABLE_DEACTIVATION);

                tr         = IndexedMatrix.Identity;
                tr._origin = new IndexedVector3(0f, 6f, 0f);
                //tr.getBasis().setEulerZYX(0,0,0);
                RigidBody pBodyB = LocalCreateRigidBody(mass, ref tr, shape);
                pBodyB.SetActivationState(ActivationState.DISABLE_DEACTIVATION);

                IndexedMatrix frameInA, frameInB;
                frameInA = IndexedMatrix.CreateTranslation(-5, 0, 0);
                frameInB = IndexedMatrix.CreateTranslation(5, 0, 0);

                Generic6DofConstraint pGen6DOF = new Generic6DofConstraint(pBodyA, pBodyB, ref frameInA, ref frameInB, true);
                //		btGeneric6DofConstraint* pGen6DOF = new btGeneric6DofConstraint(*pBodyA, *pBodyB, frameInA, frameInB, false);
                IndexedVector3 linearLower = new IndexedVector3(-10, -2, -1);
                pGen6DOF.SetLinearLowerLimit(ref linearLower);
                IndexedVector3 linearUpper = new IndexedVector3(10, 2, 1);
                pGen6DOF.SetLinearUpperLimit(ref linearUpper);
                // ? why again?
                //linearLower = new IndexedVector3(-10,0,0);
                //pGen6DOF.setLinearLowerLimit(ref linearLower);
                //		pGen6DOF.setLinearUpperLimit(IndexedVector3(10., 0., 0.));
                //		pGen6DOF.setLinearLowerLimit(IndexedVector3(0., 0., 0.));
                //		pGen6DOF.setLinearUpperLimit(IndexedVector3(0., 0., 0.));

                //		pGen6DOF.getTranslationalLimitMotor().m_enableMotor[0] = true;
                //		pGen6DOF.getTranslationalLimitMotor().m_targetVelocity[0] = 5.0f;
                //		pGen6DOF.getTranslationalLimitMotor().m_maxMotorForce[0] = 0.1f;


                //		pGen6DOF.setAngularLowerLimit(IndexedVector3(0., SIMD_HALF_PI*0.9, 0.));
                //		pGen6DOF.setAngularUpperLimit(IndexedVector3(0., -SIMD_HALF_PI*0.9, 0.));
                //		pGen6DOF.setAngularLowerLimit(IndexedVector3(0., 0., -SIMD_HALF_PI));
                //		pGen6DOF.setAngularUpperLimit(IndexedVector3(0., 0., SIMD_HALF_PI));

                IndexedVector3 angularLower = new IndexedVector3(-MathUtil.SIMD_HALF_PI * 0.5f, -0.75f, -MathUtil.SIMD_HALF_PI * 0.8f);
                IndexedVector3 angularUpper = -angularLower;
                pGen6DOF.SetAngularLowerLimit(ref angularLower);
                pGen6DOF.SetAngularUpperLimit(ref angularUpper);
                //		pGen6DOF.setAngularLowerLimit(IndexedVector3(0.f, -0.75, SIMD_HALF_PI * 0.8f));
                //		pGen6DOF.setAngularUpperLimit(IndexedVector3(0.f, 0.75, -SIMD_HALF_PI * 0.8f));
                //		pGen6DOF.setAngularLowerLimit(IndexedVector3(0.f, -SIMD_HALF_PI * 0.8f, SIMD_HALF_PI * 1.98f));
                //		pGen6DOF.setAngularUpperLimit(IndexedVector3(0.f, SIMD_HALF_PI * 0.8f,  -SIMD_HALF_PI * 1.98f));



                //		pGen6DOF.setAngularLowerLimit(IndexedVector3(-0.75,-0.5, -0.5));
                //		pGen6DOF.setAngularUpperLimit(IndexedVector3(0.75,0.5, 0.5));
                //		pGen6DOF.setAngularLowerLimit(IndexedVector3(-0.75,0., 0.));
                //		pGen6DOF.setAngularUpperLimit(IndexedVector3(0.75,0., 0.));

                m_dynamicsWorld.AddConstraint(pGen6DOF, true);
                pGen6DOF.SetDbgDrawSize(5.0f);
            }
#endif
#if true
            { // create a ConeTwist constraint
                IndexedMatrix tr = IndexedMatrix.CreateTranslation(-10, 5, 0);

                RigidBody pBodyA = LocalCreateRigidBody(1.0f, ref tr, shape);
                pBodyA.SetActivationState(ActivationState.DISABLE_DEACTIVATION);

                tr = IndexedMatrix.CreateTranslation(-10, -5, 0);

                RigidBody pBodyB = LocalCreateRigidBody(0.0f, ref tr, shape);

                IndexedMatrix frameInA, frameInB;
                frameInA         = MathUtil.SetEulerZYX(0, 0, MathUtil.SIMD_HALF_PI);
                frameInA._origin = new IndexedVector3(0, -5, 0);
                frameInB         = MathUtil.SetEulerZYX(0, 0, MathUtil.SIMD_HALF_PI);
                frameInB._origin = new IndexedVector3(0, 5, 0);

                ConeTwistConstraint pCT = new ConeTwistConstraint(pBodyA, pBodyB, ref frameInA, ref frameInB);
                pCT.SetLimit(MathUtil.SIMD_QUARTER_PI * 0.6f, MathUtil.SIMD_QUARTER_PI, MathUtil.SIMD_PI * 0.8f, 0.5f);         // soft limit == hard limit
                m_dynamicsWorld.AddConstraint(pCT, true);
                pCT.SetDbgDrawSize(5.0f);
            }
#endif
#if true
            { // Hinge connected to the world, with motor (to hinge motor with new and old constraint solver)
                // WORKS OK
                IndexedMatrix tr    = IndexedMatrix.Identity;
                RigidBody     pBody = LocalCreateRigidBody(1.0f, ref tr, shape);
                pBody.SetActivationState(ActivationState.DISABLE_DEACTIVATION);
                IndexedVector3 btPivotA = new IndexedVector3(10.0f, 0.0f, 0.0f);
                IndexedVector3 btAxisA  = new IndexedVector3(0.0f, 0.0f, 1.0f);

                HingeConstraint pHinge = new HingeConstraint(pBody, ref btPivotA, ref btAxisA, false);
                //		pHinge.enableAngularMotor(true, -1.0, 0.165); // use for the old solver
                pHinge.EnableAngularMotor(true, -1.0f, 1.65f);         // use for the new SIMD solver
                m_dynamicsWorld.AddConstraint(pHinge);
                pHinge.SetDbgDrawSize(5.0f);
            }
#endif
#if true
            {
                // WORKS OK
                // create a universal joint using generic 6DOF constraint
                // create two rigid bodies
                // static bodyA (parent) on top:
                IndexedMatrix tr     = IndexedMatrix.CreateTranslation(20, 4, 0);
                RigidBody     pBodyA = LocalCreateRigidBody(0.0f, ref tr, shape);
                pBodyA.SetActivationState(ActivationState.DISABLE_DEACTIVATION);
                // dynamic bodyB (child) below it :
                tr = IndexedMatrix.CreateTranslation(20, 0, 0);
                RigidBody pBodyB = LocalCreateRigidBody(1.0f, ref tr, shape);
                pBodyB.SetActivationState(ActivationState.DISABLE_DEACTIVATION);
                // add some (arbitrary) data to build constraint frames
                IndexedVector3 parentAxis = new IndexedVector3(1.0f, 0.0f, 0.0f);
                IndexedVector3 childAxis  = new IndexedVector3(0.0f, 0.0f, 1.0f);
                IndexedVector3 anchor     = new IndexedVector3(20.0f, 2.0f, 0.0f);

                UniversalConstraint pUniv = new UniversalConstraint(pBodyA, pBodyB, ref anchor, ref parentAxis, ref childAxis);
                pUniv.SetLowerLimit(-MathUtil.SIMD_HALF_PI * 0.5f, -MathUtil.SIMD_HALF_PI * 0.5f);
                pUniv.SetUpperLimit(MathUtil.SIMD_HALF_PI * 0.5f, MathUtil.SIMD_HALF_PI * 0.5f);
                // add constraint to world
                m_dynamicsWorld.AddConstraint(pUniv, true);
                // draw constraint frames and limits for debugging
                pUniv.SetDbgDrawSize(5.0f);
            }
#endif

#if true
            // WORKS OK
            { // create a generic 6DOF constraint with springs
                IndexedMatrix tr = IndexedMatrix.CreateTranslation(-20f, 16f, 0f);
                //tr.setIdentity();
                //tr.setOrigin(btVector3(btScalar(-20.), btScalar(16.), btScalar(0.)));
                //tr.getBasis().setEulerZYX(0,0,0);
                RigidBody pBodyA = LocalCreateRigidBody(0.0f, ref tr, shape);
                pBodyA.SetActivationState(ActivationState.DISABLE_DEACTIVATION);

                //tr.setIdentity();
                //tr.setOrigin(btVector3(btScalar(-10.), btScalar(16.), btScalar(0.)));
                //tr.getBasis().setEulerZYX(0,0,0);
                tr = IndexedMatrix.CreateTranslation(-10, 16, 0);
                RigidBody pBodyB = LocalCreateRigidBody(1.0f, ref tr, shape);
                pBodyB.SetActivationState(ActivationState.DISABLE_DEACTIVATION);

                IndexedMatrix frameInA = IndexedMatrix.CreateTranslation(10f, 0f, 0f);
                IndexedMatrix frameInB = IndexedMatrix.CreateTranslation(0f, 0f, 0f);

                Generic6DofSpringConstraint pGen6DOFSpring = new Generic6DofSpringConstraint(pBodyA, pBodyB, ref frameInA, ref frameInB, true);
                pGen6DOFSpring.SetLinearUpperLimit(new IndexedVector3(5f, 0f, 0f));
                pGen6DOFSpring.SetLinearLowerLimit(new IndexedVector3(-5f, 0f, 0f));

                pGen6DOFSpring.SetAngularLowerLimit(new IndexedVector3(0f, 0f, -1.5f));
                pGen6DOFSpring.SetAngularUpperLimit(new IndexedVector3(0f, 0f, 1.5f));

                m_dynamicsWorld.AddConstraint(pGen6DOFSpring, true);
                pGen6DOFSpring.SetDbgDrawSize(5.0f);

                pGen6DOFSpring.EnableSpring(0, true);
                pGen6DOFSpring.SetStiffness(0, 39.478f);
                pGen6DOFSpring.SetDamping(0, 0.5f);
                pGen6DOFSpring.EnableSpring(5, true);
                pGen6DOFSpring.SetStiffness(5, 39.478f);
                pGen6DOFSpring.SetDamping(0, 0.3f);
                pGen6DOFSpring.SetEquilibriumPoint();
            }
#endif
#if true
            {
                // WORKS OK
                // create a Hinge2 joint
                // create two rigid bodies
                // static bodyA (parent) on top:
                IndexedMatrix tr = IndexedMatrix.CreateTranslation(-20f, 4f, 0f);

                RigidBody pBodyA = LocalCreateRigidBody(0.0f, ref tr, shape);
                pBodyA.SetActivationState(ActivationState.DISABLE_DEACTIVATION);
                // dynamic bodyB (child) below it :
                tr = IndexedMatrix.CreateTranslation(-20f, 0f, 0f);
                RigidBody pBodyB = LocalCreateRigidBody(1.0f, ref tr, shape);
                pBodyB.SetActivationState(ActivationState.DISABLE_DEACTIVATION);
                // add some data to build constraint frames
                IndexedVector3   parentAxis = new IndexedVector3(0.0f, 1.0f, 0.0f);
                IndexedVector3   childAxis  = new IndexedVector3(1.0f, 0.0f, 0.0f);
                IndexedVector3   anchor     = new IndexedVector3(-20.0f, 0.0f, 0.0f);
                Hinge2Constraint pHinge2    = new Hinge2Constraint(pBodyA, pBodyB, ref anchor, ref parentAxis, ref childAxis);
                pHinge2.SetLowerLimit(-MathUtil.SIMD_HALF_PI * 0.5f);
                pHinge2.SetUpperLimit(MathUtil.SIMD_HALF_PI * 0.5f);
                // add constraint to world
                m_dynamicsWorld.AddConstraint(pHinge2, true);
                // draw constraint frames and limits for debugging
                pHinge2.SetDbgDrawSize(5.0f);
            }
#endif
#if true
            {
                // WORKS OK
                // create a Hinge joint between two dynamic bodies
                // create two rigid bodies
                // static bodyA (parent) on top:
                IndexedMatrix tr     = IndexedMatrix.CreateTranslation(-20f, -2f, 0f);
                RigidBody     pBodyA = LocalCreateRigidBody(1.0f, ref tr, shape);
                pBodyA.SetActivationState(ActivationState.DISABLE_DEACTIVATION);
                // dynamic bodyB:
                tr = IndexedMatrix.CreateTranslation(-30f, -2f, 0f);
                RigidBody pBodyB = LocalCreateRigidBody(10.0f, ref tr, shape);
                pBodyB.SetActivationState(ActivationState.DISABLE_DEACTIVATION);
                // add some data to build constraint frames
                IndexedVector3 axisA  = new IndexedVector3(0.0f, 1.0f, 0.0f);
                IndexedVector3 axisB  = new IndexedVector3(0.0f, 1.0f, 0.0f);
                IndexedVector3 pivotA = new IndexedVector3(-5.0f, 0.0f, 0.0f);
                IndexedVector3 pivotB = new IndexedVector3(5.0f, 0.0f, 0.0f);

                spHingeDynAB = new HingeConstraint(pBodyA, pBodyB, ref pivotA, ref pivotB, ref axisA, ref axisB);
                spHingeDynAB.SetLimit(-MathUtil.SIMD_HALF_PI * 0.5f, MathUtil.SIMD_HALF_PI * 0.5f);
                // add constraint to world
                m_dynamicsWorld.AddConstraint(spHingeDynAB, true);
                // draw constraint frames and limits for debugging
                spHingeDynAB.SetDbgDrawSize(5.0f);
            }
#endif

#if true
            { // 6DOF connected to the world, with motor
                IndexedMatrix tr    = IndexedMatrix.CreateTranslation(10, -15, 0);
                RigidBody     pBody = LocalCreateRigidBody(1.0f, ref tr, shape);
                pBody.SetActivationState(ActivationState.DISABLE_DEACTIVATION);
                IndexedMatrix         frameB   = IndexedMatrix.Identity;
                Generic6DofConstraint pGen6Dof = new Generic6DofConstraint(pBody, ref frameB, false);
                m_dynamicsWorld.AddConstraint(pGen6Dof);
                pGen6Dof.SetDbgDrawSize(5.0f);

                pGen6Dof.SetAngularLowerLimit(new IndexedVector3(0, 0, 0));
                pGen6Dof.SetAngularUpperLimit(new IndexedVector3(0, 0, 0));
                pGen6Dof.SetLinearLowerLimit(new IndexedVector3(-10.0f, 0, 0));
                pGen6Dof.SetLinearUpperLimit(new IndexedVector3(10.0f, 0, 0));

                pGen6Dof.GetTranslationalLimitMotor().m_enableMotor[0]    = true;
                pGen6Dof.GetTranslationalLimitMotor().m_targetVelocity[0] = 5.0f;
                pGen6Dof.GetTranslationalLimitMotor().m_maxMotorForce[0]  = 0.1f;
            }
#endif
        }
示例#12
0
        /*private void MyTickCallBack(ManifoldPoint cp, CollisionObjectWrapper colobj0wrap, int partid0, int index0, CollisionObjectWrapper colobj1wrap, int partid1, int index1)
         * {
         *  Debug.WriteLine("MyTickCallBack");
         *  int numManifolds = BtWorld.Dispatcher.NumManifolds;
         *  RigidBodyImp myRb;
         *  //Debug.WriteLine("numManifolds: " + numManifolds);
         *  for (int i = 0; i < numManifolds; i++)
         *  {
         *      PersistentManifold contactManifold = BtWorld.Dispatcher.GetManifoldByIndexInternal(i);
         *      int numContacts = contactManifold.NumContacts;
         *      if (numContacts > 0)
         *      {
         *          CollisionObject obA = (CollisionObject) contactManifold.Body0;
         *          CollisionObject obB = (CollisionObject) contactManifold.Body1;
         *
         *         // Debug.WriteLine(numContacts);
         *          var pnA = obA.UserObject;
         *
         *          for (int j = 0; j < numContacts; j++)
         *          {
         *              ManifoldPoint pt = contactManifold.GetContactPoint(j);
         *
         *          }
         *      }
         *  }
         * }*/


        /// <summary>
        /// Adds the rigid body.
        /// </summary>
        /// <param name="mass">The mass.</param>
        /// <param name="worldTransform">The world transform.</param>
        /// <param name="orientation">The orientation.</param>
        /// <param name="colShape">The col shape.</param>
        /// <returns></returns>
        public IRigidBodyImp AddRigidBody(float mass, float3 worldTransform, float3 orientation, ICollisionShapeImp colShape /*, float3 intertia*/)
        {
            // Use bullet to do what needs to be done:


            var btMatrix = Matrix.RotationX(orientation.x)
                           * Matrix.RotationY(orientation.y)
                           * Matrix.RotationZ(orientation.z)
                           * Matrix.Translation(worldTransform.x, worldTransform.y, worldTransform.z);

            var btMotionState = new DefaultMotionState(btMatrix);


            var shapeType = colShape.GetType().ToString();

            CollisionShape btColShape;

            // var isStatic = false;
            switch (shapeType)
            {
            //Primitives
            case "Fusee.Engine.BoxShapeImp":
                var box = (BoxShapeImp)colShape;
                var btBoxHalfExtents = Translator.Float3ToBtVector3(box.HalfExtents);
                btColShape = new BoxShape(btBoxHalfExtents);
                break;

            case "Fusee.Engine.CapsuleShapeImp":
                var capsule = (CapsuleShapeImp)colShape;
                btColShape = new CapsuleShape(capsule.Radius, capsule.HalfHeight);
                break;

            case "Fusee.Engine.ConeShapeImp":
                var cone = (ConeShapeImp)colShape;
                btColShape = new ConeShape(cone.Radius, cone.Height);
                break;

            case "Fusee.Engine.CylinderShapeImp":
                var cylinider             = (CylinderShapeImp)colShape;
                var btCylinderHalfExtents = Translator.Float3ToBtVector3(cylinider.HalfExtents);
                btColShape = new CylinderShape(btCylinderHalfExtents);
                break;

            case "Fusee.Engine.MultiSphereShapeImp":
                var multiSphere = (MultiSphereShapeImp)colShape;
                var btPositions = new Vector3[multiSphere.SphereCount];
                var btRadi      = new float[multiSphere.SphereCount];
                for (int i = 0; i < multiSphere.SphereCount; i++)
                {
                    var pos = Translator.Float3ToBtVector3(multiSphere.GetSpherePosition(i));
                    btPositions[i] = pos;
                    btRadi[i]      = multiSphere.GetSphereRadius(i);
                }
                btColShape = new MultiSphereShape(btPositions, btRadi);
                break;

            case "Fusee.Engine.SphereShapeImp":
                var sphere   = (SphereShapeImp)colShape;
                var btRadius = sphere.Radius;
                btColShape = new SphereShape(btRadius);
                break;

            //Misc
            case "Fusee.Engine.CompoundShapeImp":
                var compShape = (CompoundShapeImp)colShape;
                btColShape = new CompoundShape(true);
                btColShape = compShape.BtCompoundShape;
                break;

            case "Fusee.Engine.EmptyShapeImp":
                btColShape = new EmptyShape();
                break;

            //Meshes
            case "Fusee.Engine.ConvexHullShapeImp":
                var convHull = (ConvexHullShapeImp)colShape;
                var btPoints = new Vector3[convHull.GetNumPoints()];
                for (int i = 0; i < convHull.GetNumPoints(); i++)
                {
                    var point = convHull.GetScaledPoint(i);
                    btPoints[i] = Translator.Float3ToBtVector3(point);
                }
                btColShape = new ConvexHullShape(btPoints);
                //btColShape.LocalScaling = new Vector3(3,3,3);
                break;

            case "Fusee.Engine.StaticPlaneShapeImp":
                var staticPlane = (StaticPlaneShapeImp)colShape;
                Debug.WriteLine("staticplane: " + staticPlane.Margin);
                var btNormal = Translator.Float3ToBtVector3(staticPlane.PlaneNormal);
                btColShape = new StaticPlaneShape(btNormal, staticPlane.PlaneConstant);
                // isStatic = true;
                //btColShape.Margin = 0.04f;
                //Debug.WriteLine("btColshape" + btColShape.Margin);
                break;

            case "Fusee.Engine.GImpactMeshShapeImp":
                var gImpMesh = (GImpactMeshShapeImp)colShape;
                gImpMesh.BtGImpactMeshShape.UpdateBound();
                var btGimp = new GImpactMeshShape(gImpMesh.BtGImpactMeshShape.MeshInterface);

                btGimp.UpdateBound();
                btColShape = btGimp;

                break;

            //Default
            default:
                Debug.WriteLine("defaultImp");
                btColShape = new EmptyShape();
                break;
            }

            var btLocalInertia = btColShape.CalculateLocalInertia(mass);
            // btLocalInertia *= (10.0f*10);
            RigidBodyConstructionInfo btRbcInfo = new RigidBodyConstructionInfo(mass, btMotionState, btColShape,
                                                                                btLocalInertia);

            var btRigidBody = new RigidBody(btRbcInfo);

            btRigidBody.Restitution    = 0.2f;
            btRigidBody.Friction       = 0.2f;
            btRigidBody.CollisionFlags = CollisionFlags.CustomMaterialCallback;

            BtWorld.AddRigidBody(btRigidBody);
            btRbcInfo.Dispose();
            var retval = new RigidBodyImp();

            retval._rbi            = btRigidBody;
            btRigidBody.UserObject = retval;
            return(retval);
        }
示例#13
0
        public void Init(string MediaDir)
        {
            #region Configuracion Basica de World

            //Creamos el mundo fisico por defecto.
            collisionConfiguration = new DefaultCollisionConfiguration();
            dispatcher             = new CollisionDispatcher(collisionConfiguration);
            GImpactCollisionAlgorithm.RegisterAlgorithm(dispatcher);
            constraintSolver      = new SequentialImpulseConstraintSolver();
            overlappingPairCache  = new DbvtBroadphase(); //AxisSweep3(new BsVector3(-5000f, -5000f, -5000f), new BsVector3(5000f, 5000f, 5000f), 8192);
            dynamicsWorld         = new DiscreteDynamicsWorld(dispatcher, overlappingPairCache, constraintSolver, collisionConfiguration);
            dynamicsWorld.Gravity = new TGCVector3(0, -100f, 0).ToBulletVector3();

            #endregion Configuracion Basica de World

            #region Capsula

            //Cuerpo rigido de una capsula basica
            capsuleRigidBody = BulletRigidBodyFactory.Instance.CreateCapsule(10, 50, new TGCVector3(200, 500, 200), 10, false);

            //Valores que podemos modificar a partir del RigidBody base
            capsuleRigidBody.SetDamping(0.1f, 0f);
            capsuleRigidBody.Restitution = 0.1f;
            capsuleRigidBody.Friction    = 1;

            //Agregamos el RidigBody al World
            dynamicsWorld.AddRigidBody(capsuleRigidBody);

            #endregion Capsula

            #region Terreno

            //Creamos el RigidBody basico del Terreno
            var meshRigidBody = BulletRigidBodyFactory.Instance.CreateSurfaceFromHeighMap(triangleDataVB);

            //Agregamos algo de friccion al RigidBody ya que este va a interactuar con objetos moviles
            //del World
            meshRigidBody.Friction = 0.5f;

            //Agregamos el RigidBody del terreno al World
            dynamicsWorld.AddRigidBody(meshRigidBody);

            #endregion Terreno

            #region Esfera

            //Creamos una esfera para interactuar
            pokeball = BulletRigidBodyFactory.Instance.CreateBall(10f, 0.5f, new TGCVector3(100f, 500f, 100f));
            pokeball.SetDamping(0.1f, 0.5f);
            pokeball.Restitution = 1f;
            //Agregamos la pokebola al World
            dynamicsWorld.AddRigidBody(pokeball);

            //Textura de pokebola
            var texturePokeball = TgcTexture.createTexture(D3DDevice.Instance.Device, MediaDir + @"Texturas\pokeball.jpg");

            //Se crea una esfera de tamaño 1 para escalarla luego (en render)
            sphereMesh = new TGCSphere(1, texturePokeball, TGCVector3.Empty);

            //Tgc no crea el vertex buffer hasta invocar a update values.
            sphereMesh.updateValues();

            #endregion Esfera

            #region Personaje

            //Cargamos personaje
            var skeletalLoader = new TgcSkeletalLoader();
            personaje = skeletalLoader.loadMeshAndAnimationsFromFile(
                MediaDir + "SkeletalAnimations\\Robot\\Robot-TgcSkeletalMesh.xml",
                MediaDir + "SkeletalAnimations\\Robot\\",
                new[]
            {
                MediaDir + "SkeletalAnimations\\Robot\\Caminando-TgcSkeletalAnim.xml",
                MediaDir + "SkeletalAnimations\\Robot\\Parado-TgcSkeletalAnim.xml"
            });

            //Le cambiamos la textura para diferenciarlo un poco
            personaje.changeDiffuseMaps(new[]
            {
                TgcTexture.createTexture(D3DDevice.Instance.Device,
                                         MediaDir + "SkeletalAnimations\\Robot\\Textures\\uvwGreen.jpg")
            });

            //Configurar animacion inicial
            personaje.playAnimation("Parado", true);

            #endregion Personaje

            #region Cajas

            var sizeBox = 20f;

            //Textura de caja
            var textureBox = TgcTexture.createTexture(D3DDevice.Instance.Device, MediaDir + @"MeshCreator\Textures\Madera\cajaMadera2.jpg");

            box = BulletRigidBodyFactory.Instance.CreateBox(new TGCVector3(sizeBox, sizeBox, sizeBox), 0, new TGCVector3(0, 12, 0), 0, 0, 0, 0.5f, true);
            dynamicsWorld.AddRigidBody(box);
            boxMesh = TGCBox.fromSize(new TGCVector3(40f, 40f, 40f), textureBox);
            boxMesh.updateValues();

            sizeBox = 40f;
            boxB    = BulletRigidBodyFactory.Instance.CreateBox(new TGCVector3(sizeBox, sizeBox, sizeBox), 0, new TGCVector3(100, 40, 0), 0, 0, 0, 0.5f, true);
            dynamicsWorld.AddRigidBody(boxB);
            boxMeshB = TGCBox.fromSize(new TGCVector3(80f, 80f, 80f), textureBox);
            boxMeshB.updateValues();

            box45 = BulletRigidBodyFactory.Instance.CreateBox(new TGCVector3(sizeBox, sizeBox, sizeBox), 0, new TGCVector3(200, 40, 0), BulletSharp.MathUtil.SIMD_QUARTER_PI, 0, 0, 0.5f, true);
            dynamicsWorld.AddRigidBody(box45);

            boxPush = BulletRigidBodyFactory.Instance.CreateBox(new TGCVector3(sizeBox, sizeBox, sizeBox), 0.5f, new TGCVector3(-200, 60, 0), BulletSharp.MathUtil.SIMD_QUARTER_PI, 0, 0, 0.25f, true);
            dynamicsWorld.AddRigidBody(boxPush);

            boxMeshPush = TGCBox.fromSize(new TGCVector3(80f, 80f, 80f), textureBox);
            boxMeshPush.updateValues();

            #endregion Cajas

            #region Escalera

            var a             = 0;
            var textureStones = TgcTexture.createTexture(D3DDevice.Instance.Device, MediaDir + @"Texturas\stones.bmp");

            //la altura de cualquier cubo que quiera subir una capsula debe ser menor a la mitad del radio
            var size = new TGCVector3(50, 4, 20);
            escalon = TGCBox.fromSize(size, textureStones);

            //Se crean 10 escalonescd d
            while (a < 10)
            {
                escalonRigidBody = BulletRigidBodyFactory.Instance.CreateBox(size, 0, new TGCVector3(200, a * 4 + 10, a * 20 + 100), 0, 0, 0, 0.1f, true);

                escalonesRigidBodies.Add(escalonRigidBody);

                dynamicsWorld.AddRigidBody(escalonRigidBody);

                a++;
            }

            #endregion Escalera

            #region Plataforma

            textureStones       = TgcTexture.createTexture(D3DDevice.Instance.Device, MediaDir + @"Texturas\cobblestone_quad.jpg");
            rigidBodyPlataforma = BulletRigidBodyFactory.Instance.CreateBox(new TGCVector3(50f, 15f, 50f), 0, new TGCVector3(200, 42.5f, 315), 0, 0, 0, 0.5f, true);
            dynamicsWorld.AddRigidBody(rigidBodyPlataforma);
            plataforma = TGCBox.fromSize(new TGCVector3(50f, 15f, 50f), textureStones);
            plataforma.updateValues();

            #endregion Plataforma

            #region Columna

            columnaRigidBody = BulletRigidBodyFactory.Instance.CreateCylinder(new TGCVector3(10, 50, 10), new TGCVector3(100, 50, 100), 0);
            dynamicsWorld.AddRigidBody(columnaRigidBody);
            var columnaLoader = new TgcSceneLoader();
            columnaMesh          = columnaLoader.loadSceneFromFile(MediaDir + @"MeshCreator\Meshes\Cimientos\PilarEgipcio\PilarEgipcio-TgcScene.xml", MediaDir + @"MeshCreator\Meshes\Cimientos\PilarEgipcio\").Meshes[0];
            columnaMesh.Position = new TGCVector3(100, 7.5f, 100);
            columnaMesh.UpdateMeshTransform();

            #endregion Columna

            director = new TGCVector3(0, 0, 1);
        }
示例#14
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);

            // create the ground
            CollisionShape groundShape = new BoxShape(50, 50, 50);

            collisionShapes.Add(groundShape);
            CollisionObject ground = LocalCreateRigidBody(0, Matrix4.CreateTranslation(0, -50, 0), groundShape);

            ground.UserObject = "Ground";

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

            CollisionShape colShape = new BoxShape(1);

            collisionShapes.Add(colShape);
            Vector3 localInertia = colShape.CalculateLocalInertia(mass);

            const float start_x = StartPosX - ArraySizeX / 2;
            const float start_y = StartPosY;
            const 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++)
                    {
                        Matrix4 startTransform = Matrix4.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);
                    }
                }
            }
        }
示例#15
0
        protected override void Initialize()
        {
            base.Initialize();
            SetCameraDistance(50.0f);

            ///collision configuration contains default setup for memory, collision setup
            m_collisionConfiguration = new DefaultCollisionConfiguration();
            //m_collisionConfiguration.setConvexConvexMultipointIterations();

            ///use the default collision dispatcher. For parallel processing you can use a diffent dispatcher (see Extras/BulletMultiThreaded)
            m_dispatcher = new CollisionDispatcher(m_collisionConfiguration);

            m_broadphase = new DbvtBroadphase();

            ///the default constraint solver. For parallel processing you can use a different solver (see Extras/BulletMultiThreaded)
            m_constraintSolver = new SequentialImpulseConstraintSolver();

            m_dynamicsWorld = new DiscreteDynamicsWorld(m_dispatcher, m_broadphase, m_constraintSolver, m_collisionConfiguration);

            IndexedVector3 gravity = new IndexedVector3(0, -10, 0);

            m_dynamicsWorld.SetGravity(ref gravity);


            // NEW => btGhostPairCallback =================================
            m_ghostPairCallback = new GhostPairCallback();
            m_dynamicsWorld.GetBroadphase().GetOverlappingPairCache().SetInternalGhostPairCallback(m_ghostPairCallback);        // Needed once to enable ghost objects inside Bullet

            // NEW => btGhostObject =======================================
            m_ghostObject = new GhostObject();
            CollisionShape shape = new BoxShape(new IndexedVector3(5f));        // As far as I know only the world aabb of the shape will be used (i.e. a box always parallel to the x,y,z axis of variable size)

            m_collisionShapes.Add(shape);
            m_ghostObject.SetCollisionShape(shape);
            m_ghostObject.SetCollisionFlags(CollisionFlags.CF_NO_CONTACT_RESPONSE);             // We can choose to make it "solid" if we want...
            m_dynamicsWorld.AddCollisionObject(m_ghostObject, CollisionFilterGroups.SensorTrigger, CollisionFilterGroups.AllFilter & ~CollisionFilterGroups.SensorTrigger);
            //m_ghostObject.setWorldTransform(btTransform(btQuaternion::getIdentity(),btVector3(0,5,-15)));
            IndexedMatrix im = IndexedMatrix.CreateFromQuaternion(quatDeg45Y);

            im._origin = new IndexedVector3(0, 5, -15);
            m_ghostObject.SetWorldTransform(im);

            // NEW => btPairCachingGhostObject ============================
            m_pairCachingGhostObject = new PairCachingGhostObject();
            shape = new ConeShape(7.0f, 14.0f);
            m_collisionShapes.Add(shape);
            m_pairCachingGhostObject.SetCollisionShape(shape);
            m_pairCachingGhostObject.SetCollisionFlags(CollisionFlags.CF_NO_CONTACT_RESPONSE);  // We can choose to make it "solid" if we want...
            m_dynamicsWorld.AddCollisionObject(m_pairCachingGhostObject, CollisionFilterGroups.SensorTrigger, CollisionFilterGroups.AllFilter & ~CollisionFilterGroups.SensorTrigger);
            //m_pairCachingGhostObject.setWorldTransform(btTransform(btQuaternion::getIdentity(),btVector3(0,5,15)));
            im._origin = new IndexedVector3(0, 7, 15);
            m_pairCachingGhostObject.SetWorldTransform(im);
            //=============================================================

            ///create a few basic rigid bodies
            CollisionShape groundShape = new BoxShape(new IndexedVector3(50));

            m_collisionShapes.Add(groundShape);

            IndexedMatrix groundTransform = IndexedMatrix.Identity;

            groundTransform._origin = new IndexedVector3(0, -50, 0);

            float mass = 0.0f;

            LocalCreateRigidBody(mass, groundTransform, groundShape);

            // spawn some cubes (code pasted from appBasicDemo...)
            if (true)
            {
                //create a few dynamic rigidbodies
                CollisionShape colShape = new BoxShape(new IndexedVector3(SCALING, SCALING, SCALING));
                //btCollisionShape* colShape = new btSphereShape(btScalar(1.));
                //CollisionShape colShape = new CylinderShape(new IndexedVector3(1f, 1, 1f));
                m_collisionShapes.Add(colShape);

                /// Create Dynamic Objects
                IndexedMatrix startTransform = IndexedMatrix.Identity;

                mass = 1f;

                //rigidbody is dynamic if and only if mass is non zero, otherwise static
                bool isDynamic = mass != 0f;

                IndexedVector3 localInertia = IndexedVector3.Zero;
                if (isDynamic)
                {
                    colShape.CalculateLocalInertia(mass, out localInertia);
                }
                float start_x = START_POS_X - ARRAY_SIZE_X / 2;
                float start_y = START_POS_Y;
                float start_z = START_POS_Z - ARRAY_SIZE_Z / 2;

                for (int k = 0; k < ARRAY_SIZE_Y; k++)
                {
                    for (int i = 0; i < ARRAY_SIZE_X; i++)
                    {
                        for (int j = 0; j < ARRAY_SIZE_Z; j++)
                        {
                            startTransform._origin = (new IndexedVector3(2.0f * i + start_x, 20 + 2.0f * k + start_y, 2.0f * j + start_z) * SCALING);

                            //using motionstate is recommended, it provides interpolation capabilities, and only synchronizes 'active' objects
                            DefaultMotionState        myMotionState = new DefaultMotionState(startTransform, IndexedMatrix.Identity);
                            RigidBodyConstructionInfo rbInfo        = new RigidBodyConstructionInfo(mass, myMotionState, colShape, localInertia);
                            RigidBody body = new RigidBody(rbInfo);
                            //body.setContactProcessingThreshold(colShape.getContactBreakingThreshold());
                            body.SetActivationState(ActivationState.ISLAND_SLEEPING);

                            m_dynamicsWorld.AddRigidBody(body);
                            body.SetActivationState(ActivationState.ISLAND_SLEEPING);
                            body.SetUserPointer(String.Format("Box X{0} Y{1} Z{2}", k, i, j));
                        }
                    }
                }
            }

            ClientResetScene();
        }
示例#16
0
        public void Init(string MediaDir)
        {
            #region Configuracion Basica de World

            //Creamos el mundo fisico por defecto.
            collisionConfiguration = new DefaultCollisionConfiguration();
            dispatcher             = new CollisionDispatcher(collisionConfiguration);
            GImpactCollisionAlgorithm.RegisterAlgorithm(dispatcher);
            constraintSolver      = new SequentialImpulseConstraintSolver();
            overlappingPairCache  = new DbvtBroadphase(); //AxisSweep3(new BsVector3(-5000f, -5000f, -5000f), new BsVector3(5000f, 5000f, 5000f), 8192);
            dynamicsWorld         = new DiscreteDynamicsWorld(dispatcher, overlappingPairCache, constraintSolver, collisionConfiguration);
            dynamicsWorld.Gravity = new TGCVector3(0, -100f, 0).ToBulletVector3();

            #endregion Configuracion Basica de World

            strength = 5.8f;
            angle    = 0.5f;

            foreach (var mesh in meshes)
            {
                var childTriangleMesh = construirTriangleMeshShape(mesh);
                var buildingbody      = construirRigidBodyDeChildTriangleMeshShape(childTriangleMesh, mesh.Position, mesh.Scale);


                //buildingbody.Translate(mesh.Position.ToBulletVector3());
                dynamicsWorld.AddRigidBody(buildingbody);
            }

            //Se crea un plano ya que esta escena tiene problemas
            //con la definición de triangulos para el suelo
            var floorShape = new StaticPlaneShape(TGCVector3.Up.ToBulletVector3(), 10);
            floorShape.LocalScaling = new TGCVector3().ToBulletVector3();
            var floorMotionState = new DefaultMotionState();
            var floorInfo        = new RigidBodyConstructionInfo(0, floorMotionState, floorShape);
            floorBody                 = new RigidBody(floorInfo);
            floorBody.Friction        = 0.5f;
            floorBody.RollingFriction = 1;
            floorBody.Restitution     = 1f;
            floorBody.UserObject      = "floorBody";
            dynamicsWorld.AddRigidBody(floorBody);

            var meshRigidBody = BulletRigidBodyFactory.Instance.CreateSurfaceFromHeighMap(terreno.getData());
            dynamicsWorld.AddRigidBody(meshRigidBody);

            var loader = new TgcSceneLoader();

            //Se crea el cuerpo rígido de la caja, en la definicio de CreateBox el ultimo parametro representa si se quiere o no
            //calcular el momento de inercia del cuerpo. No calcularlo lo que va a hacer es que la caja que representa el personaje
            //no rote cuando colicione contra el mundo.
            personajeBody = BulletRigidBodyFactory.Instance.CreateCapsule(10, 10, personaje.Position, 2.55f, false);

            personajeBody.Gravity = new TGCVector3(0, -100, 0).ToBulletVector3();
            personajeBody.SetDamping(0.3f, 0f);
            personajeBody.Restitution     = 0.1f;
            personajeBody.Friction        = 1;
            personajeBody.ActivationState = ActivationState.IslandSleeping;

            dynamicsWorld.AddRigidBody(personajeBody);

            director = new TGCVector3(-1, 0, 0);
        }