Ejemplo n.º 1
0
        /// <summary>
        /// Makes a set of vertices for the chain shape
        /// by creating two offset vertices perpendicular
        /// to the averaged direction from the current vertex
        /// and it's two connected vertices. Returned vertices
        /// are in counterclockwise order
        /// </summary>
        /// <param name="chain">chain shape to work on</param>
        /// <returns>new Triangularizable Vertices for chain shape</returns>
        private static Vertices CreateChainVertices(ChainShape chain)
        {
            Matrix         rotMat            = Matrix.CreateRotationZ(MathHelper.PiOver2);
            Vertices       chainTextVerts    = new Vertices(chain.Vertices.Count * 2);
            List <Vector2> posChainTextVerts = new List <Vector2>(chain.Vertices.Count);
            List <Vector2> negChainTextVerts = new List <Vector2>(chain.Vertices.Count);

            for (int i = 0; i < chain.Vertices.Count; i++)
            {
                var     curVertex = chain.Vertices[i];
                Vector2 direction = Vector2.Zero;
                Vector2 distance  = Vector2.Zero;
                if (i == 0)
                {
                    distance = chain.Vertices[i + 1] - curVertex;
                }
                else if (i < chain.Vertices.Count - 1)
                {
                    distance = (chain.Vertices[i + 1] - curVertex) + (curVertex - chain.Vertices[i - 1]);
                }
                else
                {
                    distance = curVertex - chain.Vertices[i - 1];
                }

                direction = Vector2.Normalize(Vector2.Transform(distance, rotMat)).ToSimUnits();
                posChainTextVerts.Add(curVertex + (direction * 2f));
                negChainTextVerts.Insert(0, curVertex - (direction * 2f));
            }

            chainTextVerts.AddRange(posChainTextVerts);
            chainTextVerts.AddRange(negChainTextVerts);

            return(chainTextVerts);
        }
Ejemplo n.º 2
0
        private static Vertices GetVertices(Texture2D texture, Model model)
        {
            BoundingSphere bs = new BoundingSphere();

            bool first = true;

            foreach (ModelMesh mesh in model.Meshes)
            {
                if (first)
                {
                    bs    = mesh.BoundingSphere;
                    first = false;
                }
                else
                {
                    bs = BoundingSphere.CreateMerged(bs, mesh.BoundingSphere);
                }
            }

            bs.Center.X = bs.Center.Z;
            bs.Radius  *= 1.5f;
            Vertices textureVertices = new Vertices();


            // do marching squares
            Vertices v = new Vertices();

            v.AddRange(MarchingSquare.DoMarch(texture).ToArray());

            // transform the vectors
            for (int i = 0; i < v.Count; i++)
            {
                v[i] = new Vector2(v[i].X * 2 * bs.Radius / (texture.Width - 1) + bs.Center.X - bs.Radius, (texture.Height - 1 - v[i].Y) * 2 * bs.Radius / (texture.Height - 1) + bs.Center.Y - bs.Radius);
            }

            List <Vector2> points = new List <Vector2>(v);

            for (int i = 3; i < points.Count; i++)
            {
                if (isColinear(points[i - 2], points[i - 1], points[i]))
                {
                    points.Remove(points[i - 1]);
                    i--;
                }
            }

            v.Clear();
            v.AddRange(points.ToArray());

            return(v);
        }
Ejemplo n.º 3
0
        //*********************************************************************************
        public void AddEdge(Line edge)
        {
            Edges.Add(edge);
            Vertices.AddRange(edge.GetPoints());

            //SortVertices();
        }
Ejemplo n.º 4
0
        public void AddGeometry(IEnumerable <Vector3> vertices, IEnumerable <uint> indices)
        {
            var vo = (uint)Vertices.Count;

            Vertices.AddRange(vertices);
            Indices.AddRange(indices.Select(i => vo + i));
        }
Ejemplo n.º 5
0
        public override void OnEntityTransformChanged(Transform.Component comp)
        {
            base.OnEntityTransformChanged(comp);
            if (_ignoreTransformChanges)
            {
                return;
            }

            // we only care about scale. base handles pos/rot
            if (comp == Transform.Component.Scale)
            {
                // fetch the Vertices, clear them, add our originals and scale them
                PolygonShape poly  = Body.FixtureList[0].Shape as PolygonShape;
                Vertices     verts = poly.Vertices;
                verts.Clear();
                verts.AddRange(_verts);
                verts.Scale(Transform.Scale);
                poly.SetVerticesNoCopy(verts);

                // wake the body if it is asleep to update collisions
                if (!Body.IsAwake)
                {
                    Body.IsAwake = true;
                }
            }
        }
Ejemplo n.º 6
0
            public void Insert(List <int> data)
            {
                var vertices = data.Select(x => new Vertex
                {
                    Data = x
                }).ToList();

                if (!_lastVertices.Any())
                {
                    _lastVertices = vertices;
                }
                else
                {
                    foreach (var vertex in vertices)
                    {
                        foreach (var v in _lastVertices)
                        {
                            var edge = new Edge
                            {
                                From  = v,
                                To    = vertex,
                                Value = EdgeValue(v.Data, vertex.Data)
                            };

                            v.Edges.Add(edge);
                            vertex.Edges.Add(edge);
                        }
                    }

                    Vertices.AddRange(_lastVertices);

                    _lastVertices = vertices;
                }
            }
