Exemplo n.º 1
0
        public void Build(int columnIndex, int rowIndex, int sliceIndex, out BodyDescription bodyDescription)
        {
            bodyDescription = new BodyDescription
            {
                Pose = new RigidPose
                {
                    Position    = new Vector3(columnIndex, rowIndex, sliceIndex) * Spacing + Origin,
                    Orientation = BepuUtilities.Quaternion.Identity
                },
                LocalInertia = new BodyInertia {
                    InverseMass = 1
                },
                Collidable = new CollidableDescription
                {
                    Continuity        = new ContinuousDetectionSettings(),
                    SpeculativeMargin = 0.1f,
                    Shape             = ShapeIndex
                }
            };

            var inverseInertia = bodyDescription.LocalInertia.InverseMass * InverseInertiaMultiplier;

            bodyDescription.LocalInertia.InverseInertiaTensor.M11 = inverseInertia;
            bodyDescription.LocalInertia.InverseInertiaTensor.M22 = inverseInertia;
            bodyDescription.LocalInertia.InverseInertiaTensor.M33 = inverseInertia;
        }
Exemplo n.º 2
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.º 3
0
 public void Build(int columnIndex, int rowIndex, int sliceIndex, out BodyDescription bodyDescription)
 {
     bodyDescription = new BodyDescription
     {
         Pose = new RigidPose
         {
             Position    = new Vector3(columnIndex, rowIndex, sliceIndex) * Spacing + Origin,
             Orientation = BepuUtilities.Quaternion.Identity
                           //Orientation = BepuUtilities.Quaternion.CreateFromAxisAngle(Vector3.Normalize(new Vector3(1, 1, 1)), MathHelper.PiOver4 * 9.83f)
                           //Orientation = BepuUtilities.Quaternion.CreateFromAxisAngle(Vector3.Normalize(new Vector3(0, 1, 0)), rowIndex * MathHelper.Pi * 0.1f)
         },
         LocalInertia = LocalInertia,
         Collidable   = new CollidableDescription
         {
             Continuity        = new ContinuousDetectionSettings(),
             SpeculativeMargin = 0.04f,
             Shape             = ShapeIndex
         },
         Activity = new BodyActivityDescription
         {
             SleepThreshold = .01f,
             MinimumTimestepCountUnderThreshold = 32
         },
         //Velocity = new BodyVelocity { Angular = new Vector3(0, (rowIndex % 2 - 0.5f) * 20, 0) }
         //Velocity = new BodyVelocity { Angular = new Vector3(1, 0, 0) }
     };
 }
