Esempio n. 1
0
        public override void Initialize()
        {
            var model = GetModelFromOwner();
            var size  = MeasureMesh(model);

            Entity = new Sphere(
                MathConverter.Convert(Manager.Owner.Location),
                size.X / 2,
                Mass);

            if (Mass <= 0)
            {
                Entity.BecomeKinematic();
            }
            else
            {
                Entity.BecomeDynamic(Mass);
            }

            base.Initialize();
        }
Esempio n. 2
0
        public Player(ContentRepository repo,
#if WPF
                      MonoGameControl.
#else
                      Microsoft.Xna.Framework.
#endif
                      Game game, Camera camera, Tunnel tunnel)
            : base(
                "Player",
                new Box(MathConverter.Convert(new Vector3(0, 0, 20)), 4f, 1f, 2.5f),
                repo.LoadModel("Models/Ship2"),
                Matrix.CreateScale(0.0025f) * Matrix.CreateRotationX((float)Math.PI),
                game, camera)
        {
            _world              = World;
            _tunnel             = tunnel;
            Angle               = 0f;
            _distanceFromCenter = 7.8f;
            _zDistance          = 6f;
            _tiltRotation       = 0f;
        }
Esempio n. 3
0
        public static void CastRay(Ray ray, float maxDistance, bool filterStaticMeshes,
                                   out RayCastResult result)
        {
            result = new RayCastResult();

            if (filterStaticMeshes)
            {
                SimulationSpace.RayCast(
                    MathConverter.Convert(ray),
                    maxDistance,
                    FilterStaticMesh,
                    out result);
            }
            else
            {
                SimulationSpace.RayCast(
                    MathConverter.Convert(ray),
                    maxDistance,
                    out result);
            }
        }
Esempio n. 4
0
        public static void CastRay(Ray ray, float maxDistance, bool filterStaticMeshes,
                                   out PhysicsComponent.GameObjectInfo info)
        {
            RayCastResult result = new RayCastResult();

            info = null;

            if (filterStaticMeshes)
            {
                SimulationSpace.RayCast(
                    MathConverter.Convert(ray),
                    maxDistance,
                    FilterStaticMesh,
                    out result);
            }
            else
            {
                SimulationSpace.RayCast(
                    MathConverter.Convert(ray),
                    maxDistance,
                    out result);
            }

            if (result.HitObject != null)
            {
                if (result.HitObject is Collidable)
                {
                    var collidable = result.HitObject as Collidable;

                    if (collidable.Tag != null)
                    {
                        if (collidable.Tag is PhysicsComponent.GameObjectInfo)
                        {
                            info = collidable.Tag as PhysicsComponent.GameObjectInfo;
                        }
                    }
                }
            }
        }
        public override void Initialize()
        {
            var model = TryAndGetModelFromOwner();

            if (model != null)
            {
                Vector3[] vertices;
                int[]     indices;

                ModelDataExtractor.GetVerticesAndIndicesFromModel(model, out vertices, out indices);

                var mesh = new StaticMesh(MathConverter.Convert(vertices), indices,
                                          new BEPUutilities.AffineTransform(MathConverter.Convert(Owner.World.Translation)));

                mesh.Tag = Owner.ID;

                //static mesh is the only exception when working with physics entities
                PhysicsManager.AddStaticMesh(mesh);
            }

            base.Initialize();
        }
Esempio n. 6
0
        public override void GetMeshData(List <VertexPositionNormalTexture> vertices, List <ushort> indices)
        {
            for (int i = 0; i < DisplayedObject.SurfaceTriangles.Count; i++)
            {
                Vector3 upVector = MathConverter.Convert(DisplayedObject.UpVector);
                vertices.Add(new VertexPositionNormalTexture(MathConverter.Convert(DisplayedObject.SurfaceTriangles[i][0]), upVector, new Vector2(0, 0)));
                vertices.Add(new VertexPositionNormalTexture(MathConverter.Convert(DisplayedObject.SurfaceTriangles[i][1]), upVector, new Vector2(0, 1)));
                vertices.Add(new VertexPositionNormalTexture(MathConverter.Convert(DisplayedObject.SurfaceTriangles[i][2]), upVector, new Vector2(1, 0)));

                vertices.Add(new VertexPositionNormalTexture(MathConverter.Convert(DisplayedObject.SurfaceTriangles[i][0]), -upVector, new Vector2(0, 0)));
                vertices.Add(new VertexPositionNormalTexture(MathConverter.Convert(DisplayedObject.SurfaceTriangles[i][1]), -upVector, new Vector2(0, 1)));
                vertices.Add(new VertexPositionNormalTexture(MathConverter.Convert(DisplayedObject.SurfaceTriangles[i][2]), -upVector, new Vector2(1, 0)));

                indices.Add((ushort)(i * 6));
                indices.Add((ushort)(i * 6 + 1));
                indices.Add((ushort)(i * 6 + 2));

                indices.Add((ushort)(i * 6 + 3));
                indices.Add((ushort)(i * 6 + 5));
                indices.Add((ushort)(i * 6 + 4));
            }
        }
        public void BenchmarkInvert()
        {
            var swf = new Stopwatch();
            var swd = new Stopwatch();

            var deltas = new List <decimal>();

            foreach (var m in testCases)
            {
                Matrix3x3 testCase = m;

                for (int i = 0; i < 10000; i++)
                {
                    FloatMatrix3x3 floatMatrix = MathConverter.Convert(testCase);
                    FloatMatrix3x3 expected;
                    swf.Start();
                    FloatMatrix3x3.Invert(ref floatMatrix, out expected);
                    swf.Stop();

                    Matrix3x3 actual;
                    swd.Start();
                    Matrix3x3.Invert(ref testCase, out actual);
                    swd.Stop();

                    if (float.IsInfinity(expected.M11) || float.IsNaN(expected.M11))
                    {
                        expected = new FloatMatrix3x3();
                    }

                    foreach (decimal delta in GetDeltas(expected, actual))
                    {
                        deltas.Add(delta);
                    }
                }
            }
            output.WriteLine("Max error: {0} ({1} times precision)", deltas.Max(), deltas.Max() / Fix64.Precision);
            output.WriteLine("Average precision: {0} ({1} times precision)", deltas.Average(), deltas.Average() / Fix64.Precision);
            output.WriteLine("Fix64.Invert time = {0}ms, float.Invert time = {1}ms", swf.ElapsedMilliseconds, swd.ElapsedMilliseconds);
        }
Esempio n. 8
0
        private void OnRenderObject()
        {
            if (drawLines)
            {
                Camera camera = Camera.current;

                Vector3 min = new Vector3(-GRID_SIZE, 0, -GRID_SIZE);
                Vector3 max = new Vector3(GRID_SIZE, 0, GRID_SIZE);

                DrawLines.DrawGrid(camera, Color.white, min, max, 1, transform.localToWorldMatrix);

                Matrix4x4d m         = MathConverter.ToMatrix4x4d(transform.localToWorldMatrix);
                Vector4[]  Positions = new Vector4[Body.Positions.Length];
                for (int i = 0; i < Positions.Length; i++)
                {
                    Positions[i] = Body.Positions[i];
                }
                DrawLines.DrawVertices(LINE_MODE.TRIANGLES, camera, Color.red, Positions, Body.Indices, MathConverter.ToMatrix4x4(m));

                DrawLines.DrawBounds(camera, Color.green, StaticBounds, Matrix4x4d.Identity);
            }
        }
