public static Body CreateRoundedRectangle(World world, GGame.Math.Fix64 width, GGame.Math.Fix64 height, GGame.Math.Fix64 xRadius, GGame.Math.Fix64 yRadius, int segments, GGame.Math.Fix64 density, Vector2 position = new Vector2(), GGame.Math.Fix64 rotation = new Fix64(), BodyType bodyType = BodyType.Static, object userData = null)
        {
            Vertices verts = PolygonUtils.CreateRoundedRectangle(width, height, xRadius, yRadius, segments);

            //There are too many vertices in the capsule. We decompose it.
            if (verts.Count >= Settings.MaxPolygonVertices)
            {
                List <Vertices> vertList = Triangulate.ConvexPartition(verts, TriangulationAlgorithm.Earclip, true, 0.001f);
                return(CreateCompoundPolygon(world, vertList, density, position, rotation, bodyType, userData));
            }

            return(CreatePolygon(world, verts, density, position, rotation, bodyType, userData));
        }
        public static List <Fixture> AttachSolidArc(float density, float radians, int sides, float radius, Body body)
        {
            Vertices arc = PolygonUtils.CreateArc(radians, sides, radius);

            arc.Rotate((MathHelper.Pi - radians) / 2);

            //Close the arc
            arc.Add(arc[0]);

            List <Vertices> triangles = Triangulate.ConvexPartition(arc, TriangulationAlgorithm.Earclip);

            return(AttachCompoundPolygon(triangles, density, body));
        }
        public Body CreateRoundedRectangle(float width, float height, float xRadius, float yRadius, int segments, float density, Vector2 position = new Vector2(), float rotation = 0, BodyType bodyType = BodyType.Static)
        {
            Vertices verts = PolygonTools.CreateRoundedRectangle(width, height, xRadius, yRadius, segments);

            //There are too many vertices in the capsule. We decompose it.
            if (verts.Count >= Settings.MaxPolygonVertices)
            {
                List <Vertices> vertList = Triangulate.ConvexPartition(verts, TriangulationAlgorithm.Earclip);
                return(CreateCompoundPolygon(vertList, density, position, rotation, bodyType));
            }

            return(CreatePolygon(verts, density, position, rotation, bodyType));
        }
        public Body CreateCapsule(float height, float topRadius, int topEdges, float bottomRadius, int bottomEdges, float density, Vector2 position = new Vector2(), float rotation = 0, BodyType bodyType = BodyType.Static)
        {
            Vertices verts = PolygonTools.CreateCapsule(height, topRadius, topEdges, bottomRadius, bottomEdges);

            //There are too many vertices in the capsule. We decompose it.
            if (verts.Count >= Settings.MaxPolygonVertices)
            {
                List <Vertices> vertList = Triangulate.ConvexPartition(verts, TriangulationAlgorithm.Earclip);
                return(CreateCompoundPolygon(vertList, density, position, rotation, bodyType));
            }

            return(CreatePolygon(verts, density, position, rotation, bodyType));
        }
