예제 #1
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);
        }
예제 #2
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;
            }
예제 #3
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)));
        }
예제 #4
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)));
        }
예제 #5
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)
                        )
                    );
            }
        }
예제 #6
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)));
        }
예제 #7
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)
            }));
        }
예제 #8
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)));
        }
예제 #9
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)));
        }
예제 #10
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);
예제 #11
0
        public unsafe override void Initialize(ContentArchive content, Camera camera)
        {
            camera.Position = new Vector3(-30, 8, -60);
            camera.Yaw      = MathHelper.Pi * 3f / 4;
            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());

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

            boxShape.ComputeInertia(1, out var boxInertia);
            var       boxIndex       = Simulation.Shapes.Add(boxShape);
            const int forkCount      = 20;
            const int blocksPerChain = 20;

            BodyHandle[] blockHandles = new BodyHandle[blocksPerChain];
            for (int forkIndex = 0; forkIndex < forkCount; ++forkIndex)
            {
                //Build the blocks.
                for (int blockIndex = 0; blockIndex < blocksPerChain; ++blockIndex)
                {
                    var bodyDescription = BodyDescription.CreateDynamic(
                        new Vector3(0, 5 + blockIndex * (boxShape.Height + 1), (forkIndex - forkCount * 0.5f) * (boxShape.Length + 4)),
                        //Make the uppermost block kinematic to hold up the rest of the chain.
                        blockIndex == blocksPerChain - 1 ? new BodyInertia() : boxInertia,
                        new CollidableDescription(boxIndex, .1f),
                        new BodyActivityDescription(.01f, 32));
                    blockHandles[blockIndex] = Simulation.Bodies.Add(bodyDescription);
                }
                //Build the chains.
                for (int i = 1; i < blocksPerChain; ++i)
                {
                    var ballSocket = new BallSocket
                    {
                        LocalOffsetA   = new Vector3(0, 1f, 0),
                        LocalOffsetB   = new Vector3(0, -1f, 0),
                        SpringSettings = new SpringSettings(30, 5)
                    };
                    Simulation.Solver.Add(blockHandles[i - 1], blockHandles[i], ref ballSocket);
                }
            }

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

            //Build the coin description for the ponz-I mean ICO.
            var coinShape = new Cylinder(1.5f, 0.2f);

            coinShape.ComputeInertia(1, out var coinInertia);
            coinDescription = BodyDescription.CreateDynamic(RigidPose.Identity, coinInertia, new CollidableDescription(Simulation.Shapes.Add(coinShape), 0.1f), new BodyActivityDescription(0.01f));
        }
        internal BodyHandle CreateDynamic(Vector3 position, Quaternion rotation, TypedIndex shape, float mass)
        {
            simulation.Shapes.GetShape <Sphere>(shape.Index).ComputeInertia(mass, out BodyInertia inertia);
            BodyDescription bodyDescription = BodyDescription.CreateDynamic(
                new RigidPose(position.ToBEPU(), rotation.ToBEPU()),
                new BodyVelocity(new BEPUVector3(0f, 0f, 0f)),
                inertia,
                new CollidableDescription(shape, 0.1f),
                new BodyActivityDescription(-1));

            return(simulation.Bodies.Add(bodyDescription));
        }
예제 #13
0
        //Default constructor
        public EnemyEntity(Vector3 SpawnLocation)
        {
            //Store the entities default location then add a new physics collider into the world physics simulation
            DefaultLocation           = SpawnLocation;
            EntityColliderShape       = new Cylinder(0.6f, 1.7f);
            EntityColliderDescription = new CollidableDescription(Program.World.World.Shapes.Add(EntityColliderShape), 0.25f);
            EntityColliderShape.ComputeInertia(1, out var Inertia);
            Program.World.World.Bodies.Add(BodyDescription.CreateDynamic(new RigidPose(SpawnLocation, Quaternion.Identity), Inertia, EntityColliderDescription, new BodyActivityDescription(0.01f)));

            //Pass it to the entity manager to be stored with all the others and set the enemies type value
            EntityManager.AddEntity(this);
            this.Type = "Skeleton Warrior";
        }