Esempio n. 9
0
        public static void GetShapeMeshData(EntityCollidable collidable, List <VertexPositionNormalTexture> vertices, List <ushort> indices)
        {
            MobileMeshShape shape        = collidable.Shape as MobileMeshShape;
            var             tempVertices = new VertexPositionNormalTexture[shape.TriangleMesh.Data.Vertices.Length];

            for (int i = 0; i < shape.TriangleMesh.Data.Vertices.Length; i++)
            {
                BEPUphysics.MathExtensions.Vector3 position;
                shape.TriangleMesh.Data.GetVertexPosition(i, out position);
                tempVertices[i] = new VertexPositionNormalTexture(
                    MathConverter.Convert(position),
                    Vector3.Zero,
                    Vector2.Zero);
            }

            for (int i = 0; i < shape.TriangleMesh.Data.Indices.Length; i++)
            {
                indices.Add((ushort)shape.TriangleMesh.Data.Indices[i]);
            }
            for (int i = 0; i < indices.Count; i += 3)
            {
                int     a      = indices[i];
                int     b      = indices[i + 1];
                int     c      = indices[i + 2];
                Vector3 normal = Vector3.Normalize(Vector3.Cross(
                                                       tempVertices[c].Position - tempVertices[a].Position,
                                                       tempVertices[b].Position - tempVertices[a].Position));
                tempVertices[a].Normal += normal;
                tempVertices[b].Normal += normal;
                tempVertices[c].Normal += normal;
            }

            for (int i = 0; i < tempVertices.Length; i++)
            {
                tempVertices[i].Normal.Normalize();
                vertices.Add(tempVertices[i]);
            }
        }
Esempio n. 10
0
        /// <summary>
        /// Moves the constraint lines to the proper location relative to the entities involved.
        /// </summary>
        public override void Update()
        {
            //Move lines around
            Vector3 left  = MathConverter.Convert(LineObject.ConnectionB.Position - LineObject.Basis.PrimaryAxis);
            Vector3 right = MathConverter.Convert(LineObject.ConnectionB.Position + LineObject.Basis.PrimaryAxis);

            Vector3 upwardsOffset    = Vector3.TransformNormal(MathConverter.Convert(LineObject.Basis.XAxis), Matrix.CreateFromAxisAngle(MathConverter.Convert(LineObject.Basis.PrimaryAxis), LineObject.MaximumAngle));
            Vector3 topRightPosition = right + upwardsOffset;
            Vector3 topLeftPosition  = left + upwardsOffset;

            Vector3 downwardsOffset     = Vector3.TransformNormal(MathConverter.Convert(LineObject.Basis.XAxis), Matrix.CreateFromAxisAngle(MathConverter.Convert(LineObject.Basis.PrimaryAxis), LineObject.MinimumAngle));
            Vector3 bottomRightPosition = right + downwardsOffset;
            Vector3 bottomLeftPosition  = left + downwardsOffset;

            middle.PositionA = left;
            middle.PositionB = right;

            topLeft.PositionA = left;
            topLeft.PositionB = topLeftPosition;

            topRight.PositionA = right;
            topRight.PositionB = topRightPosition;

            top.PositionA = topLeftPosition;
            top.PositionB = topRightPosition;

            bottomLeft.PositionA = left;
            bottomLeft.PositionB = bottomLeftPosition;

            bottomRight.PositionA = right;
            bottomRight.PositionB = bottomRightPosition;

            bottom.PositionA = bottomLeftPosition;
            bottom.PositionB = bottomRightPosition;

            testAxis.PositionA = MathConverter.Convert(LineObject.ConnectionB.Position);
            testAxis.PositionB = MathConverter.Convert(LineObject.ConnectionB.Position + LineObject.TestAxis);
        }
Esempio n. 11
0
        public static void GetShapeMeshData(EntityCollidable collidable, List <VertexPositionNormalTexture> vertices, List <ushort> indices)
        {
            var shape = collidable.Shape as ConvexShape;

            if (shape == null)
            {
                throw new ArgumentException("Wrong shape type for this helper.");
            }
            var vertexPositions = new BEPUutilities.Vector3[SampleDirections.Length];

            for (int i = 0; i < SampleDirections.Length; ++i)
            {
                shape.GetLocalExtremePoint(SampleDirections[i], out vertexPositions[i]);
            }

            var hullIndices = new RawList <int>();

            ConvexHullHelper.GetConvexHull(vertexPositions, hullIndices);


            var hullTriangleVertices = new RawList <BEPUutilities.Vector3>();

            foreach (int i in hullIndices)
            {
                hullTriangleVertices.Add(vertexPositions[i]);
            }

            for (ushort i = 0; i < hullTriangleVertices.Count; i += 3)
            {
                Vector3 normal = MathConverter.Convert(BEPUutilities.Vector3.Normalize(BEPUutilities.Vector3.Cross(hullTriangleVertices[i + 2] - hullTriangleVertices[i], hullTriangleVertices[i + 1] - hullTriangleVertices[i])));
                vertices.Add(new VertexPositionNormalTexture(MathConverter.Convert(hullTriangleVertices[i]), normal, new Vector2(0, 0)));
                vertices.Add(new VertexPositionNormalTexture(MathConverter.Convert(hullTriangleVertices[i + 1]), normal, new Vector2(1, 0)));
                vertices.Add(new VertexPositionNormalTexture(MathConverter.Convert(hullTriangleVertices[i + 2]), normal, new Vector2(0, 1)));
                indices.Add(i);
                indices.Add((ushort)(i + 1));
                indices.Add((ushort)(i + 2));
            }
        }
Esempio n. 12
0
        public static void RunStoreToConverter()
        {
            PoolGenerator gs = new PoolGenerator("GeneratorS");
            PoolGenerator gc = new PoolGenerator("GeneratorC");

            ListStorage s = new ListStorage();

            s.Enable();
            s.Name = "Store";

            MathConverter c = new MathConverter();

            c.Enable();
            c.Name = "Calculator";

            Builder.DataConnect(s, c);

            Builder.ActivationConnect(gs, s);
            Builder.ActivationConnect(gc, c);

            gs.Enable();
            gc.Enable();
        }
Esempio n. 13
0
        public override void Draw(GameTime gameTime)
        {
            //Notice that the entity's worldTransform property is being accessed here.
            //This property is returns a rigid transformation representing the orientation
            //and translation of the entity combined.
            //There are a variety of properties available in the entity, try looking around
            //in the list to familiarize yourself with it.
            Matrix worldMatrix = MathConverter.Convert(Transform * entity.WorldTransform);


            model.CopyAbsoluteBoneTransformsTo(boneTransforms);
            foreach (ModelMesh mesh in model.Meshes)
            {
                foreach (BasicEffect effect in mesh.Effects)
                {
                    effect.World      = boneTransforms[mesh.ParentBone.Index] * worldMatrix;
                    effect.View       = MathConverter.Convert((Game as GettingStartedGame).Camera.ViewMatrix);
                    effect.Projection = MathConverter.Convert((Game as GettingStartedGame).Camera.ProjectionMatrix);
                }
                mesh.Draw();
            }
            base.Draw(gameTime);
        }
Esempio n. 14
0
        /// <summary>
        /// Draws the given image.
        /// </summary>
        /// <param name="image">The source of pixel data to be rendered.</param>
        /// <param name="destinationOrigin">The origin point where to draw the image.</param>
        public void DrawImage(
            IImage image,
            Vector2 destinationOrigin)
        {
            if (_renderTarget == null)
            {
                return;
            }

            image.EnsureNotNull(nameof(image));

            var internalImage = (IImageInternal)image;

            internalImage.EnsureNotNull(nameof(internalImage));

            if (_deviceContext != null)
            {
                var d2dImage = internalImage.GetImageObject(this.Device) as D2D.ID2D1Image;
                d2dImage.EnsureNotNull(nameof(d2dImage));

                _deviceContext.DrawImage(
                    d2dImage,
                    MathConverter.RawFromVector2(destinationOrigin),
                    null,
                    D2D.InterpolationMode.Linear,
                    D2D.CompositeMode.SourceOver);
            }
            else
            {
                var bitmap = internalImage.TryGetSourceBitmap();

                if (bitmap != null)
                {
                    this.DrawBitmap(bitmap, destinationOrigin);
                }
            }
        }