Beispiel #5
0
        public List <Fixture> CreateSolidArc(float density, float radians, int sides, float radius)
        {
            Vertices arc = PolygonTools.CreateArc(radians, sides, radius);

            arc.Rotate((Constant.Pi - radians) / 2);

            //Close the arc
            arc.Add(arc[0]);

            List <Vertices> triangles = Triangulate.ConvexPartition(arc, TriangulationAlgorithm.Earclip);

            return(CreateCompoundPolygon(triangles, density));
        }
        /// <summary>
        /// Creates a list of vertices from a texture.
        /// </summary>
        /// <param name="texture">The texture to make a body from</param>
        /// <param name="scale">The scale of the texture</param>
        /// <param name="imageSize">The size of each individual image in the hitbox</param>
        /// <param name="density">The density of the object (Will almost always be one</param>
        /// <param name="algorithm">The decomposition algorithm to use</param>
        /// <remarks> Available algorithms to use are Bayazit, Dealuny, Earclip, Flipcode, Seidel, SeidelTrapazoid</remarks>
        /// @warning In order for this to work the input must have a transparent background. I highly reccomend that you
        /// only use this with PNGs as that is what I have tested and I know they work. This will only produce a bosy as
        /// clean as the texture you give it, so avoid partically transparent areas and little edges.
        private List <Vertices>[] CreateVerticesFromTexture(Texture2D texture, float scale, Point imageSize,
                                                            float density = 1, TriangulationAlgorithm algorithm = TriangulationAlgorithm.Earclip)
        {
            int SpriteSheetSize = texture.Width * texture.Height;
            int IndividualSize  = imageSize.X * imageSize.Y;

            uint[] TextureData = new uint[SpriteSheetSize]; //Array to copy texture info into
            texture.GetData(TextureData);                   //Gets which pixels of the texture are actually filled

            List <uint[]> IndividualData = new List <uint[]>();

            for (int Processed = 0; Processed < SpriteSheetSize; Processed += IndividualSize)
            {
                uint[] TempArray = new uint[IndividualSize];

                try {
                    Array.Copy(TextureData, Processed, TempArray, 0, IndividualSize);
                } catch (ArgumentException) {
                    //At the end of textures the amount of data left might be to small
                    Array.Copy(TextureData, Processed, TempArray, 0, TextureData.Length - Processed);
                }


                IndividualData.Add(TempArray);
            }

            List <Vertices>[] TextureVertices = new List <Vertices> [IndividualData.Count];

            for (int count = 0; count < IndividualData.Count; ++count)
            {
                uint[] I = IndividualData[count];

                Vertices        vertices   = TextureConverter.DetectVertices(I, texture.Width);
                List <Vertices> VertexList = Triangulate.ConvexPartition(vertices, algorithm);

                Vector2 VertScale = new Vector2(ConvertUnits.ToSimUnits(scale));

                foreach (Vertices vert in VertexList)
                {
                    vert.Scale(ref VertScale); //Scales the vertices to match the size we specified
                }
                Vector2 Centroid = -vertices.GetCentroid();
                vertices.Translate(ref Centroid);
                //basketOrigin = -centroid;

                TextureVertices[count] = VertexList;
            }

            return(TextureVertices);
        }
        public BreakableBody(World world, Vertices vertices, float density, Vector2 position = new Vector2(), float rotation = 0) : this(world)
        {
            MainBody = World.CreateBody(position, rotation, BodyType.Dynamic);

            //TODO: Implement a Voronoi diagram algorithm to split up the vertices
            List <Vertices> triangles = Triangulate.ConvexPartition(vertices, TriangulationAlgorithm.Earclip);

            foreach (Vertices part in triangles)
            {
                PolygonShape polygonShape = new PolygonShape(part, density);
                Fixture      fixture      = MainBody.CreateFixture(polygonShape);
                Parts.Add(fixture);
            }
        }
Beispiel #8
0
        public static Body CreateGear(World world, float radius, int numberOfTeeth, float tipPercentage, float toothHeight, float density, Vector2 position = new Vector2(), float rotation = 0, BodyType bodyType = BodyType.Static, object userData = null)
        {
            var gearPolygon = PolygonTools.CreateGear(radius, numberOfTeeth, tipPercentage, toothHeight);

            //Gears can in some cases be convex
            if (!gearPolygon.IsConvex())
            {
                //Decompose the gear:
                var list = Triangulate.ConvexPartition(gearPolygon, TriangulationAlgorithm.Earclip);
                return(CreateCompoundPolygon(world, list, density, position, rotation, bodyType, userData));
            }

            return(CreatePolygon(world, gearPolygon, density, position, rotation, bodyType, userData));
        }
