Exemplo n.º 1
0
        protected void iniPhysx(Vector3 startPosition)
        {
            BodyDescription boxBody = new BodyDescription();

            boxBody.AngularVelocity = new StillDesign.PhysX.MathPrimitives.Vector3(1, 0, 0);
            boxBody.Mass            = 2000;

            //Material
            MaterialDescription materialDesc = new MaterialDescription();

            materialDesc.Restitution     = 0.001f;
            materialDesc.StaticFriction  = 0.5f;
            materialDesc.DynamicFriction = 0.5f;
            materialDesc.Name            = "Test";
            this.game.scene.CreateMaterial(materialDesc);


            BoxShapeDescription boxShapeDesc = new BoxShapeDescription();

            boxShapeDesc.Dimensions = new StillDesign.PhysX.MathPrimitives.Vector3(20.5f, 6.4f, 34.0f);
            boxShapeDesc.Material   = this.game.scene.Materials[1];
            boxShapeDesc.Mass       = 2000;

            ActorDescription actor = new ActorDescription();

            actor.GlobalPose      = StillDesign.PhysX.MathPrimitives.Matrix.Translation(startPosition.X, startPosition.Y, startPosition.Z);
            actor.BodyDescription = boxBody;
            actor.Shapes.Add(boxShapeDesc);

            this.actor = this.game.scene.CreateActor(actor);
            this.shape = this.actor.CreateShape(boxShapeDesc) as BoxShape;
        }
Exemplo n.º 2
0
        public void Initialize()
        {
            if (Behaviour.RefNumber == 99) //flag waving guy
            {
                SetAction(Behaviour.Actions[7], true);
            }
            else
            {
                SetAction(Behaviour.Standing, true);
            }
            Position            = Instructions[InitialInstruction].Position;
            _currentInstruction = InitialInstruction;

            if (Instructions[_currentInstruction].AutoY)
            {
                StillDesign.PhysX.RaycastHit hit = PhysX.Instance.Scene.RaycastClosestShape(new StillDesign.PhysX.Ray(Position + new Vector3(0, 10, 0), Vector3.Down), StillDesign.PhysX.ShapesType.Static);
                Position = hit.WorldImpact;
            }

            ActorDescription actorDesc = new ActorDescription();

            actorDesc.BodyDescription = new BodyDescription(1);
            actorDesc.BodyDescription.MassSpaceInertia = new Vector3(1, 1, 1);
            actorDesc.BodyDescription.BodyFlags       |= BodyFlag.Kinematic;

            BoxShapeDescription box = new BoxShapeDescription(1.6f, 2.5f, 1.6f);

            box.Flags         = ShapeFlag.TriggerOnEnter;
            box.LocalPosition = new Vector3(0, 1, 0);
            actorDesc.Shapes.Add(box);
            _physXActor = PhysX.Instance.Scene.CreateActor(actorDesc);
            _physXActor.GlobalPosition = Position;
            _physXActor.UserData       = this;
        }
Exemplo n.º 3
0
        public static void RunCharacterTest()
        {
            Core core = new Core();

            StillDesign.PhysX.Scene scene = core.CreateScene();

            ControllerManager manager = scene.CreateControllerManager();

            CapsuleControllerDescription desc = new CapsuleControllerDescription(2, 10);
            CapsuleController            capsuleController = manager.CreateController <CapsuleController>(desc);


            BoxShapeDescription boxShapeDesc = new BoxShapeDescription(1, 1, 1);
            ActorDescription    actorDesc    = new ActorDescription(boxShapeDesc);

            actorDesc.BodyDescription = new BodyDescription(1f);

            Actor actor = scene.CreateActor(actorDesc);

            //capsuleController.Move( Vector3.Up );

            // Update Physics
            scene.Simulate(1.0f / 60.0f);
            scene.FlushStream();
            scene.FetchResults(SimulationStatus.RigidBodyFinished, true);

            capsuleController.Move(Vector3.Up);

            core.Dispose();
        }
Exemplo n.º 4
0
        protected void iniPhysx(Vector3 startPosition)
        {
            BodyDescription boxBody = new BodyDescription();
            boxBody.AngularVelocity = new StillDesign.PhysX.MathPrimitives.Vector3(1, 0, 0);
            boxBody.Mass = 2000;

            //Material
            MaterialDescription materialDesc = new MaterialDescription();
            materialDesc.Restitution = 0.001f;
            materialDesc.StaticFriction = 0.5f;
            materialDesc.DynamicFriction = 0.5f;
            materialDesc.Name = "Test";
            this.game.scene.CreateMaterial(materialDesc);

            BoxShapeDescription boxShapeDesc = new BoxShapeDescription();
            boxShapeDesc.Dimensions = new StillDesign.PhysX.MathPrimitives.Vector3(20.5f, 6.4f, 34.0f);
            boxShapeDesc.Material = this.game.scene.Materials[1];
            boxShapeDesc.Mass = 2000;

            ActorDescription actor = new ActorDescription();

            actor.GlobalPose = StillDesign.PhysX.MathPrimitives.Matrix.Translation(startPosition.X, startPosition.Y, startPosition.Z);
            actor.BodyDescription = boxBody;
            actor.Shapes.Add(boxShapeDesc);

            this.actor = this.game.scene.CreateActor(actor);
            this.shape = this.actor.CreateShape(boxShapeDesc) as BoxShape;
        }
Exemplo n.º 5
0
Arquivo: Prefabs.cs Projeto: zhuowp/ge
        public static GameObject CreateBin()
        {
            var shapes = new BoxShapeDescription[]
            {
                new BoxShapeDescription(new Vector3(3.0f, 0.5f, 3.0f), new Vector3(0f, 0f, 0f)), // Bottom
                new BoxShapeDescription(new Vector3(3.0f, 0.5f, 3.0f),
                                        new Vector3(-1.75f, 1.75f, 0f), Quaternion.CreateFromAxisAngle(-Vector3.UnitZ, (float)Math.PI / 2)),
                new BoxShapeDescription(new Vector3(3.0f, 0.5f, 3.0f),
                                        new Vector3(1.75f, 1.75f, 0f), Quaternion.CreateFromAxisAngle(Vector3.UnitZ, (float)Math.PI / 2)),
                new BoxShapeDescription(new Vector3(3.0f, 0.5f, 3.0f),
                                        new Vector3(0f, 1.75f, 1.75f), Quaternion.CreateFromAxisAngle(-Vector3.UnitX, (float)Math.PI / 2)),
                new BoxShapeDescription(new Vector3(3.0f, 0.5f, 3.0f),
                                        new Vector3(0f, 1.75f, -1.75f), Quaternion.CreateFromAxisAngle(Vector3.UnitX, (float)Math.PI / 2))
            };

            GameObject bin = new GameObject("Bin");
            var        csc = new CompoundShapeCollider(shapes, 40.0f);

            bin.AddComponent(csc);

            foreach (var shape in shapes)
            {
                var mc = new MeshRenderer(
                    new SimpleMeshDataProvider(CubeModel.Vertices, CubeModel.Indices),
                    Path.Combine("Textures", "Stone.png"));
                mc.RenderOffset = Matrix4x4.CreateScale(3.0f, 0.5f, 3.0f)
                                  * Matrix4x4.CreateFromQuaternion(shape.Orientation)
                                  * Matrix4x4.CreateTranslation(csc.EntityCenter + shape.Position)
                ;
                bin.AddComponent(mc);
            }

            return(bin);
        }
Exemplo n.º 6
0
        public static SLAct createBox(float x, float y, float z, float density, bool fix)
        {
            Vector3          pos       = new Vector3(x, y, z);
            ActorDescription actorDesc = new ActorDescription();
            BodyDescription  bodyDesc  = new BodyDescription();

            actorDesc.SetToDefault();
            bodyDesc.SetToDefault();

            BoxShapeDescription capsuleDesc = new BoxShapeDescription()
            {
                LocalPose = Matrix.Translation(new Vector3(0, 0, 0)),
                //Name = mName
                // LocalRotation = Matrix.CreateRotationZ(45)
            };

            actorDesc.Shapes.Add(capsuleDesc);
            if (density > 0)
            {
                actorDesc.BodyDescription = bodyDesc;
                actorDesc.Density         = density;
            }
            actorDesc.GlobalPose = Matrix.Translation(pos);

            SLAct act = new SLAct(actorDesc);

            act.no_gravity = fix;
            return(act);
        }
Exemplo n.º 7
0
        public static PhysX.Fluid FluidWithEmitterAndDrain(Scene scene)
        {
            const int maximumParticles = 1000;

            var fluidEmitterDesc = new FluidEmitterDescription()
            {
                DimensionX   = 0.5f,
                DimensionY   = 0.5f,
                Rate         = 15,
                RelativePose =
                    Matrix.RotationAxis(new Vector3(0, 1, 0), (float)Math.PI) *
                    Matrix.Translation(-40, 10, -50),
                Shape       = EmitterShape.Rectangular,
                Type        = EmitterType.ConstantFlowRate,
                RandomAngle = 0.5f
            };

            fluidEmitterDesc.Flags |= (FluidEmitterFlag.Enabled | FluidEmitterFlag.Visualization);

            var fluidDesc = new FluidDescription()
            {
                Emitters         = { fluidEmitterDesc },
                Flags            = FluidFlag.Enabled | FluidFlag.Visualization,
                MaximumParticles = maximumParticles
            };

            fluidDesc.ParticleWriteData.AllocatePositionBuffer <Vector3>(maximumParticles);
            fluidDesc.ParticleWriteData.NumberOfParticles = maximumParticles;

            var fluid = scene.CreateFluid(fluidDesc);

            // Ledge
            {
                var boxShapeDesc = new BoxShapeDescription(5, 0.1f, 5);

                var drainActorDesc = new ActorDescription()
                {
                    GlobalPose = Matrix.RotationX(-0.5f) * Matrix.Translation(-40, 5, -52),
                    Shapes     = { boxShapeDesc }
                };

                var drianActor = scene.CreateActor(drainActorDesc);
            }

            // Drain
            {
                var boxShapeDesc = new BoxShapeDescription(5, 0.1f, 5);
                boxShapeDesc.Flags |= ShapeFlag.FluidDrain;

                var drainActorDesc = new ActorDescription()
                {
                    GlobalPose = Matrix.Translation(-40, 0, -55),
                    Shapes     = { boxShapeDesc }
                };

                var drianActor = scene.CreateActor(drainActorDesc);
            }

            return(fluid);
        }
Exemplo n.º 8
0
        private void CreateBoxes(Nx.Material material)
        {
            for (int x = 0; x < XCount; x++)
                for (int y = 0; y < YCount; y++)
                    for (int z = 0; z < ZCount; z++)
                    {
                        var rigidBodyDesc = new BodyDescription();

                        var boxDesc = new BoxShapeDescription
                        {
                            Material = material,
                            Dimensions = new NxVector3(WidthX / 2, WidthY / 2, WidthZ / 2)
                        };

                        var actorDesc = new ActorDescription(boxDesc)
                        {
                            BodyDescription = rigidBodyDesc,
                            Density = 10.0f,
                            GlobalPose = NxMath.Matrix.Translation(
                                                   XOffset + x * XSpace - ((XCount - 1) * XSpace / 2),
                                                   YOffset + y * YSpace - ((YCount - 1) * YSpace / 2),
                                                   ZOffset + z * ZSpace - ((ZCount - 1) * ZSpace / 2)),
                            UserData = _boxModel
                        };

                        if (!actorDesc.IsValid())
                            throw new Exception("ActorDesc invalid!");

                        var actor = _scene.CreateActor(actorDesc);
                        if (actor == null)
                            throw new Exception("Actor invalid!");
                    }
        }
        public BoundingBox CalculateBoundingBox(MeshCollisionData data)
        {
            var boundingBox = new BoundingBox();

            for (int i = 0; i < data.Boxes.Count; i++)
            {
                var box   = data.Boxes[i];
                var shape = new BoxShapeDescription(box.Dimensions);
                shape.LocalPose = box.Orientation;

                //WARNING: this is slow , really slow
                Vector3[] corners   = (new BoundingBox(-box.Dimensions * Vector3.One * 0.5f, box.Dimensions * Vector3.One * 0.5f)).GetCorners();
                var       transform = new Vector3[corners.Length];

                Vector3.Transform(corners, ref box.Orientation, transform);

                var bs = BoundingBox.CreateFromPoints(transform);



                boundingBox = boundingBox.MergeWith(bs);
            }

            //TODO: convex boundingbox not implemented!

            if (data.TriangleMesh != null)
            {
                boundingBox = boundingBox.MergeWith(calculateBBTriangleMesh(data.TriangleMesh));
            }

            return(boundingBox);
        }
Exemplo n.º 10
0
		public static PhysX.Fluid FluidWithEmitterAndDrain(Scene scene)
		{
			const int maximumParticles = 1000;

			var fluidEmitterDesc = new FluidEmitterDescription()
			{
				DimensionX = 0.5f,
				DimensionY = 0.5f,
				Rate = 15,
				RelativePose = 
					Matrix.RotationAxis(new Vector3(0, 1, 0), (float)Math.PI) *
					Matrix.Translation(-40, 10, -50),
				Shape = EmitterShape.Rectangular,
				Type = EmitterType.ConstantFlowRate,
				RandomAngle = 0.5f
			};
			fluidEmitterDesc.Flags |= (FluidEmitterFlag.Enabled | FluidEmitterFlag.Visualization);

			var fluidDesc = new FluidDescription()
			{
				Emitters = { fluidEmitterDesc },
				Flags = FluidFlag.Enabled | FluidFlag.Visualization,
				MaximumParticles = maximumParticles
			};
			fluidDesc.ParticleWriteData.AllocatePositionBuffer<Vector3>(maximumParticles);
			fluidDesc.ParticleWriteData.NumberOfParticles = maximumParticles;

			var fluid = scene.CreateFluid(fluidDesc);

			// Ledge
			{
				var boxShapeDesc = new BoxShapeDescription(5, 0.1f, 5);

				var drainActorDesc = new ActorDescription()
				{
					GlobalPose = Matrix.RotationX(-0.5f) * Matrix.Translation(-40, 5, -52),
					Shapes = { boxShapeDesc }
				};

				var drianActor = scene.CreateActor(drainActorDesc);
			}

			// Drain
			{
				var boxShapeDesc = new BoxShapeDescription(5, 0.1f, 5);
				boxShapeDesc.Flags |= ShapeFlag.FluidDrain;

				var drainActorDesc = new ActorDescription()
				{
					GlobalPose = Matrix.Translation(-40, 0, -55),
					Shapes = { boxShapeDesc }
				};

				var drianActor = scene.CreateActor(drainActorDesc);
			}

			return fluid;
		}
        /// <summary>
        /// You can put a scale (-1) operation in the global pose, it works! (not for convex meshes though!)
        /// NOTE: WARNING: scaling not supported!!! (still not supported, it has been delayed for several reasons)
        /// </summary>
        /// <param name="data"></param>
        /// <param name="scene"></param>
        /// <param name="globalPose"></param>
        /// <returns></returns>
        private ActorDescription createActorDesc(MeshCollisionData data, StillDesign.PhysX.Scene scene, Matrix globalPose)
        {
            // From PhysX SDK:
            //There are some performance implications of compound shapes that the user should be aware of:
            //You should avoid static actors being compounds; there's a limit to the number of triangles allowed in one actor's mesh shapes and subshapes exceeding the limit will be ignored.
            //TODO: is this about triangle meshes only? EDIT: i dont think so



            // Pull scaling out of the transformation
            Vector3    scale, translation;
            Quaternion rotation;

            globalPose.Decompose(out scale, out rotation, out translation);

            //globalPose = Matrix.CreateFromQuaternion(rotation) * Matrix.CreateTranslation(translation);
            var scaleMat = Matrix.Identity;// Matrix.CreateScale(scale);


            ActorDescription actorDesc = new ActorDescription();

            for (int i = 0; i < data.Boxes.Count; i++)
            {
                var box   = data.Boxes[i];
                var shape = new BoxShapeDescription(box.Dimensions);
                shape.LocalPose = box.Orientation * scaleMat;
                actorDesc.Shapes.Add(shape);
            }

            for (int i = 0; i < data.ConvexMeshes.Count; i++)
            {
                var convex = data.ConvexMeshes[i];
                var shape  = new ConvexShapeDescription();
                shape.ConvexMesh = MeshPhysicsPool.CreateConvexMesh(scene, convex);

                shape.Flags = ShapeFlag.Visualization;
                actorDesc.Shapes.Add(shape);
            }



            if (data.TriangleMesh != null)
            {
                TriangleMesh triangleMesh;
                triangleMesh = MeshPhysicsPool.CreateTriangleMesh(scene, data.TriangleMesh);

                TriangleMeshShapeDescription shapeDesc = new TriangleMeshShapeDescription();
                shapeDesc.TriangleMesh = triangleMesh;
                shapeDesc.Flags        = ShapeFlag.Visualization; // Vizualization enabled, obviously (not obviously enabled, obvious that this enables visualization)

                actorDesc.Shapes.Add(shapeDesc);
            }

            actorDesc.GlobalPose = globalPose;
            return(actorDesc);
        }
Exemplo n.º 12
0
        private static Actor CreateBoxActor( Scene scene, float sizeX, float sizeY, float sizeZ )
        {
            var actorDesc = new ActorDescription();
            var bodyDesc = new BodyDescription();

            var boxDesc = new BoxShapeDescription( sizeX, sizeY, sizeZ );

            actorDesc.Shapes.Add( boxDesc );

            actorDesc.BodyDescription = bodyDesc;
            actorDesc.Density = 10;

            return scene.CreateActor( actorDesc );
        }
Exemplo n.º 13
0
		public static void SimpleBoxes(Scene scene)
		{
			for (int x = 0; x < 5; x++)
			{
				BoxShapeDescription boxShapeDesc = new BoxShapeDescription(2, 3, 8);

				ActorDescription actorDesc = new ActorDescription()
				{
					Name = String.Format("Box {0}", x),
					BodyDescription = new BodyDescription(10.0f),
					GlobalPose = Matrix.Translation(100, 15 + 3 * x, 20),
					Shapes = { boxShapeDesc }
				};

				Actor actor = scene.CreateActor(actorDesc);
			}
		}
Exemplo n.º 14
0
        public static PrismaticJoint PrismaticJointWithLimit(Scene scene)
        {
            Actor actorA, actorB;
            {
                BoxShapeDescription boxShapeDesc = new BoxShapeDescription(3, 3, 3);

                BodyDescription bodyDesc = new BodyDescription(10.0f);
                bodyDesc.BodyFlags |= BodyFlag.Kinematic;

                ActorDescription actorDesc = new ActorDescription()
                {
                    BodyDescription = bodyDesc,
                    GlobalPose      = Matrix.Translation(70, 25, -65),
                    Shapes          = { boxShapeDesc }
                };
                actorA = scene.CreateActor(actorDesc);
            }
            {
                BoxShapeDescription boxShapeDesc = new BoxShapeDescription(3, 3, 3);

                ActorDescription actorDesc = new ActorDescription()
                {
                    BodyDescription = new BodyDescription(10.0f),
                    GlobalPose      = Matrix.Translation(70, 15, -65),
                    Shapes          = { boxShapeDesc }
                };
                actorB = scene.CreateActor(actorDesc);
            }

            PrismaticJointDescription prismaticJointDesc = new PrismaticJointDescription()
            {
                Actor1 = actorA,
                Actor2 = actorB,
            };

            prismaticJointDesc.SetGlobalAnchor(new Vector3(70, 20, -65));
            prismaticJointDesc.SetGlobalAxis(new Vector3(0, 1, 0));

            PrismaticJoint prismaticJoint = scene.CreateJoint(prismaticJointDesc) as PrismaticJoint;

            LimitPlane limitPlane = new LimitPlane(new Vector3(0, 1, 0), new Vector3(-30, 8, -30), 0);

            prismaticJoint.AddLimitPlane(limitPlane);

            return(prismaticJoint);
        }
Exemplo n.º 15
0
        public static void SimpleBoxes(Scene scene)
        {
            for (int x = 0; x < 5; x++)
            {
                BoxShapeDescription boxShapeDesc = new BoxShapeDescription(2, 3, 8);

                ActorDescription actorDesc = new ActorDescription()
                {
                    Name            = String.Format("Box {0}", x),
                    BodyDescription = new BodyDescription(10.0f),
                    GlobalPose      = Matrix.Translation(100, 15 + 3 * x, 20),
                    Shapes          = { boxShapeDesc }
                };

                Actor actor = scene.CreateActor(actorDesc);
            }
        }