Esempio n. 15
0
        public void ApplyTransformation()
        {
            if (_dynamicPhysicsObject == null)
            {
                RotationMatrix = Matrix.CreateRotationX((float)AngleX) * Matrix.CreateRotationY((float)AngleY) *
                                 Matrix.CreateRotationZ((float)AngleZ);
                Matrix scaleMatrix = Matrix.CreateScale(Scale);
                _worldOldMatrix = scaleMatrix * RotationMatrix * Matrix.CreateTranslation(Position);

                WorldTransform.Scale = Scale;
                WorldTransform.World = _worldOldMatrix;

                if (StaticPhysicsObject != null)
                {
                    AffineTransform change = new AffineTransform(
                        new BEPUutilities.Vector3(Scale.X, Scale.Y, Scale.Z),
                        Quaternion.CreateFromRotationMatrix(MathConverter.Convert(RotationMatrix)),
                        MathConverter.Convert(Position));

                    if (!MathConverter.Equals(change.Matrix, StaticPhysicsObject.WorldTransform.Matrix))
                    {
                        //StaticPhysicsMatrix = MathConverter.Copy(Change.Matrix);

                        StaticPhysicsObject.WorldTransform = change;
                    }
                }
            }
            else
            {
                //Has something changed?
                WorldTransform.Scale = Scale;
                _worldOldMatrix      = Extensions.CopyFromBepuMatrix(_worldOldMatrix, _dynamicPhysicsObject.WorldTransform);
                Matrix scaleMatrix = Matrix.CreateScale(Scale);
                //WorldOldMatrix = Matrix.CreateScale(Scale)*WorldOldMatrix;
                WorldTransform.World = scaleMatrix * _worldOldMatrix;
            }
        }
Esempio n. 16
0
        internal void CheckPhysics()
        {
            if (_dynamicPhysicsObject == null)
            {
                return;
            }

            _worldNewMatrix = Extensions.CopyFromBepuMatrix(_worldNewMatrix, _dynamicPhysicsObject.WorldTransform);

            if (_worldNewMatrix != _worldOldMatrix)
            {
                WorldTransform.HasChanged = true;
                _worldOldMatrix           = _worldNewMatrix;
                Position = _worldOldMatrix.Translation;
            }
            else
            {
                if (Position != _worldNewMatrix.Translation && GameSettings.e_enableeditor)
                {
                    //DynamicPhysicsObject.Position = new BEPUutilities.Vector3(Position.X, Position.Y, Position.Z);
                    _dynamicPhysicsObject.Position = MathConverter.Convert(Position);
                }
                //    DynamicPhysicsObject.Position = new BEPUutilities.Vector3(Position.X, Position.Y, Position.Z);
                //    //WorldNewMatrix = Extensions.CopyFromBepuMatrix(WorldNewMatrix, DynamicPhysicsObject.WorldTransform);
                //    //if (Position != WorldNewMatrix.Translation)
                //    //{
                //    //    var i = 0;
                //    //}

                //}
                //else
                //{
                //    //Position = WorldOldMatrix.Translation;
                //}
            }
        }
Esempio n. 17
0
        private void BuildPhysicsMesh(object o, MeshBuildEventArgs e)
        {
            Chunk chunk = (Chunk)o;

            if (e.Vertices.Length <= 0)
            {
                return;
            }

            lock (chunk.TagSync)
            {
                if (chunk.Tag != null && chunk.Tag is BEPUChunkTag)
                {
                    BEPUChunkTag tag = (BEPUChunkTag)chunk.Tag;

                    lock (_physicsMutex)
                    {
                        _space.Remove(tag.Mesh);
                        //modelDrawer.Remove(tag.Mesh.Mesh);
                    }
                }
                else
                {
                    chunk.Tag = new BEPUChunkTag();
                }

                StaticMesh mesh = new StaticMesh(MathConverter.Convert(e.Vertices), e.Indices);

                lock (_physicsMutex)
                {
                    _space.Add(mesh);
                    //modelDrawer.Add(mesh.Mesh);
                    ((BEPUChunkTag)chunk.Tag).Mesh = mesh;
                }
            }
        }
        public void AddConverter(WordConverter cvt)
        {
            // 設定已知的轉換器。

            if (cvt is ContextTagConverter)
            {
                m_ContextTagConverter = (ContextTagConverter)cvt;
                return;
            }
            if (cvt is ChineseWordConverter)
            {
                m_ChineseConverter = (ChineseWordConverter)cvt;
                return;
            }
            if (cvt is EnglishWordConverter)
            {
                m_EnglishConverter = (EnglishWordConverter)cvt;
                return;
            }
            if (cvt is MathConverter)   // 數學符號轉換器.
            {
                m_MathConverter = (MathConverter)cvt;
                return;
            }
            if (cvt is PhoneticConverter)               // 音標轉換器.
            {
                m_PhoneticConverter = (PhoneticConverter)cvt;
                return;
            }

            // 加入其他未知的轉換器。
            if (m_Converters.IndexOf(cvt) < 0)
            {
                m_Converters.Add(cvt);
            }
        }
Esempio n. 19
0
        static void Main(string[] args)
        {
            Console.WriteLine("-------------------------------------------------");
            Console.WriteLine("Conversion of decimal to binary system.");
            Console.WriteLine("-------------------------------------------------");
            Console.WriteLine(MathConverter.DecToBin(8));


            Console.WriteLine("\n-------------------------------------------------");
            Console.WriteLine("Conversion of binary to decimal system.");
            Console.WriteLine("-------------------------------------------------");
            Console.WriteLine(MathConverter.BinToDec("0101"));


            Console.WriteLine("\n-------------------------------------------------");
            Console.WriteLine("Conversion of decimal number to roman.");
            Console.WriteLine("-------------------------------------------------");
            Console.WriteLine(MathConverter.DecToRoman(3269));


            Console.WriteLine("\n-------------------------------------------------");
            Console.WriteLine("Conversion of roman number to decimal.");
            Console.WriteLine("-------------------------------------------------");
            Console.WriteLine(MathConverter.RomanToDec("XLMCD"));


            Console.WriteLine("\n-------------------------------------------------");
            Console.WriteLine("Solving of a quadratic equation.");
            Console.WriteLine("-------------------------------------------------");
            ExtraMath.SolveQuadraticEquation(1, -3, -4);

            Console.WriteLine("\n-------------------------------------------------");
            Console.WriteLine("Generation of random double.");
            Console.WriteLine("-------------------------------------------------");
            ExtraMath.GenerateRndNum(new Random(), 0.56256, 10.581254);
        }
Esempio n. 20
0
        public override void Initialize()
        {
            var model = GetModelFromOwner();

            if (model != null)
            {
                Vector3[] vertices;
                int[]     indices;

                ModelDataExtractor.GetVerticesAndIndicesFromModel(
                    model,
                    out vertices,
                    out indices);

                Mesh = new StaticMesh(
                    MathConverter.Convert(vertices),
                    indices,
                    new BEPUutilities.AffineTransform(
                        MathConverter.Convert(Manager.Owner.Location)));
                Mesh.Tag = Manager.Owner.ID;

                PhysicsEngine.AddStaticMesh(Mesh);
            }
        }