Beispiel #9
0
        /// <summary>
        /// Convert a closed path into a polygon.
        /// Convex decomposition is automatically performed.
        /// </summary>
        /// <param name="path">The path.</param>
        /// <param name="body">The body.</param>
        /// <param name="density">The density.</param>
        /// <param name="subdivisions">The subdivisions.</param>
        public static void ConvertPathToPolygon(Path path, Body body, float density, int subdivisions)
        {
            if (!path.IsClosed)
            {
                throw new Exception("The path must be closed to convert to a polygon.");
            }

            var verts           = path.GetVertices(subdivisions);
            var decomposedVerts = Triangulate.ConvexPartition(new Vertices(verts), TriangulationAlgorithm.Bayazit);

            foreach (Vertices item in decomposedVerts)
            {
                body.CreateFixture(new PolygonShape(item, density));
            }
        }
        public static Body CreateCapsule(World world, float height, float topRadius, int topEdges, float bottomRadius,
                                         int bottomEdges, float density, Vector2 position = new Vector2(), float rotation = 0,
                                         BodyType bodyType = BodyType.Static, object userData = null)
        {
            var verts = PolygonUtils.CreateCapsule(height, topRadius, topEdges, bottomRadius, bottomEdges);

            //There are too many vertices in the capsule. We decompose it.
            if (verts.Count >= Settings.MaxPolygonVertices)
            {
                var vertList = Triangulate.ConvexPartition(verts, TriangulationAlgorithm.Earclip);
                return(CreateCompoundPolygon(world, vertList, density, position, rotation, bodyType, userData));
            }

            return(CreatePolygon(world, verts, density, position, rotation, bodyType, userData));
        }
Beispiel #11
0
        /// <summary>
        /// Creates a rounded rectangle.
        /// Note: Automatically decomposes the capsule if it contains too many vertices (controlled by Settings.MaxPolygonVertices)
        /// </summary>
        /// <param name="world">The world.</param>
        /// <param name="width">The width.</param>
        /// <param name="height">The height.</param>
        /// <param name="xRadius">The x radius.</param>
        /// <param name="yRadius">The y radius.</param>
        /// <param name="segments">The segments.</param>
        /// <param name="density">The density.</param>
        /// <param name="position">The position.</param>
        /// <returns></returns>
        public static Body CreateRoundedRectangle(World world, float width, float height, float xRadius, float yRadius, int segments, float density, Vector2 position, object userData = null)
        {
            Vertices verts = PolygonTools.CreateRoundedRectangle(width, height, xRadius, yRadius, segments);

            //There are too many vertices in the capsule. We decompose it.
            if (verts.Count >= Settings.MaxPolygonVertices)
            {
                List <Vertices> vertList = Triangulate.ConvexPartition(verts, TriangulationAlgorithm.Earclip);
                Body            body     = CreateCompoundPolygon(world, vertList, density, userData);
                body.Position = position;
                return(body);
            }

            return(CreatePolygon(world, verts, density));
        }
        public static Body CreateGear(World world, GGame.Math.Fix64 radius, int numberOfTeeth, GGame.Math.Fix64 tipPercentage, GGame.Math.Fix64 toothHeight, GGame.Math.Fix64 density, Vector2 position = new Vector2(), GGame.Math.Fix64 rotation = new Fix64(), BodyType bodyType = BodyType.Static, object userData = null)
        {
            Vertices gearPolygon = PolygonUtils.CreateGear(radius, numberOfTeeth, tipPercentage, toothHeight);

            //Gears can in some cases be convex
            if (!gearPolygon.IsConvex())
            {
                //Decompose the gear:
                List <Vertices> list = Triangulate.ConvexPartition(gearPolygon, TriangulationAlgorithm.Earclip, true, 0.001f);

                return(CreateCompoundPolygon(world, list, density, position, rotation, bodyType, userData));
            }

            return(CreatePolygon(world, gearPolygon, density, position, rotation, bodyType, userData));
        }
        public Body CreateGear(float radius, int numberOfTeeth, float tipPercentage, float toothHeight, float density, Vector2 position = new Vector2(), float rotation = 0, BodyType bodyType = BodyType.Static)
        {
            Vertices gearPolygon = PolygonTools.CreateGear(radius, numberOfTeeth, tipPercentage, toothHeight);

            //Gears can in some cases be convex
            if (!gearPolygon.IsConvex())
            {
                //Decompose the gear:
                List <Vertices> list = Triangulate.ConvexPartition(gearPolygon, TriangulationAlgorithm.Earclip);

                return(CreateCompoundPolygon(list, density, position, rotation, bodyType));
            }

            return(CreatePolygon(gearPolygon, density, position, rotation, bodyType));
        }