예제 #14
0
        protected override void DefinePhysicsObject(float size, float mass)
        {
            var shape      = new Box(this.World.Hook.WorldSize * 2, 200, 200); //todo: size
            var position2d = new Vector2(0, this.World.Hook.WorldSize);

            ShapeHandle = World.Simulation.Shapes.Add(shape);
            BodyHandle  = World.Simulation.Bodies.Add(BodyDescription.CreateDynamic(
                                                          new Vector3(position2d.X, 0, position2d.Y),
                                                          GetBodyInertia(shape, mass),
                                                          new CollidableDescription(ShapeHandle, 0.1f),
                                                          new BodyActivityDescription(0.00f)
                                                          ));
        }
예제 #15
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);

            //Because characters are dynamic, they require a defined BodyInertia. For the purposes of the demos, we don't want them to rotate or fall over, so the inverse inertia tensor is left at its default value of all zeroes.
            //This is effectively equivalent to giving it an infinite inertia tensor- in other words, no torque will cause it to rotate.
            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);
        internal void AddCharacter(Character character)
        {
            var characterShape = character.Shape();

            characterShape.ComputeInertia(1, out var characterInertia);

            int handle = Simulation.Bodies.Add(BodyDescription.CreateDynamic(character.GetStartPosition(), characterInertia, new CollidableDescription(Simulation.Shapes.Add(characterShape), 0.1f), new BodyActivityDescription(0.01f)));

            handleUnits.Add(handle, character);
            character.SetBodyHandle(handle);
            character.PeriodicAABB();
            character.SetCharacterInput(bufferPool, handle, Simulation);
            //character.SetBodyReference(Simulation.Bodies.GetBodyReference(handle));
        }
예제 #17
0
        private void createObjects()
        {
            for (int a = 0; a < 7000; a++)
            {
                var ringBoxShape = new Box(1, 1, 1);
                ringBoxShape.ComputeInertia(1, out var ringBoxInertia);
                var boxDescription = BodyDescription.CreateDynamic(new Vector3(), ringBoxInertia,
                                                                   new CollidableDescription(Simulation.Shapes.Add(ringBoxShape), 0.1f),
                                                                   new BodyActivityDescription(0.01f));

                boxDescription.Pose = new RigidPose(new Vector3(1, 9, 10 + a), new Quaternion(0, 0, 0, 1));
                bodyHandle          = Simulation.Bodies.Add(boxDescription);
            }
        }
예제 #18
0
파일: Bepu.cs 프로젝트: parapoohda/testBepu
        void CreateCharacter(CharacterControllers characterCTs, Vector3 position, int unitId)
        {
            var shape      = new Capsule(0.5f, 1);
            var shapeIndex = Simulation.Shapes.Add(shape);

            bodyHandle = Simulation.Bodies.Add(BodyDescription.CreateDynamic(position, new BodyInertia {
                InverseMass = 1f / 1f
            }, new CollidableDescription(shapeIndex, 0.1f), new BodyActivityDescription(shape.Radius * 0.02f)));
            character = new Character(unitId, "test", this, position);
            character.SetCharacterInput(characterCTs, bodyHandle, Simulation);
            characters.Add(character.UnitId, character);
            //Console.WriteLine($"characters[0]: {characters}");

            //character = new CharacterInput(characters, position, new Capsule(0.5f, 1), 0.1f, 1, 20, 100, 6, 4, MathF.PI * 0.4f);
        }