Ejemplo n.º 7
0
            public void Insert(int data)
            {
                var vertex = new Vertex
                {
                    Data = data
                };

                if (!_lastVertices.Any())
                {
                    _lastVertices.Add(vertex);
                }
                else
                {
                    foreach (var v in _lastVertices)
                    {
                        var edge = new Edge
                        {
                            From  = v,
                            To    = vertex,
                            Value = EdgeValue(v.Data, vertex.Data)
                        };

                        v.Edges.Add(edge);
                        vertex.Edges.Add(edge);
                    }

                    Vertices.AddRange(_lastVertices);
                    _lastVertices = new List <Vertex>
                    {
                        vertex
                    };
                }
            }
Ejemplo n.º 8
0
        protected override void InitFromMeshData(Device device, GeometryGenerator.MeshData mesh)
        {
            var subset = new MeshGeometry.Subset {
                FaceCount   = mesh.Indices.Count / 3,
                FaceStart   = 0,
                VertexCount = mesh.Vertices.Count,
                VertexStart = 0
            };

            Subsets.Add(subset);

            var max = new Vector3(float.MinValue);
            var min = new Vector3(float.MaxValue);

            foreach (var vertex in mesh.Vertices)
            {
                max = Vector3.Maximize(max, vertex.Position);
                min = Vector3.Minimize(min, vertex.Position);
            }

            BoundingBox = new BoundingBox(min, max);

            Vertices.AddRange(mesh.Vertices.Select(v => new PosNormalTexTan(v.Position, v.Normal, v.TexC, v.TangentU)).ToList());
            Indices.AddRange(mesh.Indices.Select(i => (short)i));

            Materials.Add(new Material {
                Ambient = Color.Gray, Diffuse = Color.White, Specular = new Color4(16, 1, 1, 1)
            });
            DiffuseMapSRV.Add(null);
            NormalMapSRV.Add(null);

            ModelMesh.SetSubsetTable(Subsets);
            ModelMesh.SetVertices(device, Vertices);
            ModelMesh.SetIndices(device, Indices);
        }
Ejemplo n.º 9
0
        /// <summary>
        /// Split the given face on the given plane. Remove the original face
        /// and add as many new faces as required for the split.
        /// </summary>
        /// <param name="faceIndex">The index of the face to split.</param>
        /// <param name="plane">The plane to split the face on. The face will not be split
        /// if it is not intersected by this plane.</param>
        /// <param name="onPlaneDistance">If a given edge of the face has a vertex that is within
        /// this distance of the plane, the edge will not be split.</param>
        /// <returns>Returns if the edge was actually split.</returns>
        public bool SplitFace(int faceIndex, Plane plane, double onPlaneDistance = .001)
        {
            var newVertices = new List <Vector3Float>();
            var newFaces    = new List <Face>();

            if (Faces[faceIndex].Split(this.Vertices, plane, newFaces, newVertices, onPlaneDistance))
            {
                var vertexCount = Vertices.Count;
                // remove the face index
                Faces.RemoveAt(faceIndex);
                // add the new vertices
                Vertices.AddRange(newVertices);
                // add the new faces (have to make the vertex indices to the new vertices
                foreach (var newFace in newFaces)
                {
                    Face faceNewIndices = newFace;
                    faceNewIndices.v0 += vertexCount;
                    faceNewIndices.v1 += vertexCount;
                    faceNewIndices.v2 += vertexCount;
                    Faces.Add(faceNewIndices);
                }

                CleanAndMerge();

                return(true);
            }

            return(false);
        }
Ejemplo n.º 10
0
        public override void Update()
        {
            base.Update();

            // Dividers
            DrawLine(new Vector2(0, HALF_H), new Vector2(0, -HALF_H), Color.White);
            DrawLine(new Vector2(-HALF_W, 0), new Vector2(HALF_W, 0), Color.White);

            // Goal markers
            DrawCircle(goal, 10, 10, Color.Green);
            DrawCircle(goal + new Vector2(HALF_W, 0), 10, 10, Color.Green);
            DrawCircle(goal + new Vector2(0, -HALF_H), 10, 10, Color.Green);
            DrawCircle(goal + new Vector2(HALF_W, -HALF_H), 10, 10, Color.Green);

            // Solution Spaces
            DrawCircle(hingeJT.DefaultPosition, hingeJT.SolutionSpaceRadius(), 30, Color.DarkRed);
            DrawCircle(hingeJI.DefaultPosition, hingeJI.SolutionSpaceRadius(), 30, Color.DarkRed);
            DrawCircle(hingeDLS.DefaultPosition, hingeDLS.SolutionSpaceRadius(), 30, Color.DarkRed);
            DrawCircle(hingeCCD.DefaultPosition, hingeCCD.SolutionSpaceRadius(), 30, Color.DarkRed);

            // Joints
            Vertices.AddRange(hingeJT.GetVertices());
            Vertices.AddRange(hingeJI.GetVertices());
            Vertices.AddRange(hingeDLS.GetVertices());
            Vertices.AddRange(hingeCCD.GetVertices());
        }
Ejemplo n.º 11
0
        public TS_contour(List <TS_point> vertices) : this()
        {
            Vertices.AddRange(vertices);

            CalcProperties();
            //Sides.AddRange(GenerateSides(Vertices));
        }
Ejemplo n.º 12
0
        public Vertices ToVertices()
        {
            Vertices vertices = new Vertices();

            vertices.AddRange(Flatten());
            return(vertices);
        }