Beispiel #14
0
        public static Body CreateGear(World world, float radius, int numberOfTeeth, float tipPercentage, float toothHeight, float density, object userData = null)
        {
            Vertices gearPolygon = PolygonTools.CreateGear(radius, numberOfTeeth, tipPercentage, toothHeight);

            //Gears can in some cases be convex
            if (!gearPolygon.IsConvex())
            {
                //Decompose the gear:
                List <Vertices> list = Triangulate.ConvexPartition(gearPolygon, TriangulationAlgorithm.Earclip);

                return(CreateCompoundPolygon(world, list, density, userData));
            }

            return(CreatePolygon(world, gearPolygon, density, userData));
        }
Beispiel #15
0
        public static List <Fixture> AttachRoundedRectangle(float width, float height, float xRadius, float yRadius, int segments, float density, Body body, object userData = null)
        {
            var verts = PolygonTools.CreateRoundedRectangle(width, height, xRadius, yRadius, segments);

            //There are too many vertices in the capsule. We decompose it.
            if (verts.Count >= Settings.MaxPolygonVertices)
            {
                var vertList = Triangulate.ConvexPartition(verts, TriangulationAlgorithm.Earclip);
                return(AttachCompoundPolygon(vertList, density, body, userData));
            }

            var fixtures = new List <Fixture>(1);

            fixtures.Add(AttachPolygon(verts, density, body, userData));
            return(fixtures);
        }
        private Body Create(List <VerticesExt> ext)
        {
            Body b = BodyFactory.CreateBody(World, bodyType: BodyType.Dynamic);

            foreach (VerticesExt ve in ext)
            {
                List <Vertices> decomposed = Triangulate.ConvexPartition(ve, TriangulationAlgorithm.Bayazit);

                foreach (Vertices v in decomposed)
                {
                    FixtureFactory.AttachPolygon(v, 1, b);
                }
            }

            return(b);
        }
Beispiel #17
0
        /// <summary>
        /// Convert a closed path into a polygon.
        /// Convex decomposition is automatically performed.
        /// </summary>
        /// <param name="path">The path.</param>
        /// <param name="body">The body.</param>
        /// <param name="density">The density.</param>
        /// <param name="subdivisions">The subdivisions.</param>
        public static void ConvertPathToPolygon(Path path, Body body, GGame.Math.Fix64 density, int subdivisions)
        {
            if (!path.Closed)
            {
                throw new Exception("The path must be closed to convert to a polygon.");
            }

            List <Vector2> verts = path.GetVertices(subdivisions);

            List <Vertices> decomposedVerts = Triangulate.ConvexPartition(new Vertices(verts), TriangulationAlgorithm.Bayazit, true, 0.001f);

            foreach (Vertices item in decomposedVerts)
            {
                body.CreateFixture(new PolygonShape(item, density));
            }
        }
Beispiel #18
0
        public static Body CreateRoundedRectangle(World world, float width, float height, float xRadius, float yRadius,
                                                  int segments, float density, Vector2 position = new Vector2(),
                                                  float rotation  = 0, BodyType bodyType = BodyType.Static,
                                                  object userData = null)
        {
            var verts = PolygonTools.CreateRoundedRectangle(width, height, xRadius, yRadius, segments);

            //There are too many vertices in the rect. We decompose it.
            if (verts.Count >= Settings.MaxPolygonVertices)
            {
                var vertList = Triangulate.ConvexPartition(verts, TriangulationAlgorithm.Earclip);
                return(CreateCompoundPolygon(world, vertList, density, position, rotation, bodyType, userData));
            }

            return(CreatePolygon(world, verts, density, position, rotation, bodyType, userData));
        }