Esempio n. 21
0
        public override void Update(Fix64 dt)
        {
            if (Game.KeyboardInput.IsKeyDown(Keys.Left))
            {
                rayCastDirection = Matrix3x3.Transform(rayCastDirection, Matrix3x3.CreateFromAxisAngle(Vector3.Forward, .01m));
            }
            if (Game.KeyboardInput.IsKeyDown(Keys.Right))
            {
                rayCastDirection = Matrix3x3.Transform(rayCastDirection, Matrix3x3.CreateFromAxisAngle(Vector3.Forward, -.01m));
            }
            if (Game.KeyboardInput.IsKeyDown(Keys.Down))
            {
                rayCastDirection = Matrix3x3.Transform(rayCastDirection, Matrix3x3.CreateFromAxisAngle(Vector3.Right, .01m));
            }
            if (Game.KeyboardInput.IsKeyDown(Keys.Up))
            {
                rayCastDirection = Matrix3x3.Transform(rayCastDirection, Matrix3x3.CreateFromAxisAngle(Vector3.Right, -.01m));
            }


            if (Game.KeyboardInput.IsKeyDown(Keys.P))
            {
                Debug.WriteLine("Break.");
            }

            base.Update(dt);

            RigidTransform localTransformB;
            RigidTransform aTransform = a.CollisionInformation.WorldTransform, bTransform = b.CollisionInformation.WorldTransform;

            MinkowskiToolbox.GetLocalTransform(ref aTransform, ref bTransform, out localTransformB);

            Vector3 position;

            if (MPRToolbox.GetLocalOverlapPosition((a.CollisionInformation.Shape as ConvexShape), (b.CollisionInformation.Shape as ConvexShape), ref localTransformB, out position))
            {
                //Vector3 rayCastDirection = new Vector3(1,0,0);// (Vector3.Normalize(localDirection) + Vector3.Normalize(collidableB.worldTransform.Position - collidableA.worldTransform.Position)) / 2;
                Fix64   previousT;
                Vector3 previousNormal;
                Fix64   t;
                Vector3 normal;

                rayCastDirection = localTransformB.Position;
                MPRToolbox.LocalSurfaceCast((a.CollisionInformation.Shape as ConvexShape), (b.CollisionInformation.Shape as ConvexShape), ref localTransformB, ref rayCastDirection, out previousT, out previousNormal);
                //Vector3 secondDirection = Vector3.Cross(rayCastDirection, Vector3.Up);
                //MPRTesting.LocalSurfaceCast((a.CollisionInformation.Shape as ConvexShape), (b.CollisionInformation.Shape as ConvexShape), ref localTransformB, ref secondDirection, out t, out normal);
                //if (t < previousT)
                //{
                //    previousNormal = normal;
                //    previousT = t;
                //}
                //Vector3 thirdDirection = Vector3.Cross(secondDirection, rayCastDirection);
                //MPRTesting.LocalSurfaceCast((a.CollisionInformation.Shape as ConvexShape), (b.CollisionInformation.Shape as ConvexShape), ref localTransformB, ref thirdDirection, out t, out normal);
                //if (t < previousT)
                //{
                //    previousNormal = normal;
                //    previousT = t;
                //}
                //Vector3 fourthDirection = -secondDirection;
                //MPRTesting.LocalSurfaceCast((a.CollisionInformation.Shape as ConvexShape), (b.CollisionInformation.Shape as ConvexShape), ref localTransformB, ref fourthDirection, out t, out normal);
                //if (t < previousT)
                //{
                //    previousNormal = normal;
                //    previousT = t;
                //}
                //Vector3 fifthDirection = -thirdDirection;
                //MPRTesting.LocalSurfaceCast((a.CollisionInformation.Shape as ConvexShape), (b.CollisionInformation.Shape as ConvexShape), ref localTransformB, ref fifthDirection, out t, out normal);
                //if (t < previousT)
                //{
                //    previousNormal = normal;
                //    previousT = t;
                //}

                //Correct the penetration depth.

                MPRToolbox.LocalSurfaceCast((a.CollisionInformation.Shape as ConvexShape), (b.CollisionInformation.Shape as ConvexShape), ref localTransformB, ref previousNormal, out t, out normal);
                contactDepth  = t;
                contactNormal = previousNormal;

                ////Converge to local minimum.
                //while (true)
                //{
                //    MPRTesting.LocalSurfaceCast((a.CollisionInformation.Shape as ConvexShape), (b.CollisionInformation.Shape as ConvexShape), ref localTransformB, ref previousNormal, out t, out normal);
                //    if (previousT - t <= Toolbox.BigEpsilon)
                //        break;

                //    previousT = t;
                //    previousNormal = normal;
                //}
            }

            #region Box Box minkowski sum
            ////Construct explicit minkowski sum.
            //Vector3[] aLines = new Vector3[8];
            //aLines[0] = new Vector3(-boxWidth / 2, -boxHeight / 2, -boxLength / 2);
            //aLines[1] = new Vector3(-boxWidth / 2, -boxHeight / 2, boxLength / 2);
            //aLines[2] = new Vector3(-boxWidth / 2, boxHeight / 2, -boxLength / 2);
            //aLines[3] = new Vector3(-boxWidth / 2, boxHeight / 2, boxLength / 2);
            //aLines[4] = new Vector3(boxWidth / 2, -boxHeight / 2, -boxLength / 2);
            //aLines[5] = new Vector3(boxWidth / 2, -boxHeight / 2, boxLength / 2);
            //aLines[6] = new Vector3(boxWidth / 2, boxHeight / 2, -boxLength / 2);
            //aLines[7] = new Vector3(boxWidth / 2, boxHeight / 2, boxLength / 2);

            //Vector3[] bLines = new Vector3[8];
            //bLines[0] = new Vector3(-groundWidth / 2, -groundHeight / 2, -groundLength / 2);
            //bLines[1] = new Vector3(-groundWidth / 2, -groundHeight / 2, groundLength / 2);
            //bLines[2] = new Vector3(-groundWidth / 2, groundHeight / 2, -groundLength / 2);
            //bLines[3] = new Vector3(-groundWidth / 2, groundHeight / 2, groundLength / 2);
            //bLines[4] = new Vector3(groundWidth / 2, -groundHeight / 2, -groundLength / 2);
            //bLines[5] = new Vector3(groundWidth / 2, -groundHeight / 2, groundLength / 2);
            //bLines[6] = new Vector3(groundWidth / 2, groundHeight / 2, -groundLength / 2);
            //bLines[7] = new Vector3(groundWidth / 2, groundHeight / 2, groundLength / 2);

            //for (int i = 0; i < 8; i++)
            //    aLines[i] = Vector3.Transform(aLines[i], localTransformB.Matrix);

            //List<Vector3> vertices = new List<Vector3>();
            //for (int i = 0; i < 8; i++)
            //{
            //    for (int j = 0; j < 8; j++)
            //    {

            //        if (b.CollisionInformation.Pairs.Count > 0)
            //        {
            //            if (b.CollisionInformation.Pairs[0].BroadPhaseOverlap.EntryA == b.CollisionInformation)
            //                vertices.Add(aLines[i] - bLines[j]);
            //            else
            //                vertices.Add(bLines[i] - aLines[j]);
            //        }
            //        else
            //        {
            //            vertices.Add(bLines[i] - aLines[j]);
            //        }
            //    }
            //}

            //var indices = new List<int>();
            //Toolbox.GetConvexHull(vertices, indices);
            #endregion

            #region Arbitrary minkowski sum
            var     vertices = new List <Vector3>();
            Vector3 max;
            var     direction   = new Vector3();
            int     NumSamples  = 16;
            Fix64   angleChange = MathHelper.TwoPi / NumSamples;

            for (int i = 1; i < NumSamples / 2 - 1; i++)
            {
                Fix64 phi    = MathHelper.PiOver2 - i * angleChange;
                var   sinPhi = Fix64.Sin(phi);
                var   cosPhi = Fix64.Cos(phi);
                for (int j = 0; j < NumSamples; j++)
                {
                    Fix64 theta = j * angleChange;
                    direction.X = Fix64.Cos(theta) * cosPhi;
                    direction.Y = sinPhi;
                    direction.Z = Fix64.Sin(theta) * cosPhi;


                    MinkowskiToolbox.GetLocalMinkowskiExtremePoint(a.CollisionInformation.Shape as ConvexShape, b.CollisionInformation.Shape as ConvexShape, ref direction, ref localTransformB, out max);

                    vertices.Add(max);
                }
            }


            MinkowskiToolbox.GetLocalMinkowskiExtremePoint(a.CollisionInformation.Shape as ConvexShape, b.CollisionInformation.Shape as ConvexShape, ref Toolbox.UpVector, ref localTransformB, out max);
            vertices.Add(max);
            MinkowskiToolbox.GetLocalMinkowskiExtremePoint(a.CollisionInformation.Shape as ConvexShape, b.CollisionInformation.Shape as ConvexShape, ref Toolbox.DownVector, ref localTransformB, out max);
            vertices.Add(max);



            var indices = new List <int>();
            ConvexHullHelper.GetConvexHull(vertices, indices);
            #endregion

            minkowskiLines.Clear();
            for (int i = 0; i < indices.Count; i += 3)
            {
                minkowskiLines.Add(new VertexPositionColor(MathConverter.Convert(vertices[indices[i]]), Microsoft.Xna.Framework.Color.Blue));
                minkowskiLines.Add(new VertexPositionColor(MathConverter.Convert(vertices[indices[i + 1]]), Microsoft.Xna.Framework.Color.Blue));

                minkowskiLines.Add(new VertexPositionColor(MathConverter.Convert(vertices[indices[i + 1]]), Microsoft.Xna.Framework.Color.Blue));
                minkowskiLines.Add(new VertexPositionColor(MathConverter.Convert(vertices[indices[i + 2]]), Microsoft.Xna.Framework.Color.Blue));

                minkowskiLines.Add(new VertexPositionColor(MathConverter.Convert(vertices[indices[i + 2]]), Microsoft.Xna.Framework.Color.Blue));
                minkowskiLines.Add(new VertexPositionColor(MathConverter.Convert(vertices[indices[i]]), Microsoft.Xna.Framework.Color.Blue));
            }
        }
 public string Floor(decimal number)
 {
     return($"The floor of {number} is: {MathConverter.Floor(number)};");
 }