Exemplo n.º 16
0
        public BoxShape(RigidBody rigidBody, Matrix4x4 realParentPose, Material material, BoxShapeDescriptor descriptor)
        {
            var boxShapeDescription = new BoxShapeDescription(descriptor.WidthX, descriptor.WidthY, descriptor.WidthZ)
                                          {
                                              Material = material._wrappedMaterial
                                          };

            _wrappedBoxShape =
                (StillDesign.PhysX.BoxShape)
                rigidBody.WrappedActor.CreateShape(boxShapeDescription);
            SetRealParentPose(realParentPose);
            UserData = descriptor.UserData;
            if (rigidBody.HasDefaultShape)
            {
                rigidBody.WrappedActor.Shapes[0].Dispose();
                rigidBody.HasDefaultShape = false;
            }
        }
Exemplo n.º 17
0
        public BoxShape(RigidBody rigidBody, Matrix4x4 realParentPose, Material material, BoxShapeDescriptor descriptor)
        {
            var boxShapeDescription = new BoxShapeDescription(descriptor.WidthX, descriptor.WidthY, descriptor.WidthZ)
            {
                Material = material._wrappedMaterial
            };

            _wrappedBoxShape =
                (StillDesign.PhysX.BoxShape)
                rigidBody.WrappedActor.CreateShape(boxShapeDescription);
            SetRealParentPose(realParentPose);
            UserData = descriptor.UserData;
            if (rigidBody.HasDefaultShape)
            {
                rigidBody.WrappedActor.Shapes[0].Dispose();
                rigidBody.HasDefaultShape = false;
            }
        }
Exemplo n.º 18
0
		public static PrismaticJoint PrismaticJointWithLimit(Scene scene)
		{
			Actor actorA, actorB;
			{
				BoxShapeDescription boxShapeDesc = new BoxShapeDescription(3, 3, 3);

				BodyDescription bodyDesc = new BodyDescription(10.0f);
				bodyDesc.BodyFlags |= BodyFlag.Kinematic;

				ActorDescription actorDesc = new ActorDescription()
				{
					BodyDescription = bodyDesc,
					GlobalPose = Matrix.Translation(70, 25, -65),
					Shapes = { boxShapeDesc }
				};
				actorA = scene.CreateActor(actorDesc);
			}
			{
				BoxShapeDescription boxShapeDesc = new BoxShapeDescription(3, 3, 3);

				ActorDescription actorDesc = new ActorDescription()
				{
					BodyDescription = new BodyDescription(10.0f),
					GlobalPose = Matrix.Translation(70, 15, -65),
					Shapes = { boxShapeDesc }
				};
				actorB = scene.CreateActor(actorDesc);
			}

			PrismaticJointDescription prismaticJointDesc = new PrismaticJointDescription()
			{
				Actor1 = actorA,
				Actor2 = actorB,
			};
			prismaticJointDesc.SetGlobalAnchor(new Vector3(70, 20, -65));
			prismaticJointDesc.SetGlobalAxis(new Vector3(0, 1, 0));

			PrismaticJoint prismaticJoint = scene.CreateJoint(prismaticJointDesc) as PrismaticJoint;

			LimitPlane limitPlane = new LimitPlane(new Vector3(0, 1, 0), new Vector3(-30, 8, -30), 0);
			prismaticJoint.AddLimitPlane(limitPlane);

			return prismaticJoint;
		}
Exemplo n.º 19
0
        public BarCog(PhysicsEngine engine)
        {
            var actorDesc = new ActorDescription();

            actorDesc.BodyDescription = new BodyDescription(100);

            var boxShapeDesc = new BoxShapeDescription(100, 1f, 1f);

            actorDesc.Shapes.Add(boxShapeDesc);


            for (float i = -50; i < 51; i += 2)
            {
                Cog.AddCogToothShapes(actorDesc, new Vector3(i, 0, 0.8f), Vector3.UnitZ, Vector3.UnitY);
            }


            Actor = engine.Scene.CreateActor(actorDesc);
        }
        protected override void LoadContent(GraphicInfo GraphicInfo, GraphicFactory factory, IContentManager contentManager)
        {
            PhysxPhysicWorld PhysxPhysicWorld = World.PhysicWorld as PhysxPhysicWorld;

            base.LoadContent(GraphicInfo, factory, contentManager);
            {
                SimpleModel simpleModel = new SimpleModel(factory, "Model//block");
                simpleModel.SetTexture(factory.CreateTexture2DColor(1, 1, Color.Blue), TextureType.DIFFUSE);

                BoxShapeDescription SphereGeometry    = new BoxShapeDescription(1000, 5, 1000);
                PhysxPhysicObject   PhysxPhysicObject = new PhysxPhysicObject(SphereGeometry,
                                                                              Matrix.Identity, new Vector3(1000, 5, 1000));

                ForwardXNABasicShader shader    = new ForwardXNABasicShader(ForwardXNABasicShaderDescription.Default());
                ForwardMaterial       fmaterial = new ForwardMaterial(shader);
                IObject obj = new IObject(fmaterial, simpleModel, PhysxPhysicObject);
                this.World.AddObject(obj);

                shader.BasicEffect.EnableDefaultLighting();
            }

            {
                ///very basic vehicle !!!
                ///no wheels also =P
                Vehicle     Vehicle     = new Vehicle(PhysxPhysicWorld.Scene);
                SimpleModel simpleModel = new SimpleModel(factory, "Model//block");
                simpleModel.SetTexture(factory.CreateTexture2DColor(1, 1, Color.Green));
                PhysxPhysicObject tmesh = new PhysxPhysicObject(Vehicle.VehicleBodyActor, new Vector3(5, 3, 7));

                ForwardXNABasicShader shader    = new ForwardXNABasicShader(ForwardXNABasicShaderDescription.Default());
                ForwardMaterial       fmaterial = new ForwardMaterial(shader);
                UserObject <Vehicle>  obj       = new UserObject <Vehicle>(fmaterial, simpleModel, tmesh, Vehicle);
                obj.OnUserUpdate += new Action <UserObject <StillDesign.PhysX.Samples.Vehicle> >(obj_OnUserUpdate);
                this.World.AddObject(obj);
            }

            BallThrowPhysx28 BallThrowBullet = new BallThrowPhysx28(this.World, GraphicFactory);

            this.AttachCleanUpAble(BallThrowBullet);

            this.World.CameraManager.AddCamera(new CameraFirstPerson(GraphicInfo));
        }
        protected override void LoadContent(GraphicInfo GraphicInfo, GraphicFactory factory ,IContentManager contentManager)
        {
            PhysxPhysicWorld PhysxPhysicWorld = World.PhysicWorld as PhysxPhysicWorld;

            base.LoadContent(GraphicInfo, factory, contentManager);
            {
                SimpleModel simpleModel = new SimpleModel(factory, "Model//block");
                simpleModel.SetTexture(factory.CreateTexture2DColor(1, 1, Color.Blue), TextureType.DIFFUSE);

                BoxShapeDescription SphereGeometry = new BoxShapeDescription(1000, 5, 1000);
                PhysxPhysicObject PhysxPhysicObject = new PhysxPhysicObject(SphereGeometry,
                    Matrix.Identity, new Vector3(1000, 5, 1000));

                ForwardXNABasicShader shader = new ForwardXNABasicShader(ForwardXNABasicShaderDescription.Default());
                ForwardMaterial fmaterial = new ForwardMaterial(shader);
                IObject obj = new IObject(fmaterial, simpleModel, PhysxPhysicObject);
                this.World.AddObject(obj);

                shader.BasicEffect.EnableDefaultLighting();
            }

            {
                ///very basic vehicle !!!
                ///no wheels also =P
                Vehicle Vehicle = new Vehicle(PhysxPhysicWorld.Scene);
                SimpleModel simpleModel = new SimpleModel(factory, "Model//block");
                simpleModel.SetTexture(factory.CreateTexture2DColor(1, 1, Color.Green));
                PhysxPhysicObject tmesh = new PhysxPhysicObject(Vehicle.VehicleBodyActor, new Vector3(5, 3, 7));

                ForwardXNABasicShader shader = new ForwardXNABasicShader(ForwardXNABasicShaderDescription.Default());
                ForwardMaterial fmaterial = new ForwardMaterial(shader);
                UserObject<Vehicle> obj = new UserObject<Vehicle>(fmaterial, simpleModel, tmesh,Vehicle);
                obj.OnUserUpdate += new Action<UserObject<StillDesign.PhysX.Samples.Vehicle>>(obj_OnUserUpdate);
                this.World.AddObject(obj);

            }

            BallThrowPhysx28 BallThrowBullet = new BallThrowPhysx28(this.World, GraphicFactory);
            this.AttachCleanUpAble(BallThrowBullet);

            this.World.CameraManager.AddCamera(new CameraFirstPerson(GraphicInfo));
        }
Exemplo n.º 22
0
        private Actor CreateActor(RigidBodyDescriptor descriptor, Scene scene)
        {
            var materialDesc = new MaterialDescription
            {
                DynamicFriction        = 0.5f,
                StaticFriction         = 0.5f,
                Restitution            = 0.7f,
                FrictionCombineMode    = CombineMode.Average,
                RestitutionCombineMode = CombineMode.Average
            };

            DefaultMaterial = scene.CreateMaterial(materialDesc);
            var boxDesc = new BoxShapeDescription
            {
                Material   = DefaultMaterial,
                Dimensions = new Vector3(1, 1, 1)
            };
            ///////////////////////////////////////////////



            //resolve the motion type
            var rigidBodyDesc = descriptor.MotionType == MotionType.Static
                                    ? null
                                    : new BodyDescription();

            if (descriptor.MotionType == MotionType.Kinematic)
            {
                rigidBodyDesc.BodyFlags = BodyFlag.Kinematic;
            }

            HasDefaultShape = true;
            var actorDesc = new ActorDescription(boxDesc)
            {
                BodyDescription = rigidBodyDesc,
                Density         = 10.0f,
                GlobalPose      = descriptor.Pose.ToPhysX(),
                UserData        = descriptor.UserData
            };

            return(scene.CreateActor(actorDesc));
        }
Exemplo n.º 23
0
        private void CreateBoxes(Nx.Material material)
        {
            for (int x = 0; x < XCount; x++)
            {
                for (int y = 0; y < YCount; y++)
                {
                    for (int z = 0; z < ZCount; z++)
                    {
                        var rigidBodyDesc = new BodyDescription();

                        var boxDesc = new BoxShapeDescription
                        {
                            Material   = material,
                            Dimensions = new NxVector3(WidthX / 2, WidthY / 2, WidthZ / 2)
                        };

                        var actorDesc = new ActorDescription(boxDesc)
                        {
                            BodyDescription = rigidBodyDesc,
                            Density         = 10.0f,
                            GlobalPose      = NxMath.Matrix.Translation(
                                XOffset + x * XSpace - ((XCount - 1) * XSpace / 2),
                                YOffset + y * YSpace - ((YCount - 1) * YSpace / 2),
                                ZOffset + z * ZSpace - ((ZCount - 1) * ZSpace / 2)),
                            UserData = _boxModel
                        };

                        if (!actorDesc.IsValid())
                        {
                            throw new Exception("ActorDesc invalid!");
                        }

                        var actor = _scene.CreateActor(actorDesc);
                        if (actor == null)
                        {
                            throw new Exception("Actor invalid!");
                        }
                    }
                }
            }
        }
Exemplo n.º 24
0
        private void CreateTower(Nx.Material material, NxVector3 descriptor, int xCount, int yCount, int zCount, float xSpace, float ySpace, float zSpace, float xOffset, float yOffset, float zOffset)
        {
            for (int x = 0; x < xCount; x++)
            {
                for (int y = 0; y < yCount; y++)
                {
                    for (int z = 0; z < zCount; z++)
                    {
                        var rigidBodyDesc = new BodyDescription();

                        var boxDesc = new BoxShapeDescription
                        {
                            Material   = material,
                            Dimensions = new NxVector3(descriptor.X / 2, descriptor.Y / 2, descriptor.Z / 2)
                        };

                        var actorDesc = new ActorDescription(boxDesc)
                        {
                            BodyDescription = rigidBodyDesc,
                            Density         = 10.0f,
                            GlobalPose      = NxMath.Matrix.Translation(
                                xOffset + x * xSpace - ((xCount - 1) * xSpace / 2),
                                yOffset + y * ySpace - ((yCount - 1) * ySpace / 2),
                                zOffset + z * zSpace - ((zCount - 1) * zSpace / 2)),
                            UserData = _boxModel
                        };

                        if (!actorDesc.IsValid())
                        {
                            throw new Exception("ActorDesc invalid!");
                        }

                        var actor = _scene.CreateActor(actorDesc);
                        if (actor == null)
                        {
                            throw new Exception("Actor invalid!");
                        }
                    }
                }
            }
        }
Exemplo n.º 25
0
        public static void CreateContactReport(Scene scene, Actor groundActor)
        {
            // Contact report
            // When the capsule actor hits the ground make it bounce by using the conact report
            {
                CapsuleShapeDescription capsuleShapeDesc = new CapsuleShapeDescription(1, 5);

                ActorDescription actorDesc = new ActorDescription()
                {
                    GlobalPose      = Matrix.Translation(-30, 20, 0),
                    BodyDescription = new BodyDescription(10.0f),
                    Name            = "Report Capsule",
                    Shapes          = { capsuleShapeDesc }
                };

                var contactReportActor = scene.CreateActor(actorDesc);

                scene.SetActorPairFlags(contactReportActor, groundActor, ContactPairFlag.All);

                scene.UserContactReport = new ContactReport(contactReportActor, groundActor);
            }

            // Trigger Reports
            {
                BoxShapeDescription boxShapeDesc = new BoxShapeDescription(15, 8, 15);
                boxShapeDesc.Flags |= (ShapeFlag.TriggerOnEnter | ShapeFlag.TriggerOnLeave);

                ActorDescription actorDesc = new ActorDescription()
                {
                    GlobalPose = Matrix.Translation(-30, 4, 0),
                    Shapes     = { boxShapeDesc }
                };
                scene.CreateActor(actorDesc);

                scene.UserTriggerReport = new TriggerReport();
            }

            scene.UserNotify = new Notify();
        }
Exemplo n.º 26
0
		public static void CreateContactReport(Scene scene, Actor groundActor)
		{
			// Contact report
			// When the capsule actor hits the ground make it bounce by using the conact report
			{
				CapsuleShapeDescription capsuleShapeDesc = new CapsuleShapeDescription(1, 5);

				ActorDescription actorDesc = new ActorDescription()
				{
					GlobalPose = Matrix.Translation(-30, 20, 0),
					BodyDescription = new BodyDescription(10.0f),
					Name = "Report Capsule",
					Shapes = { capsuleShapeDesc }
				};

				var contactReportActor = scene.CreateActor(actorDesc);

				scene.SetActorPairFlags(contactReportActor, groundActor, ContactPairFlag.All);

				scene.UserContactReport = new ContactReport(contactReportActor, groundActor);
			}

			// Trigger Reports
			{
				BoxShapeDescription boxShapeDesc = new BoxShapeDescription(15, 8, 15);
				boxShapeDesc.Flags |= (ShapeFlag.TriggerOnEnter | ShapeFlag.TriggerOnLeave);

				ActorDescription actorDesc = new ActorDescription()
				{
					GlobalPose = Matrix.Translation(-30, 4, 0),
					Shapes = { boxShapeDesc }
				};
				scene.CreateActor(actorDesc);

				scene.UserTriggerReport = new TriggerReport();
			}

			scene.UserNotify = new Notify();
		}
Exemplo n.º 27
0
        public static Actor CreateBox(Vector3 pos, Vector3 boxDim, float density)
        {
            var actorDesc = new ActorDescription();
            var bodyDesc  = new BodyDescription();

            var boxShapeDesc = new BoxShapeDescription
            {
                Dimensions = new Vector3(boxDim.X, boxDim.Y, boxDim.Z),
                //LocalPose = Matrix.CreateTranslation(0, boxDim.Y, 0)
            };

            actorDesc.Shapes.Add(boxShapeDesc);
            actorDesc.GlobalPose = Matrix.CreateTranslation(pos);

            if (density > 0)
            {
                actorDesc.BodyDescription = bodyDesc;
                actorDesc.Density         = density;
            }

            return(PhysX.Instance.Scene.CreateActor(actorDesc));
        }
Exemplo n.º 28
0
        public static RevoluteJoint RevoluteJoint(Scene scene)
        {
            BoxShapeDescription boxShapeDescA = new BoxShapeDescription(3, 3, 3);
            BoxShapeDescription boxShapeDescB = new BoxShapeDescription(3, 3, 3);

            ActorDescription actorDescA = new ActorDescription()
            {
                BodyDescription = new BodyDescription(10.0f),
                GlobalPose      = Matrix.Translation(75, 1.5f, -55),
                Shapes          = { boxShapeDescA }
            };
            Actor actorA = scene.CreateActor(actorDescA);

            ActorDescription actorDescB = new ActorDescription()
            {
                BodyDescription = new BodyDescription(10.0f),
                GlobalPose      = Matrix.Translation(70, 1.5f, -55),
                Shapes          = { boxShapeDescB }
            };
            Actor actorB = scene.CreateActor(actorDescB);

            //

            RevoluteJointDescription revoluteJointDesc = new RevoluteJointDescription()
            {
                Actor1 = actorA,
                Actor2 = actorB,
                Motor  = new MotorDescription(20, 20.1f, true)
            };

            revoluteJointDesc.Flags |= RevoluteJointFlag.MotorEnabled;
            revoluteJointDesc.SetGlobalAnchor(new Vector3(73.5f, 1.5f, -55));
            revoluteJointDesc.SetGlobalAxis(new Vector3(1, 0, 0));

            RevoluteJoint revoluteJoint = scene.CreateJoint(revoluteJointDesc) as RevoluteJoint;

            return(revoluteJoint);
        }
Exemplo n.º 29
0
        private Actor CreateActor(RigidBodyDescriptor descriptor, Scene scene)
        {
         
            var materialDesc = new MaterialDescription
            {
                DynamicFriction = 0.5f,
                StaticFriction = 0.5f,
                Restitution = 0.7f,
                FrictionCombineMode = CombineMode.Average,
                RestitutionCombineMode = CombineMode.Average
            };
            DefaultMaterial = scene.CreateMaterial(materialDesc);
            var boxDesc = new BoxShapeDescription
            {
                Material = DefaultMaterial,
                Dimensions = new Vector3(1, 1, 1)
            };
            ///////////////////////////////////////////////



            //resolve the motion type
            var rigidBodyDesc = descriptor.MotionType == MotionType.Static
                                    ? null
                                    : new BodyDescription();
            if (descriptor.MotionType == MotionType.Kinematic)
                rigidBodyDesc.BodyFlags = BodyFlag.Kinematic;

            HasDefaultShape = true;
            var actorDesc = new ActorDescription(boxDesc)
                                {
                                    BodyDescription = rigidBodyDesc,
                                    Density = 10.0f,
                                    GlobalPose = descriptor.Pose.ToPhysX(),
                                    UserData = descriptor.UserData
                                };
            return scene.CreateActor(actorDesc);
        }
Exemplo n.º 30
0
		public static RevoluteJoint RevoluteJoint(Scene scene)
		{
			BoxShapeDescription boxShapeDescA = new BoxShapeDescription(3, 3, 3);
			BoxShapeDescription boxShapeDescB = new BoxShapeDescription(3, 3, 3);

			ActorDescription actorDescA = new ActorDescription()
			{
				BodyDescription = new BodyDescription(10.0f),
				GlobalPose = Matrix.Translation(75, 1.5f, -55),
				Shapes = { boxShapeDescA }
			};
			Actor actorA = scene.CreateActor(actorDescA);

			ActorDescription actorDescB = new ActorDescription()
			{
				BodyDescription = new BodyDescription(10.0f),
				GlobalPose = Matrix.Translation(70, 1.5f, -55),
				Shapes = { boxShapeDescB }
			};
			Actor actorB = scene.CreateActor(actorDescB);

			//

			RevoluteJointDescription revoluteJointDesc = new RevoluteJointDescription()
			{
				Actor1 = actorA,
				Actor2 = actorB,
				Motor = new MotorDescription(20, 20.1f, true)
			};
			revoluteJointDesc.Flags |= RevoluteJointFlag.MotorEnabled;
			revoluteJointDesc.SetGlobalAnchor(new Vector3(73.5f, 1.5f, -55));
			revoluteJointDesc.SetGlobalAxis(new Vector3(1, 0, 0));

			RevoluteJoint revoluteJoint = scene.CreateJoint(revoluteJointDesc) as RevoluteJoint;

			return revoluteJoint;
		}