Exemplo n.º 4
0
        public unsafe override void Initialize(ContentArchive content, Camera camera)
        {
            camera.Position = new Vector3(0, 10, 40);
            camera.Yaw      = 0;
            camera.Pitch    = 0;
            Simulation      = Simulation.Create(BufferPool, new DemoNarrowPhaseCallbacks(), new DemoPoseIntegratorCallbacks(new Vector3(0, -10, 0)), new PositionFirstTimestepper());

            var box     = new Box(2f, 2f, 2f);
            var capsule = new Capsule(1f, 1f);
            var sphere  = new Sphere(1.5f);

            box.ComputeInertia(1, out var boxInertia);
            capsule.ComputeInertia(1, out var capsuleInertia);
            sphere.ComputeInertia(1, out var sphereInertia);
            var       boxIndex     = Simulation.Shapes.Add(box);
            var       capsuleIndex = Simulation.Shapes.Add(capsule);
            var       sphereIndex  = Simulation.Shapes.Add(sphere);
            const int width        = 12;
            const int height       = 3;
            const int length       = 12;

            for (int i = 0; i < width; ++i)
            {
                for (int j = 0; j < height; ++j)
                {
                    for (int k = 0; k < length; ++k)
                    {
                        var location = new Vector3(5, 5, 5) * new Vector3(i, j, k) + new Vector3(-width * 2.5f, 2.5f, -length * 2.5f);
                        //CreateKinematic is just a helper function that sets the inertia to all zeroes. We'll set the inertia to the actual value in the following switch.
                        var bodyDescription = BodyDescription.CreateKinematic(location, new CollidableDescription(default, 0.1f), new BodyActivityDescription(0.1f));
Exemplo n.º 5
0
        private BodyDescription CreateBoxDescription(float width, float height, float lenght)
        {
            var boxShape      = new Box(width, height, lenght);
            var boxShapeIndex = Simulation.Shapes.Add(boxShape);

            boxShape.ComputeInertia(1, out var boxInertia);
            Symmetric3x3.Scale(boxInertia.InverseInertiaTensor, .5f, out boxInertia.InverseInertiaTensor);
            var boxDescription = new BodyDescription()
            {
                LocalInertia = boxInertia,
                Pose         = new RigidPose
                {
                    Position    = Vector3.Zero,
                    Orientation = Quaternion.Identity
                },
                Activity = new BodyActivityDescription {
                    MinimumTimestepCountUnderThreshold = 32, SleepThreshold = .01f
                },
                Collidable = new CollidableDescription {
                    Shape = boxShapeIndex, SpeculativeMargin = .1f
                },
            };

            return(boxDescription);
        }
Exemplo n.º 6
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.º 7
0
        private PhyObject CreateVanilla(ObjectState state, CollidableDescription collidableDescription, BodyInertia bodyInertia)
        {
            PhyObject phy;

            if (state.mass != 0)
            {
                BodyDescription boxDescription = BodyDescription.CreateDynamic(state.position, bodyInertia,
                                                                               collidableDescription,
                                                                               new BodyActivityDescription(0.01f));

                boxDescription.Pose = new RigidPose(state.position, state.quaternion);
                var bodyHandle = Simulation.Bodies.Add(boxDescription);



                phy = SetUpPhyObject(bodyHandle, state);
                objectsHandlers.Add(bodyHandle, phy);
            }
            else
            {
                StaticDescription description = new StaticDescription(state.position, state.quaternion, collidableDescription);
                StaticHandle      handle      = Simulation.Statics.Add(description);
                //collidableMaterials.Allocate(handle) = new SimpleMaterial { FrictionCoefficient = 1, MaximumRecoveryVelocity = float.MaxValue, SpringSettings = new SpringSettings(1f, 1f) };
                phy = SetUpPhyObject(handle, state);
                staticObjectsHandlers.Add(handle, (StaticPhyObject)phy);
                //objectsHandlers.Add(handle,phy);
            }


            return(phy);
        }
Exemplo n.º 8
0
 public MovingPlatform(CollidableDescription collidable, double timeOffset, float goalSatisfactionTime, Simulation simulation, Func <double, RigidPose> poseCreator)
 {
     PoseCreator = poseCreator;
     BodyHandle  = simulation.Bodies.Add(BodyDescription.CreateKinematic(poseCreator(timeOffset), collidable, new BodyActivityDescription(-1)));
     InverseGoalSatisfactionTime = 1f / goalSatisfactionTime;
     TimeOffset = timeOffset;
 }
Exemplo n.º 9
0
        static BodyReference AddBody <TShape>(TShape shape, float mass, RigidPose pose, Simulation simulation) where TShape : struct, IConvexShape
        {
            var shapeIndex = simulation.Shapes.Add(shape);

            shape.ComputeInertia(mass, out var inertia);
            var description = new BodyDescription
            {
                Activity = new BodyActivityDescription {
                    SleepThreshold = 0, MinimumTimestepCountUnderThreshold = 32
                },
                Collidable = new CollidableDescription
                {
                    Continuity = new ContinuousDetectionSettings {
                        Mode = ContinuousDetectionMode.Discrete
                    },
                    SpeculativeMargin = .1f,
                    //Note that this always registers a new shape instance. You could be more clever/efficient and share shapes, but the goal here is to show the most basic option.
                    //Also, the cost of registering different shapes isn't that high for tiny implicit shapes.
                    Shape = shapeIndex
                },
                LocalInertia = inertia,
                Pose         = pose
            };

            return(new BodyReference(simulation.Bodies.Add(description), simulation.Bodies));
        }
Exemplo n.º 10
0
        public override void Initialize(ContentArchive content, Camera camera)
        {
            camera.Position = new Vector3(0, 7, 20);
            camera.Yaw      = 0;
            camera.Pitch    = 0;

            //The PositionFirstTimestepper is the simplest timestepping mode, but since it integrates velocity into position at the start of the frame, directly modified velocities outside of the timestep
            //will be integrated before collision detection or the solver has a chance to intervene. That's fine in this demo. Other built-in options include the PositionLastTimestepper and the SubsteppingTimestepper.
            //Note that the timestepper also has callbacks that you can use for executing logic between processing stages, like BeforeCollisionDetection.
            Simulation = Simulation.Create(BufferPool, new DemoNarrowPhaseCallbacks(), new DemoPoseIntegratorCallbacks(new Vector3(0, -10, 0)), new PositionFirstTimestepper());

            Simulation.Statics.Add(new StaticDescription(new Vector3(), new CollidableDescription(Simulation.Shapes.Add(new Box(100, 1, 100)), 0.1f)));

            var random      = new Random(5);
            var shapeToDrop = new Box(1, 1, 1);

            shapeToDrop.ComputeInertia(1, out var shapeToDropInertia);
            var descriptionToDrop = BodyDescription.CreateDynamic(new Vector3(), shapeToDropInertia, new CollidableDescription(Simulation.Shapes.Add(shapeToDrop), 0.3f), new BodyActivityDescription(0.01f));

            for (int i = 0; i < 128; ++i)
            {
                descriptionToDrop.Pose.Position = new Vector3(-5 + 10 * (float)random.NextDouble(), 45 + 150 * (float)random.NextDouble(), -5 + 10 * (float)random.NextDouble());
                Simulation.Bodies.Add(descriptionToDrop);
            }

            //Add in a static object to test against. Note that the mesh triangles are one sided, so some of the queries whose centers are beneath the mesh do not generate any contacts.
            DemoMeshHelper.CreateDeformedPlane(20, 20, (x, y) => { return(new Vector3(x * 5 - 50, 3 * MathF.Sin(x) * MathF.Sin(y), y * 5 - 50)); }, Vector3.One, BufferPool, out var mesh);
            Simulation.Statics.Add(new StaticDescription(new Vector3(0, 0, 0), new CollidableDescription(Simulation.Shapes.Add(mesh), 0.1f)));
        }
Exemplo n.º 11
0
        public unsafe override void Initialize(ContentArchive content, Camera camera)
        {
            camera.Position = new Vector3(-70, 8, 318);
            camera.Yaw      = MathHelper.Pi * 1f / 4;
            camera.Pitch    = 0;
            Simulation      = Simulation.Create(BufferPool, new DemoNarrowPhaseCallbacks(), new DemoPoseIntegratorCallbacks(new Vector3(0, -10, 0)), new PositionFirstTimestepper());

            var boxShape = new Box(1, 1, 1);

            boxShape.ComputeInertia(1, out var boxInertia);
            var       boxIndex     = Simulation.Shapes.Add(boxShape);
            const int pyramidCount = 120;

            for (int pyramidIndex = 0; pyramidIndex < pyramidCount; ++pyramidIndex)
            {
                const int rowCount = 20;
                for (int rowIndex = 0; rowIndex < rowCount; ++rowIndex)
                {
                    int columnCount = rowCount - rowIndex;
                    for (int columnIndex = 0; columnIndex < columnCount; ++columnIndex)
                    {
                        Simulation.Bodies.Add(BodyDescription.CreateDynamic(new Vector3(
                                                                                (-columnCount * 0.5f + columnIndex) * boxShape.Width,
                                                                                (rowIndex + 0.5f) * boxShape.Height,
                                                                                (pyramidIndex - pyramidCount * 0.5f) * (boxShape.Length + 4)),
                                                                            boxInertia,
                                                                            new CollidableDescription(boxIndex, 0.1f),
                                                                            new BodyActivityDescription(0.01f)));
                    }
                }
            }

            Simulation.Statics.Add(new StaticDescription(new Vector3(0, -0.5f, 0), new CollidableDescription(Simulation.Shapes.Add(new Box(2500, 1, 2500)), 0.1f)));
        }
Exemplo n.º 12
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.º 13
0
        public void Build(int columnIndex, int rowIndex, int sliceIndex, out BodyDescription bodyDescription)
        {
            bodyDescription = new BodyDescription
            {
                Pose = new RigidPose
                {
                    Position    = new Vector3(columnIndex, rowIndex, sliceIndex) * Spacing + Origin,
                    Orientation = BepuUtilities.Quaternion.Identity
                },
                LocalInertia = new BodyInertia {
                    InverseMass = rowIndex > 0 ? 1 : 0
                },
                Collidable = new CollidableDescription
                {
                    Continuity        = new ContinuousDetectionSettings(),
                    SpeculativeMargin = 0.1f,
                    Shape             = ShapeIndex
                },
                Activity = new BodyActivityDescription
                {
                    SleepThreshold = 0.1f,
                    MinimumTimestepCountUnderThreshold = 16
                }
            };

            var inverseInertia = bodyDescription.LocalInertia.InverseMass * InverseInertiaMultiplier;

            bodyDescription.LocalInertia.InverseInertiaTensor.XX = inverseInertia;
            bodyDescription.LocalInertia.InverseInertiaTensor.YY = inverseInertia;
            bodyDescription.LocalInertia.InverseInertiaTensor.ZZ = inverseInertia;
        }
Exemplo n.º 14
0
        public unsafe override void Initialize(ContentArchive content, Camera camera)
        {
            camera.Position = new Vector3(20, 10, 20);
            camera.Yaw      = MathHelper.Pi * -1f / 4;
            camera.Pitch    = MathHelper.Pi * 0.05f;
            var masks = new CollidableProperty <ulong>();

            characters = new CharacterControllers(BufferPool);
            Simulation = Simulation.Create(BufferPool, new CharacterNarrowphaseCallbacks(characters), new DemoPoseIntegratorCallbacks(new Vector3(0, -10, 0)), new PositionFirstTimestepper());

            var random = new Random(5);

            for (int i = 0; i < 8192; ++i)
            {
                ref var character = ref characters.AllocateCharacter(
                    Simulation.Bodies.Add(
                        BodyDescription.CreateDynamic(
                            new Vector3(250 * (float)random.NextDouble() - 125, 2, 250 * (float)random.NextDouble() - 125), new BodyInertia {
                    InverseMass = 1
                },
                            new CollidableDescription(Simulation.Shapes.Add(new Capsule(0.5f, 1f)), 0.1f),
                            new BodyActivityDescription(-1))));

                character.CosMaximumSlope                 = .707f;
                character.LocalUp                         = Vector3.UnitY;
                character.MaximumHorizontalForce          = 10;
                character.MaximumVerticalForce            = 10;
                character.MinimumSupportContinuationDepth = -0.1f;
                character.MinimumSupportDepth             = -0.01f;
                character.TargetVelocity                  = new Vector2(4, 0);
                character.ViewDirection                   = new Vector3(0, 0, -1);
                character.JumpVelocity                    = 4;
            }
Exemplo n.º 15
0
        private void AddBody <T>() where T : unmanaged, IConvexShape
        {
            T withType = (T)colliderShape;

            colliderShape.ComputeInertia(mass, out BodyInertia inertia);

            if (isStatic)
            {
                staticHandle = PhysicsHandler.Simulation.Statics.Add(
                    new StaticDescription(
                        parent.Movement.Position,
                        new CollidableDescription(
                            PhysicsHandler.Simulation.Shapes.Add(withType),
                            0.1f
                            )
                        )
                    );
            }
            else
            {
                bodyHandle = PhysicsHandler.Simulation.Bodies.Add(
                    BodyDescription.CreateDynamic(
                        parent.Movement.Position,
                        inertia,
                        new CollidableDescription(
                            PhysicsHandler.Simulation.Shapes.Add(withType),
                            0.1f
                            ),
                        new BodyActivityDescription(0.01f)
                        )
                    );
            }
        }
Exemplo n.º 16
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.º 17
0
        public override void Initialize(ContentArchive content, Camera camera)
        {
            camera.Position = new Vector3(0, 7, 20);
            camera.Yaw      = 0;
            camera.Pitch    = 0;

            Simulation = Simulation.Create(BufferPool, new DemoNarrowPhaseCallbacks(), new DemoPoseIntegratorCallbacks(new Vector3(0, -10, 0)));

            Simulation.Statics.Add(new StaticDescription(new Vector3(), new CollidableDescription(Simulation.Shapes.Add(new Box(100, 1, 100)), 0.1f)));

            var random      = new Random(5);
            var shapeToDrop = new Box(1, 1, 1);

            shapeToDrop.ComputeInertia(1, out var shapeToDropInertia);
            var descriptionToDrop = BodyDescription.CreateDynamic(new Vector3(), shapeToDropInertia, new CollidableDescription(Simulation.Shapes.Add(shapeToDrop), 0.3f), new BodyActivityDescription(0.01f));

            for (int i = 0; i < 128; ++i)
            {
                descriptionToDrop.Pose.Position = new Vector3(-5 + 10 * (float)random.NextDouble(), 45 + 150 * (float)random.NextDouble(), -5 + 10 * (float)random.NextDouble());
                Simulation.Bodies.Add(descriptionToDrop);
            }

            //Add in a static object to test against. Note that the mesh triangles are one sided, so some of the queries whose centers are beneath the mesh do not generate any contacts.
            DemoMeshHelper.CreateDeformedPlane(20, 20, (x, y) => { return(new Vector3(x * 5 - 50, 3 * MathF.Sin(x) * MathF.Sin(y), y * 5 - 50)); }, Vector3.One, BufferPool, out var mesh);
            Simulation.Statics.Add(new StaticDescription(new Vector3(0, 0, 0), new CollidableDescription(Simulation.Shapes.Add(mesh), 0.1f)));
        }
Exemplo n.º 18
0
        int BuildSpinner(Vector3 initialPosition, float rotationSpeed)
        {
            var spinnerBase = Simulation.Bodies.Add(BodyDescription.CreateDynamic(initialPosition, new BodyInertia {
                InverseMass = 1e-2f
            }, new CollidableDescription(Simulation.Shapes.Add(new Box(2, 2, 2)), 0.1f), new BodyActivityDescription(0.01f)));
            var bladeShape = new Box(5, 0.01f, 1);

            bladeShape.ComputeInertia(1, out var bladeInertia);
            var shapeIndex = Simulation.Shapes.Add(bladeShape);
            //Note that both the minimum progression duration and the sweep convergence duration are both very small at 1e-4.
            //That will detect collisions with a precision equal to an update rate of 10,000hz.
            //The blades are extremely thin and spinning very quickly, so that kind of precision is helpful.
            //Note that you can likely get away with a larger sweep convergence duration.
            //The sweep convergence duration is the maximum size of the 'time of first impact' region that the sweep is allowed to terminate with;
            //using a time of impact which is a little bit off won't usually cause much of a problem.
            //Minimum progression duration is far more important to keep small, since collisions with a duration below the minimum progression duration may be missed entirely.

            //Note that it's possible for the blades to still go through each other in certain corner cases- the CCD sweep only detects time of *first* impact.
            //It's possible for the contacts associated with the first impact to be insufficient for later collisions within the same frame.
            //It's pretty rare, though- if you have a situation where that sort of failure is common, consider increasing the collidable's speculative margin or using a higher update rate.
            //(The reason why we don't always just rely on large speculative margins is ghost collisions- the speculative contacts might not represent collisions
            //that would have actually happened, but get included in the constraint solution anyway. They're fairly rare, but it's something to watch out for.)
            var spinnerBlade = Simulation.Bodies.Add(BodyDescription.CreateDynamic(initialPosition, bladeInertia, new CollidableDescription(shapeIndex, 0.2f, ContinuousDetectionSettings.Continuous(1e-4f, 1e-4f)), new BodyActivityDescription(0.01f)));

            Simulation.Solver.Add(spinnerBase, spinnerBlade, new Hinge {
                LocalHingeAxisA = new Vector3(0, 0, 1), LocalHingeAxisB = new Vector3(0, 0, 1), LocalOffsetB = new Vector3(0, 0, -3), SpringSettings = new SpringSettings(30, 1)
            });
            Simulation.Solver.Add(spinnerBase, spinnerBlade, new AngularAxisMotor {
                LocalAxisA = new Vector3(0, 0, 1), Settings = new MotorSettings(10, 1e-4f), TargetVelocity = rotationSpeed
            });
            return(Simulation.Solver.Add(spinnerBase, new OneBodyLinearServo {
                ServoSettings = ServoSettings.Default, SpringSettings = new SpringSettings(30, 1)
            }));
        }
Exemplo n.º 19
0
        public override void Initialize(ContentArchive content, Camera camera)
        {
            camera.Position = new Vector3(-30, 8, -60);
            camera.Yaw      = MathHelper.Pi * 3f / 4;
            camera.Pitch    = 0;

            Simulation = Simulation.Create(BufferPool, new DefaultNarrowPhaseCallbacks(), new DefaultPoseIntegratorCallbacks(BufferPool));
            var boxShape  = new Box(1, 1, 1);
            var baseShape = new Box(10, 1, 10);


            boxShape.ComputeInertia(1, out var boxInertia);

            var boxShapeIndex  = Simulation.Shapes.Add(boxShape);
            var baseShapeIndex = Simulation.Shapes.Add(baseShape);


            var boxDescription = new BodyDescription
            {
                //Make the uppermost block kinematic to hold up the rest of the chain.
                LocalInertia = boxInertia,
                Pose         = new RigidPose
                {
                    Position    = new Vector3(0, 2, 0),
                    Orientation = Quaternion.Identity
                },
                Activity = new BodyActivityDescription {
                    MinimumTimestepCountUnderThreshold = 32, SleepThreshold = .01f
                },
                Collidable = new CollidableDescription {
                    Shape = boxShapeIndex, SpeculativeMargin = .1f
                },
            };


            var baseDescription = new BodyDescription
            {
                //Make the uppermost block kinematic to hold up the rest of the chain.
                LocalInertia = new BodyInertia(),
                Pose         = new RigidPose
                {
                    Position    = new Vector3(0, 0, 0),
                    Orientation = Quaternion.Identity
                },
                Activity = new BodyActivityDescription {
                    MinimumTimestepCountUnderThreshold = 32, SleepThreshold = .01f
                },
                Collidable = new CollidableDescription {
                    Shape = baseShapeIndex, SpeculativeMargin = .1f
                },
            };

            var boxIndex  = Simulation.Bodies.Add(boxDescription);
            var baseIndex = Simulation.Bodies.Add(baseDescription);

            _boxReference  = new BodyReference(boxIndex, Simulation.Bodies);
            _baseReference = new BodyReference(baseIndex, Simulation.Bodies);
        }
Exemplo n.º 20
0
        //List<DebugStep> debugSteps;
        public override void Initialize(ContentArchive content, Camera camera)
        {
            camera.Position = new Vector3(0, -2.5f, 10);
            camera.Yaw      = 0;
            camera.Pitch    = 0;

            Simulation = Simulation.Create(BufferPool, new DemoNarrowPhaseCallbacks(), new DemoPoseIntegratorCallbacks(new Vector3(0, 0, 0)));

            const int pointCount = 128;

            points = new QuickList <Vector3>(pointCount * 2, BufferPool);
            //points.Allocate(BufferPool) = new Vector3(0, 0, 0);
            //points.Allocate(BufferPool) = new Vector3(0, 0, 1);
            //points.Allocate(BufferPool) = new Vector3(0, 1, 0);
            //points.Allocate(BufferPool) = new Vector3(0, 1, 1);
            //points.Allocate(BufferPool) = new Vector3(1, 0, 0);
            //points.Allocate(BufferPool) = new Vector3(1, 0, 1);
            //points.Allocate(BufferPool) = new Vector3(1, 1, 0);
            //points.Allocate(BufferPool) = new Vector3(1, 1, 1);
            var random = new Random(5);

            for (int i = 0; i < pointCount; ++i)
            {
                points.AllocateUnsafely() = new Vector3(3 * (float)random.NextDouble(), 1 * (float)random.NextDouble(), 3 * (float)random.NextDouble());
                //points.AllocateUnsafely() = new Vector3(0, 1, 0) + Vector3.Normalize(new Vector3((float)random.NextDouble() * 2 - 1, (float)random.NextDouble() * 2 - 1, (float)random.NextDouble() * 2 - 1)) * (float)random.NextDouble();
            }

            var pointsBuffer = points.Span.Slice(0, points.Count);

            ConvexHullHelper.CreateShape(pointsBuffer, BufferPool, out _, out var hullShape);
            const int iterationCount = 100;
            var       start          = Stopwatch.GetTimestamp();

            for (int i = 0; i < iterationCount; ++i)
            {
                ConvexHullHelper.CreateShape(pointsBuffer, BufferPool, out _, out var perfTestShape);
                perfTestShape.Dispose(BufferPool);
            }
            var end = Stopwatch.GetTimestamp();

            Console.WriteLine($"Hull computation time (us): {(end - start) * 1e6 / (iterationCount * Stopwatch.Frequency)}");


            hullShape.ComputeInertia(1, out var inertia);

            Simulation.Bodies.Add(BodyDescription.CreateDynamic(new Vector3(0, 0, 0), inertia, new CollidableDescription(Simulation.Shapes.Add(hullShape), 10.1f), new BodyActivityDescription(0.01f)));

            Simulation.Statics.Add(new StaticDescription(new Vector3(-25, -5, 0), new CollidableDescription(Simulation.Shapes.Add(new Sphere(2)), 0.1f)));
            Simulation.Statics.Add(new StaticDescription(new Vector3(-20, -5, 0), new CollidableDescription(Simulation.Shapes.Add(new Capsule(0.5f, 2)), 0.1f)));
            Simulation.Statics.Add(new StaticDescription(new Vector3(-15, -5, 0), new CollidableDescription(Simulation.Shapes.Add(new Box(2f, 2f, 2f)), 0.1f)));
            Simulation.Statics.Add(new StaticDescription(new Vector3(-10, -5, 5), new CollidableDescription(Simulation.Shapes.Add(new Triangle {
                A = new Vector3(0, 0, -10), B = new Vector3(5, 0, -10), C = new Vector3(0, 0, -5)
            }), 0.1f)));
            Simulation.Statics.Add(new StaticDescription(new Vector3(-5, -5, 0), new CollidableDescription(Simulation.Shapes.Add(new Cylinder(1, 1)), 0.1f)));
            Simulation.Statics.Add(new StaticDescription(new Vector3(-5, -5, 5), new CollidableDescription(Simulation.Shapes.Add(new Cylinder(1, 1)), 0.1f)));
            Simulation.Statics.Add(new StaticDescription(new Vector3(0, -5, 0), new CollidableDescription(Simulation.Shapes.Add(hullShape), 0.1f)));
        }
Exemplo n.º 21
0
        private int Instantiate(BodyDescription bodyReference, ref Vector3 position, ref Quaternion orientation)
        {
            bodyReference.Pose.Position    = position;
            bodyReference.Pose.Orientation = orientation;
            var index = Simulation.Bodies.Add(bodyReference);

            _createdObjects.Add(index, BufferPool);
            return(index);
        }
Exemplo n.º 22
0
        private void LoadPhysics()
        {
            //Physics
            BufferPool = new BufferPool();

            Radii = new List <float>();

            SphereHandles = new List <BodyHandle>();

            var targetThreadCount = Math.Max(1,
                                             Environment.ProcessorCount > 4 ? Environment.ProcessorCount - 2 : Environment.ProcessorCount - 1);

            ThreadDispatcher = new SimpleThreadDispatcher(targetThreadCount);

            Simulation = Simulation.Create(BufferPool, new NarrowPhaseCallbacks(),
                                           new PoseIntegratorCallbacks(new NumericVector3(0, -500, 0)), new PositionFirstTimestepper());

            //     Simulation.Statics.Add(new StaticDescription(new NumericVector3(0, 0, 0),
            //new CollidableDescription(Simulation.Shapes.Add(new Box(2000, 100, 5000)), 1)));
            //  for (int i=0;i<MatrixWorld.Count;i++)
            //  {
            //      Matrix world = MatrixWorld[i];
            //      Simulation.Statics.Add(new StaticDescription(new NumericVector3(world.Translation.X, world.Translation.Y, world.Translation.Z),
            //     new CollidableDescription(Simulation.Shapes.Add(new Box(200, 100, 500)), 1)));
            //  }
            //Simulation.Statics.Add(new StaticDescription(new NumericVector3(0, -20, 0),
            //  new CollidableDescription(Simulation.Shapes.Add(new Box(200, 100, 500)), 1)));

            //Simulation.Statics.Add(new StaticDescription(new NumericVector3(9, 28, 200), new CollidableDescription(Simulation.Shapes.Add(new Sphere(2f)),1)));
            //Simulation.Statics.Add(new StaticDescription(new ))

            /* for (int i = 0; i < MatrixWorld.Count(); i++)
             * {
             *   Simulation.Statics.Add(new StaticDescription(MatrixWorld[i].))
             *   Floor.Draw(MatrixWorld[i], Camera.View, Camera.Projection);
             * }*/


            //Simulation.Statics.Add(new StaticDescription(new NumericVector3(0, -20, 0), new CollidableDescription(Simulation.Shapes.Add(
            //  new Box(2000, 100, 2000)), 1)));
            //Esfera
            SpheresWorld = new List <Matrix>();


            var radius          = 5f;
            var sphereShape     = new Sphere(radius);
            var position        = Vector3Utils.toNumeric(PlayerInitialPosition);
            var bodyDescription = BodyDescription.CreateConvexDynamic(position, 1 / radius * radius * radius,
                                                                      Simulation.Shapes, sphereShape);

            var bodyHandle = Simulation.Bodies.Add(bodyDescription);

            SphereHandles.Add(bodyHandle);

            Radii.Add(radius);
        }
Exemplo n.º 23
0
        public override void Initialize(ContentArchive content, Camera camera)
        {
            camera.Position = new Vector3(0, 4, -6);
            camera.Yaw      = MathHelper.Pi;

            Simulation = Simulation.Create(BufferPool, new DemoNarrowPhaseCallbacks(), new DemoPoseIntegratorCallbacks(new Vector3(0, 0, 0)));

            Simulation.Bodies.Add(BodyDescription.CreateConvexKinematic(new Vector3(), Simulation.Shapes, new Box(3, 1, 4)));
            Simulation.Bodies.Add(BodyDescription.CreateConvexDynamic(new Vector3(0, 1.1f, 0), 1, Simulation.Shapes, new Box(2, 1, 3)));
        }
        internal BodyHandle CreateKinematic(Vector3 position, Quaternion rotation, TypedIndex shape)
        {
            BodyDescription bodyDescription = BodyDescription.CreateKinematic(
                new RigidPose(position.ToBEPU(), rotation.ToBEPU()),
                new BodyVelocity(new BEPUVector3(0f, 0f, 0f)),
                new CollidableDescription(shape, 0.1f),
                new BodyActivityDescription(-1));

            return(simulation.Bodies.Add(bodyDescription));
        }
Exemplo n.º 25
0
        //Update the body with a new location
        public void UpdateBody(Simulation World)
        {
            Vector3 UpdatePosition = new Vector3(Position.X, Position.Y + 1.5f, Position.Z);

            BodyPose = new RigidPose(UpdatePosition, Rotation);
            BodyShape.ComputeInertia(1, out var Inertia);
            BodyDescription = BodyDescription.CreateKinematic(BodyPose, CollidableDescription, ActivityDescription);
            World.Bodies.ApplyDescription(BodyHandle, ref BodyDescription);
            NewPosition = false;
        }
Exemplo n.º 26
0
        public BodyReference AddDynamic(BodyDescription description, object context = null)
        {
            var handle = Simulation.Bodies.Add(description);

            if (context != null)
            {
                _dynamicContexts[handle] = context;
            }
            return(new BodyReference(handle, Simulation.Bodies));
        }
Exemplo n.º 27
0
        private void LoadVehiclePhysics(Scene scene)
        {
            // Create a 2 ton car with 4 wheels
            BodyDescription bodyDesc = new BodyDescription()
            {
                Mass = 2000
            };

            //bodyDesc.MassLocalPose = Matrix.CreateTranslation( 0, -1.5f, 0 ); // Seems not to be working

            ActorDesc = new ActorDescription()
            {
                BodyDescription = bodyDesc,
                Shapes          = { new BoxShapeDescription(5, 3, 7) },
                GlobalPose      = Matrix.Translation(-50, 5, -70)
            };

            VehicleBodyActor = scene.CreateActor(ActorDesc);
            VehicleBodyActor.SetCenterOfMassOffsetLocalPosition(new Vector3(0, -1.5f, 0)); // Move the COM to the bottom of the vehicle to stop it flipping over so much

            //

            WheelShapeDescription leftFrontDesc = new WheelShapeDescription()
            {
                Radius           = 0.8f,
                SuspensionTravel = 1,
                LocalPosition    = new Vector3(-2.5f, -1, 3)
            };

            WheelShapeDescription leftRearDesc = new WheelShapeDescription()
            {
                Radius           = 0.8f,
                SuspensionTravel = 1,
                LocalPosition    = new Vector3(-2.5f, -1, -3),
            };

            WheelShapeDescription rightFrontDesc = new WheelShapeDescription()
            {
                Radius           = 0.8f,
                SuspensionTravel = 1,
                LocalPosition    = new Vector3(2.5f, -1, 3)
            };

            WheelShapeDescription rightRearDesc = new WheelShapeDescription()
            {
                Radius           = 0.8f,
                SuspensionTravel = 1,
                LocalPosition    = new Vector3(2.5f, -1, -3)
            };

            this.LeftFront  = VehicleBodyActor.CreateShape(leftFrontDesc) as WheelShape;
            this.LeftRear   = VehicleBodyActor.CreateShape(leftRearDesc) as WheelShape;
            this.RightFront = VehicleBodyActor.CreateShape(rightFrontDesc) as WheelShape;
            this.RightRear  = VehicleBodyActor.CreateShape(rightRearDesc) as WheelShape;
        }
Exemplo n.º 28
0
		private void LoadVehiclePhysics(Scene scene)
		{
			// Create a 2 ton car with 4 wheels
			BodyDescription bodyDesc = new BodyDescription()
			{
				Mass = 2000
			};
			//bodyDesc.MassLocalPose = Matrix.CreateTranslation( 0, -1.5f, 0 ); // Seems not to be working

			ActorDescription actorDesc = new ActorDescription()
			{
				BodyDescription = bodyDesc,
				Shapes = { new BoxShapeDescription(5, 3, 7) },
				GlobalPose = Matrix.Translation(-50, 5, -70)
			};

			_vehicleBodyActor = scene.CreateActor(actorDesc);
			_vehicleBodyActor.SetCenterOfMassOffsetLocalPosition(new Vector3(0, -1.5f, 0)); // Move the COM to the bottom of the vehicle to stop it flipping over so much

			//

			WheelShapeDescription leftFrontDesc = new WheelShapeDescription()
			{
				Radius = 0.8f,
				SuspensionTravel = 1,
				LocalPosition = new Vector3(-2.5f, -1, 3)
			};

			WheelShapeDescription leftRearDesc = new WheelShapeDescription()
			{
				Radius = 0.8f,
				SuspensionTravel = 1,
				LocalPosition = new Vector3(-2.5f, -1, -3),
			};

			WheelShapeDescription rightFrontDesc = new WheelShapeDescription()
			{
				Radius = 0.8f,
				SuspensionTravel = 1,
				LocalPosition = new Vector3(2.5f, -1, 3)
			};

			WheelShapeDescription rightRearDesc = new WheelShapeDescription()
			{
				Radius = 0.8f,
				SuspensionTravel = 1,
				LocalPosition = new Vector3(2.5f, -1, -3)
			};

			this.LeftFront = _vehicleBodyActor.CreateShape(leftFrontDesc) as WheelShape;
			this.LeftRear = _vehicleBodyActor.CreateShape(leftRearDesc) as WheelShape;
			this.RightFront = _vehicleBodyActor.CreateShape(rightFrontDesc) as WheelShape;
			this.RightRear = _vehicleBodyActor.CreateShape(rightRearDesc) as WheelShape;
		}
Exemplo n.º 29
0
        public override void Initialize(ContentArchive content, Camera camera)
        {
            camera.Position = new Vector3(0, 10, 40);
            camera.Yaw      = 0;
            camera.Pitch    = 0;
            //Note the higher stiffness on contacts for this demo. That's not ideal for general stability at the demo timestep duration default of 60hz, but
            //this demo doesn't have any significant solver complexity and we want to see the CCD in action more clearly- which means more rigid contact.
            //Having objects bounce a bunch on impact makes it harder to see.
            //Also note that the PositionFirstTimestepper is the simplest timestepping mode, but since it integrates velocity into position at the start of the frame, directly modified velocities outside of the timestep
            //will be integrated before collision detection or the solver has a chance to intervene. That's fine in this demo. Other built-in options include the PositionLastTimestepper and the SubsteppingTimestepper.
            //Note that the timestepper also has callbacks that you can use for executing logic between processing stages, like BeforeCollisionDetection.
            Simulation = Simulation.Create(BufferPool, new DemoNarrowPhaseCallbacks()
            {
                ContactSpringiness = new SpringSettings(120, 1)
            }, new DemoPoseIntegratorCallbacks(new Vector3(0, -10, 0)), new PositionFirstTimestepper());

            var shape = new Box(1, 1, 1);

            shape.ComputeInertia(1, out var inertia);
            var shapeIndex = Simulation.Shapes.Add(shape);

            for (int i = 0; i < 10; ++i)
            {
                for (int j = 0; j < 10; ++j)
                {
                    //These two falling dynamics have pretty small speculative margins. The second one uses continuous collision detection sweeps to generate speculative contacts.
                    Simulation.Bodies.Add(BodyDescription.CreateDynamic(new Vector3(-4 - 2 * j, 100 + (i + j) * 2, i * 2), new BodyVelocity {
                        Linear = new Vector3(0, -150, 0)
                    }, inertia,
                                                                        new CollidableDescription(shapeIndex, 0.01f), new BodyActivityDescription(0.01f)));
                    //The minimum progression duration parameter at 1e-3 means the CCD sweep won't miss any collisions that last at least 1e-3 units of time- so, if time is measured in seconds,
                    //then this will capture any collision that an update rate of 1000hz would.
                    //Note also that the sweep convergence threshold is actually pretty loose at 100hz. Despite that, it can still lead to reasonably good speculative contacts with solid impact behavior.
                    //That's because the sweep does not directly generate contacts- it generates a time of impact estimate, and then the discrete contact generation
                    //runs to create the actual contact manifold. That provides high quality contact positions and speculative depths.
                    //If the ground that these boxes were smashing into was something like a mesh- which is infinitely thin- you may want to increase the sweep accuracy.
                    Simulation.Bodies.Add(BodyDescription.CreateDynamic(new Vector3(4 + 2 * j, 100 + (i + j) * 2, i * 2), new BodyVelocity {
                        Linear = new Vector3(0, -150, 0)
                    }, inertia,
                                                                        new CollidableDescription(shapeIndex, 0.01f, ContinuousDetectionSettings.Continuous(1e-3f, 1e-2f)), new BodyActivityDescription(0.01f)));
                }
            }
            rolloverInfo = new RolloverInfo();
            rolloverInfo.Add(new Vector3(-12, 2, 0), "Discrete");
            rolloverInfo.Add(new Vector3(12, 2, 0), "Continuous");

            //Build a couple of spinners to ram into each other to showcase angular CCD. Note that the spin speeds are slightly different- that helps avoid
            //synchronization that makes the blades frequently miss each other, which sorta ruins a CCD demo.
            spinnerMotorA = BuildSpinner(new Vector3(-5, 10, -5), 53);
            spinnerMotorB = BuildSpinner(new Vector3(5, 10, -5), 59);
            rolloverInfo.Add(new Vector3(0, 12, -5), "High angular velocity continuous detection");

            Simulation.Statics.Add(new StaticDescription(new Vector3(0, -5f, 0), new CollidableDescription(Simulation.Shapes.Add(new Box(300, 10, 300)), 0.1f)));
        }
Exemplo n.º 30
0
        public CharacterInput(CharacterControllers characters, Vector3 initialPosition, Capsule shape,
                              float speculativeMargin, float mass, float maximumHorizontalForce, float maximumVerticalGlueForce,
                              float jumpVelocity, float speed, float maximumSlope = MathF.PI * 0.25f)
        {
            this.characters = characters;
            var shapeIndex = characters.Simulation.Shapes.Add(shape);

            bodyHandle = characters.Simulation.Bodies.Add(BodyDescription.CreateDynamic(initialPosition, new BodyInertia {
                InverseMass = 1f / mass
            }, new CollidableDescription(shapeIndex, speculativeMargin), new BodyActivityDescription(shape.Radius * 0.02f)));
            ref var character = ref characters.AllocateCharacter(bodyHandle, out var characterIndex);
Exemplo n.º 31
0
 Vector3 CreateRing(Vector3 position, Box ringBoxShape, BodyDescription bodyDescription, float radius, int heightPerPlatformLevel, int platformLevels)
 {
     for (int platformIndex = 0; platformIndex < platformLevels; ++platformIndex)
     {
         var wallOffset = ringBoxShape.HalfLength - ringBoxShape.HalfWidth;
         CreateRingWall(position, ringBoxShape, bodyDescription, heightPerPlatformLevel, radius + wallOffset);
         CreateRingWall(position, ringBoxShape, bodyDescription, heightPerPlatformLevel, radius - wallOffset);
         CreateRingPlatform(position + new Vector3(0, heightPerPlatformLevel * ringBoxShape.Height, 0), ringBoxShape, bodyDescription, radius);
         position.Y += heightPerPlatformLevel * ringBoxShape.Height + ringBoxShape.Width;
     }
     return(position);
 }
Exemplo n.º 32
0
 public bool GetBody(int columnIndex, int rowIndex, int sliceIndex, out int handle, out BodyDescription bodyDescription)
 {
     if (!TryGetId(columnIndex, rowIndex, sliceIndex, out var id))
     {
         handle          = -1;
         bodyDescription = new BodyDescription();
         return(false);
     }
     handle = bodyHandles[id];
     bodies.GetDescription(handle, out bodyDescription);
     return(true);
 }
Exemplo n.º 33
0
 static void TryConnectTo(int sliceIndex, int rowIndex, int columnIndex,
                          ref BodyDescription bodyDescription,
                          ref LatticeBodyGetter ids,
                          ref ConstraintAdder constraintAdder)
 {
     if (ids.GetBody(columnIndex, rowIndex, sliceIndex, out var otherHandle, out var otherDescription) &&
         (bodyDescription.LocalInertia.InverseMass > 0 || otherDescription.LocalInertia.InverseMass > 0))
     {
         CreateBallSocket(ref bodyDescription.Pose, ref otherDescription.Pose, out var description);
         constraintAdder.Add(ref description, otherHandle);
     }
 }
Exemplo n.º 34
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.º 35
0
        protected override void iniPhysx()
        {
            BodyDescription bodyDesc = new BodyDescription();
            bodyDesc.Mass = 5;
            this.shapeDesc = new WheelShapeDescription();
            this.shapeDesc.Radius = this.Radius;
            shapeDesc.SuspensionTravel = 10;
            //shapeDesc.LocalPosition = localPosition;

            ActorDescription actorDesc = new ActorDescription();
            actorDesc.BodyDescription = bodyDesc;
            actorDesc.GlobalPose = StillDesign.PhysX.MathPrimitives.Matrix.Translation(100,30,0);
            actorDesc.Shapes.Add(shapeDesc);
            this.actor = game.scene.CreateActor(actorDesc);
            this.shape = actor.Shapes[0];
            //this.shape = this.actor.CreateShape(shapeDesc) as WheelShape;
        }
Exemplo n.º 36
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.º 37
0
        private void FlubberTest()
        {
            // Let's set the default material to make things BOUNCY.
            Material defaultMaterial = this.Scene.DefaultMaterial;
            defaultMaterial.StaticFriction = 0.0f;
            defaultMaterial.DynamicFriction = 0.01f;
            defaultMaterial.Restitution = 1.0f;
            defaultMaterial.RestitutionCombineMode = CombineMode.Max;

            // Here's another box.  This will be a container for the flubber to bounce around in.
            ActorDescription boxActor = new ActorDescription();
            // The back piece of the box.
            boxActor.Shapes.Add(new BoxShapeDescription(new Vector3(40.0f, 40.0f, 2.0f))
                {
                    LocalPosition = new Vector3(0.0f, 0.0f, -19.0f)
                });
            // The front piece of the box.
            boxActor.Shapes.Add(new BoxShapeDescription(new Vector3(40.0f, 40.0f, 2.0f))
                {
                    LocalPosition = new Vector3(0.0f, 0.0f, 19.0f)
                });
            // The left piece of the box.
            boxActor.Shapes.Add(new BoxShapeDescription(new Vector3(2.0f, 40.0f, 40.0f))
                {
                    LocalPosition = new Vector3(-19.0f, 0.0f, 0.0f)
                });
            // The right piece of the box.
            boxActor.Shapes.Add(new BoxShapeDescription(new Vector3(2.0f, 40.0f, 40.0f))
                {
                    LocalPosition = new Vector3(19.0f, 0.0f, 0.0f)
                });
            // The top piece of the box.
            boxActor.Shapes.Add(new BoxShapeDescription(new Vector3(40.0f, 2.0f, 40.0f))
                {
                    LocalPosition = new Vector3(0.0f, 19.0f, 0.0f)
                });
            // The bottom piece of the box.
            boxActor.Shapes.Add(new BoxShapeDescription(new Vector3(40.0f, 2.0f, 40.0f))
                {
                    LocalPosition = new Vector3(0.0f, -19.0f, 0.0f)
                });
            boxActor.GlobalPose *= Matrix.CreateTranslation(new Vector3(0.0f, 20.0f, 0.0f));
            this.Scene.CreateActor(boxActor);

            // Now we'll create a sphere inside the box.  It will start at the center of the box with
            // a random initial velocity.
            Random rand = new Random();
            const double speed = 100.0f;
            BodyDescription flubberDesc = new BodyDescription();
            flubberDesc.LinearVelocity = new Vector3((float) rand.NextDouble(),
                                                     (float) rand.NextDouble(),
                                                     (float) rand.NextDouble());
            flubberDesc.LinearVelocity.Normalize();
            flubberDesc.LinearVelocity -= new Vector3(0.5f);
            flubberDesc.LinearVelocity *= (float)(speed);
            flubberDesc.AngularDamping = 0.0f;
            flubberDesc.LinearDamping = 0.0f;

            ActorDescription flubberActor = new ActorDescription();
            flubberActor.Shapes.Add(new SphereShapeDescription(2.0f));
            flubberActor.GlobalPose *= Matrix.CreateTranslation(new Vector3(0.0f, 20.0f, 0.0f));
            flubberActor.BodyDescription = flubberDesc;
            flubberActor.Density = 10.0f;
            this.Scene.CreateActor(flubberActor);
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="PhysxTriangleMesh"/> class.
 /// For cooked Models
 /// </summary>
 /// <param name="PhysxPhysicWorld">The physx physic world.</param>
 /// <param name="FileStream">The file stream.</param>
 /// <param name="localTransformation">The local transformation.</param>
 /// <param name="worldTransformation">The world transformation.</param>
 /// <param name="scale">The scale.</param>
 /// <param name="MaterialDescription">The material description.</param>
 public PhysxTriangleMesh(PhysxPhysicWorld PhysxPhysicWorld, FileStream FileStream, Microsoft.Xna.Framework.Matrix localTransformation, Microsoft.Xna.Framework.Matrix worldTransformation, Microsoft.Xna.Framework.Vector3 scale, MaterialDescription MaterialDescription)
 {            
     TriangleMesh triangleMesh = PhysxPhysicWorld.Core.CreateTriangleMesh(FileStream);
     TriangleMeshShapeDescription bunnyShapeDesc = new TriangleMeshShapeDescription();
     bunnyShapeDesc.TriangleMesh = triangleMesh;
     BodyDescription bodyDesc = new BodyDescription();
     ActorDesc.Shapes.Add(bunnyShapeDesc);
     ActorDesc.BodyDescription = bodyDesc;
     this.Scale = scale;
 }
Exemplo n.º 39
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.º 40
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.º 41
0
        private void SimpleBoxTest()
        {
            // Let's create a simple material.
            Material defaultMaterial = this.Scene.DefaultMaterial;
            defaultMaterial.StaticFriction = 0.5f;
            defaultMaterial.DynamicFriction = 0.5f;
            defaultMaterial.Restitution = 0.5f;

            // First, let's create a ground plane for the box to bounce on.
            ActorDescription planeActor = new ActorDescription();
            planeActor.Shapes.Add(new PlaneShapeDescription(Vector3.Up, 0.0f));
            this.Scene.CreateActor(planeActor);

            // Let's create a box!
            // This describes the physics properties of the box.  We only need to make one
            // of these if it is a dynamic object.  Static objects don't need a BodyDescription.
            BodyDescription boxDesc = new BodyDescription();
            boxDesc.AngularDamping = 0.5f;
            boxDesc.LinearVelocity = Vector3.Zero;
            // This describes the size and positioning of the box.
            ActorDescription boxActor = new ActorDescription();
            boxActor.Shapes.Add(new BoxShapeDescription(new Vector3(2.0f)));
            boxActor.Density = 10.0f;
            boxActor.GlobalPose *= Matrix.CreateTranslation(new Vector3(0.0f, 20.0f, 0.0f));
            boxActor.BodyDescription = boxDesc;
            // Let's add it to the scene!
            this.Scene.CreateActor(boxActor);
        }