Esempio n. 23
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="modelManager"></param>
        /// <param name="descriptor"></param>
        /// <param name="scene"></param>
        /// <param name="entity"></param>
        public KinematicModel(PhysicsManager physicsManager, ModelDescriptor descriptor, Scene scene, Entity entity)
        {
            this.entity         = entity;
            this.physicsManager = physicsManager;
            this.scene          = scene;
            this.preTransform   = descriptor.ComputePreTransformMatrix();
            this.nodeCount      = scene.Nodes.Count;

            convexHulls = new BepuEntity[nodeCount];
            var transforms = new Matrix[nodeCount];

            animSnapshot = new Matrix[nodeCount];
            offsets      = new Vector3[nodeCount];

            movers   = new EntityMover[nodeCount];
            rotators = new EntityRotator[nodeCount];

            scene.ComputeAbsoluteTransforms(transforms);


            for (int i = 0; i < scene.Nodes.Count; i++)
            {
                var node = scene.Nodes[i];

                if (node.MeshIndex < 0)
                {
                    continue;
                }

                var mesh     = scene.Meshes[node.MeshIndex];
                var indices  = mesh.GetIndices();
                var vertices = mesh.Vertices
                               .Select(v2 => MathConverter.Convert(v2.Position))
                               .ToList();

                var ms        = new MotionState();
                var transform = transforms[i] * preTransform *entity.GetWorldMatrix(1);

                var p = transform.TranslationVector;
                var q = Fusion.Core.Mathematics.Quaternion.RotationMatrix(transform);

                ms.AngularVelocity = MathConverter.Convert(Vector3.Zero);
                ms.LinearVelocity  = MathConverter.Convert(Vector3.Zero);
                ms.Orientation     = MathConverter.Convert(q);
                ms.Position        = MathConverter.Convert(p);

                //	recenter shape :
                //	https://bepuphysics.codeplex.com/wikipage?title=Shape%20Recentering
                var offset      = BEPUVector3.Zero;
                var convexShape = new ConvexHullShape(vertices, out offset);
                var convexHull  = new BepuEntity(convexShape, 0);

                offsets[i] = MathConverter.Convert(offset);

                convexHull.Tag = entity;

                convexHulls[i] = convexHull;

                movers[i]   = new EntityMover(convexHull);
                rotators[i] = new EntityRotator(convexHull);

                physicsManager.PhysSpace.Add(convexHull);
                physicsManager.PhysSpace.Add(movers[i]);
                physicsManager.PhysSpace.Add(rotators[i]);
            }
        }
Esempio n. 24
0
 public void Update(GameTime gameTime)
 {
     if (!SystemCore.PhysicsOnBackgroundThread)
     {
         mobileMesh.WorldTransform = MathConverter.Convert(Microsoft.Xna.Framework.Matrix.CreateTranslation(offset)) * MathConverter.Convert(ParentObject.Transform.AbsoluteTransform);
     }
     else
     {
         mobileMesh.BufferedStates.States.WorldTransform = MathConverter.Convert(Microsoft.Xna.Framework.Matrix.CreateTranslation(offset)) * MathConverter.Convert(ParentObject.Transform.AbsoluteTransform);
     }
 }