Exemplo n.º 31
0
        protected override void LoadContent(GraphicInfo GraphicInfo, GraphicFactory factory, IContentManager contentManager)
        {
            PhysxPhysicWorld PhysxPhysicWorld = World.PhysicWorld as PhysxPhysicWorld;

            base.LoadContent(GraphicInfo, factory, contentManager);

            {
                SimpleModel simpleModel = new SimpleModel(factory, "Model//cenario");

                PhysxTriangleMesh tmesh = new PhysxTriangleMesh(PhysxPhysicWorld, simpleModel,
                                                                Matrix.Identity, Vector3.One);

                DeferredNormalShader shader    = new DeferredNormalShader();
                DeferredMaterial     fmaterial = new DeferredMaterial(shader);
                IObject obj = new IObject(fmaterial, simpleModel, tmesh);
                this.World.AddObject(obj);
            }

            PhysxPhysicObject frame;
            {
                var         boxShapeDesc = new BoxShapeDescription(3, 10, 3);
                SimpleModel SimpleModel  = new PloobsEngine.Modelo.SimpleModel(factory, "Model/block");
                SimpleModel.SetTexture(factory.CreateTexture2DColor(1, 1, Color.Red), TextureType.DIFFUSE);

                frame = new PloobsEngine.Physics.PhysxPhysicObject(boxShapeDesc, Matrix.CreateTranslation(50, 5, 50), new Vector3(3, 10, 3));
                DeferredNormalShader shader    = new DeferredNormalShader();
                DeferredMaterial     fmaterial = new DeferredMaterial(shader);
                IObject obj = new IObject(fmaterial, SimpleModel, frame);
                this.World.AddObject(obj);
            }

            //Create an attached emitter
            FluidEmitterDescription emitterDesc = new FluidEmitterDescription();

            emitterDesc.MaximumParticles       = 0;
            emitterDesc.DimensionX             = 8f;
            emitterDesc.DimensionY             = 8f;
            emitterDesc.Type                   = EmitterType.ConstantFlowRate;
            emitterDesc.Rate                   = 150.0f;
            emitterDesc.FluidVelocityMagnitude = 60.0f;
            emitterDesc.ParticleLifetime       = 8.0f;
            emitterDesc.Shape                  = EmitterShape.Rectangular;

            //attach to actor
            emitterDesc.Flags = FluidEmitterFlag.AddBodyVelocity | FluidEmitterFlag.Enabled | FluidEmitterFlag.Visualization;
            emitterDesc.RepulsionCoefficient = 0.02f;

            //emitterDesc.RelativePose = Phyx.Matrix.RotationX((float)Math.PI / 2);
            emitterDesc.RelativePose *= Phyx.Matrix.Translation(0, 20f, 0);

            emitterDesc.FrameShape = frame.Actor.Shapes[0];

            FluidDescription fluidDesc = new FluidDescription();

            fluidDesc.MaximumParticles            = 2500;
            fluidDesc.KernelRadiusMultiplier      = 5.0f;
            fluidDesc.RestParticlesPerMeter       = 5.0f;
            fluidDesc.MotionLimitMultiplier       = 0.9f;
            fluidDesc.PacketSizeMultiplier        = 16;
            fluidDesc.CollisionDistanceMultiplier = 0.12f;
            fluidDesc.Stiffness   = 50.0f;
            fluidDesc.Viscosity   = 40.0f;
            fluidDesc.RestDensity = 1000.0f;
            fluidDesc.Damping     = 0.0f;
            fluidDesc.RestitutionForStaticShapes     = 0.2f;
            fluidDesc.DynamicFrictionForStaticShapes = 0.05f;
            fluidDesc.Flags            = FluidFlag.Enabled | FluidFlag.Visualization;
            fluidDesc.SimulationMethod = FluidSimulationMethod.SmoothedParticleHydrodynamics;

            fluidDesc.ParticleWriteData.AllocatePositionBuffer <Phyx.Vector3>(fluidDesc.MaximumParticles);
            fluidDesc.ParticleWriteData.NumberOfParticles = fluidDesc.MaximumParticles;

            FluidMOdel       FluidMOdel       = new PloobsEngine.Modelo.FluidMOdel(factory, "teste", null, fluidDesc.MaximumParticles);
            PhysxFluidObject PhysxFluidObject = new PloobsEngine.Physics.PhysxFluidObject(fluidDesc);
            FluidShader      FluidShader      = new FluidShader();
            DeferredMaterial ForwardMaterial  = new DeferredMaterial(FluidShader);
            IObject          IObject          = new IObject(ForwardMaterial, FluidMOdel, PhysxFluidObject);

            this.World.AddObject(IObject);

            PhysxFluidObject.Fluid.CreateFluidEmitter(emitterDesc);

            #region NormalLight
            DirectionalLightPE ld1 = new DirectionalLightPE(Vector3.Left, Color.White);
            DirectionalLightPE ld2 = new DirectionalLightPE(Vector3.Right, Color.White);
            DirectionalLightPE ld3 = new DirectionalLightPE(Vector3.Backward, Color.White);
            DirectionalLightPE ld4 = new DirectionalLightPE(Vector3.Forward, Color.White);
            DirectionalLightPE ld5 = new DirectionalLightPE(Vector3.Down, Color.White);
            float li = 0.5f;
            ld1.LightIntensity = li;
            ld2.LightIntensity = li;
            ld3.LightIntensity = li;
            ld4.LightIntensity = li;
            ld5.LightIntensity = li;
            this.World.AddLight(ld1);
            this.World.AddLight(ld2);
            this.World.AddLight(ld3);
            this.World.AddLight(ld4);
            this.World.AddLight(ld5);
            #endregion


            BallThrowPhysx28 BallThrowBullet = new BallThrowPhysx28(this.World, GraphicFactory, false);
            this.AttachCleanUpAble(BallThrowBullet);

            this.World.CameraManager.AddCamera(new CameraFirstPerson(GraphicInfo));
        }
Exemplo n.º 32
0
        public static NonCar GenerateNonCar(CActor actor, List <NoncarFile> nonCars)
        {
            if (actor.Model == null)
            {
                return(null);
            }
            if (actor.Name.StartsWith("&"))
            {
                int        index      = int.Parse(actor.Name.Substring(1, 2));
                NoncarFile nonCarFile = nonCars.Find(a => a.IndexNumber == index);

                if (nonCarFile == null)
                {
                    Debug.WriteLine("No noncar matching " + actor.Name);
                    return(null);
                }

                ActorDescription actorDesc = new ActorDescription();
                actorDesc.BodyDescription = new BodyDescription()
                {
                    Mass = nonCarFile.Mass
                };

                BoxShapeDescription boxDesc = new BoxShapeDescription();
                boxDesc.Size          = nonCarFile.BoundingBox.GetSize();
                boxDesc.LocalPosition = nonCarFile.BoundingBox.GetCenter();
                actorDesc.Shapes.Add(boxDesc);

                foreach (Vector3 extraPoint in nonCarFile.ExtraBoundingBoxPoints)
                {
                    SphereShapeDescription extra = new SphereShapeDescription(0.2f);
                    extra.LocalPosition = extraPoint;
                    extra.Mass          = 0;
                    actorDesc.Shapes.Add(extra);
                }

                Vector3    scaleout, transout;
                Quaternion b;
                bool       success = actor.Matrix.Decompose(out scaleout, out b, out transout);
                //if (!success) throw new Exception();

                Matrix m =
                    Matrix.CreateFromQuaternion(b) *
                    Matrix.CreateTranslation(transout);

                StillDesign.PhysX.Actor instance = PhysX.Instance.Scene.CreateActor(actorDesc);
                instance.GlobalPose = m;
                instance.SetCenterOfMassOffsetLocalPosition(nonCarFile.CenterOfMass);
                instance.Group = PhysXConsts.NonCarId;

                //foreach (Shape s in instance.Shapes)
                //    s.SetFlag(ShapeFlag.Visualization, false);

                NonCar noncar = new NonCar {
                    Config = nonCarFile, CActor = actor
                };
                instance.UserData = noncar;
                actor.AttachToPhysX(instance);

                if (nonCarFile.BendAngleBeforeSnapping > 0)
                {
                    noncar.AttachToGround();
                }
                instance.Sleep();
                return(noncar);
            }
            else
            {
                return(null);
            }
        }
        protected override void LoadContent(GraphicInfo GraphicInfo, GraphicFactory factory, IContentManager contentManager)
        {
            PhysxPhysicWorld PhysxPhysicWorld = World.PhysicWorld as PhysxPhysicWorld;
            base.LoadContent(GraphicInfo, factory, contentManager);

            {
                SimpleModel simpleModel = new SimpleModel(factory, "Model//cenario");

                PhysxTriangleMesh tmesh = new PhysxTriangleMesh(PhysxPhysicWorld, simpleModel,
                    Matrix.Identity, Vector3.One);

                DeferredNormalShader shader = new DeferredNormalShader();
                DeferredMaterial fmaterial = new DeferredMaterial(shader);
                IObject obj = new IObject(fmaterial, simpleModel, tmesh);
                this.World.AddObject(obj);
            }

            PhysxPhysicObject frame;
            {
                var boxShapeDesc = new BoxShapeDescription(3, 10, 3);
                SimpleModel SimpleModel = new PloobsEngine.Modelo.SimpleModel(factory, "Model/block");
                SimpleModel.SetTexture(factory.CreateTexture2DColor(1, 1, Color.Red), TextureType.DIFFUSE);

                frame = new PloobsEngine.Physics.PhysxPhysicObject(boxShapeDesc, Matrix.CreateTranslation(50, 5, 50), new Vector3(3, 10, 3));
                DeferredNormalShader shader = new DeferredNormalShader();
                DeferredMaterial fmaterial = new DeferredMaterial(shader);
                IObject obj = new IObject(fmaterial, SimpleModel, frame);
                this.World.AddObject(obj);
            }

            //Create an attached emitter
            FluidEmitterDescription emitterDesc = new FluidEmitterDescription();
            emitterDesc.MaximumParticles = 0;
            emitterDesc.DimensionX = 8f;
            emitterDesc.DimensionY = 8f;
            emitterDesc.Type = EmitterType.ConstantFlowRate;
            emitterDesc.Rate = 150.0f;
            emitterDesc.FluidVelocityMagnitude = 60.0f;
            emitterDesc.ParticleLifetime = 8.0f;
            emitterDesc.Shape = EmitterShape.Rectangular;

            //attach to actor
            emitterDesc.Flags = FluidEmitterFlag.AddBodyVelocity | FluidEmitterFlag.Enabled | FluidEmitterFlag.Visualization;
            emitterDesc.RepulsionCoefficient = 0.02f;

            //emitterDesc.RelativePose = Phyx.Matrix.RotationX((float)Math.PI / 2);
            emitterDesc.RelativePose *= Phyx.Matrix.Translation(0, 20f, 0);

            emitterDesc.FrameShape = frame.Actor.Shapes[0];

            FluidDescription fluidDesc = new FluidDescription();
            fluidDesc.MaximumParticles = 2500;
            fluidDesc.KernelRadiusMultiplier = 5.0f;
            fluidDesc.RestParticlesPerMeter = 5.0f;
            fluidDesc.MotionLimitMultiplier = 0.9f;
            fluidDesc.PacketSizeMultiplier = 16;
            fluidDesc.CollisionDistanceMultiplier = 0.12f;
            fluidDesc.Stiffness = 50.0f;
            fluidDesc.Viscosity = 40.0f;
            fluidDesc.RestDensity = 1000.0f;
            fluidDesc.Damping = 0.0f;
            fluidDesc.RestitutionForStaticShapes = 0.2f;
            fluidDesc.DynamicFrictionForStaticShapes = 0.05f;
            fluidDesc.Flags = FluidFlag.Enabled | FluidFlag.Visualization;
            fluidDesc.SimulationMethod = FluidSimulationMethod.SmoothedParticleHydrodynamics;

            fluidDesc.ParticleWriteData.AllocatePositionBuffer<Phyx.Vector3>(fluidDesc.MaximumParticles);
            fluidDesc.ParticleWriteData.NumberOfParticles = fluidDesc.MaximumParticles;

            FluidMOdel FluidMOdel = new PloobsEngine.Modelo.FluidMOdel(factory, "teste", null, fluidDesc.MaximumParticles);
            PhysxFluidObject PhysxFluidObject = new PloobsEngine.Physics.PhysxFluidObject(fluidDesc);
            FluidShader FluidShader = new FluidShader();
            DeferredMaterial ForwardMaterial = new DeferredMaterial(FluidShader);
            IObject IObject = new IObject(ForwardMaterial, FluidMOdel, PhysxFluidObject);
            this.World.AddObject(IObject);

            PhysxFluidObject.Fluid.CreateFluidEmitter(emitterDesc);

            #region NormalLight
            DirectionalLightPE ld1 = new DirectionalLightPE(Vector3.Left, Color.White);
            DirectionalLightPE ld2 = new DirectionalLightPE(Vector3.Right, Color.White);
            DirectionalLightPE ld3 = new DirectionalLightPE(Vector3.Backward, Color.White);
            DirectionalLightPE ld4 = new DirectionalLightPE(Vector3.Forward, Color.White);
            DirectionalLightPE ld5 = new DirectionalLightPE(Vector3.Down, Color.White);
            float li = 0.5f;
            ld1.LightIntensity = li;
            ld2.LightIntensity = li;
            ld3.LightIntensity = li;
            ld4.LightIntensity = li;
            ld5.LightIntensity = li;
            this.World.AddLight(ld1);
            this.World.AddLight(ld2);
            this.World.AddLight(ld3);
            this.World.AddLight(ld4);
            this.World.AddLight(ld5);
            #endregion


            BallThrowPhysx28 BallThrowBullet = new BallThrowPhysx28(this.World, GraphicFactory, false);
            this.AttachCleanUpAble(BallThrowBullet);

            this.World.CameraManager.AddCamera(new CameraFirstPerson(GraphicInfo));
        }