Beispiel #19
0
        public static List <Fixture> AttachGear(this Body body, float radius, int numberOfTeeth, float tipPercentage, float toothHeight, float density)
        {
            var gearPolygon = PolygonTools.CreateGear(FSConvert.DisplayToSim * radius, numberOfTeeth, tipPercentage, FSConvert.DisplayToSim * toothHeight);

            // Gears can in some cases be convex
            if (!gearPolygon.IsConvex())
            {
                //Decompose the gear:
                var list = Triangulate.ConvexPartition(gearPolygon, TriangulationAlgorithm.Earclip);
                return(body.AttachCompoundPolygon(list, density));
            }

            var fixtures = new List <Fixture>();

            fixtures.Add(body.AttachPolygon(gearPolygon, density));
            return(fixtures);
        }
Beispiel #20
0
        void CreateBody(Vertices vertices)
        {
            if (vertices == null)
            {
                return;
            }

            World.Clear();

            _sw.Start();
            _bodies[0]          = BodyFactory.CreateCompoundPolygon(World, Triangulate.ConvexPartition(vertices, TriangulationAlgorithm.Seidel), 1);
            _bodies[0].Position = new Vector2(-30, 28);
            _timings[0]         = _sw.ElapsedMilliseconds;

            //_sw.Restart();
            _sw.Stop(); _sw.Start();
            _bodies[1]          = BodyFactory.CreateCompoundPolygon(World, Triangulate.ConvexPartition(vertices, TriangulationAlgorithm.SeidelTrapezoids), 1);
            _bodies[1].Position = new Vector2(0, 28);
            _timings[1]         = _sw.ElapsedMilliseconds;

            //_sw.Restart();
            _sw.Stop(); _sw.Start();
            _bodies[2]          = BodyFactory.CreateCompoundPolygon(World, Triangulate.ConvexPartition(vertices, TriangulationAlgorithm.Delauny), 1);
            _bodies[2].Position = new Vector2(30, 28);
            _timings[2]         = _sw.ElapsedMilliseconds;

            //_sw.Restart();
            _sw.Stop(); _sw.Start();
            _bodies[3]          = BodyFactory.CreateCompoundPolygon(World, Triangulate.ConvexPartition(vertices, TriangulationAlgorithm.Earclip), 1);
            _bodies[3].Position = new Vector2(-30, 5);
            _timings[3]         = _sw.ElapsedMilliseconds;

            //_sw.Restart();
            _sw.Stop(); _sw.Start();
            _bodies[4]          = BodyFactory.CreateCompoundPolygon(World, Triangulate.ConvexPartition(vertices, TriangulationAlgorithm.Flipcode), 1);
            _bodies[4].Position = new Vector2(0, 5);
            _timings[4]         = _sw.ElapsedMilliseconds;

            //_sw.Restart();
            _sw.Stop(); _sw.Start();
            _bodies[5]          = BodyFactory.CreateCompoundPolygon(World, Triangulate.ConvexPartition(vertices, TriangulationAlgorithm.Bayazit), 1);
            _bodies[5].Position = new Vector2(30, 5);
            _timings[5]         = _sw.ElapsedMilliseconds;

            _sw.Stop();
        }