예제 #19
0
        public override void Initialize(ContentArchive content, Camera camera)
        {
            camera.Position = new Vector3(0, 5, 25);
            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());

            //Drop a pyramid on top of the sensor so there are more contacts to look at.
            var boxShape = new Box(1, 1, 1);

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

            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 + 10, 0),
                                                                        boxInertia,
                                                                        new CollidableDescription(boxIndex, 0.1f),
                                                                        new BodyActivityDescription(0.01f)));
                }
            }


            sensorBodyHandle = Simulation.Bodies.Add(BodyDescription.CreateConvexDynamic(new Vector3(0, 0, 1), 10, Simulation.Shapes, new Box(4, 2, 6)));

            //Put a mesh under the sensor so that nonconvex contacts are shown.
            const int planeWidth  = 128;
            const int planeHeight = 128;

            DemoMeshHelper.CreateDeformedPlane(planeWidth, planeHeight,
                                               (int x, int y) =>
            {
                return(new Vector3(x - planeWidth / 2, 1 * MathF.Cos(x / 2f) * MathF.Sin(y / 2f), y - planeHeight / 2));
            }, new Vector3(2, 1, 2), BufferPool, out var planeMesh);
            Simulation.Statics.Add(new StaticDescription(new Vector3(0, -2, 0), QuaternionEx.CreateFromAxisAngle(new Vector3(0, 1, 0), MathF.PI / 2),
                                                         new CollidableDescription(Simulation.Shapes.Add(planeMesh), 0.1f)));
        }
예제 #20
0
        public override void ProcessBlock(float deltaTime, BlockAccessor block)
        {
            var entities  = block.GetEntityData();
            var rbs       = block.GetComponentData <RigidBody>();
            var colliders = block.GetReadOnlyComponentData <InternalColliderHandle>();

            for (int i = 0; i < block.length; i++)
            {
                var shapeIdx = colliders[i].shapeIdx;


                int handle;
                if (rbs[i].mass == 0)
                {
                    afterUpdateCommands.AddComponent(entities[i],
                                                     new InternalRigidBodyHandle()
                    {
                        rigidBodyHandle = handle =
                            PhysicsSystem.Simulation.Bodies.Add(
                                BodyDescription.CreateKinematic(RigidPose.Identity,
                                                                new CollidableDescription(
                                                                    shapeIdx, 0.1f,
                                                                    new ContinuousDetectionSettings {
                            Mode = (ContinuousDetectionMode)rbs[i].detectionMode
                        }),
                                                                new BodyActivityDescription(sleepThreshold: 0.001f)))
                    });
                }
                else
                {
                    afterUpdateCommands.AddComponent(entities[i],
                                                     new InternalRigidBodyHandle()
                    {
                        rigidBodyHandle = handle =
                            PhysicsSystem.Simulation.Bodies.Add(
                                BodyDescription.CreateDynamic(RigidPose.Identity, colliders[i].inertia,
                                                              new CollidableDescription(
                                                                  shapeIdx, 0.1f,
                                                                  new ContinuousDetectionSettings {
                            Mode = (ContinuousDetectionMode)rbs[i].detectionMode
                        }),
                                                              new BodyActivityDescription(sleepThreshold: 0.001f)))
                    });
                }

                PhysicsSystem.rigidBodyEntityDictionary.Add(handle, entities[i]);
            }
        }