Exemplo n.º 34
0
		public void LoadPhysics()
		{
			Core _core = this.Core;
			Scene _scene = this.Scene;

			#region Some Boxes
			for( int x = 0; x < 5; x++ )
			{
				BoxShapeDescription boxShapeDesc = new BoxShapeDescription( 2, 3, 8 );
				
				ActorDescription actorDesc = new ActorDescription()
				{
					Name = String.Format( "Box {0}", x ),
					BodyDescription = new BodyDescription( 10.0f ),
					GlobalPose = Matrix.Translation( 100, 15 + 3 * x, 20 ),
					Shapes = { boxShapeDesc }
				};

				Actor actor = _scene.CreateActor( actorDesc );
			}
			#endregion

			//#region Cloth (Flag)
			//{
			//    // Create a Grid of Points
			//    VertexGrid grid = VertexGrid.CreateGrid( 10, 10 );

			//    ClothMeshDescription clothMeshDesc = new ClothMeshDescription();
			//        clothMeshDesc.AllocateVertices<Vector3>( grid.Points.Length );
			//        clothMeshDesc.AllocateTriangles<int>( grid.Indices.Length / 3 );

			//        clothMeshDesc.VertexCount = grid.Points.Length;
			//        clothMeshDesc.TriangleCount = grid.Indices.Length / 3;

			//        clothMeshDesc.VerticesStream.SetData( grid.Points );
			//        clothMeshDesc.TriangleStream.SetData( grid.Indices );

			//        // We are using 32 bit integers, so make sure the 16 bit flag is removed.
			//        // 32 bits are the default, so this isn't technically needed
			//        clothMeshDesc.Flags &= ~MeshFlag.Indices16Bit;

			//    // Write the cooked data to memory
			//    MemoryStream memoryStream = new MemoryStream();

			//    Cooking.InitializeCooking();
			//    Cooking.CookClothMesh( clothMeshDesc, memoryStream );
			//    Cooking.CloseCooking();

			//    // Need to reset the position of the stream to the beginning
			//    memoryStream.Position = 0;

			//    ClothMesh clothMesh = _core.CreateClothMesh( memoryStream );

			//    //

			//    ClothDescription clothDesc = new ClothDescription()
			//    {
			//        ClothMesh = clothMesh,
			//        Flags = ClothFlag.Gravity | ClothFlag.Bending | ClothFlag.CollisionTwoway | ClothFlag.Visualization,
			//        GlobalPose =
			//            Matrix.CreateFromYawPitchRoll( 0, (float)Math.PI / 2.0f, (float)Math.PI / 2.0f ) *
			//            Matrix.CreateTranslation( 0, 20, 0 )
			//    };
			//    clothDesc.MeshData.AllocatePositions<Vector3>( grid.Points.Length );
			//    clothDesc.MeshData.AllocateIndices<int>( grid.Indices.Length );

			//    clothDesc.MeshData.MaximumVertices = grid.Points.Length;
			//    clothDesc.MeshData.MaximumIndices = grid.Indices.Length;

			//    clothDesc.MeshData.NumberOfVertices = grid.Points.Length;
			//    clothDesc.MeshData.NumberOfIndices = grid.Indices.Length;

			//    _flag = _scene.CreateCloth( clothDesc );

			//    // Flag Pole
			//    ActorDescription flagPoleActorDesc = new ActorDescription()
			//    {
			//        GlobalPose = Matrix.CreateTranslation( 0, 10, 0 ),
			//        Shapes = { new BoxShapeDescription( 1.0f, 20.0f, 1.0f ) }
			//    };

			//    Actor flagPoleActor = _scene.CreateActor( flagPoleActorDesc );

			//    _flag.AttachToShape( flagPoleActor.Shapes[ 0 ], 0 );
			//    _flag.WindAcceleration = new Vector3( 10, 10, 10 );
			//    _flag.BendingStiffness = 0.1f;
			//}
			//#endregion
			
			#region Revolute Joint
			{
				BoxShapeDescription boxShapeDescA = new BoxShapeDescription( 3, 3, 3 );
				BoxShapeDescription boxShapeDescB = new BoxShapeDescription( 3, 3, 3 );

				ActorDescription actorDescA = new ActorDescription()
				{
					BodyDescription = new BodyDescription( 10.0f ),
					GlobalPose = Matrix.Translation( 75, 1.5f, 55 ),
					Shapes = { boxShapeDescA }
				};
				Actor actorA = _scene.CreateActor( actorDescA );

				ActorDescription actorDescB = new ActorDescription()
				{
					BodyDescription = new BodyDescription( 10.0f ),
					GlobalPose = Matrix.Translation( 70, 1.5f, 55 ),
					Shapes = { boxShapeDescB }
				};
				Actor actorB = _scene.CreateActor( actorDescB );

				//

				RevoluteJointDescription revoluteJointDesc = new RevoluteJointDescription()
				{
					Actor1 = actorA,
					Actor2 = actorB,
					Motor = new MotorDescription( 20, 20.1f, true )
				};
				revoluteJointDesc.Flags |= RevoluteJointFlag.MotorEnabled;
				revoluteJointDesc.SetGlobalAnchor( new Vector3( 73.5f, 1.5f, 55 ) );
				revoluteJointDesc.SetGlobalAxis( new Vector3( 1, 0, 0 ) );

				RevoluteJoint revoluteJoint = _scene.CreateJoint( revoluteJointDesc ) as RevoluteJoint;
			}
			#endregion

			#region Prismatic Joint with Limit
			{
				Actor actorA, actorB;
				{
					BoxShapeDescription boxShapeDesc = new BoxShapeDescription( 3, 3, 3 );

					BodyDescription bodyDesc = new BodyDescription( 10.0f );
						bodyDesc.BodyFlags |= BodyFlag.Kinematic;

					ActorDescription actorDesc = new ActorDescription()
					{
						BodyDescription = bodyDesc,
						GlobalPose = Matrix.Translation( 70, 25, 65 ),
						Shapes = { boxShapeDesc }
					};
					actorA = _scene.CreateActor( actorDesc );
				}
				{
					BoxShapeDescription boxShapeDesc = new BoxShapeDescription( 3, 3, 3 );

					ActorDescription actorDesc = new ActorDescription()
					{
						BodyDescription = new BodyDescription( 10.0f ),
						GlobalPose = Matrix.Translation( 70, 15, 65 ),
						Shapes = { boxShapeDesc }
					};
					actorB = _scene.CreateActor( actorDesc );
				}

				PrismaticJointDescription prismaticJointDesc = new PrismaticJointDescription()
				{
					Actor1 = actorA,
					Actor2 = actorB,
				};
				prismaticJointDesc.SetGlobalAnchor( new Vector3( 70, 20, 65 ) );
				prismaticJointDesc.SetGlobalAxis( new Vector3( 0, 1, 0 ) );

				PrismaticJoint prismaticJoint = _scene.CreateJoint( prismaticJointDesc ) as PrismaticJoint;

				LimitPlane limitPlane = new LimitPlane( new Vector3( 0, 1, 0 ), new Vector3( -30, 8, -30 ), 0 );
					prismaticJoint.AddLimitPlane( limitPlane );
			}
			#endregion
			
			#region Fluid
			{
				const int maximumParticles = 1000;

				FluidEmitterDescription fluidEmitterDesc = new FluidEmitterDescription()
				{
					DimensionX = 0.5f,
					DimensionY = 0.5f,
					Rate = 15,
					RelativePose = Matrix.Translation( -40, 10, 50 ),
					Shape = EmitterShape.Rectangular,
					Type = EmitterType.ConstantFlowRate,
					RandomAngle = 0.5f
				};
				fluidEmitterDesc.Flags |= ( FluidEmitterFlag.Enabled | FluidEmitterFlag.Visualization );

				FluidDescription fluidDesc = new FluidDescription()
				{
					Emitters = { fluidEmitterDesc },
					Flags = FluidFlag.Enabled | FluidFlag.Visualization,
					MaximumParticles = maximumParticles
				};
				fluidDesc.ParticleWriteData.AllocatePositionBuffer<Vector3>( maximumParticles );
				fluidDesc.ParticleWriteData.NumberOfParticles = maximumParticles;

				Fluid fluid = _scene.CreateFluid( fluidDesc );

				// Ledge
				{
					BoxShapeDescription boxShapeDesc = new BoxShapeDescription( 5, 0.1f, 5 );
					
					ActorDescription drainActorDesc = new ActorDescription()
					{
						GlobalPose = Matrix.RotationX( 0.5f ) * Matrix.Translation( -40, 5, 52 ),
						Shapes =  { boxShapeDesc }
					};

					Actor drianActor = _scene.CreateActor( drainActorDesc );
				}

				// Drain
				{
					BoxShapeDescription boxShapeDesc = new BoxShapeDescription( 5, 0.1f, 5 );
						boxShapeDesc.Flags |= ShapeFlag.FluidDrain;

					ActorDescription drainActorDesc = new ActorDescription()
					{
						GlobalPose = Matrix.Translation( -40, 0, 55 ),
						Shapes = { boxShapeDesc }
					};

					Actor drianActor = _scene.CreateActor( drainActorDesc );
				}
			}
			#endregion
			
			#region Force Field
			{
				BoxForceFieldShapeDescription boxForceFieldShapeDesc = new BoxForceFieldShapeDescription()
				{
					Size = new Vector3( 10, 10, 10 )
				};

				ForceFieldLinearKernelDescription kernelDesc = new ForceFieldLinearKernelDescription()
				{
					Constant = new Vector3( 0, 100.0f, 0 )
				};

				ForceFieldLinearKernel kernel = _scene.CreateForceFieldLinearKernel( kernelDesc );

				ForceFieldShapeGroupDescription shapeGroupDesc = new ForceFieldShapeGroupDescription()
				{
					Shapes = { boxForceFieldShapeDesc }
				};

				ForceFieldShapeGroup shapeGroup = _scene.CreateForceFieldShapeGroup( shapeGroupDesc );

				BoxForceFieldShape boxForceFieldShape = shapeGroup.CreateShape( boxForceFieldShapeDesc ) as BoxForceFieldShape;
				boxForceFieldShape.Pose = Matrix.Translation( 30, 5, 0 );

				ForceFieldDescription forceFieldDesc = new ForceFieldDescription()
				{
					Kernel = kernel,
					ShapeGroups = { shapeGroup }
				};
				ForceField forceField = _scene.CreateForceField( forceFieldDesc );
			}
			#endregion
			
			#region Heightfield
			{
				int rows = 25;
				int columns = 25;

				HeightFieldSample[] samples = new HeightFieldSample[ rows * columns ];
				for( int r = 0; r < rows; r++ )
				{
					for( int c = 0; c < columns; c++ )
					{
						// Put a z and x curve together
						double h = Math.Sin( c ) * Math.Cos( r ) * short.MaxValue;

						HeightFieldSample sample = new HeightFieldSample()
						{
							Height = (short)h,
							MaterialIndex0 = 0,
							MaterialIndex1 = 1,
							TessellationFlag = 0
						};

						samples[ r * columns + c ] = sample;
					}
				}

				HeightFieldDescription heightFieldDesc = new HeightFieldDescription()
				{
					NumberOfRows = rows,
					NumberOfColumns = columns
				};
				heightFieldDesc.SetSamples( samples );

				HeightField heightField = _core.CreateHeightField( heightFieldDesc );
				
				//

				HeightFieldShapeDescription heightFieldShapeDesc = new HeightFieldShapeDescription()
				{
					HeightField = heightField,
					HoleMaterial = 2,
					// The max height of our samples is short.MaxValue and we want it to be 1
					HeightScale = 1.0f / (float)short.MaxValue,
					RowScale = 3,
					ColumnScale = 3
				};
				heightFieldShapeDesc.LocalPosition = new Vector3( -0.5f * rows * 1 * heightFieldShapeDesc.RowScale, 0, -0.5f * columns * 1 * heightFieldShapeDesc.ColumnScale );

				ActorDescription actorDesc = new ActorDescription()
				{
					GlobalPose = Matrix.Translation( 100, 0, 0 ),
					Shapes = { heightFieldShapeDesc }
				};
				Actor actor = _scene.CreateActor( actorDesc );
			}
			#endregion
			
			//#region Convex Mesh
			//{
			//    ModelMesh mesh = _torusModel.Meshes.First();

			//    Matrix[] transforms = new Matrix[ _torusModel.Bones.Count ];
			//    _torusModel.CopyAbsoluteBoneTransformsTo( transforms );

			//    // Gets the vertices from the mesh
			//    VertexPositionNormalTexture[] vertices = new VertexPositionNormalTexture[ mesh.MeshParts[ 0 ].NumVertices ];
			//    mesh.VertexBuffer.GetData<VertexPositionNormalTexture>( vertices );

			//    //

			//    // Allocate memory for the points and triangles
			//    var convexMeshDesc = new ConvexMeshDescription()
			//    {
			//        PointCount = vertices.Length
			//    };
			//    convexMeshDesc.Flags |= ConvexFlag.ComputeConvex;
			//    convexMeshDesc.AllocatePoints<Vector3>( vertices.Length );

			//    // Write in the points and triangles
			//    // We only want the Position component of the vertex. Also scale down the mesh
			//    foreach( VertexPositionNormalTexture vertex in vertices )
			//    {
			//        Vector3 position = Vector3.Transform( vertex.Position, Matrix.CreateScale( 0.1f, 0.1f, 0.1f ) * transforms[ 0 ] );

			//        convexMeshDesc.PointsStream.Write( position );
			//    }

			//    //

			//    // Cook to memory or to a file
			//    MemoryStream stream = new MemoryStream();
			//    //FileStream stream = new FileStream( @"Convex Mesh.cooked", FileMode.CreateNew );

			//    Cooking.InitializeCooking( new ConsoleOutputStream() );
			//    Cooking.CookConvexMesh( convexMeshDesc, stream );
			//    Cooking.CloseCooking();

			//    stream.Position = 0;

			//    ConvexMesh convexMesh = _core.CreateConvexMesh( stream );

			//    ConvexShapeDescription convexShapeDesc = new ConvexShapeDescription( convexMesh );

			//    ActorDescription actorDesc = new ActorDescription()
			//    {
			//        BodyDescription = new BodyDescription( 10.0f ),
			//        GlobalPose = Matrix.CreateTranslation( 30, 30, 0 )
			//    };
			//    actorDesc.Shapes.Add( convexShapeDesc );

			//    _torusActor = _scene.CreateActor( actorDesc );
			//}
			//#endregion
			
			//#region SoftBody
			//if( false ) // Enable to view soft bodies, they run slowly
			//{
			//    XmlDocument doc = new XmlDocument();
			//        doc.Load( "Teapot.xml" );
				
			//    // Not how NxuStream are meant to used but what ever :S
			//    Vector3[] vertices = ReadVertices( doc.SelectSingleNode( "/NXUSTREAM2/NxuPhysicsCollection/NxSoftBodyMeshDesc/vertices" ) );
			//    int[] tetrahedraSingles = ReadTetrahedra( doc.SelectSingleNode( "/NXUSTREAM2/NxuPhysicsCollection/NxSoftBodyMeshDesc/tetrahedra" ) );

			//    var softBodyMeshDesc = new SoftBodyMeshDescription()
			//    {
			//        VertexCount = vertices.Length,
			//        TetrahedraCount = tetrahedraSingles.Length / 4 // Tetrahedras come in quadruples of ints
			//    };

			//    softBodyMeshDesc.AllocateVertices<Vector3>( softBodyMeshDesc.VertexCount );
			//    softBodyMeshDesc.AllocateTetrahedra<int>( softBodyMeshDesc.TetrahedraCount ); // Note: T is an int. T is the type of each point

			//    softBodyMeshDesc.VertexStream.SetData( vertices );
			//    softBodyMeshDesc.TetrahedraStream.SetData( tetrahedraSingles );

			//    MemoryStream memoryStream = new MemoryStream();

			//    Cooking.InitializeCooking();
			//    Cooking.CookSoftBodyMesh( softBodyMeshDesc, memoryStream );
			//    Cooking.CloseCooking();

			//    memoryStream.Position = 0;

			//    SoftBodyMesh softBodyMesh = _core.CreateSoftBodyMesh( memoryStream );

			//    SoftBodyDescription desc = new SoftBodyDescription()
			//    {
			//        GlobalPose = Matrix.CreateTranslation( -30, 20, -30 ),
			//        SoftBodyMesh = softBodyMesh
			//    };
			//    desc.Flags |= SoftBodyFlag.Visualization;

			//    desc.MeshData.AllocatePositions<Vector3>( vertices.Length );
			//    desc.MeshData.AllocateIndices<int>( tetrahedraSingles.Length );

			//    SoftBody softBody = _scene.CreateSoftBody( desc );
			//}
			//#endregion

			//#region Reports
			//// Contact report
			//// When the capsule actor hits the ground make it bounce by using the conact report
			//{
			//    CapsuleShapeDescription capsuleShapeDesc = new CapsuleShapeDescription( 1, 5 );
				
			//    ActorDescription actorDesc = new ActorDescription()
			//    {
			//        GlobalPose = Matrix.CreateTranslation( -30, 20, 0 ),
			//        BodyDescription = new BodyDescription( 10.0f ),
			//        Name = "Report Capsule",
			//        Shapes = { capsuleShapeDesc }
			//    };

			//    _contactReportActor = _scene.CreateActor( actorDesc );

			//    _scene.SetActorPairFlags( _contactReportActor, _groundActor, ContactPairFlag.All );

			//    _scene.UserContactReport = new ContactReport( this );
			//}

			//// Trigger Reports
			//{
			//    BoxShapeDescription boxShapeDesc = new BoxShapeDescription( 15, 8, 15 );
			//        boxShapeDesc.Flags |= ( ShapeFlag.TriggerOnEnter | ShapeFlag.TriggerOnLeave );

			//    ActorDescription actorDesc = new ActorDescription()
			//    {
			//        GlobalPose = Matrix.CreateTranslation( -30, 4, 0 ),
			//        Shapes = { boxShapeDesc }
			//    };
			//    _scene.CreateActor( actorDesc );

			//    _scene.UserTriggerReport = new TriggerReport( this );
			//}

			//_scene.UserNotify = new Notify( this );
			//#endregion

			//#region Wheel
			//{
			//    _basicVehicle = new Vehicle( this );
			//}
			//#endregion

			#region Controller
			{
				ControllerManager manager = _scene.CreateControllerManager();

				CapsuleControllerDescription capsuleControllerDesc = new CapsuleControllerDescription( 4, 3 );

				CapsuleController capsuleController = manager.CreateController<CapsuleController>( capsuleControllerDesc );
					capsuleController.Position = new Vector3( 0, 1.5f + 2, -15 );
					capsuleController.Actor.Name = "BoxController";
					capsuleController.SetCollisionEnabled( true );
			}
			#endregion
		}
Exemplo n.º 35
0
        public static void TestPhysicsError()
        {
            Game game1 = new Game();

            game1.Run();

            /*XNAGame game = new XNAGame();
             * bool flag = false;
             * game.UpdateEvent += delegate
             * {
             *  if ( flag ) game.Exit();
             *  flag = true;
             * };
             *
             * game.Run();*/

            using (PhysicsEngine engine = new PhysicsEngine())
            {
                StillDesign.PhysX.Scene scene;
                CapsuleController       controller = null;

                ControllerManager manager;

                /*
                 * game.InitializeEvent +=
                 *  delegate
                 *  {*/

                engine.Initialize(null);
                scene = engine.Scene;


                manager = scene.CreateControllerManager();


                CapsuleControllerDescription capsuleControllerDesc = new CapsuleControllerDescription(0.5f, 1);

                CapsuleController capsuleController = manager.CreateController <CapsuleController>(capsuleControllerDesc);

                controller = capsuleController;

                ActorDescription actorDesc;
                Actor            actor;

                BoxShapeDescription boxShapeDesc = new BoxShapeDescription(1, 1, 1);

                actorDesc = new ActorDescription(boxShapeDesc);
                actorDesc.BodyDescription = new BodyDescription(1f);

                actor = engine.Scene.CreateActor(actorDesc);
                actor.GlobalPosition = new Vector3(1, 4, 0);

                controller.Move(Vector3.Up);
                engine.Update(null);
                controller.Move(Vector3.Up);


                /*    };
                 *
                 * game.UpdateEvent += delegate { if (flag) game.Exit();
                 *                               flag = true; };
                 *
                 * game.Run();*/
            }
        }
Exemplo n.º 36
0
        public static NonCar GenerateNonCar(CActor actor, List<NoncarFile> nonCars)
        {
            if (actor.Model == null) return null;
            if (actor.Name.StartsWith("&"))
            {
                int index = int.Parse(actor.Name.Substring(1, 2));
                NoncarFile nonCarFile = nonCars.Find(a => a.IndexNumber == index);

                if (nonCarFile == null)
                {
                    Debug.WriteLine("No noncar matching " + actor.Name);
                    return null;
                }

                ActorDescription actorDesc = new ActorDescription();
                actorDesc.BodyDescription = new BodyDescription() { Mass = nonCarFile.Mass };

                BoxShapeDescription boxDesc = new BoxShapeDescription();
                boxDesc.Size = nonCarFile.BoundingBox.GetSize();
                boxDesc.LocalPosition = nonCarFile.BoundingBox.GetCenter();
                actorDesc.Shapes.Add(boxDesc);

                foreach (Vector3 extraPoint in nonCarFile.ExtraBoundingBoxPoints)
                {
                    SphereShapeDescription extra = new SphereShapeDescription(0.2f);
                    extra.LocalPosition = extraPoint;
                    extra.Mass = 0;
                    actorDesc.Shapes.Add(extra);
                }

                Vector3 scaleout, transout;
                Quaternion b;
                bool success = actor.Matrix.Decompose(out scaleout, out b, out transout);
                //if (!success) throw new Exception();

                Matrix m =
                    Matrix.CreateFromQuaternion(b) *
                    Matrix.CreateTranslation(transout);

                StillDesign.PhysX.Actor instance = PhysX.Instance.Scene.CreateActor(actorDesc);
                instance.GlobalPose = m;
                instance.SetCenterOfMassOffsetLocalPosition(nonCarFile.CenterOfMass);
                instance.Group = PhysXConsts.NonCarId;

                //foreach (Shape s in instance.Shapes)
                //    s.SetFlag(ShapeFlag.Visualization, false);

                NonCar noncar = new NonCar { Config = nonCarFile, CActor = actor };
                instance.UserData = noncar;
                actor.AttachToPhysX(instance);

                if (nonCarFile.BendAngleBeforeSnapping > 0)
                {
                    noncar.AttachToGround();
                }
                instance.Sleep();
                return noncar;

            }
            else
            {
                return null;
            }
        }
        protected override void LoadContent(GraphicInfo GraphicInfo, GraphicFactory factory ,IContentManager contentManager)
        {
            PhysxPhysicWorld PhysxPhysicWorld = World.PhysicWorld as PhysxPhysicWorld;            
            base.LoadContent(GraphicInfo, factory, contentManager);

            // Create a simple fluid description with fluids and visualization enabled
            FluidDescription fluidDesc = new FluidDescription()
            {
                Flags = FluidFlag.Enabled | FluidFlag.Visualization,
            };

            // Store our particle positions somewhere (as our particle generation function below generates and unknown number of particles at runtime we need a list instead of an array)
            var particlePositions = new List<Phyx.Vector3>();

            // Move all the particles by this offset
            Phyx.Vector3 position = new Phyx.Vector3(0, 20, 0);

            // Number of particles in the x, y and z directions
            int sideNum = 10;
            float distance = 1f;

            float radius = sideNum * distance * 0.5f;

            for (int i = 0; i < sideNum; i++)
            {
                for (int j = 0; j < sideNum; j++)
                {
                    for (int k = 0; k < sideNum; k++)
                    {
                        Phyx.Vector3 p = new Phyx.Vector3(i * distance, j * distance, k * distance);

                        if ((p - new Phyx.Vector3(radius, radius, radius)).Length() < radius)
                        {
                            p += position - new Phyx.Vector3(radius, radius, radius);

                            particlePositions.Add(p);
                        }
                    }
                }
            }

            // Allocate memory for the initial particle positions to be stored in
            // And then set the position buffer
            fluidDesc.InitialParticleData.AllocatePositionBuffer<Phyx.Vector3>(particlePositions.Count);
            fluidDesc.InitialParticleData.NumberOfParticles = particlePositions.Count;
            fluidDesc.InitialParticleData.PositionBuffer.SetData(particlePositions.ToArray());

            // Allocate memory for PhysX to store the position of each particle
            fluidDesc.ParticleWriteData.AllocatePositionBuffer<Phyx.Vector3>(particlePositions.Count);
            fluidDesc.ParticleWriteData.NumberOfParticles = particlePositions.Count;

            InstancedBilboardModel InstancedBilboardModel = new InstancedBilboardModel(factory, "teste", "Textures/Smoke", new BilboardInstance[] { new BilboardInstance() }, particlePositions.Count);
            PhysxFluidObject PhysxFluidObject = new PloobsEngine.Physics.PhysxFluidObject(fluidDesc);
            DeferredInstancedBilboardShader DeferredInstancedBilboardShader = new PloobsEngine.Material.DeferredInstancedBilboardShader(BilboardType.Spherical);
            DeferredInstancedBilboardShader.AlphaTestLimit = 0.2f;
            FluidMaterial DeferredMaterial = new FluidMaterial(DeferredInstancedBilboardShader, particlePositions.Count, new Vector2(0.2f));
            IObject IObject = new IObject(DeferredMaterial, InstancedBilboardModel, PhysxFluidObject);
            this.World.AddObject(IObject);


            // Ledge
            {
                var boxShapeDesc = new BoxShapeDescription(10, 0.2f, 10);
                SimpleModel SimpleModel = new PloobsEngine.Modelo.SimpleModel(factory, "Model/block");
                SimpleModel.SetTexture(factory.CreateTexture2DColor(1, 1, Color.Red), TextureType.DIFFUSE);

                PhysxPhysicObject PhysxPhysicObject = new PloobsEngine.Physics.PhysxPhysicObject(boxShapeDesc,
                    (Phyx.Matrix.RotationZ(0.3f) *
                        Phyx.Matrix.Translation(0, 5, 0)).AsXNA(), new Vector3(10, 0.2f, 10));
                DeferredNormalShader shader = new DeferredNormalShader();
                DeferredMaterial fmaterial = new DeferredMaterial(shader);
                IObject obj = new IObject(fmaterial, SimpleModel, PhysxPhysicObject);
                this.World.AddObject(obj);                        
            }

            #region NormalLight
            DirectionalLightPE ld1 = new DirectionalLightPE(Vector3.Left, Color.White);
            DirectionalLightPE ld2 = new DirectionalLightPE(Vector3.Right, Color.White);
            DirectionalLightPE ld3 = new DirectionalLightPE(Vector3.Backward, Color.White);
            DirectionalLightPE ld4 = new DirectionalLightPE(Vector3.Forward, Color.White);
            DirectionalLightPE ld5 = new DirectionalLightPE(Vector3.Down, Color.White);
            float li = 0.5f;
            ld1.LightIntensity = li;
            ld2.LightIntensity = li;
            ld3.LightIntensity = li;
            ld4.LightIntensity = li;
            ld5.LightIntensity = li;
            this.World.AddLight(ld1);
            this.World.AddLight(ld2);
            this.World.AddLight(ld3);
            this.World.AddLight(ld4);
            this.World.AddLight(ld5);
            #endregion


            BallThrowPhysx28 BallThrowBullet = new BallThrowPhysx28(this.World, GraphicFactory,false);
            this.AttachCleanUpAble(BallThrowBullet);

            this.World.CameraManager.AddCamera(new CameraFirstPerson(GraphicInfo));
        }
        protected override void LoadContent(GraphicInfo GraphicInfo, GraphicFactory factory ,IContentManager contentManager)
        {
            PhysxPhysicWorld PhysxPhysicWorld = World.PhysicWorld as PhysxPhysicWorld;
            
            base.LoadContent(GraphicInfo, factory, contentManager);

            const int maximumParticles = 1000;
            var fluidEmitterDesc = new FluidEmitterDescription()
            {
                DimensionX = 0.5f,
                DimensionY = 0.5f,
                Rate = 15,
                RelativePose =
                    Phyx.Matrix.RotationAxis(new Phyx.Vector3(0, 1, 0), (float)Math.PI) *
                    Phyx.Matrix.Translation(-40, 10, -50),
                Shape = EmitterShape.Rectangular,
                Type = EmitterType.ConstantFlowRate,
                RandomAngle = 0.5f
            };
            fluidEmitterDesc.Flags |= (FluidEmitterFlag.Enabled | FluidEmitterFlag.Visualization);

            var fluidDesc = new FluidDescription()
            {
                Emitters = { fluidEmitterDesc },
                Flags = FluidFlag.Enabled | FluidFlag.Visualization | FluidFlag.Enabled,
                MaximumParticles = maximumParticles,
                
            };
            fluidDesc.ParticleWriteData.AllocatePositionBuffer<Vector3>(maximumParticles);
            fluidDesc.ParticleWriteData.NumberOfParticles = maximumParticles;
            
            fluid = PhysxPhysicWorld.Scene.CreateFluid(fluidDesc);

                       
            Texture2D tex = factory.GetTexture2D("Textures/Smoke");
            for (int i = 0; i < maximumParticles; i++)
            {
                Billboard3D Billboard3D = new Billboard3D(tex,Vector3.Zero,new Vector2(0.002f));
                Billboard3D.Enabled = false;
                CPUSphericalBillboardComponent.Billboards.Add(Billboard3D);
            }


            // Ledge
            {
                var boxShapeDesc = new BoxShapeDescription(5, 0.1f, 5);
                SimpleModel SimpleModel = new PloobsEngine.Modelo.SimpleModel(factory, "Model/block");
                SimpleModel.SetTexture(factory.CreateTexture2DColor(1, 1, Color.Red), TextureType.DIFFUSE);
                PhysxPhysicObject PhysxPhysicObject = new PloobsEngine.Physics.PhysxPhysicObject(boxShapeDesc,
                    (Phyx.Matrix.RotationX(-0.5f) * Phyx.Matrix.Translation(-40, 5, -52)).AsXNA(),new Vector3(5,0.1f,5));
                ForwardXNABasicShader shader = new ForwardXNABasicShader(ForwardXNABasicShaderDescription.Default());
                ForwardMaterial fmaterial = new ForwardMaterial(shader);
                IObject obj = new IObject(fmaterial, SimpleModel, PhysxPhysicObject);
                this.World.AddObject(obj);
            }

            // Drain
            {
                var boxShapeDesc = new BoxShapeDescription(5, 0.1f, 5);
                boxShapeDesc.Flags |= ShapeFlag.FluidDrain;

                var drainActorDesc = new ActorDescription()
                {
                    GlobalPose = Phyx.Matrix.Translation(-40, 0, -55),
                    Shapes = { boxShapeDesc }
                };

                var drianActor = PhysxPhysicWorld.Scene.CreateActor(drainActorDesc);
            }            

            BallThrowPhysx28 BallThrowBullet = new BallThrowPhysx28(this.World, GraphicFactory);
            this.AttachCleanUpAble(BallThrowBullet);

            this.World.CameraManager.AddCamera(new CameraFirstPerson(GraphicInfo));
        }