Esempio n. 25
0
        /// <summary>
        /// Handles the input and movement of the character.
        /// </summary>
        /// <param name="dt">Time since last frame in simulation seconds.</param>
        /// <param name="keyboardInput">Keyboard state.</param>
        /// <param name="gamePadInput">Gamepad state.</param>
        public void Update(float dt, KeyboardState keyboardInput, GamePadState gamePadInput)
        {
            //Update the wheel's graphics.
            for (int k = 0; k < WheelModels.Count; k++)
            {
                WheelModels[k].WorldTransform = MathConverter.Convert(Vehicle.Wheels[k].Shape.WorldTransform);
            }

            if (IsActive)
            {
                //The reason for the more complicated handling of turning is that real tanks'
                //treads target a certain speed and will apply positive or negative forces
                //to reach it.

                //The normal Vehicle class is slightly different.  If you're rolling down a hill
                //with a target velocity of 30 and you're actually going 40, the vehicle doesn't
                //try to slow down.  It won't have to apply any force to reach its goal, and lets
                //itself coast faster.

                //To change direction while moving, a tank can slow down one track.  Friction will
                //force a pivot.  Slowing down one track on this vehicle doesn't do anything
                //because the wheels will happily roll as fast as the other track, even if not
                //applying any driving force.

                //To overcome this difference, the opposite track actually tries to drive backward.
                //This forces the vehicle wheels to actually do work to slow down the track.
                //Going at full speed and reversing a track's direction can be a little jarring, so
                //its maximum force is modified dynamically to make it feel more correct.
#if XBOX360
                float speed = gamePadInput.Triggers.Right * ForwardSpeed + gamePadInput.Triggers.Left * BackwardSpeed;
                foreach (Wheel wheel in Vehicle.Wheels)
                {
                    wheel.DrivingMotor.TargetSpeed           = speed;
                    wheel.DrivingMotor.MaximumForwardForce   = MaximumDriveForce;
                    wheel.DrivingMotor.MaximumBackwardForce  = MaximumDriveForce;
                    wheel.SlidingFriction.DynamicCoefficient = BaseSlidingFriction;
                    wheel.SlidingFriction.StaticCoefficient  = BaseSlidingFriction;
                }
                //Thumbsticks can have small values even when left alone, so allow a little margin.
                const float stickMargin = .1f;
                //"Approximately stationary" is good enough to turn normally.  Pick a reasonable tolerance.
                const float fullTurnSpeedLimit = 1;
                if (speed > fullTurnSpeedLimit)
                {
                    if (gamePadInput.ThumbSticks.Left.X < -stickMargin)
                    {
                        foreach (Wheel wheel in leftTrack)
                        {
                            //Tell one of the tracks to reverse direction, but don't let it
                            //run at full force.  This helps prevents wild spinouts and encourages
                            //more 'tanky' movement.
                            wheel.DrivingMotor.TargetSpeed          = -gamePadInput.ThumbSticks.Left.X * BackwardSpeed;
                            wheel.DrivingMotor.MaximumBackwardForce = MaximumDriveForce / 2;
                        }

                        //It's possible to configure the tank in such a way
                        //that you won't have to use separate sliding frictions while turning,
                        //but cheating is a lot easier.
                        ReduceSlidingFriction();
                    }
                    if (gamePadInput.ThumbSticks.Left.X > stickMargin)
                    {
                        foreach (Wheel wheel in rightTrack)
                        {
                            wheel.DrivingMotor.TargetSpeed          = gamePadInput.ThumbSticks.Left.X * BackwardSpeed;
                            wheel.DrivingMotor.MaximumBackwardForce = MaximumDriveForce / 2;
                        }
                        ReduceSlidingFriction();
                    }
                }
                else if (speed < -fullTurnSpeedLimit)
                {
                    if (gamePadInput.ThumbSticks.Left.X > stickMargin)
                    {
                        foreach (Wheel wheel in leftTrack)
                        {
                            wheel.DrivingMotor.TargetSpeed         = gamePadInput.ThumbSticks.Left.X * ForwardSpeed;
                            wheel.DrivingMotor.MaximumForwardForce = MaximumDriveForce / 2;
                        }
                        ReduceSlidingFriction();
                    }
                    if (gamePadInput.ThumbSticks.Left.X < -stickMargin)
                    {
                        foreach (Wheel wheel in rightTrack)
                        {
                            wheel.DrivingMotor.TargetSpeed         = -gamePadInput.ThumbSticks.Left.X * ForwardSpeed;
                            wheel.DrivingMotor.MaximumForwardForce = MaximumDriveForce / 2;
                        }
                        ReduceSlidingFriction();
                    }
                }
                else
                {
                    if (gamePadInput.ThumbSticks.Left.X < 0)
                    {
                        //Turn left
                        foreach (Wheel wheel in leftTrack)
                        {
                            wheel.DrivingMotor.TargetSpeed = -gamePadInput.ThumbSticks.Left.X * BackwardSpeed / 5;
                        }
                        foreach (Wheel wheel in rightTrack)
                        {
                            wheel.DrivingMotor.TargetSpeed = -gamePadInput.ThumbSticks.Left.X * ForwardSpeed / 5;
                        }
                        ReduceSlidingFriction();
                    }
                    if (gamePadInput.ThumbSticks.Left.X > 0)
                    {
                        //Turn right
                        foreach (Wheel wheel in leftTrack)
                        {
                            wheel.DrivingMotor.TargetSpeed = gamePadInput.ThumbSticks.Left.X * ForwardSpeed / 5;
                        }
                        foreach (Wheel wheel in rightTrack)
                        {
                            wheel.DrivingMotor.TargetSpeed = gamePadInput.ThumbSticks.Left.X * BackwardSpeed / 5;
                        }
                        ReduceSlidingFriction();
                    }
                }

                if (gamePadInput.IsButtonDown(Buttons.LeftStick))
                {
                    foreach (Wheel wheel in Vehicle.Wheels)
                    {
                        wheel.Brake.IsBraking = true;
                    }
                }
                else
                {
                    foreach (Wheel wheel in Vehicle.Wheels)
                    {
                        wheel.Brake.IsBraking = false;
                    }
                }
#else
                //Reset properties to defaults.
                foreach (Wheel wheel in Vehicle.Wheels)
                {
                    wheel.Brake.IsBraking = false;
                    wheel.DrivingMotor.MaximumForwardForce   = MaximumDriveForce;
                    wheel.DrivingMotor.MaximumBackwardForce  = MaximumDriveForce;
                    wheel.SlidingFriction.DynamicCoefficient = BaseSlidingFriction;
                    wheel.SlidingFriction.StaticCoefficient  = BaseSlidingFriction;
                }

                List <Wheel> wheelsToAccelerate;
                if (keyboardInput.IsKeyDown(Keys.E))
                {
                    if (keyboardInput.IsKeyDown(Keys.S))
                    {
                        //Turn left while going forward
                        wheelsToAccelerate = rightTrack;
                        foreach (Wheel wheel in leftTrack)
                        {
                            //Tell one of the tracks to reverse direction, but don't let it
                            //run at full force.  This helps prevents wild spinouts and encourages
                            //more 'tanky' movement.
                            wheel.DrivingMotor.TargetSpeed          = BackwardSpeed;
                            wheel.DrivingMotor.MaximumBackwardForce = MaximumDriveForce / 2;
                        }
                        //It's possible to configure the tank in such a way
                        //that you won't have to use separate sliding frictions while turning,
                        //but cheating is a lot easier.
                        ReduceSlidingFriction();
                    }
                    else if (keyboardInput.IsKeyDown(Keys.F))
                    {
                        //Turn right while going forward
                        wheelsToAccelerate = leftTrack;
                        foreach (Wheel wheel in rightTrack)
                        {
                            wheel.DrivingMotor.TargetSpeed          = BackwardSpeed;
                            wheel.DrivingMotor.MaximumBackwardForce = MaximumDriveForce / 2;
                        }
                        ReduceSlidingFriction();
                    }
                    else
                    {
                        wheelsToAccelerate = Vehicle.Wheels;
                    }

                    //Drive
                    foreach (Wheel wheel in wheelsToAccelerate)
                    {
                        wheel.DrivingMotor.TargetSpeed = ForwardSpeed;
                    }
                }
                else if (keyboardInput.IsKeyDown(Keys.D))
                {
                    if (keyboardInput.IsKeyDown(Keys.F))
                    {
                        //Turn right while going back
                        wheelsToAccelerate = rightTrack;
                        foreach (Wheel wheel in leftTrack)
                        {
                            wheel.DrivingMotor.TargetSpeed         = ForwardSpeed;
                            wheel.DrivingMotor.MaximumForwardForce = MaximumDriveForce / 2;
                        }
                        ReduceSlidingFriction();
                    }
                    else if (keyboardInput.IsKeyDown(Keys.S))
                    {
                        //Turn left while going back
                        wheelsToAccelerate = leftTrack;
                        foreach (Wheel wheel in rightTrack)
                        {
                            wheel.DrivingMotor.TargetSpeed         = ForwardSpeed;
                            wheel.DrivingMotor.MaximumForwardForce = MaximumDriveForce / 2;
                        }
                        ReduceSlidingFriction();
                    }
                    else
                    {
                        wheelsToAccelerate = Vehicle.Wheels;
                    }
                    //Reverse
                    foreach (Wheel wheel in wheelsToAccelerate)
                    {
                        wheel.DrivingMotor.TargetSpeed = BackwardSpeed;
                    }
                }
                else if (keyboardInput.IsKeyDown(Keys.S))
                {
                    //Turn left
                    foreach (Wheel wheel in leftTrack)
                    {
                        wheel.DrivingMotor.TargetSpeed = BackwardSpeed / 5;
                    }
                    foreach (Wheel wheel in rightTrack)
                    {
                        wheel.DrivingMotor.TargetSpeed = ForwardSpeed / 5;
                    }
                    ReduceSlidingFriction();
                }
                else if (keyboardInput.IsKeyDown(Keys.F))
                {
                    //Turn right
                    foreach (Wheel wheel in leftTrack)
                    {
                        wheel.DrivingMotor.TargetSpeed = ForwardSpeed / 5;
                    }
                    foreach (Wheel wheel in rightTrack)
                    {
                        wheel.DrivingMotor.TargetSpeed = BackwardSpeed / 5;
                    }
                    ReduceSlidingFriction();
                }
                else
                {
                    //Idle
                    foreach (Wheel wheel in Vehicle.Wheels)
                    {
                        wheel.DrivingMotor.TargetSpeed = 0;
                    }
                }
                if (keyboardInput.IsKeyDown(Keys.Space))
                {
                    //Brake
                    foreach (Wheel wheel in Vehicle.Wheels)
                    {
                        wheel.Brake.IsBraking = true;
                    }
                }
#endif
            }
            else
            {
                //Parking brake
                foreach (Wheel wheel in Vehicle.Wheels)
                {
                    wheel.Brake.IsBraking = true;
                    //Don't want the car to keep trying to drive.
                    wheel.DrivingMotor.TargetSpeed = 0;
                }
            }
        }