예제 #21
0
        public unsafe override void Initialize(ContentArchive content, Camera camera)
        {
            camera.Position = new Vector3(-30, 40, -30);
            camera.Yaw      = MathHelper.Pi * 3f / 4;
            camera.Pitch    = MathHelper.Pi * 0.2f;

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

            var ringBoxShape = new Box(0.5f, 1, 3);

            ringBoxShape.ComputeInertia(1, out var ringBoxInertia);
            var boxDescription = BodyDescription.CreateDynamic(new Vector3(), ringBoxInertia,
                                                               new CollidableDescription(Simulation.Shapes.Add(ringBoxShape), 0.1f),
                                                               new BodyActivityDescription(0.01f));

            var       layerPosition     = new Vector3();
            const int layerCount        = 6;
            var       innerRadius       = 15f;
            var       heightPerPlatform = 3;
            var       platformsPerLayer = 1;
            var       ringSpacing       = 0.5f;

            for (int layerIndex = 0; layerIndex < layerCount; ++layerIndex)
            {
                var ringCount = layerCount - layerIndex;
                for (int ringIndex = 0; ringIndex < ringCount; ++ringIndex)
                {
                    CreateRing(Simulation, layerPosition, ringBoxShape, boxDescription, innerRadius + ringIndex * (ringBoxShape.Length + ringSpacing) + layerIndex * (ringBoxShape.Length - ringBoxShape.Width), heightPerPlatform, platformsPerLayer);
                }
                layerPosition.Y += platformsPerLayer * (ringBoxShape.Height * heightPerPlatform + ringBoxShape.Width);
            }

            //Console.WriteLine($"box count: {Simulation.Bodies.ActiveSet.Count}");
            Simulation.Statics.Add(new StaticDescription(new Vector3(0, -0.5f, 0), new CollidableDescription(Simulation.Shapes.Add(new Box(500, 1, 500)), 0.1f)));

            var bulletShape = new Sphere(0.5f);

            bulletShape.ComputeInertia(.1f, out var bulletInertia);
            bulletDescription = BodyDescription.CreateDynamic(new Vector3(), bulletInertia, new CollidableDescription(Simulation.Shapes.Add(bulletShape), 10), new BodyActivityDescription(0.01f));

            var shootiePatootieShape = new Sphere(3f);

            shootiePatootieShape.ComputeInertia(100, out var shootiePatootieInertia);
            shootiePatootieDescription = BodyDescription.CreateDynamic(new Vector3(), shootiePatootieInertia, new CollidableDescription(Simulation.Shapes.Add(shootiePatootieShape), 10), new BodyActivityDescription(0.01f));
        }
예제 #22
0
파일: GameObject.cs 프로젝트: tottaka/GameX
        public void SetCollider(PhysicsType type)
        {
            if (PhysicsBodyInitialized)
            {
                RemoveCollider();

                if (type == PhysicsType.None)
                {
                    PhysicsType = type;
                    if (Physics.PhysicsObjects.Contains(this))
                    {
                        Physics.PhysicsObjects.Remove(this);
                    }

                    return;
                }
            }

            if (type == PhysicsType.Cube)
            {
                Box shape = new Box(2.0f, 2.0f, 2.0f);
                ShapeIndex = Physics.simulator.Shapes.Add(shape);
                Shape      = shape;
            }
            else if (type == PhysicsType.Sphere)
            {
                Sphere shape = new Sphere(2.0f);
                ShapeIndex = Physics.simulator.Shapes.Add(shape);
                Shape      = shape;
            }

            Shape.ComputeInertia(Mass, out BodyInertia inertia);

            PhysicsDescription = BodyDescription.CreateDynamic(transform.Position, inertia, new CollidableDescription(ShapeIndex, 0.1f), new BodyActivityDescription(0.01f));
            BodyHandle         = Physics.simulator.Bodies.Add(PhysicsDescription);
            BodyReference      = Physics.simulator.Bodies.GetBodyReference(BodyHandle);

            if (!Physics.PhysicsObjects.Contains(this))
            {
                Physics.PhysicsObjects.Add(this);
            }

            PhysicsType            = type;
            PhysicsBodyInitialized = true;
            physicsEnabled         = true;
        }