Ejemplo n.º 13
0
        public static BodyTemplate Scale(this BodyTemplate bodyTemplate, Vector2 scale)
        {
            List <FixtureTemplate> fixtures = new List <FixtureTemplate>(bodyTemplate.Fixtures.Count);

            foreach (var fixture in bodyTemplate.Fixtures)
            {
                Shape shapeCopy;

                switch (fixture.Shape.ShapeType)
                {
                case ShapeType.Polygon:
                    Vertices verticesCopy = new Vertices();
                    verticesCopy.AddRange(((PolygonShape)fixture.Shape).Vertices);
                    verticesCopy.Scale(scale);
                    shapeCopy = new PolygonShape(verticesCopy, fixture.Shape.Density);
                    break;

                // TODO: support other shape types
                default:
                    throw new NotSupportedException();
                }

                FixtureTemplate fixtureCopy = new FixtureTemplate();
                fixtureCopy.Shape = shapeCopy;
                fixtures.Add(fixtureCopy);
            }

            BodyTemplate newBodyTemplate = new BodyTemplate();

            newBodyTemplate.Fixtures = fixtures;

            return(newBodyTemplate);
        }
Ejemplo n.º 14
0
    private void BuildWallMesh(int subMesh, DoorGridElement[] gridElements, Vector3 direction)
    {
        Triangles [subMesh] = new List <int> ();
        //Back Vector is used to transform a 2DVec back to a 3DVec
        //It doesn't matter which point on the plane / wall it actually is, as long as it stores the
        //X or Y coordinate that is missing from the 2DVec. Subtract position to get coordinate in object space
        Vector3 backVec = abstractBounds.FindCorner(0, direction) - abstractBounds.transform.position;

        foreach (DoorGridElement gridElement in gridElements)
        {
            if (!gridElement.IsInsideDoor)
            {
                Rect    elementRect = gridElement.Rect;
                Vector3 x1y1        = Vec2ToVec3(elementRect.position, backVec, direction);
                Vector3 x1y2        = Vec2ToVec3(new Vector2(elementRect.position.x, elementRect.position.y + elementRect.height), backVec, direction);
                Vector3 x2y2        = Vec2ToVec3(elementRect.position + elementRect.size, backVec, direction);
                Vector3 x2y1        = Vec2ToVec3(new Vector2(elementRect.position.x + elementRect.width, elementRect.position.y), backVec, direction);
                Vertices.AddRange(new Vector3[] { x1y1, x1y2, x2y2, x2y1 });
                int length = Vertices.Count;

                //Walls should face inward. Triangle order therefore depends on the walls direction
                if (direction == Vector3.forward || direction == Vector3.left)
                {
                    Triangles[subMesh].AddRange(new int[] { length - 4, length - 3, length - 1 });
                    Triangles[subMesh].AddRange(new int[] { length - 1, length - 3, length - 2 });
                }
                else
                {
                    Triangles[subMesh].AddRange(new int[] { length - 1, length - 2, length - 4 });
                    Triangles[subMesh].AddRange(new int[] { length - 4, length - 2, length - 3 });
                }
            }
        }
    }
Ejemplo n.º 15
0
        //TODO : IT

        internal override Annotation Clone(IDocumentEssential owner, Page page)
        {
            if (Page == null)
            {
                PointF[] points = Vertices.ToArray();
                ApplyOwner(owner);
                SetPage(page, true);

                Vertices.Clear();
                Vertices.Page = page;
                Vertices.AddRange(points);

                return(this);
            }

            PDFDictionary res = AnnotationBase.Copy(Dictionary);

            MarkupAnnotationBase.CopyTo(Dictionary, res);
            PolygonPolylineAnnotation.CopyTo(Dictionary, res, Page, page);

            PolylineAnnotation annot = new PolylineAnnotation(res, owner);

            annot.SetPage(Page, false);
            annot.SetPage(page, true);
            return(annot);
        }
Ejemplo n.º 16
0
        public Mesh(List <Vector3Float> v, FaceList f)
        {
            Vertices.Clear();
            Vertices.AddRange(v);

            Faces.Clear();
            Faces.AddRange(f);
        }
        public override void Update()
        {
            base.Update();

            DrawCircle(goal, 10, 10, Color.Green);
            DrawCircle(Vector2.Zero, baseJoint.SolutionSpaceRadius(), 100, Color.DarkRed);

            Vertices.AddRange(baseJoint.GetVertices());
        }
Ejemplo n.º 18
0
 public virtual Vertices ToVertices()
 {
     if (_verticesInValidated)
     {
         _vertices.Clear();
         _vertices.AddRange(Flatten());
     }
     return(new Vertices(_vertices));
 }
Ejemplo n.º 19
0
    //Used for floor and ceil
    private void BuildPlaneMesh(int subMesh, Vector3 direction, params int[] cornerIndices)
    {
        Triangles [subMesh] = new List <int> ();
        Vertices.AddRange(abstractBounds.RelativeCorners(cornerIndices[0], cornerIndices[1], cornerIndices[2], cornerIndices[3]));
        int length = Vertices.Count;

        Triangles[subMesh].AddRange(new int[] { length - 4, length - 3, length - 1 });
        Triangles[subMesh].AddRange(new int[] { length - 1, length - 3, length - 2 });
        CalculateUVs(subMesh, direction);
    }