Exemplo n.º 39
0
		protected override void LoadPhysics(Scene scene)
		{
			CCDSkeleton ccdSkeletonForBox;

			// Create a CCD Skeleton
			{
				Vector3 size = new Vector3(5, 5, 5);

				int[] indices =
				{
					0, 1, 3,
					0, 3, 2,
					3, 7, 6,
					3, 6, 2,
					1, 5, 7,
					1, 7, 3,
					4, 6, 7,
					4, 7, 5,
					1, 0, 4,
					5, 1, 4,
					4, 0, 2,
					4, 2, 6
				};

				Vector3[] vertices =
				{
					new Vector3( size.X, -size.Y, -size.Z ),
					new Vector3( size.X, -size.Y, size.Z ),
					new Vector3( size.X, size.Y, -size.Z ),
					new Vector3( size.X,  size.Y,  size.Z ),
					new Vector3( -size.X, -size.Y, -size.Z ),
					new Vector3( -size.X, -size.Y, size.Z ),
					new Vector3( -size.X,  size.Y, -size.Z ),
					new Vector3( -size.X,  size.Y,  size.Z )
				};

				TriangleMeshDescription triangleMeshDesc = new TriangleMeshDescription();
				triangleMeshDesc.AllocateVertices<Vector3>(vertices.Length);
				triangleMeshDesc.AllocateTriangles<int>(indices.Length);

				triangleMeshDesc.VerticesStream.SetData(vertices);
				triangleMeshDesc.TriangleStream.SetData(indices);

				triangleMeshDesc.VertexCount = vertices.Length;
				triangleMeshDesc.TriangleCount = indices.Length / 3;

				ccdSkeletonForBox = scene.Core.CreateCCDSkeleton(triangleMeshDesc);

				// Enable CCD and CCD Visualization
				scene.Core.SetParameter(PhysicsParameter.ContinuousCollisionDetection, true);
				scene.Core.SetParameter(PhysicsParameter.VisualizeContinuousCollisionDetectionTests, true);
			}

			// Create a large 2 polygon triangle mesh plane
			// For CCD to work/be used many conditions must be met (check the docs for full list)
			// One of those conditions is that one of the objects must be a triangle mesh or a convex mesh (for static-dynamic)
			{
				Vector3[] vertices = 
				{
					new Vector3( -100, 5, -100 ),
					new Vector3( -100, 5, 100 ),
					new Vector3( 100, 5, -100 ),
					new Vector3( 100, 5, 100 ),
				};

				int[] indices =
				{
					0, 1, 2,
					1, 3, 2
				};

				TriangleMeshDescription triangleMeshDesc = new TriangleMeshDescription();
				triangleMeshDesc.TriangleCount = indices.Length / 3;
				triangleMeshDesc.VertexCount = vertices.Length;

				triangleMeshDesc.AllocateTriangles<int>(triangleMeshDesc.TriangleCount);
				triangleMeshDesc.AllocateVertices<Vector3>(triangleMeshDesc.VertexCount);

				triangleMeshDesc.TriangleStream.SetData(indices);
				triangleMeshDesc.VerticesStream.SetData(vertices);

				TriangleMesh triangleMesh;
				using (MemoryStream s = new MemoryStream())
				{
					Cooking.InitializeCooking();
					Cooking.CookTriangleMesh(triangleMeshDesc, s);
					Cooking.CloseCooking();

					s.Position = 0;
					triangleMesh = scene.Core.CreateTriangleMesh(s);
				}

				TriangleMeshShapeDescription triangleMeshShapeDesc = new TriangleMeshShapeDescription()
				{
					TriangleMesh = triangleMesh,
					Flags = ShapeFlag.Visualization
				};

				ActorDescription actorDesc = new ActorDescription()
				{
					Shapes = { triangleMeshShapeDesc }
				};

				Actor actor = scene.CreateActor(actorDesc);
			}

			// Make 20 boxes fall down
			for (int x = 0; x < 20; x++)
			{
				BoxShapeDescription boxShapeDesc = new BoxShapeDescription(2, 3, 8);
				// Assign the CCD Skeleton to the shape
				boxShapeDesc.CCDSkeleton = ccdSkeletonForBox;

				ActorDescription actorDesc = new ActorDescription()
				{
					Name = String.Format("Box {0}", x),
					BodyDescription = new BodyDescription(10.0f),
					GlobalPose = Matrix.Translation(0, 15 + 3 * x, 0),
					Shapes = { boxShapeDesc }
				};

				Actor actor = scene.CreateActor(actorDesc);
			}
		}
        protected override void LoadContent(GraphicInfo GraphicInfo, GraphicFactory factory, IContentManager contentManager)
        {
            PhysxPhysicWorld PhysxPhysicWorld = World.PhysicWorld as PhysxPhysicWorld;

            base.LoadContent(GraphicInfo, factory, contentManager);

            for (int i = 0; i < 3; i++)
            {
                ///Different from others examples, we use a model to provide the vertices to the cloth
                ///Model must be "closed"
                ClothMeshDescription ClothMeshDescription = new ClothMeshDescription();
                ClothMeshDescription.WeldingDistance = 0.0001f;
                ClothMeshDescription.Flags           = (MeshFlag)(int)ClothMeshFlag.WeldVertices;


                ClothModel ClothModel = new PloobsEngine.Modelo.ClothModel(factory, PhysxPhysicWorld,
                                                                           ClothMeshDescription, "Model//ball", Vector3.One * 25, "Textures//meiofio");

                var clothDesc = new ClothDescription()
                {
                    Friction  = 0.5f,
                    ClothMesh = ClothModel.ClothMesh,
                    Pressure  = 0.9f, ///experiment changing this =P
                    Flags     = ClothFlag.Bending | ClothFlag.CollisionTwoway | ClothFlag.Visualization | ClothFlag.Pressure | ClothFlag.Gravity | ClothFlag.SelfCollision | ClothFlag.TriangleCollision,
                    Thickness = 0.4f,
                };


                clothDesc.MeshData.AllocatePositions <Vector3>(ClothModel.VerticesNum);
                clothDesc.MeshData.AllocateIndices <int>(ClothModel.IndicesNum);
                clothDesc.MeshData.AllocateNormals <Vector3>(ClothModel.VerticesNum);

                clothDesc.MeshData.MaximumVertices = ClothModel.VerticesNum;
                clothDesc.MeshData.MaximumIndices  = ClothModel.IndicesNum;

                clothDesc.MeshData.NumberOfVertices = ClothModel.VerticesNum;
                clothDesc.MeshData.NumberOfIndices  = ClothModel.IndicesNum;

                PhysxClothObject PhysxClothObject = new PloobsEngine.Physics.PhysxClothObject(clothDesc,
                                                                                              Matrix.CreateTranslation(100, 50, i * 100));


                ForwardXNABasicShader ForwardXNABasicShader = new PloobsEngine.Material.ForwardXNABasicShader();
                ClothMaterial         ClothMaterial         = new ClothMaterial(ForwardXNABasicShader);
                //ClothMaterial.RasterizerState.FillMode = FillMode.WireFrame;
                IObject IObject = new PloobsEngine.SceneControl.IObject(ClothMaterial, ClothModel, PhysxClothObject);
                World.AddObject(IObject);

                ForwardXNABasicShader.BasicEffect.EnableDefaultLighting();
            }

            {
                SimpleModel simpleModel = new SimpleModel(factory, "Model//block");
                simpleModel.SetTexture(factory.CreateTexture2DColor(1, 1, Color.Blue), TextureType.DIFFUSE);

                BoxShapeDescription SphereGeometry    = new BoxShapeDescription(1000, 5, 1000);
                PhysxPhysicObject   PhysxPhysicObject = new PhysxPhysicObject(SphereGeometry,
                                                                              Matrix.Identity, new Vector3(1000, 5, 1000));

                ForwardXNABasicShader shader    = new ForwardXNABasicShader(ForwardXNABasicShaderDescription.Default());
                ForwardMaterial       fmaterial = new ForwardMaterial(shader);
                IObject obj = new IObject(fmaterial, simpleModel, PhysxPhysicObject);
                this.World.AddObject(obj);

                shader.BasicEffect.EnableDefaultLighting();
            }


            BallThrowPhysx28 BallThrowBullet = new BallThrowPhysx28(this.World, GraphicFactory);

            this.AttachCleanUpAble(BallThrowBullet);
            this.World.CameraManager.AddCamera(new CameraFirstPerson(GraphicInfo));
        }
Exemplo n.º 41
0
        public VehicleChassis(Vehicle vehicle)
        {
            Vehicle = vehicle;

            Wheels = new List <VehicleWheel>();

            VehicleFile carFile = vehicle.Config;

            ActorDescription actorDesc = new ActorDescription();

            actorDesc.BodyDescription      = new BodyDescription();
            actorDesc.BodyDescription.Mass = carFile.Mass;
            var boxDesc = new BoxShapeDescription();

            boxDesc.Size          = carFile.BoundingBox.GetSize();
            boxDesc.LocalPosition = carFile.BoundingBox.GetCenter();
            boxDesc.Name          = PhysXConsts.VehicleBody;
            boxDesc.Flags        |= ShapeFlag.PointContactForce;
            actorDesc.Shapes.Add(boxDesc);

            foreach (Vector3 extraPoint in carFile.ExtraBoundingBoxPoints)
            {
                var extraDesc = new SphereShapeDescription(0.2f);
                extraDesc.LocalPosition = extraPoint;
                extraDesc.Mass          = 0;
                actorDesc.Shapes.Add(extraDesc);
            }

            using (UtilitiesLibrary lib = new UtilitiesLibrary())
            {
                Vector3 size          = carFile.Size;
                Vector3 inertiaTensor = lib.ComputeBoxInteriaTensor(Vector3.Zero, carFile.Mass, size);
                //actorDesc.BodyDescription.MassSpaceInertia = inertiaTensor;
            }


            TireFunctionDescription lngTFD = new TireFunctionDescription();

            lngTFD.ExtremumSlip   = 0.1f;
            lngTFD.ExtremumValue  = 4f;
            lngTFD.AsymptoteSlip  = 2.0f;
            lngTFD.AsymptoteValue = 3.2f;

            _rearLateralTireFn = new TireFunctionDescription();

            _rearLateralTireFn.ExtremumSlip   = 0.2f;
            _rearLateralTireFn.ExtremumValue  = 2.1f;
            _rearLateralTireFn.AsymptoteSlip  = 0.0013f * carFile.Mass;
            _rearLateralTireFn.AsymptoteValue = 0.02f;

            _frontLateralTireFn = _rearLateralTireFn;
            _frontLateralTireFn.ExtremumValue = 1.9f;

            MaterialDescription md = new MaterialDescription();

            md.Flags = MaterialFlag.DisableFriction;
            Material m = PhysX.Instance.Scene.CreateMaterial(md);

            int wheelIndex = 0;

            foreach (CWheelActor wheel in carFile.WheelActors)
            {
                WheelShapeDescription wheelDesc = new WheelShapeDescription();
                wheelDesc.InverseWheelMass            = 0.08f;
                wheelDesc.LongitudalTireForceFunction = lngTFD;
                wheelDesc.Flags    = WheelShapeFlag.ClampedFriction;
                wheelDesc.Material = m;

                wheelDesc.Radius           = wheel.IsDriven ? carFile.DrivenWheelRadius : carFile.NonDrivenWheelRadius;
                wheelDesc.SuspensionTravel = (wheel.IsFront ? carFile.SuspensionGiveFront : carFile.SuspensionGiveRear) * 18;

                float heightModifier = (wheelDesc.SuspensionTravel + wheelDesc.Radius) / wheelDesc.SuspensionTravel;

                SpringDescription spring = new SpringDescription();
                if (carFile.Mass > 3000)
                {
                    spring.SpringCoefficient = 10.5f * heightModifier * carFile.Mass;
                }
                else
                {
                    spring.SpringCoefficient = 6.5f * heightModifier * Math.Min(1000, carFile.Mass);
                }
                spring.DamperCoefficient = carFile.SuspensionDamping * 6f;

                wheelDesc.Suspension    = spring;
                wheelDesc.LocalPosition = wheel.Position;
                wheelDesc.Name          = (wheelIndex).ToString();
                wheelIndex++;

                wheelDesc.LateralTireForceFunction = wheel.IsFront ? _frontLateralTireFn : _rearLateralTireFn;
                actorDesc.Shapes.Add(wheelDesc);
            }

            _physXActor = PhysX.Instance.Scene.CreateActor(actorDesc);


            _heightOffset = _physXActor.Shapes[0].LocalPosition.Y * -2;
            if (_heightOffset < 0)
            {
                _heightOffset = 0;
            }

            foreach (Shape shape in _physXActor.Shapes)
            {
                shape.LocalPosition += new Vector3(0, _heightOffset, 0);
                if (shape is WheelShape)
                {
                    wheelIndex = int.Parse(shape.Name);
                    Wheels.Add(new VehicleWheel(this, carFile.WheelActors[wheelIndex], (WheelShape)shape, carFile.WheelActors[wheelIndex].IsLeft ? 0.17f : -0.17f)
                    {
                        Index = wheelIndex
                    });
                }
            }

            _physXActor.Group    = PhysXConsts.VehicleId;
            _physXActor.UserData = vehicle;

            _physXActor.WakeUp(60.0f);

            //_physXActor.RaiseBodyFlag(BodyFlag.DisableGravity);

            //set center of mass
            Vector3 massPos = carFile.CenterOfMass;

            massPos.Y = carFile.WheelActors[0].Position.Y - carFile.NonDrivenWheelRadius + _heightOffset + 0.35f;
            _massPos  = massPos;
            _physXActor.SetCenterOfMassOffsetLocalPosition(massPos);

            //a real power curve doesnt work too well :)
            List <float> power  = new List <float>(new float[] { 0.5f, 0.5f, 0.5f, 1f, 1f, 1.0f, 1.0f, 0 });
            List <float> ratios = new List <float>(new float[] { 3.227f, 2.360f, 1.685f, 1.312f, 1.000f, 0.793f });

            BaseGearbox gearbox = BaseGearbox.Create(false, ratios, 0.4f);

            Motor = new Motor(power, carFile.EnginePower, 6f, carFile.TopSpeed, gearbox);
            Motor.Gearbox.CurrentGear = 0;
        }
        protected override void LoadContent(GraphicInfo GraphicInfo, GraphicFactory factory ,IContentManager contentManager)
        {
            PhysxPhysicWorld PhysxPhysicWorld = World.PhysicWorld as PhysxPhysicWorld;

            base.LoadContent(GraphicInfo, factory, contentManager);

            for (int i = 0; i < 3; i++)
            {
                ClothMeshDescription ClothMeshDescription = new ClothMeshDescription();
                ClothMeshDescription.WeldingDistance = 0.0001f;
                ClothMeshDescription.Flags = (MeshFlag)(int)ClothMeshFlag.WeldVertices;


                ClothModel ClothModel = new PloobsEngine.Modelo.ClothModel(factory, PhysxPhysicWorld,
                    ClothMeshDescription, "Model//ball", Vector3.One * 25, "Textures//meiofio");

                var clothDesc = new ClothDescription()
                {
                    Friction = 0.5f,
                    ClothMesh = ClothModel.ClothMesh,
                    Pressure = 0.9f,
                    Flags = ClothFlag.Bending | ClothFlag.CollisionTwoway | ClothFlag.Visualization | ClothFlag.Pressure | ClothFlag.Gravity | ClothFlag.SelfCollision | ClothFlag.TriangleCollision,
                    Thickness = 0.4f,
                };


                clothDesc.MeshData.AllocatePositions<Vector3>(ClothModel.VerticesNum);
                clothDesc.MeshData.AllocateIndices<int>(ClothModel.IndicesNum);
                clothDesc.MeshData.AllocateNormals<Vector3>(ClothModel.VerticesNum);

                clothDesc.MeshData.MaximumVertices = ClothModel.VerticesNum;
                clothDesc.MeshData.MaximumIndices = ClothModel.IndicesNum;

                clothDesc.MeshData.NumberOfVertices = ClothModel.VerticesNum;
                clothDesc.MeshData.NumberOfIndices = ClothModel.IndicesNum;

                PhysxClothObject PhysxClothObject = new PloobsEngine.Physics.PhysxClothObject(clothDesc,
                                                    Matrix.CreateTranslation(100, 50, i * 100));


                ForwardXNABasicShader ForwardXNABasicShader = new PloobsEngine.Material.ForwardXNABasicShader();
                ClothMaterial ClothMaterial = new ClothMaterial(ForwardXNABasicShader);
                //ClothMaterial.RasterizerState.FillMode = FillMode.WireFrame;
                IObject IObject = new PloobsEngine.SceneControl.IObject(ClothMaterial, ClothModel, PhysxClothObject);
                World.AddObject(IObject);

                ForwardXNABasicShader.BasicEffect.EnableDefaultLighting();
            }

            {
                SimpleModel simpleModel = new SimpleModel(factory, "Model//block");
                simpleModel.SetTexture(factory.CreateTexture2DColor(1, 1, Color.Blue), TextureType.DIFFUSE);

                BoxShapeDescription SphereGeometry = new BoxShapeDescription(1000, 5, 1000);
                PhysxPhysicObject PhysxPhysicObject = new PhysxPhysicObject(SphereGeometry,
                    Matrix.Identity, new Vector3(1000, 5, 1000));

                ForwardXNABasicShader shader = new ForwardXNABasicShader(ForwardXNABasicShaderDescription.Default());
                ForwardMaterial fmaterial = new ForwardMaterial(shader);
                IObject obj = new IObject(fmaterial, simpleModel, PhysxPhysicObject);
                this.World.AddObject(obj);

                shader.BasicEffect.EnableDefaultLighting();
            }


            BallThrowPhysx28 BallThrowBullet = new BallThrowPhysx28(this.World, GraphicFactory);
            this.AttachCleanUpAble(BallThrowBullet);
            this.World.CameraManager.AddCamera(new CameraFirstPerson(GraphicInfo));
        }