예제 #23
0
        public unsafe override void Initialize(ContentArchive content, Camera camera)
        {
            camera.Position = new Vector3(-30, 40, -30);
            camera.Yaw      = MathHelper.Pi * 3f / 4;
            camera.Pitch    = MathHelper.Pi * 0.2f;

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

            var ringBoxShape = new Box(0.5f, 1.5f, 3);

            ringBoxShape.ComputeInertia(1, out var ringBoxInertia);
            var boxDescription = BodyDescription.CreateDynamic(new Vector3(), ringBoxInertia,
                                                               new CollidableDescription(Simulation.Shapes.Add(ringBoxShape), 0.1f),
                                                               new BodyActivityDescription(0.01f));

            var       layerPosition     = new Vector3();
            const int layerCount        = 10;
            var       innerRadius       = 5f;
            var       heightPerPlatform = 2;
            var       platformsPerLayer = 1;
            var       ringSpacing       = 0.5f;

            for (int layerIndex = 0; layerIndex < layerCount; ++layerIndex)
            {
                var ringCount = layerCount - layerIndex;
                for (int ringIndex = 0; ringIndex < ringCount; ++ringIndex)
                {
                    CreateRing(layerPosition, ringBoxShape, boxDescription, innerRadius + ringIndex * (ringBoxShape.Length + ringSpacing) + layerIndex * (ringBoxShape.Length - ringBoxShape.Width), heightPerPlatform, platformsPerLayer);
                }
                layerPosition.Y += platformsPerLayer * (ringBoxShape.Height * heightPerPlatform + ringBoxShape.Width);
            }

            Console.WriteLine($"box count: {Simulation.Bodies.ActiveSet.Count}");
            Simulation.Statics.Add(new StaticDescription(new Vector3(0, -0.5f, 0), new CollidableDescription(Simulation.Shapes.Add(new Box(500, 1, 500)), 0.1f)));

            var bulletShape = new Sphere(0.5f);

            bulletShape.ComputeInertia(.1f, out var bulletInertia);
            bulletDescription = BodyDescription.CreateDynamic(new Vector3(), bulletInertia, new CollidableDescription(Simulation.Shapes.Add(bulletShape), 10), new BodyActivityDescription(0.01f));

            var shootiePatootieShape = new Sphere(3f);

            shootiePatootieShape.ComputeInertia(1000, out var shootiePatootieInertia);
            shootiePatootieDescription = BodyDescription.CreateDynamic(new Vector3(), shootiePatootieInertia, new CollidableDescription(Simulation.Shapes.Add(shootiePatootieShape), 10), new BodyActivityDescription(0.01f));
        }
        static int AddDynamicBody(Simulation simulation, System.Numerics.Vector3 position, BepuUtilities.Quaternion rotation, object shapeType, float mass)
        {
            switch (shapeType)
            {
            case IBoxDetection boxDetection:
                IBoxDetection box      = shapeType as IBoxDetection;
                var           boxShape = new Box(box.GetSize().x, box.GetSize().y, box.GetSize().z);
                boxShape.ComputeInertia(mass, out var boxInertia);
                var boxIndex  = simulation.Shapes.Add(boxShape);
                var boxPose   = new RigidPose(position, rotation);
                var boxHandle = simulation.Bodies.Add(BodyDescription.CreateDynamic(boxPose,
                                                                                    boxInertia,
                                                                                    new CollidableDescription(boxIndex, 0.01f),
                                                                                    new BodyActivityDescription(0.01f)));
                return(boxHandle);

            case ISphereDetection sphereDetection:
                ISphereDetection sphere = shapeType as ISphereDetection;
                var sphereShape         = new Sphere(sphere.GetRadius());
                sphereShape.ComputeInertia(mass, out var sphereInertia);
                var sphereIndex  = simulation.Shapes.Add(sphereShape);
                var spherePose   = new RigidPose(position, rotation);
                var sphereHandle = simulation.Bodies.Add(BodyDescription.CreateDynamic(spherePose,
                                                                                       sphereInertia,
                                                                                       new CollidableDescription(sphereIndex, 0.01f),
                                                                                       new BodyActivityDescription(0.01f)));
                return(sphereHandle);

            case ICapsuleDetection capsuleDetection:
                ICapsuleDetection capsule = shapeType as ICapsuleDetection;
                var capsuleShape          = new Capsule(capsule.GetRadius(), capsule.GetHeight());
                capsuleShape.ComputeInertia(mass, out var capsuleInertia);
                var capsuleIndex  = simulation.Shapes.Add(capsuleShape);
                var capsulePose   = new RigidPose(position, rotation);
                var capsuleHandle = simulation.Bodies.Add(BodyDescription.CreateDynamic(capsulePose,
                                                                                        capsuleInertia,
                                                                                        new CollidableDescription(capsuleIndex, 0.01f),
                                                                                        new BodyActivityDescription(0.01f)));
                return(capsuleHandle);

            default:
                throw new ArgumentException(message: CouldNotInitializeMessage, nameof(shapeType));
            }
        }