Ejemplo n.º 20
0
        private void GenerateIndices()
        {
            List <VertexFormat> tempVertices = new List <VertexFormat>();
            List <int>          tempIndices  = new List <int>();

            foreach (VertexFormat v in Vertices)
            {
                //Search for existing vertex
                int  i     = 0;
                bool found = false;
                foreach (VertexFormat v2 in tempVertices)
                {
                    if (VertexFormat.Compare(v, v2))
                    {
                        //found
                        found = true;
                        break;
                    }
                    i++;
                }

                //In found join the normals
                if (found)
                {
                    tempIndices.Add(i);
                    VertexFormat v2 = tempVertices[i];
                }
                else
                {
                    i = tempVertices.Count;
                    tempVertices.Add(v);
                    tempIndices.Add(i);
                }

                //normal
                VertexFormat vTemp = tempVertices[i];
                vTemp.Normal   += v.Normal;
                tempVertices[i] = vTemp;
            }


            //Normalize all Vertices
            Vertices.Clear();
            foreach (VertexFormat v in tempVertices)
            {
                v.Normal.Normalize();
                Vertices.Add(v);
            }
            Vertices.AddRange(tempVertices);

            Indices.Clear();
            Indices.AddRange(tempIndices);
        }
Ejemplo n.º 21
0
        public bool Split(Plane plane, double onPlaneDistance = .001, Func <SplitData, bool> clipFace = null, bool cleanAndMerge = true)
        {
            var newVertices   = new List <Vector3Float>();
            var newFaces      = new List <Face>();
            var facesToRemove = new HashSet <int>();

            for (int i = 0; i < Faces.Count; i++)
            {
                var face = Faces[i];

                if (face.Split(this.Vertices, plane, newFaces, newVertices, onPlaneDistance, clipFace))
                {
                    // record the face for removal
                    facesToRemove.Add(i);
                }
            }

            // make a new list of all the faces we are keeping
            var keptFaces = new FaceList();

            for (int i = 0; i < Faces.Count; i++)
            {
                if (!facesToRemove.Contains(i))
                {
                    keptFaces.Add(Faces[i]);
                }
            }

            var vertexCount = Vertices.Count;

            // add the new vertices
            Vertices.AddRange(newVertices);

            // add the new faces (have to make the vertex indices to the new vertices
            foreach (var newFace in newFaces)
            {
                Face faceNewIndices = newFace;
                faceNewIndices.v0 += vertexCount;
                faceNewIndices.v1 += vertexCount;
                faceNewIndices.v2 += vertexCount;
                keptFaces.Add(faceNewIndices);
            }

            Faces = keptFaces;

            if (cleanAndMerge)
            {
                CleanAndMerge();
            }

            return(true);
        }
Ejemplo n.º 22
0
        /// <summary>
        /// Appends a copy of another mesh to this one.
        /// </summary>
        /// <param name="other">Mesh to append to this one.</param>
        public void Append(Mesh other)
        {
            Mesh dup = other.Duplicate();

            Vertices.AddRange(dup.Vertices);
            foreach (Halfedge edge in dup.Halfedges)
            {
                Halfedges.Add(edge);
            }
            foreach (Face face in dup.Faces)
            {
                Faces.Add(face);
            }
        }
Ejemplo n.º 23
0
        public override void Update()
        {
            base.Update();

            // Goal Marker
            DrawCircle(goal, 5, 5, Color.Green);

            // Solution Spaces
            DrawCircle(leftJoint.DefaultPosition, leftJoint.SolutionSpaceRadius(), 30, new Color(50, 0, 0));
            DrawCircle(rightJoint.DefaultPosition, rightJoint.SolutionSpaceRadius(), 30, new Color(50, 0, 0));

            // Joints
            Vertices.AddRange(leftJoint.GetVertices());
            Vertices.AddRange(rightJoint.GetVertices());
        }
Ejemplo n.º 24
0
    public void Calculate(int index = 0)
    {
        Vertices.Clear();
        Triangles.Clear();
        UVs.Clear();

        var s = Size / 2f;

        Vector3[] p = new Vector3[] {
            new Vector3(-s, -s, -s) + Position,             // 0 0
            new Vector3(-s, s, -s) + Position,              // 1 1
            new Vector3(s, s, -s) + Position,               // 2 2
            new Vector3(s, -s, -s) + Position,              // 3 3

            new Vector3(-s, -s, s) + Position,              // 4 0
            new Vector3(-s, s, s) + Position,               // 5 1
            new Vector3(s, s, s) + Position,                // 6 2
            new Vector3(s, -s, s) + Position,               // 7 3
        };

        for (int i = 0; i < Faces.Length; i++)
        {
            if (Faces[i])
            {
                Triangles.AddRange(AddTriangles(index + Vertices.Count));
                UVs.AddRange(UVPacker.GetCubeUVs(i, CubeTypes[type]));

                switch (i)
                {
                case 0: Vertices.AddRange(new Vector3[] { p[0], p[1], p[2], p[3] }); break;

                case 1: Vertices.AddRange(new Vector3[] { p[3], p[2], p[6], p[7] }); break;

                case 2: Vertices.AddRange(new Vector3[] { p[7], p[6], p[5], p[4] }); break;

                case 3: Vertices.AddRange(new Vector3[] { p[4], p[5], p[1], p[0] }); break;

                case 4: Vertices.AddRange(new Vector3[] { p[1], p[5], p[6], p[2] }); break;

                case 5: Vertices.AddRange(new Vector3[] { p[4], p[0], p[3], p[7] }); break;

                default: break;
                }
            }
        }

        this.Calculated = true;
    }