Exemplo n.º 43
0
        public void TestJoint()
        {
            XNAGame game = new XNAGame();

            game.SpectaterCamera.CameraPosition = new Vector3(0, 0, -40);
            PhysicsEngine engine = new PhysicsEngine();

            //game.AddXNAObject(engine);



            game.InitializeEvent += delegate
            {
                engine.Initialize();

                PhysicsDebugRendererXNA debugRenderer = new PhysicsDebugRendererXNA(game, engine.Scene);

                game.AddXNAObject(debugRenderer);


                Actor actorA, actorB;
                {
                    BoxShapeDescription boxShapeDesc = new BoxShapeDescription(3, 3, 3);

                    BodyDescription bodyDesc = new BodyDescription(10.0f);
                    bodyDesc.BodyFlags |= BodyFlag.Kinematic;

                    ActorDescription actorDesc = new ActorDescription()
                    {
                        BodyDescription = bodyDesc,
                        GlobalPose      = Matrix.CreateTranslation(70, 25, 65),
                        Shapes          = { boxShapeDesc }
                    };
                    actorA = engine.Scene.CreateActor(actorDesc);
                }
                {
                    BoxShapeDescription boxShapeDesc = new BoxShapeDescription(3, 3, 3);

                    ActorDescription actorDesc = new ActorDescription()
                    {
                        BodyDescription = new BodyDescription(10.0f),
                        GlobalPose      = Matrix.CreateTranslation(70, 15, 65),
                        Shapes          = { boxShapeDesc }
                    };
                    actorB = engine.Scene.CreateActor(actorDesc);
                }

                PrismaticJointDescription prismaticJointDesc = new PrismaticJointDescription()
                {
                    Actor1 = actorA,
                    Actor2 = actorB,
                };
                prismaticJointDesc.SetGlobalAnchor(new Vector3(70, 20, 65));
                prismaticJointDesc.SetGlobalAxis(new Vector3(0, 1, 0));

                PrismaticJoint prismaticJoint = engine.Scene.CreateJoint(prismaticJointDesc) as PrismaticJoint;

                LimitPlane limitPlane = new LimitPlane(new Vector3(0, 1, 0), new Vector3(-30, 8, -30), 0);
                prismaticJoint.AddLimitPlane(limitPlane);
            };

            game.UpdateEvent += delegate
            {
                if (game.Keyboard.IsKeyPressed(Microsoft.Xna.Framework.Input.Keys.F))
                {
                    Actor actor = PhysicsHelper.CreateDynamicSphereActor(engine.Scene, 1, 1);
                    actor.GlobalPosition = game.SpectaterCamera.CameraPosition +
                                           game.SpectaterCamera.CameraDirection * 5;
                    actor.LinearVelocity = game.SpectaterCamera.CameraDirection * 5;
                }
                engine.Update(game.Elapsed);
            };

            game.Run();

            engine.Dispose();
        }
Exemplo n.º 44
0
        private void InitTestScene(StillDesign.PhysX.Scene scene)
        {
            ActorDescription actorDesc;
            Actor            actor;

            CapsuleShapeDescription capsuleShapeDesc = new CapsuleShapeDescription(1, 3);

            actorDesc = new ActorDescription(capsuleShapeDesc);
            actorDesc.BodyDescription = new BodyDescription(1f);

            actor = scene.CreateActor(actorDesc);
            actor.GlobalOrientation = Matrix.CreateRotationX(MathHelper.PiOver2);



            BoxShapeDescription boxShapeDesc = new BoxShapeDescription(40, 1, 1);

            actorDesc = new ActorDescription(boxShapeDesc);
            actorDesc.BodyDescription = new BodyDescription(1f);

            actor = scene.CreateActor(actorDesc);
            actor.GlobalPosition = new Vector3(0, 4, 0);


            boxShapeDesc = new BoxShapeDescription(1, 1, 1);

            actorDesc = new ActorDescription(boxShapeDesc);
            actorDesc.BodyDescription = new BodyDescription(40f);

            actor = scene.CreateActor(actorDesc);
            actor.GlobalPosition = new Vector3(15, 40, 0);

            boxShapeDesc = new BoxShapeDescription(1, 1, 1);

            actorDesc = new ActorDescription(boxShapeDesc);
            actorDesc.BodyDescription = new BodyDescription(1f);

            actor = scene.CreateActor(actorDesc);
            actor.GlobalPosition = new Vector3(-13, 5, 0);

            boxShapeDesc = new BoxShapeDescription(1, 1, 1);

            actorDesc = new ActorDescription(boxShapeDesc);
            actorDesc.BodyDescription = new BodyDescription(1f);

            actor = scene.CreateActor(actorDesc);
            actor.GlobalPosition = new Vector3(-7, 5, 0);

            boxShapeDesc = new BoxShapeDescription(1, 1, 1);

            actorDesc = new ActorDescription(boxShapeDesc);
            actorDesc.BodyDescription = new BodyDescription(1f);

            actor = scene.CreateActor(actorDesc);
            actor.GlobalPosition = new Vector3(-10, 5, 0);

            boxShapeDesc = new BoxShapeDescription(1, 1, 1);

            actorDesc = new ActorDescription(boxShapeDesc);
            actorDesc.BodyDescription = new BodyDescription(1f);

            actor = scene.CreateActor(actorDesc);
            actor.GlobalPosition = new Vector3(-4, 5, 0);
        }
Exemplo n.º 45
0
        public static Actor GenerateTrackActor(RaceFile file, CActorHierarchy actors, out List<NonCar> nonCarInstances)
        {
            List<Vector3> verts = new List<Vector3>();
            List<ushort> indices = new List<ushort>();
            List<ushort> materialIndices = new List<ushort>();
            List<OpenC1.CActor> actorsList = actors.All();
            nonCarInstances = new List<NonCar>();

            for (int i = 0; i < actorsList.Count; i++)
            {
                CActor actor = actorsList[i];
                if (actor.Model == null) continue;
                if (actor.Name.StartsWith("&"))
                {
                    if (Char.IsDigit(actor.Name[1]) && Char.IsDigit(actor.Name[2]))
                    {
                        NonCar nc = GenerateNonCar(actor, file.NonCars);
                        if (nc != null)
                        {
                            nonCarInstances.Add(nc);
                            continue;  //dont-merge with track
                        }
                    }
                }

                int baseIndex = verts.Count;
                for (int j = 0; j < actor.Model.VertexCount; j++)
                    verts.Add(Vector3.Zero);

                foreach (Polygon poly in actor.Model.Polygons)
                {
                    if (poly.MaterialIndex < 0)
                        continue;

                    string materialName = actor.Model.MaterialNames == null ? "none" : actor.Model.MaterialNames[poly.MaterialIndex];
                    //this is a non-solid material
                    if (materialName.StartsWith("!"))
                        continue;

                    int index = baseIndex + poly.Vertex1;

                    indices.Add((ushort)index);
                    if (verts[index] == Vector3.Zero)
                    {
                        Vector3 transformedVec = Vector3.Transform(actors.Models._vertexPositions[actor.Model.VertexBaseIndex + poly.Vertex1], actor.Matrix);
                        verts[index] = transformedVec;
                    }
                    index = baseIndex + poly.Vertex2;
                    indices.Add((ushort)index);
                    if (verts[index] == Vector3.Zero)
                    {
                        Vector3 transformedVec = Vector3.Transform(actors.Models._vertexPositions[actor.Model.VertexBaseIndex + poly.Vertex2], actor.Matrix);
                        verts[index] = transformedVec;
                    }
                    index = baseIndex + poly.Vertex3;
                    indices.Add((ushort)index);
                    if (verts[index] == Vector3.Zero)
                    {
                        Vector3 transformedVec = Vector3.Transform(actors.Models._vertexPositions[actor.Model.VertexBaseIndex + poly.Vertex3], actor.Matrix);
                        verts[index] = transformedVec;
                    }

                    if (Char.IsDigit(materialName[0]))
                    {
                        ushort matModiferId = (ushort)(ushort.Parse(materialName.Substring(0, 1)) + 1);
                        if (matModiferId >= file.MaterialModifiers.Count) matModiferId = 0;

                        materialIndices.Add(matModiferId);
                    }
                    else
                        materialIndices.Add(0);
                }
            }

            TriangleMeshDescription meshDesc = new TriangleMeshDescription();
            meshDesc.TriangleCount = indices.Count / 3;
            meshDesc.VertexCount = verts.Count;

            meshDesc.AllocateVertices<Vector3>(meshDesc.VertexCount);
            meshDesc.AllocateTriangles<ushort>(meshDesc.TriangleCount);
            meshDesc.AllocateMaterialIndices<ushort>(materialIndices.Count);

            meshDesc.TriangleStream.SetData(indices.ToArray());
            meshDesc.VerticesStream.SetData(verts.ToArray());
            meshDesc.MaterialIndicesStream.SetData(materialIndices.ToArray());
            meshDesc.Flags = MeshFlag.Indices16Bit;

            MemoryStream s = new MemoryStream();

            Cooking.InitializeCooking();
            Cooking.CookTriangleMesh(meshDesc, s);
            Cooking.CloseCooking();

            s.Position = 0;
            TriangleMesh triangleMesh = PhysX.Instance.Core.CreateTriangleMesh(s);

            TriangleMeshShapeDescription shape = new TriangleMeshShapeDescription()
            {
                TriangleMesh = triangleMesh,
            };

            ActorDescription actorDescription = new ActorDescription()
            {
                GlobalPose = Matrix.CreateTranslation(0, 0, 0),
                Shapes = { shape }
            };

            foreach (Checkpoint checkpoint in file.Checkpoints)
            {
                ActorDescription actorDesc = new ActorDescription();

                BoxShapeDescription box = new BoxShapeDescription(checkpoint.BBox.GetSize());
                box.Flags = ShapeFlag.TriggerOnEnter | ShapeFlag.Visualization;
                actorDesc.Shapes.Add(box);
                Actor actor = PhysX.Instance.Scene.CreateActor(actorDesc);
                actor.GlobalPosition = checkpoint.BBox.GetCenter();
                actor.UserData = checkpoint;
            }

            StillDesign.PhysX.Actor environment = PhysX.Instance.Scene.CreateActor(actorDescription);
            environment.Group = PhysXConsts.TrackId;
            environment.Shapes[0].SetFlag(ShapeFlag.Visualization, false);

            CreateDefaultWaterSpecVols(file, actorsList, actors.Models);

            for (int i = 1; i < file.SpecialVolumes.Count; i++)
            {
                SpecialVolume vol = file.SpecialVolumes[i];

                Vector3 scale = new Vector3();
                Vector3 trans = new Vector3();
                Quaternion q = new Quaternion();
                Matrix matrix = vol.Matrix;
                bool success = matrix.Decompose(out scale, out q, out trans);
                if (scale.Z == 0) scale.Z = 0.1f;

                ActorDescription actorDesc = new ActorDescription();
                BoxShapeDescription box = new BoxShapeDescription(scale);

                if (success)
                {
                    if (float.IsNaN(q.X))
                        continue;
                    box.LocalRotation = Matrix.CreateFromQuaternion(q);
                }
                else
                {
                    //if the matrix cannot be decomposed, like part of the long tunnel in coasta...
                    // get the rotation by calculating some points and working out rotation from them
                    Vector3 v1 = Vector3.Transform(new Vector3(-1, -1, 1), matrix);
                    Vector3 v2 = Vector3.Transform(new Vector3(-1, 1, -1), matrix);
                    Vector3 forwards = v2 - v1;
                    forwards.Normalize();
                    box.LocalRotation = Matrix.CreateWorld(Vector3.Zero, forwards, Vector3.Up);
                }

                box.Flags = ShapeFlag.TriggerOnEnter | ShapeFlag.TriggerOnLeave | ShapeFlag.Visualization;
                actorDesc.Shapes.Add(box);
                Actor actor = PhysX.Instance.Scene.CreateActor(actorDesc);

                actor.GlobalPosition = vol.Matrix.Translation;
                actor.UserData = vol;
            }

            return environment;
        }
Exemplo n.º 46
0
        public VehicleChassis(Vehicle vehicle)
        {
            Vehicle = vehicle;

            Wheels = new List<VehicleWheel>();

            VehicleFile carFile = vehicle.Config;

            ActorDescription actorDesc = new ActorDescription();

            actorDesc.BodyDescription = new BodyDescription();
            actorDesc.BodyDescription.Mass = carFile.Mass;
            var boxDesc = new BoxShapeDescription();
            boxDesc.Size = carFile.BoundingBox.GetSize();
            boxDesc.LocalPosition = carFile.BoundingBox.GetCenter();
            boxDesc.Name = PhysXConsts.VehicleBody;
            boxDesc.Flags |= ShapeFlag.PointContactForce;
            actorDesc.Shapes.Add(boxDesc);

            foreach (Vector3 extraPoint in carFile.ExtraBoundingBoxPoints)
            {
                var extraDesc = new SphereShapeDescription(0.2f);
                extraDesc.LocalPosition = extraPoint;
                extraDesc.Mass = 0;
                actorDesc.Shapes.Add(extraDesc);
            }

            using (UtilitiesLibrary lib = new UtilitiesLibrary())
            {
                Vector3 size = carFile.Size;
                Vector3 inertiaTensor = lib.ComputeBoxInteriaTensor(Vector3.Zero, carFile.Mass, size);
                //actorDesc.BodyDescription.MassSpaceInertia = inertiaTensor;
            }

            TireFunctionDescription lngTFD = new TireFunctionDescription();
            lngTFD.ExtremumSlip = 0.1f;
            lngTFD.ExtremumValue = 4f;
            lngTFD.AsymptoteSlip = 2.0f;
            lngTFD.AsymptoteValue = 3.2f;

            _rearLateralTireFn = new TireFunctionDescription();

            _rearLateralTireFn.ExtremumSlip = 0.2f;
            _rearLateralTireFn.ExtremumValue = 2.1f;
            _rearLateralTireFn.AsymptoteSlip = 0.0013f * carFile.Mass;
            _rearLateralTireFn.AsymptoteValue = 0.02f;

            _frontLateralTireFn = _rearLateralTireFn;
            _frontLateralTireFn.ExtremumValue = 1.9f;

            MaterialDescription md = new MaterialDescription();
            md.Flags = MaterialFlag.DisableFriction;
            Material m = PhysX.Instance.Scene.CreateMaterial(md);

            int wheelIndex = 0;

            foreach (CWheelActor wheel in carFile.WheelActors)
            {
                WheelShapeDescription wheelDesc = new WheelShapeDescription();
                wheelDesc.InverseWheelMass = 0.08f;
                wheelDesc.LongitudalTireForceFunction = lngTFD;
                wheelDesc.Flags = WheelShapeFlag.ClampedFriction;
                wheelDesc.Material = m;

                wheelDesc.Radius = wheel.IsDriven ? carFile.DrivenWheelRadius : carFile.NonDrivenWheelRadius;
                wheelDesc.SuspensionTravel = (wheel.IsFront ? carFile.SuspensionGiveFront : carFile.SuspensionGiveRear) * 18;

                float heightModifier = (wheelDesc.SuspensionTravel + wheelDesc.Radius) / wheelDesc.SuspensionTravel;

                SpringDescription spring = new SpringDescription();
                if (carFile.Mass > 3000)
                    spring.SpringCoefficient = 10.5f * heightModifier * carFile.Mass;
                else
                    spring.SpringCoefficient = 6.5f * heightModifier * Math.Min(1000, carFile.Mass);
                spring.DamperCoefficient = carFile.SuspensionDamping * 6f;

                wheelDesc.Suspension = spring;
                wheelDesc.LocalPosition = wheel.Position;
                wheelDesc.Name = (wheelIndex).ToString();
                wheelIndex++;

                wheelDesc.LateralTireForceFunction = wheel.IsFront ? _frontLateralTireFn : _rearLateralTireFn;
                actorDesc.Shapes.Add(wheelDesc);
            }

            _physXActor = PhysX.Instance.Scene.CreateActor(actorDesc);

            _heightOffset = _physXActor.Shapes[0].LocalPosition.Y * -2;
            if (_heightOffset < 0) _heightOffset = 0;

            foreach (Shape shape in _physXActor.Shapes)
            {
                shape.LocalPosition += new Vector3(0, _heightOffset, 0);
                if (shape is WheelShape)
                {
                    wheelIndex = int.Parse(shape.Name);
                    Wheels.Add(new VehicleWheel(this, carFile.WheelActors[wheelIndex], (WheelShape)shape, carFile.WheelActors[wheelIndex].IsLeft ? 0.17f : -0.17f) { Index = wheelIndex });
                }
            }

            _physXActor.Group = PhysXConsts.VehicleId;
            _physXActor.UserData = vehicle;

            _physXActor.WakeUp(60.0f);

            //_physXActor.RaiseBodyFlag(BodyFlag.DisableGravity);

            //set center of mass
            Vector3 massPos = carFile.CenterOfMass;
            massPos.Y = carFile.WheelActors[0].Position.Y - carFile.NonDrivenWheelRadius + _heightOffset + 0.35f;
            _massPos = massPos;
            _physXActor.SetCenterOfMassOffsetLocalPosition(massPos);

            //a real power curve doesnt work too well :)
            List<float> power = new List<float>(new float[] { 0.5f, 0.5f, 0.5f, 1f, 1f, 1.0f, 1.0f, 0 });
            List<float> ratios = new List<float>(new float[] { 3.227f, 2.360f, 1.685f, 1.312f, 1.000f, 0.793f });

            BaseGearbox gearbox = BaseGearbox.Create(false, ratios, 0.4f);
            Motor = new Motor(power, carFile.EnginePower, 6f, carFile.TopSpeed, gearbox);
            Motor.Gearbox.CurrentGear = 0;
        }
Exemplo n.º 47
0
        protected override void LoadContent()
        {
            CCDSkeleton ccdSkeletonForBox;

            // Create a CCD Skeleton
            {
                Vector3 size = new Vector3(5, 5, 5);

                int[] indices =
                {
                    0, 1, 3,
                    0, 3, 2,
                    3, 7, 6,
                    3, 6, 2,
                    1, 5, 7,
                    1, 7, 3,
                    4, 6, 7,
                    4, 7, 5,
                    1, 0, 4,
                    5, 1, 4,
                    4, 0, 2,
                    4, 2, 6
                };

                Vector3[] vertices =
                {
                    new Vector3(size.X,  -size.Y, -size.Z),
                    new Vector3(size.X,  -size.Y, size.Z),
                    new Vector3(size.X,  size.Y,  -size.Z),
                    new Vector3(size.X,  size.Y,  size.Z),
                    new Vector3(-size.X, -size.Y, -size.Z),
                    new Vector3(-size.X, -size.Y, size.Z),
                    new Vector3(-size.X, size.Y,  -size.Z),
                    new Vector3(-size.X, size.Y,  size.Z)
                };

                TriangleMeshDescription triangleMeshDesc = new TriangleMeshDescription();
                triangleMeshDesc.AllocateVertices <Vector3>(vertices.Length);
                triangleMeshDesc.AllocateTriangles <int>(indices.Length);

                triangleMeshDesc.VerticesStream.SetData(vertices);
                triangleMeshDesc.TriangleStream.SetData(indices);

                triangleMeshDesc.VertexCount   = vertices.Length;
                triangleMeshDesc.TriangleCount = indices.Length / 3;

                ccdSkeletonForBox = _core.CreateCCDSkeleton(triangleMeshDesc);

                // Enable CCD and CCD Visualization
                _core.SetParameter(PhysicsParameter.ContinuousCollisionDetection, true);
                _core.SetParameter(PhysicsParameter.VisualizeContinuousCollisionDetectionTests, true);
            }

            // Create a large 2 polygon triangle mesh plane
            // For CCD to work/be used many conditions must be met (check the docs for full list)
            // One of those conditions is that one of the objects must be a triangle mesh or a convex mesh (for static-dynamic)
            {
                Vector3[] vertices =
                {
                    new Vector3(-100, 5, -100),
                    new Vector3(-100, 5,  100),
                    new Vector3(100,  5, -100),
                    new Vector3(100,  5,  100),
                };

                int[] indices =
                {
                    0, 1, 2,
                    1, 3, 2
                };

                TriangleMeshDescription triangleMeshDesc = new TriangleMeshDescription();
                triangleMeshDesc.TriangleCount = indices.Length / 3;
                triangleMeshDesc.VertexCount   = vertices.Length;

                triangleMeshDesc.AllocateTriangles <int>(triangleMeshDesc.TriangleCount);
                triangleMeshDesc.AllocateVertices <Vector3>(triangleMeshDesc.VertexCount);

                triangleMeshDesc.TriangleStream.SetData(indices);
                triangleMeshDesc.VerticesStream.SetData(vertices);

                MemoryStream s = new MemoryStream();

                Cooking.InitializeCooking();
                Cooking.CookTriangleMesh(triangleMeshDesc, s);
                Cooking.CloseCooking();

                s.Position = 0;
                TriangleMesh triangleMesh = _core.CreateTriangleMesh(s);

                TriangleMeshShapeDescription triangleMeshShapeDesc = new TriangleMeshShapeDescription()
                {
                    TriangleMesh = triangleMesh,
                    Flags        = ShapeFlag.Visualization
                };

                ActorDescription actorDesc = new ActorDescription()
                {
                    Shapes = { triangleMeshShapeDesc }
                };

                Actor actor = _scene.CreateActor(actorDesc);
            }

            // Make 20 boxes fall down
            for (int x = 0; x < 20; x++)
            {
                BoxShapeDescription boxShapeDesc = new BoxShapeDescription(2, 3, 8);
                // Assign the CCD Skeleton to the shape
                boxShapeDesc.CCDSkeleton = ccdSkeletonForBox;

                ActorDescription actorDesc = new ActorDescription()
                {
                    Name            = String.Format("Box {0}", x),
                    BodyDescription = new BodyDescription(10.0f),
                    GlobalPose      = Matrix.CreateTranslation(0, 15 + 3 * x, 0),
                    Shapes          = { boxShapeDesc }
                };

                Actor actor = _scene.CreateActor(actorDesc);
            }
        }