Esempio n. 26
0
        public override void GetMeshData(List <VertexPositionNormalTexture> vertices, List <ushort> indices)
        {
            int          numColumns = DisplayedObject.Shape.Heights.GetLength(0);
            int          numRows    = DisplayedObject.Shape.Heights.GetLength(1);
            TerrainShape shape      = DisplayedObject.Shape;

            //The terrain can be transformed arbitrarily.  However, the collision against the triangles is always oriented such that the transformed local
            //up vector points in the same direction as the collidable surfaces.
            //To make sure the graphics match the terrain collision, try transforming the local space up direction into world space. Treat it as a normal- it requires an adjugate transpose, not a regular transformation.

            var normalTransform = Matrix3x3.AdjugateTranspose(DisplayedObject.WorldTransform.LinearTransform);

            var reverseWinding = BEPUutilities.Vector3.Dot(normalTransform.Up, DisplayedObject.WorldTransform.LinearTransform.Up) < 0;


            for (int j = 0; j < numRows; j++)
            {
                for (int i = 0; i < numColumns; i++)
                {
                    VertexPositionNormalTexture v;
                    BEPUutilities.Vector3       position, n;
                    DisplayedObject.GetPosition(i, j, out position);
                    shape.GetLocalNormal(i, j, out n);
                    Matrix3x3.Transform(ref n, ref normalTransform, out n);
                    n.Normalize();
                    MathConverter.Convert(ref position, out v.Position);
                    MathConverter.Convert(ref n, out v.Normal);


                    if (reverseWinding)
                    {
                        Vector3.Negate(ref v.Normal, out v.Normal);
                    }
                    v.TextureCoordinate = new Vector2(i, j);

                    vertices.Add(v);

                    if (i < numColumns - 1 && j < numRows - 1)
                    {
                        if (shape.QuadTriangleOrganization == QuadTriangleOrganization.BottomLeftUpperRight)
                        {
                            //v3 v4
                            //v1 v2

                            //v1 v2 v3
                            indices.Add((ushort)(numColumns * j + i));
                            if (reverseWinding)
                            {
                                indices.Add((ushort)(numColumns * (j + 1) + i));
                                indices.Add((ushort)(numColumns * j + i + 1));
                            }
                            else
                            {
                                indices.Add((ushort)(numColumns * j + i + 1));
                                indices.Add((ushort)(numColumns * (j + 1) + i));
                            }

                            //v2 v4 v3
                            indices.Add((ushort)(numColumns * j + i + 1));
                            if (reverseWinding)
                            {
                                indices.Add((ushort)(numColumns * (j + 1) + i));
                                indices.Add((ushort)(numColumns * (j + 1) + i + 1));
                            }
                            else
                            {
                                indices.Add((ushort)(numColumns * (j + 1) + i + 1));
                                indices.Add((ushort)(numColumns * (j + 1) + i));
                            }
                        }
                        else if (shape.QuadTriangleOrganization == QuadTriangleOrganization.BottomRightUpperLeft)
                        {
                            //v1 v2 v4
                            indices.Add((ushort)(numColumns * j + i));
                            if (reverseWinding)
                            {
                                indices.Add((ushort)(numColumns * (j + 1) + i + 1));
                                indices.Add((ushort)(numColumns * j + i + 1));
                            }
                            else
                            {
                                indices.Add((ushort)(numColumns * j + i + 1));
                                indices.Add((ushort)(numColumns * (j + 1) + i + 1));
                            }

                            //v1 v4 v3
                            indices.Add((ushort)(numColumns * j + i));
                            if (reverseWinding)
                            {
                                indices.Add((ushort)(numColumns * (j + 1) + i));
                                indices.Add((ushort)(numColumns * (j + 1) + i + 1));
                            }
                            else
                            {
                                indices.Add((ushort)(numColumns * (j + 1) + i + 1));
                                indices.Add((ushort)(numColumns * (j + 1) + i));
                            }
                        }
                    }
                }
            }
        }
        private bool SolveConstraint(Vector3 p0, Vector3 p1, Vector3 p2, Vector3 p3, double invMass)
        {
            double eps = 1e-9;

            Correction[0] = Vector3.zero;
            Correction[1] = Vector3.zero;
            Correction[2] = Vector3.zero;
            Correction[3] = Vector3.zero;

            Vector3[] c = new Vector3[3];
            c[0] = MathConverter.ToVector3(InvRestMatrix.GetColumn(0));
            c[1] = MathConverter.ToVector3(InvRestMatrix.GetColumn(1));
            c[2] = MathConverter.ToVector3(InvRestMatrix.GetColumn(2));

            for (int i = 0; i < 3; i++)
            {
                for (int j = 0; j <= i; j++)
                {
                    Matrix3x3d P = new Matrix3x3d();

                    // Jacobi
                    //P.col(0) = p1 - p0;
                    //P.col(1) = p2 - p0;
                    //P.col(2) = p3 - p0;

                    // Gauss - Seidel
                    P.SetColumn(0, MathConverter.ToVector3d((p1 + Correction[1]) - (p0 + Correction[0])));
                    P.SetColumn(1, MathConverter.ToVector3d((p2 + Correction[2]) - (p0 + Correction[0])));
                    P.SetColumn(2, MathConverter.ToVector3d((p3 + Correction[3]) - (p0 + Correction[0])));

                    Vector3 fi = MathConverter.ToVector3(P * MathConverter.ToVector3d(c[i]));
                    Vector3 fj = MathConverter.ToVector3(P * MathConverter.ToVector3d(c[j]));

                    double Sij = Vector3.Dot(fi, fj);

                    double wi = 0.0, wj = 0.0, s1 = 0.0, s3 = 0.0;
                    if (NormalizeShear && i != j)
                    {
                        wi = fi.magnitude;
                        wj = fj.magnitude;
                        s1 = 1.0f / (wi * wj);
                        s3 = s1 * s1 * s1;
                    }

                    Vector3[] d = new Vector3[4];
                    d[0] = Vector3.zero;

                    for (int k = 0; k < 3; k++)
                    {
                        d[k + 1] = fj * (float)InvRestMatrix[k, i] + fi * (float)InvRestMatrix[k, j];

                        if (NormalizeShear && i != j)
                        {
                            d[k + 1] = (float)s1 * d[k + 1] - (float)Sij * (float)s3 * ((float)(wj * wj) * fi * (float)InvRestMatrix[k, i] + (float)(wi * wi) * fj * (float)InvRestMatrix[k, j]);
                        }

                        d[0] -= d[k + 1];
                    }

                    if (NormalizeShear && i != j)
                    {
                        Sij *= s1;
                    }

                    double lambda = (d[0].sqrMagnitude + d[1].sqrMagnitude + d[2].sqrMagnitude + d[3].sqrMagnitude) * invMass;

                    if (Math.Abs(lambda) < eps)
                    {
                        continue;
                    }

                    if (i == j)
                    {
                        // diagonal, stretch
                        if (NormalizeStretch)
                        {
                            double s = Math.Sqrt(Sij);
                            lambda = 2.0 * s * (s - 1.0) / lambda * Stiffness;
                        }
                        else
                        {
                            lambda = (Sij - 1.0) / lambda * Stiffness;
                        }
                    }
                    else
                    {
                        // off diagonal, shear
                        lambda = Sij / lambda * Stiffness;
                    }

                    Correction[0] -= (float)lambda * (float)invMass * d[0];
                    Correction[1] -= (float)lambda * (float)invMass * d[1];
                    Correction[2] -= (float)lambda * (float)invMass * d[2];
                    Correction[3] -= (float)lambda * (float)invMass * d[3];
                }
            }

            return(true);
        }