Ejemplo n.º 25
0
        // GJK using Voronoi regions (Christer Ericson) and Barycentric coordinates.

        /// <summary>
        /// Initialize the proxy using the given shape. The shape
        /// must remain in scope while the proxy is in use.
        /// </summary>
        /// <param name="shape">The shape.</param>
        /// <param name="index">The index.</param>
        public DistanceProxy(Shape shape, int index)
        {
            Vertices = new Vertices();

            switch (shape.ShapeType)
            {
            case ShapeType.Circle:
            {
                CircleShape circle = (CircleShape)shape;
                Vertices.Add(circle.Position);
                Radius = circle.Radius;
            }
            break;

            case ShapeType.Polygon:
            {
                PolygonShape polygon = (PolygonShape)shape;
                Vertices.AddRange(polygon.Vertices);
                Radius = polygon.Radius;
            }
            break;

            case ShapeType.Chain:
            {
                ChainShape chain = (ChainShape)shape;
                Debug.Assert(0 <= index && index < chain.Vertices.Count);
                Vertices.Add(chain.Vertices[index]);
                Vertices.Add(index + 1 < chain.Vertices.Count ? chain.Vertices[index + 1] : chain.Vertices[0]);

                Radius = chain.Radius;
            }
            break;

            case ShapeType.Edge:
            {
                EdgeShape edge = (EdgeShape)shape;
                Vertices.Add(edge.Vertex1);
                Vertices.Add(edge.Vertex2);
                Radius = edge.Radius;
            }
            break;

            default:
                Radius = 0;
                Debug.Assert(false);
                break;
            }
        }
Ejemplo n.º 26
0
        public void Add(ITriangleMesh mesh, bool weldVerticesBruteForce)
        {
            var triangleMesh = mesh as TriangleMesh;

            if (triangleMesh != null && !weldVerticesBruteForce)
            {
                // Special: mesh is TriangleMesh and no welding.

                if (triangleMesh.Vertices == null)
                {
                    return;
                }
                if (triangleMesh.Indices == null)
                {
                    return;
                }

                if (Vertices == null)
                {
                    Vertices = new List <Vector3>(triangleMesh.Vertices.Count);
                }

                int numberOfNewIndices = triangleMesh.Indices.Count;
                if (Indices == null)
                {
                    Indices = new List <int>(numberOfNewIndices);
                }

                // Add new vertices.
                int oldNumberOfVertices = Vertices.Count;
                Vertices.AddRange(triangleMesh.Vertices);

                // Add new indices. Add offset to all indices.
                for (int i = 0; i < numberOfNewIndices; i++)
                {
                    Indices.Add(triangleMesh.Indices[i] + oldNumberOfVertices);
                }

                return;
            }

            int numberOfTriangles = mesh.NumberOfTriangles;

            for (int i = 0; i < numberOfTriangles; i++)
            {
                Add(mesh.GetTriangle(i), weldVerticesBruteForce);
            }
        }
 internal override bool ParseNodeBodyElement(string id, VRMLParser parser)
 {
     if (id == "vertices")
     {
         Vertices.AddRange(parser.ParseSFVec2fOrMFVec2fValue());
     }
     else if (id == "solid")
     {
         Solid = parser.ParseBoolValue();
     }
     else
     {
         return(false);
     }
     return(true);
 }
Ejemplo n.º 28
0
        public void CommitVertex()
        {
            var vert = new Vertex(_vertex, 0, VertexSize);
            int index;

            if (!CacheVertices || !_vertexIndices.TryGetValue(vert, out index))
            {
                index = Vertices.Count;
                Vertices.AddRange(_vertex);

                if (CacheVertices)
                {
                    _vertexIndices.Add(new Vertex(Vertices, index, VertexSize), index);
                }
            }

            _primitiveIndices.Add(index / VertexSize);
        }
Ejemplo n.º 29
0
        internal override Body GenerateBody(World world, bool forSimulation = true)
        {
            Vertices verts = new Vertices();

            verts.AddRange(Points.Select(p => new Vector2(ConvertUnits.ToSimUnits(p.X + 0), ConvertUnits.ToSimUnits(p.Y + 0))));

            Body result = BodyFactory.CreatePolygon(world, verts, 1);

            if (forSimulation)
            {
                result.Restitution = Physics.Restitution;
                result.BodyType    = Physics.Dynamic ? BodyType.Dynamic : BodyType.Static;
                result.IsStatic    = !Physics.Dynamic;
            }

            result.Rotation = -(float)(Rotation * (Math.PI * 2));
            result.FixtureList.First().UserData = this;

            return(result);
        }
Ejemplo n.º 30
0
        public Arc(float radius, int sides, float startingAngle, float radians) : base()
        {
            Vertices.AddRange(new Circle(radius, sides).Vertices);
            Vertices.RemoveAt(Vertices.Count - 1);

            double curAngle     = 0.0;
            double anglePerSide = MathHelper.TwoPi / sides;

            while ((curAngle + (anglePerSide / 2.0)) < startingAngle)
            {
                curAngle += anglePerSide;

                Vertices.Add(Vertices[0]);
                Vertices.RemoveAt(0);
            }

            Vertices.Add(Vertices[0]);
            int sidesInArc = (int)((radians / anglePerSide) + 0.5);

            Vertices.RemoveRange(sidesInArc + 1, Vertices.Count - sidesInArc - 1);
        }