Beispiel #21
0
        private void CreatePolygon(Texture2D a_texture, World a_world)
        {
            //Create an array to hold the data from the texture
            uint[] data = new uint[a_texture.Width * a_texture.Height];

            //Transfer the texture data to the array
            a_texture.GetData(data);

            //Find the vertices that makes up the outline of the shape in the texture
            Vertices textureVertices = PolygonTools.CreatePolygon(data, a_texture.Width, false);

            //The tool return vertices as they were found in the texture.
            //We need to find the real center (centroid) of the vertices for 2 reasons:

            //1. To translate the vertices so the polygon is centered around the centroid.
            Vector2 centroid = -textureVertices.GetCentroid();

            textureVertices.Translate(ref centroid);

            //2. To draw the texture the correct place.
            _origin = -centroid;

            //We simplify the vertices found in the texture.
            textureVertices = SimplifyTools.ReduceByDistance(textureVertices, 4f);

            //Since it is a concave polygon, we need to partition it into several smaller convex polygons
            List <Vertices> list = Triangulate.ConvexPartition(textureVertices, TriangulationAlgorithm.Bayazit);


            //Adjust the scale of the object for WP7's lower resolution
            _scale = new Vector2(1f, 1f);

            //scale the vertices from graphics space to sim space
            Vector2 vertScale = new Vector2(ConvertUnits.ToSimUnits(1)) * _scale;

            foreach (Vertices vertices in list)
            {
                vertices.Scale(ref vertScale);
            }

            //Create a single body with multiple fixtures
            _body          = BodyFactory.CreateCompoundPolygon(a_world, list, 1f, BodyType.Dynamic);
            _body.BodyType = BodyType.Dynamic;
        }
Beispiel #22
0
        private static Body createBody(Sprite sprite, World world)
        {
            uint[] texData = new uint[sprite.Texture.Width * sprite.Texture.Height];

            sprite.Texture.GetData(texData);

            //Find the vertices that makes up the outline of the shape in the texture
            Vertices verts = PolygonTools.CreatePolygon(texData, sprite.Texture.Width, false);

            //For now we need to scale the vertices (result is in pixels, we use meters)
            Vector2 scale = new Vector2(ConvertUnits.ToSimUnits(1));

            verts.Scale(ref scale);

            //Since it is a concave polygon, we need to partition it into several smaller convex polygons
            List <Vertices> vertexList = Triangulate.ConvexPartition(verts, TriangulationAlgorithm.Bayazit);

            return(BodyFactory.CreateCompoundPolygon(world, vertexList, 1f));
        }
Beispiel #23
0
        public override void Initialize()
        {
            base.Initialize();

            //Ground
            BodyFactory.CreateEdge(World, new Vector2(-40.0f, 0.0f), new Vector2(40.0f, 0.0f));

            //Load texture that will represent the physics body
            Bitmap polygonTexture = Bitmap.FromFile("AltData/FarseerPhysics/Testbed/Content/Texture.png");

            //Create an array to hold the data from the texture
            uint[] data = new uint[polygonTexture.PixelWidth * polygonTexture.PixelHeight];

            //Transfer the texture data to the array
            BitmapData bitmapData = polygonTexture.LockBits(ImageLockMode.ReadOnly);

            byte[] src_buffer = bitmapData.Scan0;
            System.Buffer.BlockCopy(src_buffer, 0, data, 0, src_buffer.Length);
            polygonTexture.UnlockBits(bitmapData);

            //Find the vertices that makes up the outline of the shape in the texture
            Vertices verts = PolygonTools.CreatePolygon(data, polygonTexture.PixelWidth);

            //For now we need to scale the vertices (result is in pixels, we use meters)
            Vector2 scale = new Vector2(0.07f, -0.07f);

            verts.Scale(ref scale);

            //We also need to move the polygon so that (0,0) is the center of the polygon.
            Vector2 centroid = -verts.GetCentroid();

            verts.Translate(ref centroid);

            _sw.Start();
            //Create a single body with multiple fixtures
            Body compund = BodyFactory.CreateCompoundPolygon(World, Triangulate.ConvexPartition(verts, TriangulationAlgorithm.Earclip), 1);

            compund.BodyType = BodyType.Dynamic;
            compund.Position = new Vector2(0, 20);
            _sw.Stop();
        }