예제 #25
0
        public override void Initialize(ContentArchive content, Camera camera)
        {
            camera.Position = new Vector3(0, 5, 25);
            camera.Yaw      = 0;
            camera.Pitch    = 0;
            Simulation      = Simulation.Create(BufferPool, new DemoNarrowPhaseCallbacks(), new DemoPoseIntegratorCallbacks(new Vector3(0, -10, 0)));

            //Drop a pyramid on top of the sensor so there are more contacts to look at.
            var boxShape = new Box(1, 1, 1);

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

            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 + 10, 0),
                                                                        boxInertia,
                                                                        new CollidableDescription(boxIndex, 0.1f),
                                                                        new BodyActivityDescription(0.01f)));
                }
            }


            sensorBodyHandle = Simulation.Bodies.Add(BodyDescription.CreateConvexDynamic(new Vector3(0, 0, 1), 10, Simulation.Shapes, new Box(4, 2, 6)));

            //Put a mesh under the sensor so that nonconvex contacts are shown.
            const int planeWidth  = 128;
            const int planeHeight = 128;

            DemoMeshHelper.CreateDeformedPlane(planeWidth, planeHeight,
                                               (int x, int y) =>
            {
                return(new Vector3(x - planeWidth / 2, 1 * MathF.Cos(x / 2f) * MathF.Sin(y / 2f), y - planeHeight / 2));
            }, new Vector3(2, 1, 2), BufferPool, out var planeMesh);
            Simulation.Statics.Add(new StaticDescription(new Vector3(0, -2, 0), QuaternionEx.CreateFromAxisAngle(new Vector3(0, 1, 0), MathF.PI / 2),
                                                         new CollidableDescription(Simulation.Shapes.Add(planeMesh), 0.1f)));
        }
        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 DemoNarrowPhaseCallbacks(), new DemoPoseIntegratorCallbacks(new Vector3(0, -10, 0)), new PositionFirstTimestepper());

            var startTime = Stopwatch.GetTimestamp();

            DemoMeshHelper.CreateDeformedPlane(1025, 1025, (x, y) => new Vector3(x * 0.125f, MathF.Sin(x) + MathF.Sin(y), y * 0.125f), Vector3.One, BufferPool, out var originalMesh);
            Simulation.Statics.Add(new StaticDescription(new Vector3(0, 0, 0), new CollidableDescription(Simulation.Shapes.Add(originalMesh), 0.1f)));
            var endTime = Stopwatch.GetTimestamp();
            var freshConstructionTime = (endTime - startTime) / (double)Stopwatch.Frequency;

            Console.WriteLine($"Fresh construction time (ms): {freshConstructionTime * 1e3}");

            BufferPool.Take(originalMesh.GetSerializedByteCount(), out var serializedMeshBytes);
            originalMesh.Serialize(serializedMeshBytes);
            startTime = Stopwatch.GetTimestamp();
            var loadedMesh = new Mesh(serializedMeshBytes, BufferPool);

            endTime = Stopwatch.GetTimestamp();
            var loadTime = (endTime - startTime) / (double)Stopwatch.Frequency;

            Console.WriteLine($"Load time (ms): {(endTime - startTime) * 1e3 / Stopwatch.Frequency}");
            Console.WriteLine($"Relative speedup: {freshConstructionTime / loadTime}");
            Simulation.Statics.Add(new StaticDescription(new Vector3(128, 0, 0), new CollidableDescription(Simulation.Shapes.Add(loadedMesh), 0.1f)));


            BufferPool.Return(ref serializedMeshBytes);

            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.1f), new BodyActivityDescription(0.01f));

            for (int i = 0; i < 1024; ++i)
            {
                descriptionToDrop.Pose.Position = new Vector3(8 + 240 * (float)random.NextDouble(), 10 + 10 * (float)random.NextDouble(), 8 + 112 * (float)random.NextDouble());
                Simulation.Bodies.Add(descriptionToDrop);
            }
        }