Exemplo n.º 48
0
        public void Initialize()
        {
            if (Behaviour.RefNumber == 99) //flag waving guy
            {
                SetAction(Behaviour.Actions[7], true);
            }
            else
            {
                SetAction(Behaviour.Standing, true);
            }
            Position = Instructions[InitialInstruction].Position;
            _currentInstruction = InitialInstruction;

            if (Instructions[_currentInstruction].AutoY)
            {
                StillDesign.PhysX.RaycastHit hit = PhysX.Instance.Scene.RaycastClosestShape(new StillDesign.PhysX.Ray(Position + new Vector3(0, 10, 0), Vector3.Down), StillDesign.PhysX.ShapesType.Static);
                Position = hit.WorldImpact;
            }

            ActorDescription actorDesc = new ActorDescription();
            actorDesc.BodyDescription = new BodyDescription(1);
            actorDesc.BodyDescription.MassSpaceInertia = new Vector3(1, 1, 1);
            actorDesc.BodyDescription.BodyFlags |= BodyFlag.Kinematic;

            BoxShapeDescription box = new BoxShapeDescription(1.6f, 2.5f, 1.6f);
            box.Flags = ShapeFlag.TriggerOnEnter;
            box.LocalPosition = new Vector3(0, 1, 0);
            actorDesc.Shapes.Add(box);
            _physXActor = PhysX.Instance.Scene.CreateActor(actorDesc);
            _physXActor.GlobalPosition = Position;
            _physXActor.UserData = this;
        }
Exemplo n.º 49
0
        public void LoadPhysics()
        {
            Core  _core  = this.Core;
            Scene _scene = this.Scene;

            #region Some Boxes
            for (int x = 0; x < 5; x++)
            {
                BoxShapeDescription boxShapeDesc = new BoxShapeDescription(2, 3, 8);

                ActorDescription actorDesc = new ActorDescription()
                {
                    Name            = String.Format("Box {0}", x),
                    BodyDescription = new BodyDescription(10.0f),
                    GlobalPose      = Matrix.Translation(100, 15 + 3 * x, 20),
                    Shapes          = { boxShapeDesc }
                };

                Actor actor = _scene.CreateActor(actorDesc);
            }
            #endregion

            //#region Cloth (Flag)
            //{
            //    // Create a Grid of Points
            //    VertexGrid grid = VertexGrid.CreateGrid( 10, 10 );

            //    ClothMeshDescription clothMeshDesc = new ClothMeshDescription();
            //        clothMeshDesc.AllocateVertices<Vector3>( grid.Points.Length );
            //        clothMeshDesc.AllocateTriangles<int>( grid.Indices.Length / 3 );

            //        clothMeshDesc.VertexCount = grid.Points.Length;
            //        clothMeshDesc.TriangleCount = grid.Indices.Length / 3;

            //        clothMeshDesc.VerticesStream.SetData( grid.Points );
            //        clothMeshDesc.TriangleStream.SetData( grid.Indices );

            //        // We are using 32 bit integers, so make sure the 16 bit flag is removed.
            //        // 32 bits are the default, so this isn't technically needed
            //        clothMeshDesc.Flags &= ~MeshFlag.Indices16Bit;

            //    // Write the cooked data to memory
            //    MemoryStream memoryStream = new MemoryStream();

            //    Cooking.InitializeCooking();
            //    Cooking.CookClothMesh( clothMeshDesc, memoryStream );
            //    Cooking.CloseCooking();

            //    // Need to reset the position of the stream to the beginning
            //    memoryStream.Position = 0;

            //    ClothMesh clothMesh = _core.CreateClothMesh( memoryStream );

            //    //

            //    ClothDescription clothDesc = new ClothDescription()
            //    {
            //        ClothMesh = clothMesh,
            //        Flags = ClothFlag.Gravity | ClothFlag.Bending | ClothFlag.CollisionTwoway | ClothFlag.Visualization,
            //        GlobalPose =
            //            Matrix.CreateFromYawPitchRoll( 0, (float)Math.PI / 2.0f, (float)Math.PI / 2.0f ) *
            //            Matrix.CreateTranslation( 0, 20, 0 )
            //    };
            //    clothDesc.MeshData.AllocatePositions<Vector3>( grid.Points.Length );
            //    clothDesc.MeshData.AllocateIndices<int>( grid.Indices.Length );

            //    clothDesc.MeshData.MaximumVertices = grid.Points.Length;
            //    clothDesc.MeshData.MaximumIndices = grid.Indices.Length;

            //    clothDesc.MeshData.NumberOfVertices = grid.Points.Length;
            //    clothDesc.MeshData.NumberOfIndices = grid.Indices.Length;

            //    _flag = _scene.CreateCloth( clothDesc );

            //    // Flag Pole
            //    ActorDescription flagPoleActorDesc = new ActorDescription()
            //    {
            //        GlobalPose = Matrix.CreateTranslation( 0, 10, 0 ),
            //        Shapes = { new BoxShapeDescription( 1.0f, 20.0f, 1.0f ) }
            //    };

            //    Actor flagPoleActor = _scene.CreateActor( flagPoleActorDesc );

            //    _flag.AttachToShape( flagPoleActor.Shapes[ 0 ], 0 );
            //    _flag.WindAcceleration = new Vector3( 10, 10, 10 );
            //    _flag.BendingStiffness = 0.1f;
            //}
            //#endregion

            #region Revolute Joint
            {
                BoxShapeDescription boxShapeDescA = new BoxShapeDescription(3, 3, 3);
                BoxShapeDescription boxShapeDescB = new BoxShapeDescription(3, 3, 3);

                ActorDescription actorDescA = new ActorDescription()
                {
                    BodyDescription = new BodyDescription(10.0f),
                    GlobalPose      = Matrix.Translation(75, 1.5f, 55),
                    Shapes          = { boxShapeDescA }
                };
                Actor actorA = _scene.CreateActor(actorDescA);

                ActorDescription actorDescB = new ActorDescription()
                {
                    BodyDescription = new BodyDescription(10.0f),
                    GlobalPose      = Matrix.Translation(70, 1.5f, 55),
                    Shapes          = { boxShapeDescB }
                };
                Actor actorB = _scene.CreateActor(actorDescB);

                //

                RevoluteJointDescription revoluteJointDesc = new RevoluteJointDescription()
                {
                    Actor1 = actorA,
                    Actor2 = actorB,
                    Motor  = new MotorDescription(20, 20.1f, true)
                };
                revoluteJointDesc.Flags |= RevoluteJointFlag.MotorEnabled;
                revoluteJointDesc.SetGlobalAnchor(new Vector3(73.5f, 1.5f, 55));
                revoluteJointDesc.SetGlobalAxis(new Vector3(1, 0, 0));

                RevoluteJoint revoluteJoint = _scene.CreateJoint(revoluteJointDesc) as RevoluteJoint;
            }
            #endregion

            #region Prismatic Joint with Limit
            {
                Actor actorA, actorB;
                {
                    BoxShapeDescription boxShapeDesc = new BoxShapeDescription(3, 3, 3);

                    BodyDescription bodyDesc = new BodyDescription(10.0f);
                    bodyDesc.BodyFlags |= BodyFlag.Kinematic;

                    ActorDescription actorDesc = new ActorDescription()
                    {
                        BodyDescription = bodyDesc,
                        GlobalPose      = Matrix.Translation(70, 25, 65),
                        Shapes          = { boxShapeDesc }
                    };
                    actorA = _scene.CreateActor(actorDesc);
                }
                {
                    BoxShapeDescription boxShapeDesc = new BoxShapeDescription(3, 3, 3);

                    ActorDescription actorDesc = new ActorDescription()
                    {
                        BodyDescription = new BodyDescription(10.0f),
                        GlobalPose      = Matrix.Translation(70, 15, 65),
                        Shapes          = { boxShapeDesc }
                    };
                    actorB = _scene.CreateActor(actorDesc);
                }

                PrismaticJointDescription prismaticJointDesc = new PrismaticJointDescription()
                {
                    Actor1 = actorA,
                    Actor2 = actorB,
                };
                prismaticJointDesc.SetGlobalAnchor(new Vector3(70, 20, 65));
                prismaticJointDesc.SetGlobalAxis(new Vector3(0, 1, 0));

                PrismaticJoint prismaticJoint = _scene.CreateJoint(prismaticJointDesc) as PrismaticJoint;

                LimitPlane limitPlane = new LimitPlane(new Vector3(0, 1, 0), new Vector3(-30, 8, -30), 0);
                prismaticJoint.AddLimitPlane(limitPlane);
            }
            #endregion

            #region Fluid
            {
                const int maximumParticles = 1000;

                FluidEmitterDescription fluidEmitterDesc = new FluidEmitterDescription()
                {
                    DimensionX   = 0.5f,
                    DimensionY   = 0.5f,
                    Rate         = 15,
                    RelativePose = Matrix.Translation(-40, 10, 50),
                    Shape        = EmitterShape.Rectangular,
                    Type         = EmitterType.ConstantFlowRate,
                    RandomAngle  = 0.5f
                };
                fluidEmitterDesc.Flags |= (FluidEmitterFlag.Enabled | FluidEmitterFlag.Visualization);

                FluidDescription fluidDesc = new FluidDescription()
                {
                    Emitters         = { fluidEmitterDesc },
                    Flags            = FluidFlag.Enabled | FluidFlag.Visualization,
                    MaximumParticles = maximumParticles
                };
                fluidDesc.ParticleWriteData.AllocatePositionBuffer <Vector3>(maximumParticles);
                fluidDesc.ParticleWriteData.NumberOfParticles = maximumParticles;

                Fluid fluid = _scene.CreateFluid(fluidDesc);

                // Ledge
                {
                    BoxShapeDescription boxShapeDesc = new BoxShapeDescription(5, 0.1f, 5);

                    ActorDescription drainActorDesc = new ActorDescription()
                    {
                        GlobalPose = Matrix.RotationX(0.5f) * Matrix.Translation(-40, 5, 52),
                        Shapes     = { boxShapeDesc }
                    };

                    Actor drianActor = _scene.CreateActor(drainActorDesc);
                }

                // Drain
                {
                    BoxShapeDescription boxShapeDesc = new BoxShapeDescription(5, 0.1f, 5);
                    boxShapeDesc.Flags |= ShapeFlag.FluidDrain;

                    ActorDescription drainActorDesc = new ActorDescription()
                    {
                        GlobalPose = Matrix.Translation(-40, 0, 55),
                        Shapes     = { boxShapeDesc }
                    };

                    Actor drianActor = _scene.CreateActor(drainActorDesc);
                }
            }
            #endregion

            #region Force Field
            {
                BoxForceFieldShapeDescription boxForceFieldShapeDesc = new BoxForceFieldShapeDescription()
                {
                    Size = new Vector3(10, 10, 10)
                };

                ForceFieldLinearKernelDescription kernelDesc = new ForceFieldLinearKernelDescription()
                {
                    Constant = new Vector3(0, 100.0f, 0)
                };

                ForceFieldLinearKernel kernel = _scene.CreateForceFieldLinearKernel(kernelDesc);

                ForceFieldShapeGroupDescription shapeGroupDesc = new ForceFieldShapeGroupDescription()
                {
                    Shapes = { boxForceFieldShapeDesc }
                };

                ForceFieldShapeGroup shapeGroup = _scene.CreateForceFieldShapeGroup(shapeGroupDesc);

                BoxForceFieldShape boxForceFieldShape = shapeGroup.CreateShape(boxForceFieldShapeDesc) as BoxForceFieldShape;
                boxForceFieldShape.Pose = Matrix.Translation(30, 5, 0);

                ForceFieldDescription forceFieldDesc = new ForceFieldDescription()
                {
                    Kernel      = kernel,
                    ShapeGroups = { shapeGroup }
                };
                ForceField forceField = _scene.CreateForceField(forceFieldDesc);
            }
            #endregion

            #region Heightfield
            {
                int rows    = 25;
                int columns = 25;

                HeightFieldSample[] samples = new HeightFieldSample[rows * columns];
                for (int r = 0; r < rows; r++)
                {
                    for (int c = 0; c < columns; c++)
                    {
                        // Put a z and x curve together
                        double h = Math.Sin(c) * Math.Cos(r) * short.MaxValue;

                        HeightFieldSample sample = new HeightFieldSample()
                        {
                            Height           = (short)h,
                            MaterialIndex0   = 0,
                            MaterialIndex1   = 1,
                            TessellationFlag = 0
                        };

                        samples[r * columns + c] = sample;
                    }
                }

                HeightFieldDescription heightFieldDesc = new HeightFieldDescription()
                {
                    NumberOfRows    = rows,
                    NumberOfColumns = columns
                };
                heightFieldDesc.SetSamples(samples);

                HeightField heightField = _core.CreateHeightField(heightFieldDesc);

                //

                HeightFieldShapeDescription heightFieldShapeDesc = new HeightFieldShapeDescription()
                {
                    HeightField  = heightField,
                    HoleMaterial = 2,
                    // The max height of our samples is short.MaxValue and we want it to be 1
                    HeightScale = 1.0f / (float)short.MaxValue,
                    RowScale    = 3,
                    ColumnScale = 3
                };
                heightFieldShapeDesc.LocalPosition = new Vector3(-0.5f * rows * 1 * heightFieldShapeDesc.RowScale, 0, -0.5f * columns * 1 * heightFieldShapeDesc.ColumnScale);

                ActorDescription actorDesc = new ActorDescription()
                {
                    GlobalPose = Matrix.Translation(100, 0, 0),
                    Shapes     = { heightFieldShapeDesc }
                };
                Actor actor = _scene.CreateActor(actorDesc);
            }
            #endregion

            //#region Convex Mesh
            //{
            //    ModelMesh mesh = _torusModel.Meshes.First();

            //    Matrix[] transforms = new Matrix[ _torusModel.Bones.Count ];
            //    _torusModel.CopyAbsoluteBoneTransformsTo( transforms );

            //    // Gets the vertices from the mesh
            //    VertexPositionNormalTexture[] vertices = new VertexPositionNormalTexture[ mesh.MeshParts[ 0 ].NumVertices ];
            //    mesh.VertexBuffer.GetData<VertexPositionNormalTexture>( vertices );

            //    //

            //    // Allocate memory for the points and triangles
            //    var convexMeshDesc = new ConvexMeshDescription()
            //    {
            //        PointCount = vertices.Length
            //    };
            //    convexMeshDesc.Flags |= ConvexFlag.ComputeConvex;
            //    convexMeshDesc.AllocatePoints<Vector3>( vertices.Length );

            //    // Write in the points and triangles
            //    // We only want the Position component of the vertex. Also scale down the mesh
            //    foreach( VertexPositionNormalTexture vertex in vertices )
            //    {
            //        Vector3 position = Vector3.Transform( vertex.Position, Matrix.CreateScale( 0.1f, 0.1f, 0.1f ) * transforms[ 0 ] );

            //        convexMeshDesc.PointsStream.Write( position );
            //    }

            //    //

            //    // Cook to memory or to a file
            //    MemoryStream stream = new MemoryStream();
            //    //FileStream stream = new FileStream( @"Convex Mesh.cooked", FileMode.CreateNew );

            //    Cooking.InitializeCooking( new ConsoleOutputStream() );
            //    Cooking.CookConvexMesh( convexMeshDesc, stream );
            //    Cooking.CloseCooking();

            //    stream.Position = 0;

            //    ConvexMesh convexMesh = _core.CreateConvexMesh( stream );

            //    ConvexShapeDescription convexShapeDesc = new ConvexShapeDescription( convexMesh );

            //    ActorDescription actorDesc = new ActorDescription()
            //    {
            //        BodyDescription = new BodyDescription( 10.0f ),
            //        GlobalPose = Matrix.CreateTranslation( 30, 30, 0 )
            //    };
            //    actorDesc.Shapes.Add( convexShapeDesc );

            //    _torusActor = _scene.CreateActor( actorDesc );
            //}
            //#endregion

            //#region SoftBody
            //if( false ) // Enable to view soft bodies, they run slowly
            //{
            //    XmlDocument doc = new XmlDocument();
            //        doc.Load( "Teapot.xml" );

            //    // Not how NxuStream are meant to used but what ever :S
            //    Vector3[] vertices = ReadVertices( doc.SelectSingleNode( "/NXUSTREAM2/NxuPhysicsCollection/NxSoftBodyMeshDesc/vertices" ) );
            //    int[] tetrahedraSingles = ReadTetrahedra( doc.SelectSingleNode( "/NXUSTREAM2/NxuPhysicsCollection/NxSoftBodyMeshDesc/tetrahedra" ) );

            //    var softBodyMeshDesc = new SoftBodyMeshDescription()
            //    {
            //        VertexCount = vertices.Length,
            //        TetrahedraCount = tetrahedraSingles.Length / 4 // Tetrahedras come in quadruples of ints
            //    };

            //    softBodyMeshDesc.AllocateVertices<Vector3>( softBodyMeshDesc.VertexCount );
            //    softBodyMeshDesc.AllocateTetrahedra<int>( softBodyMeshDesc.TetrahedraCount ); // Note: T is an int. T is the type of each point

            //    softBodyMeshDesc.VertexStream.SetData( vertices );
            //    softBodyMeshDesc.TetrahedraStream.SetData( tetrahedraSingles );

            //    MemoryStream memoryStream = new MemoryStream();

            //    Cooking.InitializeCooking();
            //    Cooking.CookSoftBodyMesh( softBodyMeshDesc, memoryStream );
            //    Cooking.CloseCooking();

            //    memoryStream.Position = 0;

            //    SoftBodyMesh softBodyMesh = _core.CreateSoftBodyMesh( memoryStream );

            //    SoftBodyDescription desc = new SoftBodyDescription()
            //    {
            //        GlobalPose = Matrix.CreateTranslation( -30, 20, -30 ),
            //        SoftBodyMesh = softBodyMesh
            //    };
            //    desc.Flags |= SoftBodyFlag.Visualization;

            //    desc.MeshData.AllocatePositions<Vector3>( vertices.Length );
            //    desc.MeshData.AllocateIndices<int>( tetrahedraSingles.Length );

            //    SoftBody softBody = _scene.CreateSoftBody( desc );
            //}
            //#endregion

            //#region Reports
            //// Contact report
            //// When the capsule actor hits the ground make it bounce by using the conact report
            //{
            //    CapsuleShapeDescription capsuleShapeDesc = new CapsuleShapeDescription( 1, 5 );

            //    ActorDescription actorDesc = new ActorDescription()
            //    {
            //        GlobalPose = Matrix.CreateTranslation( -30, 20, 0 ),
            //        BodyDescription = new BodyDescription( 10.0f ),
            //        Name = "Report Capsule",
            //        Shapes = { capsuleShapeDesc }
            //    };

            //    _contactReportActor = _scene.CreateActor( actorDesc );

            //    _scene.SetActorPairFlags( _contactReportActor, _groundActor, ContactPairFlag.All );

            //    _scene.UserContactReport = new ContactReport( this );
            //}

            //// Trigger Reports
            //{
            //    BoxShapeDescription boxShapeDesc = new BoxShapeDescription( 15, 8, 15 );
            //        boxShapeDesc.Flags |= ( ShapeFlag.TriggerOnEnter | ShapeFlag.TriggerOnLeave );

            //    ActorDescription actorDesc = new ActorDescription()
            //    {
            //        GlobalPose = Matrix.CreateTranslation( -30, 4, 0 ),
            //        Shapes = { boxShapeDesc }
            //    };
            //    _scene.CreateActor( actorDesc );

            //    _scene.UserTriggerReport = new TriggerReport( this );
            //}

            //_scene.UserNotify = new Notify( this );
            //#endregion

            //#region Wheel
            //{
            //    _basicVehicle = new Vehicle( this );
            //}
            //#endregion

            #region Controller
            {
                ControllerManager manager = _scene.CreateControllerManager();

                CapsuleControllerDescription capsuleControllerDesc = new CapsuleControllerDescription(4, 3);

                CapsuleController capsuleController = manager.CreateController <CapsuleController>(capsuleControllerDesc);
                capsuleController.Position   = new Vector3(0, 1.5f + 2, -15);
                capsuleController.Actor.Name = "BoxController";
                capsuleController.SetCollisionEnabled(true);
            }
            #endregion
        }