Beispiel #24
0
        /// <summary>
        /// Creates a capsule.
        /// Note: Automatically decomposes the capsule if it contains too many vertices (controlled by Settings.MaxPolygonVertices)
        /// </summary>
        /// <returns></returns>
        public static Body CreateCapsule(World world, float height, float topRadius, int topEdges, float bottomRadius, int bottomEdges, float density, Vector2 position, object userData = null)
        {
            Vertices verts = PolygonTools.CreateCapsule(height, topRadius, topEdges, bottomRadius, bottomEdges);

            Body body;

            //There are too many vertices in the capsule. We decompose it.
            if (verts.Count >= Settings.MaxPolygonVertices)
            {
                List <Vertices> vertList = Triangulate.ConvexPartition(verts, TriangulationAlgorithm.Earclip);
                body          = CreateCompoundPolygon(world, vertList, density, userData);
                body.Position = position;

                return(body);
            }

            body          = CreatePolygon(world, verts, density, userData);
            body.Position = position;

            return(body);
        }
Beispiel #25
0
        public Body CreatePolygonFromTexture(Texture2D tex, World world, float density, Vector2 position, float scale, TriangulationAlgorithm algorithm = TriangulationAlgorithm.Bayazit)
        {
            uint[] texData = new uint[tex.Width * tex.Height];
            tex.GetData <uint>(texData);

            Vertices        vertices   = TextureConverter.DetectVertices(texData, tex.Width);
            List <Vertices> vertexList = Triangulate.ConvexPartition(vertices, algorithm);

            Vector2 vertScale = new Vector2(ConvertUnits.ToSimUnits(scale));

            foreach (Vertices vert in vertexList)
            {
                vert.Scale(ref vertScale);
            }

            Vector2 centroid = vertices.GetCentroid();

            vertices.Translate(ref centroid);
            //basketOrigin = -centroid;
            return(BodyFactory.CreateCompoundPolygon(world, vertexList, density, position, 100));
        }
Beispiel #26
0
        public void Decompose()
        {
            Dictionary <string, Polygon> containerCopy = new Dictionary <string, Polygon>(this);

            foreach (string key in containerCopy.Keys)
            {
                if (containerCopy[key].Closed)
                {
                    List <Vertices> partition = Triangulate.ConvexPartition(containerCopy[key].Vertices, TriangulationAlgorithm.Bayazit);
                    if (partition.Count > 1)
                    {
                        Remove(key);
                        for (int i = 0; i < partition.Count; i++)
                        {
                            this[key + "_" + i.ToString()] = new Polygon(partition[i], true);
                        }
                    }
                    _decomposed = true;
                }
            }
        }
Beispiel #27
0
        public TexturePolygon(Texture2D texture, Vector2 position, float rotation, DrawingHelper.DrawingLevel drawingLevel, Game game, World world, bool textureCenter)
            : base(texture, position, drawingLevel, game, world)
        {
            // Fetch Texure data
            uint[] data = new uint[texture.Width * texture.Height];
            texture.GetData(data);
            Vertices textureVertices = PolygonTools.CreatePolygon(data, texture.Width, true);

            // Set Polygon Centroid
            if (textureCenter) // Texture based center
            {
                Vector2 centroid = -textureVertices.GetCentroid();
                textureVertices.Translate(ref centroid);
                Origin = new Vector2(texture.Width / 2, texture.Height / 2);
            }
            else // Vertice based center
            {
                Vector2 centroid = -textureVertices.GetCentroid();
                textureVertices.Translate(ref centroid);
                Origin = new Vector2(-centroid.X, -centroid.Y);
            }

            // Simplify Polygon for performance
            textureVertices = SimplifyTools.ReduceByDistance(textureVertices, 4f);
            List <Vertices> list = Triangulate.ConvexPartition(textureVertices, TriangulationAlgorithm.Bayazit);

            // Convert polygon to sim units
            Vector2 vertScale = new Vector2(ConvertUnits.ToSimUnits(1));

            foreach (Vertices vertice in list)
            {
                vertice.Scale(ref vertScale);
            }

            // create body compound.
            RigidBody          = BodyFactory.CreateCompoundPolygon(world, list, 1f, BodyType.Static);
            RigidBody.BodyType = BodyType.Static;
            RigidBody.Position = ConvertUnits.ToSimUnits(position);
            RigidBody.Rotation = rotation;
        }
        public override void Initialize()
        {
            base.Initialize();

            //Ground
            BodyFactory.CreateEdge(World, new Vector2(-40.0f, 0.0f), new Vector2(40.0f, 0.0f));

            //Load texture that will represent the physics body
            Texture2D polygonTexture = GameInstance.Content.Load <Texture2D>("Texture");

            //Create an array to hold the data from the texture
            uint[] data = new uint[polygonTexture.Width * polygonTexture.Height];

            //Transfer the texture data to the array
            polygonTexture.GetData(data);

            //Find the vertices that makes up the outline of the shape in the texture
            Vertices verts = PolygonUtils.CreatePolygon(data, polygonTexture.Width);

            //For now we need to scale the vertices (result is in pixels, we use meters)
            Vector2 scale = new Vector2(0.07f, -0.07f);

            verts.Scale(ref scale);

            //We also need to move the polygon so that (0,0) is the center of the polygon.
            Vector2 centroid = -verts.GetCentroid();

            verts.Translate(ref centroid);

            _sw.Start();

            //Create a single body with multiple fixtures
            Body compund = BodyFactory.CreateCompoundPolygon(World, Triangulate.ConvexPartition(verts, TriangulationAlgorithm.Earclip), 1);

            compund.BodyType = BodyType.Dynamic;
            compund.Position = new Vector2(0, 20);
            _sw.Stop();
        }