예제 #27
0
        public unsafe override void Initialize(ContentArchive content, Camera camera)
        {
            camera.Position = new Vector3(-5f, 5.5f, 5f);
            camera.Yaw      = MathHelper.Pi / 4;
            camera.Pitch    = MathHelper.Pi * 0.15f;

            var filters = new BodyProperty <DeformableCollisionFilter>();

            Simulation = Simulation.Create(BufferPool, new DeformableCallbacks {
                Filters = filters
            }, new DemoPoseIntegratorCallbacks(new Vector3(0, -10, 0)));

            var   meshContent = content.Load <MeshContent>("Content\\newt.obj");
            float cellSize    = 0.1f;

            DumbTetrahedralizer.Tetrahedralize(meshContent.Triangles, cellSize, BufferPool,
                                               out var vertices, out var vertexSpatialIndices, out var cellVertexIndices, out var tetrahedraVertexIndices);
            var weldSpringiness   = new SpringSettings(30f, 0);
            var volumeSpringiness = new SpringSettings(30f, 1);

            for (int i = 0; i < 5; ++i)
            {
                NewtDemo.CreateDeformable(Simulation, new Vector3(i * 3, 5 + i * 1.5f, 0), Quaternion.CreateFromAxisAngle(new Vector3(1, 0, 0), MathF.PI * (i * 0.55f)), 1f, cellSize, weldSpringiness, volumeSpringiness, i, filters, ref vertices, ref vertexSpatialIndices, ref cellVertexIndices, ref tetrahedraVertexIndices);
            }

            BufferPool.Return(ref vertices);
            vertexSpatialIndices.Dispose(BufferPool);
            BufferPool.Return(ref cellVertexIndices);
            BufferPool.Return(ref tetrahedraVertexIndices);

            Simulation.Bodies.Add(BodyDescription.CreateConvexDynamic(new Vector3(0, 100, -.5f), 10, Simulation.Shapes, new Sphere(5)));

            Simulation.Statics.Add(new StaticDescription(new Vector3(0, -0.5f, 0), new CollidableDescription(Simulation.Shapes.Add(new Box(1500, 1, 1500)), 0.1f)));
            Simulation.Statics.Add(new StaticDescription(new Vector3(0, -1.5f, 0), new CollidableDescription(Simulation.Shapes.Add(new Sphere(3)), 0.1f)));

            var bulletShape = new Sphere(0.5f);

            bulletShape.ComputeInertia(.25f, out var bulletInertia);
            bulletDescription = BodyDescription.CreateDynamic(RigidPose.Identity, bulletInertia, new CollidableDescription(Simulation.Shapes.Add(bulletShape), 1f), new BodyActivityDescription(0.01f));

            DemoMeshHelper.LoadModel(content, BufferPool, "Content\\newt.obj", new Vector3(20), out var mesh);
            Simulation.Statics.Add(new StaticDescription(new Vector3(200, 0.5f, 120), Quaternion.CreateFromAxisAngle(Vector3.UnitY, -3 * MathHelper.PiOver4), new CollidableDescription(Simulation.Shapes.Add(mesh), 0.1f)));
        }
예제 #28
0
        protected virtual void DefinePhysicsObject(float size, float mass)
        {
            if (size == 0 || mass == 0)
            {
                throw new Exception("WorldBody defined with zero size or mass");
            }

            var shape      = new Sphere(size);
            var position2d = InitialPosition();

            ShapeHandle = World.Simulation.Shapes.Add(shape);
            BodyHandle  = World.Simulation.Bodies.Add(BodyDescription.CreateDynamic(
                                                          new Vector3(position2d.X, 0, position2d.Y),
                                                          GetBodyInertia(shape, mass),
                                                          new CollidableDescription(ShapeHandle, 150f),
                                                          //new CollidableDescription(ShapeHandle, 0.1f, ContinuousDetectionSettings.Continuous(1e-4f, 1e-4f)),
                                                          new BodyActivityDescription(0.0f)
                                                          ));
        }