Exemplo n.º 50
0
        protected override void LoadContent(GraphicInfo GraphicInfo, GraphicFactory factory, IContentManager contentManager)
        {
            PhysxPhysicWorld PhysxPhysicWorld = World.PhysicWorld as PhysxPhysicWorld;

            base.LoadContent(GraphicInfo, factory, contentManager);

            // Create a simple fluid description with fluids and visualization enabled
            FluidDescription fluidDesc = new FluidDescription()
            {
                Flags = FluidFlag.Enabled | FluidFlag.Visualization,
            };

            // Store our particle positions somewhere (as our particle generation function below generates and unknown number of particles at runtime we need a list instead of an array)
            var particlePositions = new List <Phyx.Vector3>();

            // Move all the particles by this offset
            Phyx.Vector3 position = new Phyx.Vector3(0, 20, 0);

            // Number of particles in the x, y and z directions
            int   sideNum  = 10;
            float distance = 1f;

            float radius = sideNum * distance * 0.5f;

            for (int i = 0; i < sideNum; i++)
            {
                for (int j = 0; j < sideNum; j++)
                {
                    for (int k = 0; k < sideNum; k++)
                    {
                        Phyx.Vector3 p = new Phyx.Vector3(i * distance, j * distance, k * distance);

                        if ((p - new Phyx.Vector3(radius, radius, radius)).Length() < radius)
                        {
                            p += position - new Phyx.Vector3(radius, radius, radius);

                            particlePositions.Add(p);
                        }
                    }
                }
            }

            // Allocate memory for the initial particle positions to be stored in
            // And then set the position buffer
            fluidDesc.InitialParticleData.AllocatePositionBuffer <Phyx.Vector3>(particlePositions.Count);
            fluidDesc.InitialParticleData.NumberOfParticles = particlePositions.Count;
            fluidDesc.InitialParticleData.PositionBuffer.SetData(particlePositions.ToArray());

            // Allocate memory for PhysX to store the position of each particle
            fluidDesc.ParticleWriteData.AllocatePositionBuffer <Phyx.Vector3>(particlePositions.Count);
            fluidDesc.ParticleWriteData.NumberOfParticles = particlePositions.Count;

            InstancedBilboardModel          InstancedBilboardModel          = new InstancedBilboardModel(factory, "teste", "Textures/Smoke", new BilboardInstance[] { new BilboardInstance() }, particlePositions.Count);
            PhysxFluidObject                PhysxFluidObject                = new PloobsEngine.Physics.PhysxFluidObject(fluidDesc);
            DeferredInstancedBilboardShader DeferredInstancedBilboardShader = new PloobsEngine.Material.DeferredInstancedBilboardShader(BilboardType.Spherical);

            DeferredInstancedBilboardShader.AlphaTestLimit = 0.2f;
            FluidMaterial DeferredMaterial = new FluidMaterial(DeferredInstancedBilboardShader, particlePositions.Count, new Vector2(0.2f));
            IObject       IObject          = new IObject(DeferredMaterial, InstancedBilboardModel, PhysxFluidObject);

            this.World.AddObject(IObject);


            // Ledge
            {
                var         boxShapeDesc = new BoxShapeDescription(10, 0.2f, 10);
                SimpleModel SimpleModel  = new PloobsEngine.Modelo.SimpleModel(factory, "Model/block");
                SimpleModel.SetTexture(factory.CreateTexture2DColor(1, 1, Color.Red), TextureType.DIFFUSE);

                PhysxPhysicObject PhysxPhysicObject = new PloobsEngine.Physics.PhysxPhysicObject(boxShapeDesc,
                                                                                                 (Phyx.Matrix.RotationZ(0.3f) *
                                                                                                  Phyx.Matrix.Translation(0, 5, 0)).AsXNA(), new Vector3(10, 0.2f, 10));
                DeferredNormalShader shader    = new DeferredNormalShader();
                DeferredMaterial     fmaterial = new DeferredMaterial(shader);
                IObject obj = new IObject(fmaterial, SimpleModel, PhysxPhysicObject);
                this.World.AddObject(obj);
            }

            #region NormalLight
            DirectionalLightPE ld1 = new DirectionalLightPE(Vector3.Left, Color.White);
            DirectionalLightPE ld2 = new DirectionalLightPE(Vector3.Right, Color.White);
            DirectionalLightPE ld3 = new DirectionalLightPE(Vector3.Backward, Color.White);
            DirectionalLightPE ld4 = new DirectionalLightPE(Vector3.Forward, Color.White);
            DirectionalLightPE ld5 = new DirectionalLightPE(Vector3.Down, Color.White);
            float li = 0.5f;
            ld1.LightIntensity = li;
            ld2.LightIntensity = li;
            ld3.LightIntensity = li;
            ld4.LightIntensity = li;
            ld5.LightIntensity = li;
            this.World.AddLight(ld1);
            this.World.AddLight(ld2);
            this.World.AddLight(ld3);
            this.World.AddLight(ld4);
            this.World.AddLight(ld5);
            #endregion


            BallThrowPhysx28 BallThrowBullet = new BallThrowPhysx28(this.World, GraphicFactory, false);
            this.AttachCleanUpAble(BallThrowBullet);

            this.World.CameraManager.AddCamera(new CameraFirstPerson(GraphicInfo));
        }
        protected override void LoadContent(GraphicInfo GraphicInfo, GraphicFactory factory, IContentManager contentManager)
        {
            PhysxPhysicWorld PhysxPhysicWorld = World.PhysicWorld as PhysxPhysicWorld;

            base.LoadContent(GraphicInfo, factory, contentManager);

            const int maximumParticles = 1000;
            var       fluidEmitterDesc = new FluidEmitterDescription()
            {
                DimensionX   = 0.5f,
                DimensionY   = 0.5f,
                Rate         = 15,
                RelativePose =
                    Phyx.Matrix.RotationAxis(new Phyx.Vector3(0, 1, 0), (float)Math.PI) *
                    Phyx.Matrix.Translation(-40, 10, -50),
                Shape       = EmitterShape.Rectangular,
                Type        = EmitterType.ConstantFlowRate,
                RandomAngle = 0.5f
            };

            fluidEmitterDesc.Flags |= (FluidEmitterFlag.Enabled | FluidEmitterFlag.Visualization);

            var fluidDesc = new FluidDescription()
            {
                Emitters         = { fluidEmitterDesc },
                Flags            = FluidFlag.Enabled | FluidFlag.Visualization | FluidFlag.Enabled,
                MaximumParticles = maximumParticles,
            };

            fluidDesc.ParticleWriteData.AllocatePositionBuffer <Vector3>(maximumParticles);
            fluidDesc.ParticleWriteData.NumberOfParticles = maximumParticles;

            InstancedBilboardModel          InstancedBilboardModel          = new InstancedBilboardModel(factory, "teste", "Textures/Smoke", new BilboardInstance[] { new BilboardInstance() }, maximumParticles);
            PhysxFluidObject                PhysxFluidObject                = new PloobsEngine.Physics.PhysxFluidObject(fluidDesc);
            DeferredInstancedBilboardShader DeferredInstancedBilboardShader = new PloobsEngine.Material.DeferredInstancedBilboardShader(BilboardType.Spherical);

            DeferredInstancedBilboardShader.AlphaTestLimit = 0.2f;
            FluidMaterial DeferredMaterial = new FluidMaterial(DeferredInstancedBilboardShader, maximumParticles, new Vector2(0.2f));
            IObject       IObject          = new IObject(DeferredMaterial, InstancedBilboardModel, PhysxFluidObject);

            this.World.AddObject(IObject);


            // Ledge
            {
                var         boxShapeDesc = new BoxShapeDescription(5, 0.1f, 5);
                SimpleModel SimpleModel  = new PloobsEngine.Modelo.SimpleModel(factory, "Model/block");
                SimpleModel.SetTexture(factory.CreateTexture2DColor(1, 1, Color.Red), TextureType.DIFFUSE);

                PhysxPhysicObject PhysxPhysicObject = new PloobsEngine.Physics.PhysxPhysicObject(boxShapeDesc,
                                                                                                 (Phyx.Matrix.RotationX(-0.5f) * Phyx.Matrix.Translation(-40, 5, -52)).AsXNA(), new Vector3(5, 0.1f, 5));
                DeferredNormalShader shader    = new DeferredNormalShader();
                DeferredMaterial     fmaterial = new DeferredMaterial(shader);
                IObject obj = new IObject(fmaterial, SimpleModel, PhysxPhysicObject);
                this.World.AddObject(obj);
            }

            // Drain
            {
                var boxShapeDesc = new BoxShapeDescription(5, 0.1f, 5);
                boxShapeDesc.Flags |= ShapeFlag.FluidDrain;

                var drainActorDesc = new ActorDescription()
                {
                    GlobalPose = Phyx.Matrix.Translation(-40, 0, -55),
                    Shapes     = { boxShapeDesc }
                };

                var drianActor = PhysxPhysicWorld.Scene.CreateActor(drainActorDesc);
            }

            #region NormalLight
            DirectionalLightPE ld1 = new DirectionalLightPE(Vector3.Left, Color.White);
            DirectionalLightPE ld2 = new DirectionalLightPE(Vector3.Right, Color.White);
            DirectionalLightPE ld3 = new DirectionalLightPE(Vector3.Backward, Color.White);
            DirectionalLightPE ld4 = new DirectionalLightPE(Vector3.Forward, Color.White);
            DirectionalLightPE ld5 = new DirectionalLightPE(Vector3.Down, Color.White);
            float li = 0.5f;
            ld1.LightIntensity = li;
            ld2.LightIntensity = li;
            ld3.LightIntensity = li;
            ld4.LightIntensity = li;
            ld5.LightIntensity = li;
            this.World.AddLight(ld1);
            this.World.AddLight(ld2);
            this.World.AddLight(ld3);
            this.World.AddLight(ld4);
            this.World.AddLight(ld5);
            #endregion


            BallThrowPhysx28 BallThrowBullet = new BallThrowPhysx28(this.World, GraphicFactory, false);
            this.AttachCleanUpAble(BallThrowBullet);

            this.World.CameraManager.AddCamera(new CameraFirstPerson(GraphicInfo));
        }
Exemplo n.º 52
0
        private void CreateTower(Nx.Material material, NxVector3 descriptor, int xCount, int yCount, int zCount, float xSpace, float ySpace, float zSpace, float xOffset, float yOffset, float zOffset)
        {
            for (int x = 0; x < xCount; x++)
                for (int y = 0; y < yCount; y++)
                    for (int z = 0; z < zCount; z++)
                    {
                        var rigidBodyDesc = new BodyDescription();

                        var boxDesc = new BoxShapeDescription
                                          {
                                              Material = material,
                                              Dimensions = new NxVector3(descriptor.X / 2, descriptor.Y / 2, descriptor.Z / 2)
                                          };

                        var actorDesc = new ActorDescription(boxDesc)
                                            {
                                                BodyDescription = rigidBodyDesc,
                                                Density = 10.0f,
                                                GlobalPose = NxMath.Matrix.Translation(
                                                                       xOffset + x * xSpace - ((xCount - 1) * xSpace / 2),
                                                                       yOffset + y * ySpace - ((yCount - 1) * ySpace / 2),
                                                                       zOffset + z * zSpace - ((zCount - 1) * zSpace / 2)),
                                                UserData = _boxModel
                                            };

                        if (!actorDesc.IsValid())
                            throw new Exception("ActorDesc invalid!");

                        var actor = _scene.CreateActor(actorDesc);
                        if (actor == null)
                            throw new Exception("Actor invalid!");
                    }
        }
        protected override void LoadContent(GraphicInfo GraphicInfo, GraphicFactory factory ,IContentManager contentManager)
        {
            PhysxPhysicWorld PhysxPhysicWorld = World.PhysicWorld as PhysxPhysicWorld;
            
            base.LoadContent(GraphicInfo, factory, contentManager);

            const int maximumParticles = 1000;
            var fluidEmitterDesc = new FluidEmitterDescription()
            {
                DimensionX = 0.5f,
                DimensionY = 0.5f,
                Rate = 15,
                RelativePose =
                    Phyx.Matrix.RotationAxis(new Phyx.Vector3(0, 1, 0), (float)Math.PI) *
                    Phyx.Matrix.Translation(-40, 10, -50),
                Shape = EmitterShape.Rectangular,
                Type = EmitterType.ConstantFlowRate,
                RandomAngle = 0.5f
            };
            fluidEmitterDesc.Flags |= (FluidEmitterFlag.Enabled | FluidEmitterFlag.Visualization);

            var fluidDesc = new FluidDescription()
            {
                Emitters = { fluidEmitterDesc },
                Flags = FluidFlag.Enabled | FluidFlag.Visualization | FluidFlag.Enabled,
                MaximumParticles = maximumParticles,
                
            };
            fluidDesc.ParticleWriteData.AllocatePositionBuffer<Vector3>(maximumParticles);
            fluidDesc.ParticleWriteData.NumberOfParticles = maximumParticles;

            InstancedBilboardModel InstancedBilboardModel = new InstancedBilboardModel(factory, "teste", "Textures/Smoke", new BilboardInstance[] {new BilboardInstance() }, maximumParticles);
            PhysxFluidObject PhysxFluidObject = new PloobsEngine.Physics.PhysxFluidObject(fluidDesc);
            DeferredInstancedBilboardShader DeferredInstancedBilboardShader = new PloobsEngine.Material.DeferredInstancedBilboardShader(BilboardType.Spherical);
            DeferredInstancedBilboardShader.AlphaTestLimit = 0.2f;
            FluidMaterial DeferredMaterial = new FluidMaterial(DeferredInstancedBilboardShader,maximumParticles,new Vector2(0.2f));
            IObject IObject = new IObject(DeferredMaterial, InstancedBilboardModel, PhysxFluidObject);
            this.World.AddObject(IObject);


            // Ledge
            {
                var boxShapeDesc = new BoxShapeDescription(5, 0.1f, 5);
                SimpleModel SimpleModel = new PloobsEngine.Modelo.SimpleModel(factory, "Model/block");
                SimpleModel.SetTexture(factory.CreateTexture2DColor(1, 1, Color.Red), TextureType.DIFFUSE);

                PhysxPhysicObject PhysxPhysicObject = new PloobsEngine.Physics.PhysxPhysicObject(boxShapeDesc,
                    (Phyx.Matrix.RotationX(-0.5f) * Phyx.Matrix.Translation(-40, 5, -52)).AsXNA(),new Vector3(5,0.1f,5));
                DeferredNormalShader shader = new DeferredNormalShader();
                DeferredMaterial fmaterial = new DeferredMaterial(shader);
                IObject obj = new IObject(fmaterial, SimpleModel, PhysxPhysicObject);
                this.World.AddObject(obj);
            }

            // Drain
            {
                var boxShapeDesc = new BoxShapeDescription(5, 0.1f, 5);
                boxShapeDesc.Flags |= ShapeFlag.FluidDrain;

                var drainActorDesc = new ActorDescription()
                {
                    GlobalPose = Phyx.Matrix.Translation(-40, 0, -55),
                    Shapes = { boxShapeDesc }
                };

                var drianActor = PhysxPhysicWorld.Scene.CreateActor(drainActorDesc);
            }

            #region NormalLight
            DirectionalLightPE ld1 = new DirectionalLightPE(Vector3.Left, Color.White);
            DirectionalLightPE ld2 = new DirectionalLightPE(Vector3.Right, Color.White);
            DirectionalLightPE ld3 = new DirectionalLightPE(Vector3.Backward, Color.White);
            DirectionalLightPE ld4 = new DirectionalLightPE(Vector3.Forward, Color.White);
            DirectionalLightPE ld5 = new DirectionalLightPE(Vector3.Down, Color.White);
            float li = 0.5f;
            ld1.LightIntensity = li;
            ld2.LightIntensity = li;
            ld3.LightIntensity = li;
            ld4.LightIntensity = li;
            ld5.LightIntensity = li;
            this.World.AddLight(ld1);
            this.World.AddLight(ld2);
            this.World.AddLight(ld3);
            this.World.AddLight(ld4);
            this.World.AddLight(ld5);
            #endregion


            BallThrowPhysx28 BallThrowBullet = new BallThrowPhysx28(this.World, GraphicFactory,false);
            this.AttachCleanUpAble(BallThrowBullet);

            this.World.CameraManager.AddCamera(new CameraFirstPerson(GraphicInfo));
        }
        protected override void LoadContent(GraphicInfo GraphicInfo, GraphicFactory factory ,IContentManager contentManager)
        {
            PhysxPhysicWorld PhysxPhysicWorld = World.PhysicWorld as PhysxPhysicWorld;
            
            base.LoadContent(GraphicInfo, factory, contentManager);

            const int maximumParticles = 3000;

            ///Remember
            ///There are 2 math apis (XNA AND PHYSX)
            ///Sometimes we need to convert between then
            ///Use the extension methods AsPhysx() in XNA API and AsXNA in Physx APi

            ///emitter
            var fluidEmitterDesc = new FluidEmitterDescription()
            {
                DimensionX = 1.5f,
                DimensionY = 1.5f,
                Rate = 65,
                RelativePose =
                    Phyx.Matrix.RotationAxis(new Phyx.Vector3(0, 1, 0), (float)Math.PI) *
                    Phyx.Matrix.Translation(-40, 10, -50),
                Shape = EmitterShape.Rectangular,
                Type = EmitterType.ConstantFlowRate,
                RandomAngle = 0.5f,
                

            };
            fluidEmitterDesc.Flags |= (FluidEmitterFlag.Enabled | FluidEmitterFlag.Visualization);

            ///fluid
            var fluidDesc = new FluidDescription()
            {
                Emitters = { fluidEmitterDesc },
                Flags = FluidFlag.Enabled | FluidFlag.Visualization,
                MaximumParticles = maximumParticles,
                
                
            };
            
            fluidDesc.ParticleWriteData.AllocatePositionBuffer<Vector3>(maximumParticles);
            fluidDesc.ParticleWriteData.NumberOfParticles = maximumParticles;            

            
            ///create and add the fluid to the world
            fluid = PhysxPhysicWorld.Scene.CreateFluid(fluidDesc);

            
            ///Use Billboards to render the fuild particles (dummy way)
            Texture2D tex = factory.GetTexture2D("Textures/Smoke");
            for (int i = 0; i < maximumParticles; i++)
            {
                Billboard3D Billboard3D = new Billboard3D(tex,Vector3.Zero,new Vector2(0.001f));
                Billboard3D.Enabled = false;
                CPUSphericalBillboardComponent.Billboards.Add(Billboard3D);
            }


            // Ledge
            {
                var boxShapeDesc = new BoxShapeDescription(5, 0.1f, 5);
                SimpleModel SimpleModel = new PloobsEngine.Modelo.SimpleModel(factory, "Model/block");
                SimpleModel.SetTexture(factory.CreateTexture2DColor(1, 1, Color.Red), TextureType.DIFFUSE);
                PhysxPhysicObject PhysxPhysicObject = new PloobsEngine.Physics.PhysxPhysicObject(boxShapeDesc,
                    (Phyx.Matrix.RotationX(-0.5f) * Phyx.Matrix.Translation(-40, 5, -52)).AsXNA(),new Vector3(5,0.1f,5));
                ForwardXNABasicShader shader = new ForwardXNABasicShader(ForwardXNABasicShaderDescription.Default());
                ForwardMaterial fmaterial = new ForwardMaterial(shader);
                IObject obj = new IObject(fmaterial, SimpleModel, PhysxPhysicObject);
                this.World.AddObject(obj);
            }

            // Drain
            {
                var boxShapeDesc = new BoxShapeDescription(5, 0.1f, 5);
                boxShapeDesc.Flags |= ShapeFlag.FluidDrain;

                var drainActorDesc = new ActorDescription()
                {
                    GlobalPose = Phyx.Matrix.Translation(-40, -20, -55),
                    Shapes = { boxShapeDesc }
                };

                var drianActor = PhysxPhysicWorld.Scene.CreateActor(drainActorDesc);
            }            

            BallThrowPhysx28 BallThrowBullet = new BallThrowPhysx28(this.World, GraphicFactory);
            BallThrowBullet.ballSize = 1f;
            BallThrowBullet.Speed = 25;
            this.AttachCleanUpAble(BallThrowBullet);

            CameraFirstPerson CameraFirstPerson = new CameraFirstPerson(GraphicInfo);
            CameraFirstPerson.Position = new Vector3(-35, 8, -52);
            CameraFirstPerson.LeftRightRot = MathHelper.ToRadians(125);
            this.World.CameraManager.AddCamera(CameraFirstPerson);
        }