Beispiel #29
0
        private void GenerateTerrain(int gx, int gy)
        {
            float ax = gx * CellSize;
            float ay = gy * CellSize;

            var polys = MarchingSquares.DetectSquares(
                new AABB(new Vector2(ax, ay), new Vector2(ax + CellSize, ay + CellSize)), SubCellSize, SubCellSize,
                _terrainMap, Iterations, true);

            if (polys.Count == 0)
            {
                return;
            }

            _bodyMap[gx, gy] = new List <Body>();

            // create the scale vector
            var scale = new Vector2(1f / PointsPerUnit, 1f / -PointsPerUnit);

            // create physics object for this grid cell
            foreach (var item in polys)
            {
                // does this need to be negative?
                item.Scale(ref scale);
                item.Translate(ref _topLeft);
                var simplified = SimplifyTools.CollinearSimplify(item);

                var decompPolys = Triangulate.ConvexPartition(simplified, Decomposer);

                foreach (var poly in decompPolys)
                {
                    if (poly.Count > 2)
                    {
                        _bodyMap[gx, gy].Add(BodyFactory.CreatePolygon(World, poly, 1));
                    }
                }
            }
        }
Beispiel #30
0
        /// <summary>
        /// Method for creating complex bodies.
        /// </summary>
        /// <param name="world">The new object will appear in this world</param>
        /// <param name="objectTexture">The new object will get this texture</param>
        /// <param name="Scale">The new object get scaled by this factor</param>
        /// <param name="Algo">The new object get triangulated by this triangulation algorithm</param>
        /// <returns>Returns the complex body</returns>
        public Body CreateComplexBody(World world, Texture2D objectTexture, float Scale,
                                      TriangulationAlgorithm Algo = TriangulationAlgorithm.Bayazit)
        {
            Body body = null;

            uint[] data = new uint[objectTexture.Width * objectTexture.Height];
            objectTexture.GetData(data);
            Vertices textureVertices = PolygonTools.CreatePolygon(data, objectTexture.Width, false);
            Vector2  centroid        = -textureVertices.GetCentroid();

            textureVertices.Translate(ref centroid);
            tBodyOrigin     = -centroid;
            textureVertices = SimplifyTools.DouglasPeuckerSimplify(textureVertices, 4f);
            List <Vertices> list      = Triangulate.ConvexPartition(textureVertices, Algo);
            Vector2         vertScale = new Vector2(ConvertUnits.ToSimUnits(1)) * Scale;

            foreach (Vertices vertices in list)
            {
                vertices.Scale(ref vertScale);
            }

            return(body = BodyFactory.CreateCompoundPolygon(world, list, 1f));
        }