Ejemplo n.º 31
0
        /// <summary>
        /// Makes a set of vertices for the chain shape 
        /// by creating two offset vertices perpendicular 
        /// to the averaged direction from the current vertex
        /// and it's two connected vertices. Returned vertices 
        /// are in counterclockwise order
        /// </summary>
        /// <param name="chain">chain shape to work on</param>
        /// <returns>new Triangularizable Vertices for chain shape</returns>
        private static Vertices CreateChainVertices(ChainShape chain)
        {
            Matrix rotMat = Matrix.CreateRotationZ(MathHelper.PiOver2);
            Vertices chainTextVerts = new Vertices(chain.Vertices.Count * 2);
            List<Vector2> posChainTextVerts = new List<Vector2>(chain.Vertices.Count);
            List<Vector2> negChainTextVerts = new List<Vector2>(chain.Vertices.Count);
            for (int i = 0; i < chain.Vertices.Count; i++)
            {
                var curVertex = chain.Vertices[i];
                Vector2 direction = Vector2.Zero;
                Vector2 distance = Vector2.Zero;
                if (i == 0)
                {
                    distance = chain.Vertices[i + 1] - curVertex;
                }
                else if (i < chain.Vertices.Count - 1)
                {
                    distance = (chain.Vertices[i + 1] - curVertex) + (curVertex - chain.Vertices[i - 1]);
                }
                else
                {
                    distance = curVertex - chain.Vertices[i - 1];
                }

                direction = Vector2.Normalize(Vector2.Transform(distance, rotMat)).ToSimUnits();
                posChainTextVerts.Add(curVertex + (direction * 2f));
                negChainTextVerts.Insert(0, curVertex - (direction * 2f));
            }

            chainTextVerts.AddRange(posChainTextVerts);
            chainTextVerts.AddRange(negChainTextVerts);

            return chainTextVerts;
        }
Ejemplo n.º 32
0
		public Vertices Convert(params Vector2D[] vertices)
		{
			var farseerVertices = new Vertices(vertices.Length);
			farseerVertices.AddRange(vertices.Select(t => ToSimUnits(Convert(t))));
			return farseerVertices;
		}
Ejemplo n.º 33
0
        /// <summary>
        /// 
        /// </summary>
        /// <param name="entrance"></param>
        /// <param name="last"></param>
        /// <returns></returns>
        private Vertices CreateSimplePolygon(Vector2 entrance, Vector2 last)
        {
            bool entranceFound = false;
            bool endOfHull = false;

            Vertices polygon = new Vertices(32);
            Vertices hullArea = new Vertices(32);
            Vertices endOfHullArea = new Vertices(32);

            Vector2 current = Vector2.Zero;

            #region Entrance check

            // Get the entrance point. //todo: alle möglichkeiten testen
            if (entrance == Vector2.Zero || !InBounds(ref entrance))
            {
                entranceFound = SearchHullEntrance(out entrance);

                if (entranceFound)
                {
                    current = new Vector2(entrance.X - 1f, entrance.Y);
                }
            }
            else
            {
                if (IsSolid(ref entrance))
                {
                    if (IsNearPixel(ref entrance, ref last))
                    {
                        current = last;
                        entranceFound = true;
                    }
                    else
                    {
                        Vector2 temp;
                        if (SearchNearPixels(false, ref entrance, out temp))
                        {
                            current = temp;
                            entranceFound = true;
                        }
                        else
                        {
                            entranceFound = false;
                        }
                    }
                }
            }

            #endregion

            if (entranceFound)
            {
                polygon.Add(entrance);
                hullArea.Add(entrance);

                Vector2 next = entrance;

                do
                {
                    // Search in the pre vision list for an outstanding point.
                    Vector2 outstanding;
                    if (SearchForOutstandingVertex(hullArea, out outstanding))
                    {
                        if (endOfHull)
                        {
                            // We have found the next pixel, but is it on the last bit of the hull?
                            if (endOfHullArea.Contains(outstanding))
                            {
                                // Indeed.
                                polygon.Add(outstanding);
                            }

                            // That's enough, quit.
                            break;
                        }

                        // Add it and remove all vertices that don't matter anymore
                        // (all the vertices before the outstanding).
                        polygon.Add(outstanding);
                        hullArea.RemoveRange(0, hullArea.IndexOf(outstanding));
                    }

                    // Last point gets current and current gets next. Our little spider is moving forward on the hull ;).
                    last = current;
                    current = next;

                    // Get the next point on hull.
                    if (GetNextHullPoint(ref last, ref current, out next))
                    {
                        // Add the vertex to a hull pre vision list.
                        hullArea.Add(next);
                    }
                    else
                    {
                        // Quit
                        break;
                    }

                    if (next == entrance && !endOfHull)
                    {
                        // It's the last bit of the hull, search on and exit at next found vertex.
                        endOfHull = true;
                        endOfHullArea.AddRange(hullArea);

                        // We don't want the last vertex to be the same as the first one, because it causes the triangulation code to crash.
                        if (endOfHullArea.Contains(entrance))
                            endOfHullArea.Remove(entrance);
                    }

                } while (true);
            }

            return polygon;
        }