Esempio n. 28
0
        /// <summary>
        /// This is called when the game should draw itself.
        /// </summary>
        /// <param name="gameTime">Provides a snapshot of timing values.</param>
        protected override void Draw(GameTime gameTime)
        {
            GraphicsDevice.Clear(new Color(.41f, .41f, .45f, 1));

            var viewMatrix       = Camera.ViewMatrix;
            var projectionMatrix = Camera.ProjectionMatrix;

            if (displayEntities)
            {
                ModelDrawer.Draw(viewMatrix, projectionMatrix);
            }

            if (displayConstraints)
            {
                ConstraintDrawer.Draw(viewMatrix, projectionMatrix);
            }

            LineDrawer.LightingEnabled    = false;
            LineDrawer.VertexColorEnabled = true;
            LineDrawer.World      = Matrix.Identity;
            LineDrawer.View       = MathConverter.Convert(viewMatrix);
            LineDrawer.Projection = MathConverter.Convert(projectionMatrix);

            if (displayContacts)
            {
                ContactDrawer.Draw(LineDrawer, currentSimulation.Space);
            }

            if (displayBoundingBoxes)
            {
                BoundingBoxDrawer.Draw(LineDrawer, currentSimulation.Space);
            }

            if (displaySimulationIslands)
            {
                SimulationIslandDrawer.Draw(LineDrawer, currentSimulation.Space);
            }


            //This doesn't actually draw the elements in the demo (that's the modeldrawer's job),
            //but some demos can specify their own extra stuff to draw.
            currentSimulation.Draw();

            base.Draw(gameTime);

            #region UI Drawing

            UIDrawer.Begin();
            int bottom = GraphicsDevice.Viewport.Bounds.Height;
            int right  = GraphicsDevice.Viewport.Bounds.Width;
            if (displayUI)
            {
                FPStotalSinceLast += gameTime.ElapsedGameTime.TotalSeconds;
                FPStotalFramesSinceLast++;
                if (gameTime.TotalGameTime.TotalSeconds - FPSlastTime > .25 && gameTime.ElapsedGameTime.TotalSeconds > 0)
                {
                    double avg = FPStotalSinceLast / FPStotalFramesSinceLast;
                    FPSlastTime             = gameTime.TotalGameTime.TotalSeconds;
                    FPStoDisplay            = Math.Round(1 / avg, 1);
                    averagePhysicsTime      = Math.Round(1000 * currentSimulation.PhysicsTime, 1);
                    FPStotalSinceLast       = 0;
                    FPStotalFramesSinceLast = 0;
                }

                DataTextDrawer.Draw("FPS: ", FPStoDisplay, new Vector2(50, bottom - 150));
                DataTextDrawer.Draw("Physics Time (ms): ", averagePhysicsTime, new Vector2(50, bottom - 133));
                DataTextDrawer.Draw("Collision Pairs: ", currentSimulation.Space.NarrowPhase.Pairs.Count, new Vector2(50, bottom - 116));
                if (displayActiveEntityCount)
                {
                    int countActive = 0;
                    for (int i = 0; i < currentSimulation.Space.Entities.Count; i++)
                    {
                        if (currentSimulation.Space.Entities[i].ActivityInformation.IsActive)
                        {
                            countActive++;
                        }
                    }
                    DataTextDrawer.Draw("Active Objects: ", countActive, new Vector2(50, bottom - 99));
                }
#if !WINDOWS
                DataTextDrawer.Draw("Press Start for Controls", new Vector2(50, bottom - 82));
#else
                DataTextDrawer.Draw("Press F1 for Controls", new Vector2(50, bottom - 82));
#endif

                TinyTextDrawer.Draw("Current Simulation: ", currentSimulationIndex, new Vector2(right - 200, bottom - 100));
                TinyTextDrawer.Draw(currentSimulation.Name, new Vector2(right - 180, bottom - 86));

                currentSimulation.DrawUI();
            }
            if (displayMenu)
            {
                UIDrawer.Draw(controlsMenu, new Rectangle(right / 2 - 400, bottom / 2 - 300, 800, 600), Color.White);
            }
            UIDrawer.End();

            #endregion
        }
 /// <summary>
 /// Draws the display object.
 /// </summary>
 /// <param name="viewMatrix">Current view matrix.</param>
 /// <param name="projectionMatrix">Current projection matrix.</param>
 public override void Draw(Matrix viewMatrix, Matrix projectionMatrix)
 {
     //This is not a particularly fast method of drawing.
     //It's used very rarely in the demos.
     myModel.CopyAbsoluteBoneTransformsTo(transforms);
     for (int i = 0; i < Model.Meshes.Count; i++)
     {
         for (int j = 0; j < Model.Meshes[i].Effects.Count; j++)
         {
             var effect = Model.Meshes[i].Effects[j] as BasicEffect;
             if (effect != null)
             {
                 effect.World      = transforms[Model.Meshes[i].ParentBone.Index] * MathConverter.Convert(WorldTransform);
                 effect.View       = MathConverter.Convert(viewMatrix);
                 effect.Projection = MathConverter.Convert(projectionMatrix);
             }
         }
         Model.Meshes[i].Draw();
     }
 }
 /// <summary>
 /// Gets an array of vertices and indices from the provided model.
 /// </summary>
 /// <param name="collisionModel">Model to use for the collision shape.</param>
 /// <param name="vertices">Compiled set of vertices from the model.</param>
 /// <param name="indices">Compiled set of indices from the model.</param>
 public static void GetVerticesAndIndicesFromModel(Model collisionModel, out BEPUutilities.Vector3[] vertices, out int[] indices)
 {
     Vector3[] tempVertices;
     GetVerticesAndIndicesFromModel(collisionModel, out tempVertices, out indices);
     vertices = MathConverter.Convert(tempVertices);
 }