예제 #29
0
        internal void AddCharacter(Character character)
        {
            var characterShape = character.Shape();

            characterShape.ComputeInertia(1, out var characterInertia);

            int handle = simulation.Bodies.Add(BodyDescription.CreateDynamic(character.GetStartPosition(), characterInertia, new CollidableDescription(simulation.Shapes.Add(characterShape), 0.1f), new BodyActivityDescription(0.01f)));

            handleUnits.Add(handle, character);
            character.SetBodyHandle(handle);
            character.PeriodicAABB();
            character.SetCharacterInput(bufferPool, handle, simulation);
            if (walkCharacters.TryAdd <int, Character>(1, character))
            {
                //walkCharacters.Add(1, character);
                //Console.WriteLine("===========", walkCharacters.Count);
            }
            //character.SetBodyReference(Simulation.Bodies.GetBodyReference(handle));
        }
예제 #30
0
        public unsafe override void Initialize(ContentArchive content, Camera camera)
        {
            camera.Position = new Vector3(0, 40, 200);
            camera.Yaw      = 0;
            camera.Pitch    = 0;
            //This type of position-based bounciness requires feedback from position error to drive the corrective impulses that make stuff bounce.
            //The briefer a collision is, the more damped the bounce becomes relative to the physical ideal.
            //To counteract this, a substepping timestepper is used. In the demos, we update the simulation at 60hz, so a substep count of 4 means the solver and integrator will run at 240hz.
            //That allows higher stiffnesses to be used since collisions last longer relative to the solver timestep duration.
            //(Note that substepping tends to be an extremely strong simulation stabilizer, so you can usually get away with lower solver iteration counts for better performance.)
            var collidableMaterials = new CollidableProperty <SimpleMaterial>();

            Simulation = Simulation.Create(BufferPool, new BounceCallbacks()
            {
                CollidableMaterials = collidableMaterials
            }, new DemoPoseIntegratorCallbacks(new Vector3(0, -10, 0)), new SubsteppingTimestepper(4), solverIterationCount: 2);

            var shape = new Sphere(1);

            shape.ComputeInertia(1, out var inertia);
            var ballDescription = BodyDescription.CreateDynamic(RigidPose.Identity, inertia, new CollidableDescription(Simulation.Shapes.Add(shape), 20f), new BodyActivityDescription(1e-2f));

            for (int i = 0; i < 100; ++i)
            {
                for (int j = 0; j < 100; ++j)
                {
                    //We'll drop balls in a grid. From left to right, we increase stiffness, and from back to front (relative to the camera), we'll increase damping.
                    //Note that higher frequency values tend to result in smaller bounces even at 0 damping. This is not physically realistic; it's a byproduct of the solver timestep being too long to properly handle extremely brief contacts.
                    //(Try increasing the substep count above to higher values and watch how the bounce gets closer and closer to equal height across frequency values.)
                    ballDescription.Pose.Position = new Vector3(i * 3 - 99f * 3f / 2f, 100, j * 3 - 230);
                    collidableMaterials.Allocate(Simulation.Bodies.Add(ballDescription)) = new SimpleMaterial {
                        FrictionCoefficient = 1, MaximumRecoveryVelocity = float.MaxValue, SpringSettings = new SpringSettings(5 + 0.25f * i, j * j / 10000f)
                    };
                }
            }

            collidableMaterials.Allocate(Simulation.Statics.Add(new StaticDescription(new Vector3(0, -15f, 0), new CollidableDescription(Simulation.Shapes.Add(new Box(2500, 30, 2500)), 0.1f)))) =
                new SimpleMaterial {
                FrictionCoefficient = 1, MaximumRecoveryVelocity = 2, SpringSettings = new SpringSettings(30, 1)
            };
        }