Ejemplo n.º 34
0
 public Vertices ToVertices()
 {
     Vertices vertices = new Vertices();
     vertices.AddRange(Flatten());
     return vertices;
 }
Ejemplo n.º 35
0
		Fixture j2b2Fixture(Body body, JObject fixtureValue)
		{
			
			
			if (null == fixtureValue)
				return null;
			
			
			//Fixture fixtureDef = new Fixture();
			var restitution = jsonToFloat("restitution", fixtureValue);
			var friction = jsonToFloat("friction", fixtureValue);
			var density = jsonToFloat("density", fixtureValue);
			var isSensor = fixtureValue["sensor"] == null ? false : (bool)fixtureValue["sensor"];
			
			
			var categoryBits = fixtureValue["filter-categoryBits"] == null ? 0x0001 : (int)fixtureValue["filter-categoryBits"];
			var maskBits = fixtureValue["filter-maskBits"] == null ? 0xffff : (int)fixtureValue["filter-maskBits"];
			var groupIndex = fixtureValue["filter-groupIndex"] == null ? (short)0 : (short)fixtureValue["filter-groupIndex"];
			
			
			Fixture fixture = null;
			
			
			
			if (null != fixtureValue["circle"])
			{
				JObject circleValue = (JObject)fixtureValue["circle"];
				var radius = jsonToFloat("radius", circleValue);
				var position = jsonToVec("center", circleValue);
				fixture = FixtureFactory.AttachCircle(radius, density, body, position);
			}
			else if (null != fixtureValue["edge"])
			{
				JObject edgeValue = (JObject)fixtureValue["edge"];
				var m_vertex1 = (jsonToVec("vertex1", edgeValue));
				var m_vertex2 = (jsonToVec("vertex2", edgeValue));
				fixture = FixtureFactory.AttachEdge(m_vertex1, m_vertex2, body);
				((EdgeShape)fixture.Shape).HasVertex0 = edgeValue["hasVertex0"] == null ? false : (bool)edgeValue["hasVertex0"];
				((EdgeShape)fixture.Shape).HasVertex3 = edgeValue["hasVertex3"] == null ? false : (bool)edgeValue["hasVertex3"];
				
				if (((EdgeShape)fixture.Shape).HasVertex0)
					((EdgeShape)fixture.Shape).Vertex0 = (jsonToVec("vertex0", edgeValue));
				if (((EdgeShape)fixture.Shape).HasVertex3)
					((EdgeShape)fixture.Shape).Vertex3 = (jsonToVec("vertex3", edgeValue));
				
			}
			else if (null != fixtureValue["loop"])
			{// support old
				// format (r197)
				JObject chainValue = (JObject)fixtureValue["loop"];
				int numVertices = ((JArray)chainValue["x"]).Count;
				Vertices vertices = new Vertices();
				for (int i = 0; i < numVertices; i++)
					vertices.Add(jsonToVec("vertices", chainValue, i));
				fixture = FixtureFactory.AttachChainShape(vertices, body);
				
			}
			else if (null != fixtureValue["chain"])
			{
				JObject chainValue = (JObject)fixtureValue["chain"];
				ChainShape chainShape = new ChainShape();
				int numVertices = ((JArray)chainValue["vertices"]["x"]).Count;
				
				Vertices vertices = new Vertices();
				
				
				for (int i = 0; i < numVertices; i++)
					vertices.Add(jsonToVec("vertices", chainValue, i));
				
				// FPE. See http://www.box2d.org/forum/viewtopic.php?f=4&t=7973&p=35363
				if (vertices[0] == vertices[vertices.Count - 1])
				{
					var vertices2 = new Vertices(numVertices - 1);
					vertices2.AddRange(vertices.GetRange(0, numVertices - 1));
					chainShape.CreateLoop(vertices2);
					fixture = body.CreateFixture(chainShape);
				}
				else
					fixture = FixtureFactory.AttachChainShape(vertices, body);
				
				var fixtureChain = fixture.Shape as ChainShape;
				
				var hasPrevVertex = chainValue["hasPrevVertex"] == null ? false : (bool)chainValue["hasPrevVertex"];
				var hasNextVertex = chainValue["hasNextVertex"] == null ? false : (bool)chainValue["hasNextVertex"];
				if (hasPrevVertex)
					fixtureChain.PrevVertex = (jsonToVec("prevVertex", chainValue));
				if (hasNextVertex)
					fixtureChain.NextVertex = (jsonToVec("nextVertex", chainValue));
				
			}
			else if (null != fixtureValue["polygon"])
			{
				JObject polygonValue = (JObject)fixtureValue["polygon"];
				Vertices vertices = new Vertices();
				int numVertices = ((JArray)polygonValue["vertices"]["x"]).Count;
				if (numVertices > Settings.MaxPolygonVertices)
				{
					Console.WriteLine("Ignoring polygon fixture with too many vertices.");
				}
				else if (numVertices < 2)
				{
					Console.WriteLine("Ignoring polygon fixture less than two vertices.");
				}
				else if (numVertices == 2)
				{
					Console.WriteLine("Creating edge shape instead of polygon with two vertices.");
					var m_vertex1 = (jsonToVec("vertices", polygonValue, 0));
					var m_vertex2 = (jsonToVec("vertices", polygonValue, 1));
					fixture = FixtureFactory.AttachEdge(m_vertex1, m_vertex2, body);
					
				}
				else
				{
					for (int i = 0; i < numVertices; i++)
						vertices.Add(jsonToVec("vertices", polygonValue, i));
					fixture = FixtureFactory.AttachPolygon(vertices, density, body);
				}
			}
			
			String fixtureName = fixtureValue["name"] == null ? "" : fixtureValue["name"].ToString();
			if (fixtureName != "")
			{
				SetFixtureName(fixture, fixtureName);
			}
			
			if (fixture != null)
			{
				fixture.Restitution = restitution;
				fixture.Friction = friction;
				fixture.Shape.Density = density;
				fixture.IsSensor = isSensor;
				fixture.CollisionCategories = (Category)categoryBits;
				fixture.CollidesWith = (Category)maskBits;
				fixture.CollisionGroup = groupIndex;
			}
			
			
			return fixture;
		}
Ejemplo n.º 36
0
        public override void Initialize()
        {
            base.Initialize();

            GameInstance.ViewCenter = Vector2.Zero;

            _twoShape = new Vertices
            {
                new Vector2(5.510646f,-6.312136f),
                new Vector2(5.510646f,-9.534955f),
                new Vector2(-6.016356f,-9.534955f),
                new Vector2(-6.016356f,-6.837597f),
                new Vector2(-1.933609f,-0.7320573f),
                new Vector2(-0.6714239f,1.242431f),
                new Vector2(0.07130214f,2.498066f),
                new Vector2(0.4939168f,3.344996f),
                new Vector2(0.7957863f,4.093408f),
                new Vector2(0.9769094f,4.743301f),
                new Vector2(1.037288f,5.294677f),
                new Vector2(0.9643505f,5.967545f),
                new Vector2(0.7455474f,6.44485f),
                new Vector2(0.5806286f,6.610869f),
                new Vector2(0.3776243f,6.729462f),
                new Vector2(0.1365345f,6.80062f),
                new Vector2(-0.1426414f,6.824349f),
                new Vector2(-0.4218241f,6.798073f),
                new Vector2(-0.6629166f,6.719252f),
                new Vector2(-0.8659183f,6.587883f),
                new Vector2(-1.030829f,6.403981f),
                new Vector2(-1.158469f,6.141973f),
                new Vector2(-1.249639f,5.776335f),
                new Vector2(-1.32257f,4.734189f),
                new Vector2(-1.32257f,2.935948f),
                new Vector2(-6.016356f,2.935948f),
                new Vector2(-6.016356f,3.624884f),
                new Vector2(-5.970973f,5.045072f),
                new Vector2(-5.834826f,6.129576f),
                new Vector2(-5.710837f,6.586056f),
                new Vector2(-5.520398f,7.0389f),
                new Vector2(-5.263501f,7.488094f),
                new Vector2(-4.940154f,7.933653f),
                new Vector2(-4.556844f,8.350358f),
                new Vector2(-4.120041f,8.71307f),
                new Vector2(-3.629755f,9.02178f),
                new Vector2(-3.085981f,9.276493f),
                new Vector2(-2.487104f,9.475718f),
                new Vector2(-1.8315f,9.618026f),
                new Vector2(-1.119165f,9.703418f),
                new Vector2(-0.3501012f,9.731889f),
                new Vector2(1.117107f,9.644661f),
                new Vector2(1.779295f,9.535644f),
                new Vector2(2.393876f,9.383026f),
                new Vector2(2.960846f,9.186799f),
                new Vector2(3.480206f,8.946972f),
                new Vector2(3.951957f,8.663539f),
                new Vector2(4.376098f,8.336502f),
                new Vector2(5.076675f,7.592458f),
                new Vector2(5.577088f,6.755733f),
                new Vector2(5.877342f,5.82633f),
                new Vector2(5.977431f,4.804249f),
                new Vector2(5.921109f,3.981021f),
                new Vector2(5.752138f,3.134446f),
                new Vector2(5.470524f,2.264521f),
                new Vector2(5.076274f,1.371247f),
                new Vector2(4.406482f,0.2123121f),
                new Vector2(3.298271f,-1.454563f),
                new Vector2(1.751642f,-3.629379f),
                new Vector2(-0.233405f,-6.312136f),
            };

            int beforeCount = _twoShape.Count;
            _twoShape.AddRange(_twoShape); //Duplicate the points
            _twoShape = SimplifyTools.MergeIdenticalPoints(_twoShape);

            Debug.Assert(beforeCount == _twoShape.Count); //The merge should have removed all duplicate points.

            const int xOffset = 18;
            const int yOffset = 18;

            _upperLeft = new Vertices(_twoShape);
            _upperLeft.Translate(new Vector2(-xOffset, yOffset));
            _upperLeft = SimplifyTools.ReduceByArea(_upperLeft, 0.1f);

            _upperRight = new Vertices(_twoShape);
            _upperRight.Translate(new Vector2(xOffset, yOffset));
            _upperRight = SimplifyTools.ReduceByNth(_upperRight, 3);

            _lowerLeft = new Vertices(_twoShape);
            _lowerLeft.Translate(new Vector2(-xOffset, -yOffset));
            _lowerLeft = SimplifyTools.ReduceByDistance(_lowerLeft, 0.5f);

            _lowerRight = new Vertices(_twoShape);
            _lowerRight.Translate(new Vector2(xOffset, -yOffset));
            _lowerRight = SimplifyTools.DouglasPeuckerSimplify(_lowerRight, 0.5f);
        }