GameObject GenerateCellRegionSurface(int cellIndex, Material material)
        {
            if (cellIndex<0 || cellIndex>=cells.Count) return null;
            Region region = cells [cellIndex].region;

            // Calculate region's surface points
            int numSegments = region.segments.Count;
            Connector connector = new Connector();
            if (_terrain==null) {
                connector.AddRange(region.segments);
            } else {
                for (int i = 0; i<numSegments; i++) {
                    Segment s = region.segments[i];
                    SurfaceSegmentForSurface(s, connector);
                }
            }
            Geom.Polygon surfacedPolygon = connector.ToPolygonFromLargestLineStrip();
            List<Point> surfacedPoints = surfacedPolygon.contours[0].points;

            List<PolygonPoint> ppoints = new List<PolygonPoint>(surfacedPoints.Count);
            for (int k=0;k<surfacedPoints.Count;k++) {
                double x = surfacedPoints[k].x+2;
                double y = surfacedPoints[k].y+2;
                if (!IsTooNearPolygon(x, y, ppoints)) {
                    float h = _terrain!=null ? _terrain.SampleHeight(transform.TransformPoint((float)x-2, (float)y-2,0)): 0;
                    ppoints.Add (new PolygonPoint(x, y, h));
                }
            }
            Poly2Tri.Polygon poly = new Poly2Tri.Polygon(ppoints);

            if (_terrain!=null) {
                if (steinerPoints==null) {
                    steinerPoints = new List<TriangulationPoint>(6000);
                } else {
                    steinerPoints.Clear();
                }

                float stepX = 1.0f / heightMapWidth;
                float smallStep = 1.0f / heightMapWidth;
                float y = region.rect2D.yMin + smallStep;
                float ymax = region.rect2D.yMax - smallStep;
                float[] acumY = new float[terrainRoughnessMapWidth];
                while(y<ymax) {
                    int j = (int)((y + 0.5f) * terrainRoughnessMapHeight); // * heightMapHeight)) / TERRAIN_CHUNK_SIZE;
                    if (j>=0) {
                    if (j>=terrainRoughnessMapHeight) j=terrainRoughnessMapHeight-1;
                    float sy = y + 2;
                    float xin = GetFirstPointInRow(sy, ppoints) + smallStep;
                    float xout = GetLastPointInRow(sy, ppoints) - smallStep;
                    int k0 = -1;
                    for (float x = xin; x<xout; x+=stepX) {
                        int k = (int)((x + 0.5f) * terrainRoughnessMapWidth); //)) / TERRAIN_CHUNK_SIZE;
                        if (k>=terrainRoughnessMapWidth) k=terrainRoughnessMapWidth-1;
                        if (k0!=k) {
                            k0=k;
                            stepX = terrainRoughnessMap[j,k];
                            if (acumY[k] >= stepX) acumY[k] = 0;
                            acumY[k] += smallStep;
                        }
                        if (acumY[k] >= stepX) {
                            // Gather precision height
                            float h = _terrain.SampleHeight (transform.TransformPoint(x,y,0));
                            float htl = _terrain.SampleHeight (transform.TransformPoint (x-smallStep, y+smallStep, 0));
                            if (htl>h) h = htl;
                            float htr = _terrain.SampleHeight (transform.TransformPoint (x+smallStep, y+smallStep, 0));
                            if (htr>h) h = htr;
                            float hbr = _terrain.SampleHeight (transform.TransformPoint (x+smallStep, y-smallStep, 0));
                            if (hbr>h) h = hbr;
                            float hbl = _terrain.SampleHeight (transform.TransformPoint (x-smallStep, y-smallStep, 0));
                            if (hbl>h) h = hbl;
                            steinerPoints.Add (new PolygonPoint (x+2, sy, h));
                        }
                    }
                    }
                    y += smallStep;
                    if (steinerPoints.Count>80000) {
                        break;
                    }
                }
                poly.AddSteinerPoints(steinerPoints);
            }

            P2T.Triangulate(poly);

            // Calculate & optimize mesh data
            int pointCount = poly.Triangles.Count*3;
            List<Vector3> meshPoints = new List<Vector3> (pointCount);
            int[] triNew = new int[pointCount];
            if (surfaceMeshHit == null)
                surfaceMeshHit = new Dictionary<TriangulationPoint, int> (2000);
            else
                surfaceMeshHit.Clear ();

            int triNewIndex =-1;
            int newPointsCount = -1;

            if (_gridNormalOffset>0) {
                for (int k=0;k<poly.Triangles.Count;k++) {
                    DelaunayTriangle dt = poly.Triangles[k];
                    TriangulationPoint p = dt.Points [0];
                    if (surfaceMeshHit.ContainsKey (p)) {
                        triNew [++triNewIndex] = surfaceMeshHit [p];
                    } else {
                        Vector3 np = new Vector3(p.Xf-2, p.Yf-2, -p.Zf);
                        np += transform.InverseTransformVector(_terrain.terrainData.GetInterpolatedNormal(np.x+0.5f,np.y+0.5f)) * _gridNormalOffset;
                        meshPoints.Add (np);
                        surfaceMeshHit.Add (p, ++newPointsCount);
                        triNew [++triNewIndex] = newPointsCount;
                    }
                    p = dt.Points [2];
                    if (surfaceMeshHit.ContainsKey (p)) {
                        triNew [++triNewIndex] = surfaceMeshHit [p];
                    } else {
                        Vector3 np = new Vector3(p.Xf-2, p.Yf-2, -p.Zf);
                        np += transform.InverseTransformVector(_terrain.terrainData.GetInterpolatedNormal(np.x+0.5f,np.y+0.5f)) * _gridNormalOffset;
                        meshPoints.Add (np);
                        surfaceMeshHit.Add (p, ++newPointsCount);
                        triNew [++triNewIndex] = newPointsCount;
                    }
                    p = dt.Points [1];
                    if (surfaceMeshHit.ContainsKey (p)) {
                        triNew [++triNewIndex] = surfaceMeshHit [p];
                    } else {
                        Vector3 np = new Vector3(p.Xf-2, p.Yf-2, -p.Zf);
                        np += transform.InverseTransformVector(_terrain.terrainData.GetInterpolatedNormal(np.x+0.5f,np.y+0.5f)) * _gridNormalOffset;
                        meshPoints.Add (np);
                        surfaceMeshHit.Add (p, ++newPointsCount);
                        triNew [++triNewIndex] = newPointsCount;
                    }
                }
            } else {
                for (int k=0;k<poly.Triangles.Count;k++) {
                    DelaunayTriangle dt = poly.Triangles[k];
                    TriangulationPoint p = dt.Points [0];
                    if (surfaceMeshHit.ContainsKey (p)) {
                        triNew [++triNewIndex] = surfaceMeshHit [p];
                    } else {
                        Vector3 np = new Vector3(p.Xf-2, p.Yf-2, -p.Zf);
                        meshPoints.Add (np);
                        surfaceMeshHit.Add (p, ++newPointsCount);
                        triNew [++triNewIndex] = newPointsCount;
                    }
                    p = dt.Points [2];
                    if (surfaceMeshHit.ContainsKey (p)) {
                        triNew [++triNewIndex] = surfaceMeshHit [p];
                    } else {
                        Vector3 np = new Vector3(p.Xf-2, p.Yf-2, -p.Zf);
                        meshPoints.Add (np);
                        surfaceMeshHit.Add (p, ++newPointsCount);
                        triNew [++triNewIndex] = newPointsCount;
                    }
                    p = dt.Points [1];
                    if (surfaceMeshHit.ContainsKey (p)) {
                        triNew [++triNewIndex] = surfaceMeshHit [p];
                    } else {
                        Vector3 np = new Vector3(p.Xf-2, p.Yf-2, -p.Zf);
                        meshPoints.Add (np);
                        surfaceMeshHit.Add (p, ++newPointsCount);
                        triNew [++triNewIndex] = newPointsCount;
                    }
                }
            }

            int cacheIndex = GetCacheIndexForCellRegion (cellIndex);
            string cacheIndexSTR = cacheIndex.ToString();
            // Deletes potential residual surface
            Transform t = surfacesLayer.transform.FindChild(cacheIndexSTR);
            if (t!=null) DestroyImmediate(t.gameObject);
            GameObject surf = Drawing.CreateSurface (cacheIndexSTR, meshPoints.ToArray(), triNew, material);
            _lastVertexCount += surf.GetComponent<MeshFilter>().sharedMesh.vertexCount;
            surf.transform.SetParent (surfacesLayer.transform, false);
            surf.transform.localPosition = Vector3.zero;
            surf.layer = gameObject.layer;
            if (surfaces.ContainsKey(cacheIndex)) surfaces.Remove(cacheIndex);
            surfaces.Add (cacheIndex, surf);
            return surf;
        }
        GameObject GenerateTerritoryRegionSurface(int territoryIndex, Material material, Vector2 textureScale, Vector2 textureOffset, float textureRotation)
        {
            if (territoryIndex<0 || territoryIndex>=territories.Count) return null;
            Region region = territories [territoryIndex].region;

            // Calculate region's surface points
            int numSegments = region.segments.Count;
            Connector connector = new Connector();
            if (_terrain==null) {
                connector.AddRange(region.segments);
            } else {
                for (int i = 0; i<numSegments; i++) {
                    Segment s = region.segments[i];
                    SurfaceSegmentForSurface(s, connector);
                }
            }
            Geom.Polygon surfacedPolygon = connector.ToPolygonFromLargestLineStrip();
            List<Point> surfacedPoints = surfacedPolygon.contours[0].points;

            List<PolygonPoint> ppoints = new List<PolygonPoint>(surfacedPoints.Count);
            for (int k=0;k<surfacedPoints.Count;k++) {
                double x = surfacedPoints[k].x+2;
                double y = surfacedPoints[k].y+2;
                if (!IsTooNearPolygon(x, y, ppoints)) {
                    float h = _terrain!=null ? _terrain.SampleHeight(transform.TransformPoint((float)x-2, (float)y-2,0)): 0;
                    ppoints.Add (new PolygonPoint(x, y, h));
                }
            }
            Poly2Tri.Polygon poly = new Poly2Tri.Polygon(ppoints);

            if (_terrain!=null) {

                if (steinerPoints==null) {
                    steinerPoints = new List<TriangulationPoint>(6000);
                } else {
                    steinerPoints.Clear();
                }

                float stepX = 1.0f / heightMapWidth;
                float smallStep = 1.0f / heightMapWidth;
                float y = region.rect2D.yMin + smallStep;
                float ymax = region.rect2D.yMax - smallStep;
                float[] acumY = new float[terrainRoughnessMapWidth];
                while(y<ymax) {
                    int j = (int)((y + 0.5f) * terrainRoughnessMapHeight); // * heightMapHeight)) / TERRAIN_CHUNK_SIZE;
                    if (j>=terrainRoughnessMapHeight) j=terrainRoughnessMapHeight-1;
                    float sy = y + 2;
                    float xin = GetFirstPointInRow(sy, ppoints) + smallStep;
                    float xout = GetLastPointInRow(sy, ppoints) - smallStep;
                    int k0 = -1;
                    for (float x = xin; x<xout; x+=stepX) {
                        int k = (int)((x + 0.5f) * terrainRoughnessMapWidth); //)) / TERRAIN_CHUNK_SIZE;
                        if (k>=terrainRoughnessMapWidth) k=terrainRoughnessMapWidth-1;
                        if (k0!=k) {
                            k0=k;
                            stepX = terrainRoughnessMap[j,k];
                            if (acumY[k] >= stepX) acumY[k] = 0;
                            acumY[k] += smallStep;
                        }
                        if (acumY[k] >= stepX) {
                            // Gather precision height
                            float h = _terrain.SampleHeight (transform.TransformPoint(x,y,0));
                            float htl = _terrain.SampleHeight (transform.TransformPoint (x-smallStep, y+smallStep, 0));
                            if (htl>h) h = htl;
                            float htr = _terrain.SampleHeight (transform.TransformPoint (x+smallStep, y+smallStep, 0));
                            if (htr>h) h = htr;
                            float hbr = _terrain.SampleHeight (transform.TransformPoint (x+smallStep, y-smallStep, 0));
                            if (hbr>h) h = hbr;
                            float hbl = _terrain.SampleHeight (transform.TransformPoint (x-smallStep, y-smallStep, 0));
                            if (hbl>h) h = hbl;
                            steinerPoints.Add (new PolygonPoint (x+2, sy, h));
                        }
                    }
                    y += smallStep;
                    if (steinerPoints.Count>80000) {
                        break;
                    }
                }
                poly.AddSteinerPoints(steinerPoints);
            }

            P2T.Triangulate(poly);

            Vector3[] revisedSurfPoints = new Vector3[poly.Triangles.Count*3];

            if (_gridNormalOffset>0) {
                for (int k=0;k<poly.Triangles.Count;k++) {
                    DelaunayTriangle dt = poly.Triangles[k];
                    float x = dt.Points[0].Xf-2;
                    float y = dt.Points[0].Yf-2;
                    float z = -dt.Points[0].Zf;
                    Vector3 nd = transform.InverseTransformVector(_terrain.terrainData.GetInterpolatedNormal(x+0.5f,y+0.5f)) * _gridNormalOffset;
                    revisedSurfPoints[k*3].x = x + nd.x;
                    revisedSurfPoints[k*3].y = y + nd.y;
                    revisedSurfPoints[k*3].z = z + nd.z;

                    x = dt.Points[2].Xf-2;
                    y = dt.Points[2].Yf-2;
                    z = -dt.Points[2].Zf;
                    nd = transform.InverseTransformVector(_terrain.terrainData.GetInterpolatedNormal(x+0.5f,y+0.5f)) * _gridNormalOffset;
                    revisedSurfPoints[k*3+1].x = x + nd.x;
                    revisedSurfPoints[k*3+1].y = y + nd.y;
                    revisedSurfPoints[k*3+1].z = z + nd.z;

                    x = dt.Points[1].Xf-2;
                    y = dt.Points[1].Yf-2;
                    z = -dt.Points[1].Zf;
                    nd = transform.InverseTransformVector(_terrain.terrainData.GetInterpolatedNormal(x+0.5f,y+0.5f)) * _gridNormalOffset;
                    revisedSurfPoints[k*3+2].x = x + nd.x;
                    revisedSurfPoints[k*3+2].y = y + nd.y;
                    revisedSurfPoints[k*3+2].z = z + nd.z;
                }
            } else {
                for (int k=0;k<poly.Triangles.Count;k++) {
                    DelaunayTriangle dt = poly.Triangles[k];
                    revisedSurfPoints[k*3].x = dt.Points[0].Xf-2;
                    revisedSurfPoints[k*3].y = dt.Points[0].Yf-2;
                    revisedSurfPoints[k*3].z = -dt.Points[0].Zf;
                    revisedSurfPoints[k*3+1].x = dt.Points[2].Xf-2;
                    revisedSurfPoints[k*3+1].y = dt.Points[2].Yf-2;
                    revisedSurfPoints[k*3+1].z = -dt.Points[2].Zf;
                    revisedSurfPoints[k*3+2].x = dt.Points[1].Xf-2;
                    revisedSurfPoints[k*3+2].y = dt.Points[1].Yf-2;
                    revisedSurfPoints[k*3+2].z = -dt.Points[1].Zf;
                }
            }
            int cacheIndex = GetCacheIndexForTerritoryRegion (territoryIndex);
            string cacheIndexSTR = cacheIndex.ToString();
            // Deletes potential residual surface
            Transform t = surfacesLayer.transform.FindChild(cacheIndexSTR);
            if (t!=null) DestroyImmediate(t.gameObject);
            GameObject surf = Drawing.CreateSurface (cacheIndexSTR, revisedSurfPoints, material);
            surf.transform.SetParent (surfacesLayer.transform, false);
            surf.transform.localPosition = Vector3.zero;
            surf.layer = gameObject.layer;
            if (surfaces.ContainsKey(cacheIndex)) surfaces.Remove(cacheIndex);
            surfaces.Add (cacheIndex, surf);

            return surf;
        }
    public void CreateMesh(Vector2[] vertsToCopy, Transform transform,int triangleIndex)
    {
        List<Vector3> resultsLocal = new List<Vector3>();
        List<int> resultsTriIndexesLocal = new List<int>();
        List<int> resultsTriIndexesReversedLocal = new List<int>();
        List<Vector2> uvsLocal = new List<Vector2>();
        List<Vector3> normalsLocal = new List<Vector3>();

        Sprite spr = transform.GetComponent<SpriteRenderer>().sprite;
        Rect rec = spr.rect;
        Vector3 bound = transform.GetComponent<Renderer>().bounds.max- transform.GetComponent<Renderer>().bounds.min ;
        TextureImporter textureImporter = AssetImporter.GetAtPath(AssetDatabase.GetAssetPath(spr)) as TextureImporter;

        List<PolygonPoint> p2 = new List<PolygonPoint>();

        if (triangleIndex > 0)
        {
            vertsToCopy = CreateSubVertPoints (spr.bounds,vertsToCopy.ToList(), triangleIndex).ToArray();
        }

        int i = 0;
        for (i = 0; i < vertsToCopy.Count(); i ++)
        {
            p2.Add(new PolygonPoint(vertsToCopy [i].x, vertsToCopy [i].y));
        }

        Polygon _polygon = new Polygon(p2);

        if (triangleIndex > 0)
        {
            List<TriangulationPoint> triPoints = GenerateGridPoints (spr.bounds, triangleIndex, _polygon);
            _polygon.AddSteinerPoints (triPoints);
        }

        P2T.Triangulate(_polygon);

        int idx = 0;

        foreach (DelaunayTriangle triangle in _polygon.Triangles)
        {
            Vector3 v = new Vector3();
            foreach (TriangulationPoint p in triangle.Points)
            {
                v = new Vector3((float)p.X, (float)p.Y,0);
                if(!resultsLocal.Contains(v))
                {
                    resultsLocal.Add(v);
                    resultsTriIndexesLocal.Add(idx);

                    Vector2 newUv = new Vector2((v.x/bound.x) + 0.5f,  (v.y /bound.y)  + 0.5f);

                    newUv.x *= rec.width/ spr.texture.width;
                    newUv.y *= rec.height/ spr.texture.height;

                    newUv.x += (rec.x)/ spr.texture.width;
                    newUv.y += (rec.y) / spr.texture.height;

                    SpriteMetaData[] smdArray = textureImporter.spritesheet;
                    Vector2 pivot = new Vector2(.0f,.0f);;

                    for (int k = 0; k < smdArray.Length; k++)
                    {
                        if (smdArray[k].name == spr.name)
                        {
                            switch(smdArray[k].alignment)
                            {
                                case(0):
                                smdArray[k].pivot = Vector2.zero;
                                break;
                                case(1):
                                smdArray[k].pivot = new Vector2(0f,1f) -new Vector2(.5f,.5f);
                                break;
                                case(2):
                                smdArray[k].pivot = new Vector2(0.5f,1f) -new Vector2(.5f,.5f);
                                break;
                                case(3):
                                smdArray[k].pivot = new Vector2(1f,1f) -new Vector2(.5f,.5f);
                                break;
                                case(4):
                                smdArray[k].pivot = new Vector2(0f,.5f) -new Vector2(.5f,.5f);
                                break;
                                case(5):
                                smdArray[k].pivot = new Vector2(1f,.5f) -new Vector2(.5f,.5f);
                                break;
                                case(6):
                                smdArray[k].pivot = new Vector2(0f,0f) -new Vector2(.5f,.5f);
                                break;
                                case(7):
                                smdArray[k].pivot = new Vector2(0.5f,0f) -new Vector2(.5f,.5f);
                                break;
                                case(8):
                                smdArray[k].pivot = new Vector2(1f,0f) -new Vector2(.5f,.5f);
                                break;
                                case(9):
                                smdArray[k].pivot -= new Vector2(.5f,.5f);
                                break;
                            }
                            pivot = smdArray[k].pivot ;
                        }
                    }
                    if(textureImporter.spriteImportMode == SpriteImportMode.Single)
                        pivot = textureImporter.spritePivot-new Vector2(.5f,.5f);
                    newUv.x += ((pivot.x)*rec.width)/ spr.texture.width;
                    newUv.y += ((pivot.y)*rec.height)/ spr.texture.height;

                    uvsLocal.Add(newUv);
                    normalsLocal.Add(new Vector3(0,0,-1));
                    idx++;
                }
                else
                {
                    resultsTriIndexesLocal.Add(resultsLocal.LastIndexOf(v));
                }

            }
        }

        for (int j = resultsTriIndexesLocal.Count-1; j >=0; j--)
        {
            resultsTriIndexesReversedLocal.Add(resultsTriIndexesLocal[j]);
        }

        results.AddRange(resultsLocal);
        resultsTriIndexes.AddRange(resultsTriIndexesLocal);
        resultsTriIndexesReversed.AddRange(resultsTriIndexesReversedLocal);
        uvs.AddRange(uvsLocal);
        normals.AddRange(normalsLocal);

        resultsLocal.Clear();
        resultsTriIndexesLocal.Clear();
        resultsTriIndexesReversedLocal.Clear();
        uvsLocal.Clear();
        normalsLocal.Clear();

        finalVertices = results.ToArray();

        finalNormals = normals.ToArray();
        finalUvs= uvs.ToArray();

        finalTriangles = resultsTriIndexesReversed.ToArray();
    }
    public Mesh CreateMeshFromVerts(Vector3[] vertsToCopy, Mesh mesh, List<int> pathSplitIds, Transform SpriteGO = null)
    {
        List<Vector3> resultsLocal = new List<Vector3>();
        List<int> resultsTriIndexesLocal = new List<int>();
        List<int> resultsTriIndexesReversedLocal = new List<int>();
        List<Vector2> uvsLocal = new List<Vector2>();
        List<Vector3> normalsLocal = new List<Vector3>();

        Sprite spr = new Sprite();
        Rect rec = new Rect();
        Vector3 bound = Vector3.zero;
        TextureImporter textureImporter = new TextureImporter();

        if(SpriteGO !=null && SpriteGO.GetComponent<SpriteRenderer>() && SpriteGO.GetComponent<SpriteRenderer>().sprite)
        {

            spr = SpriteGO.GetComponent<SpriteRenderer>().sprite;
            rec = spr.rect;
            bound = SpriteGO.GetComponent<Renderer>().bounds.max- SpriteGO.GetComponent<Renderer>().bounds.min ;
            textureImporter = AssetImporter.GetAtPath(AssetDatabase.GetAssetPath(spr)) as TextureImporter;

        }

        List<PolygonPoint> p2 = new List<PolygonPoint>();
        List<TriangulationPoint> extraPoints = new List<TriangulationPoint>();

        int i = 0;
        for (i = 0; i < vertsToCopy.Count(); i ++)
        {
            if(i<pathSplitIds[0])
                p2.Add(new PolygonPoint(vertsToCopy [i].x, vertsToCopy [i].y));
            else
                extraPoints.Add(new TriangulationPoint(vertsToCopy [i].x, vertsToCopy [i].y));
        }

        Polygon _polygon = new Polygon(p2);

        // this is how to add more points
        _polygon.AddSteinerPoints (extraPoints);

        P2T.Triangulate(_polygon);

        if (spr == null)
        {
            bound = new Vector3((float)(_polygon.Bounds.MaxX - _polygon.Bounds.MinX),(float)(_polygon.Bounds.MaxY - _polygon.Bounds.MinY),0 ) ;
        }

        int idx = 0;

        foreach (DelaunayTriangle triangle in _polygon.Triangles)
        {
            Vector3 v = new Vector3();
            foreach (TriangulationPoint p in triangle.Points)
            {
                v = new Vector3((float)p.X, (float)p.Y,0);
                if(!resultsLocal.Contains(v))
                {
                    resultsLocal.Add(v);
                    resultsTriIndexesLocal.Add(idx);

                    Vector2 newUv = new Vector2(((v.x-(float)_polygon.Bounds.MinX) /bound.x) ,  ((v.y-(float)_polygon.Bounds.MinY) /bound.y) );
                    if (spr != null)
                    {
                        newUv = new Vector2 ((v.x / bound.x) + 0.5f, (v.y / bound.y) + 0.5f);
                        newUv.x *= rec.width/ spr.texture.width;
                        newUv.y *= rec.height/ spr.texture.height;

                        newUv.x += (rec.x)/ spr.texture.width;
                        newUv.y += (rec.y) / spr.texture.height;

                        SpriteMetaData[] smdArray = textureImporter.spritesheet;
                        Vector2 pivot = new Vector2(.0f,.0f);;

                        for (int k = 0; k < smdArray.Length; k++)
                        {
                            if (smdArray[k].name == spr.name)
                            {
                                switch(smdArray[k].alignment)
                                {
                                    case(0):
                                    smdArray[k].pivot = Vector2.zero;
                                    break;
                                    case(1):
                                    smdArray[k].pivot = new Vector2(0f,1f) -new Vector2(.5f,.5f);
                                    break;
                                    case(2):
                                    smdArray[k].pivot = new Vector2(0.5f,1f) -new Vector2(.5f,.5f);
                                    break;
                                    case(3):
                                    smdArray[k].pivot = new Vector2(1f,1f) -new Vector2(.5f,.5f);
                                    break;
                                    case(4):
                                    smdArray[k].pivot = new Vector2(0f,.5f) -new Vector2(.5f,.5f);
                                    break;
                                    case(5):
                                    smdArray[k].pivot = new Vector2(1f,.5f) -new Vector2(.5f,.5f);
                                    break;
                                    case(6):
                                    smdArray[k].pivot = new Vector2(0f,0f) -new Vector2(.5f,.5f);
                                    break;
                                    case(7):
                                    smdArray[k].pivot = new Vector2(0.5f,0f) -new Vector2(.5f,.5f);
                                    break;
                                    case(8):
                                    smdArray[k].pivot = new Vector2(1f,0f) -new Vector2(.5f,.5f);
                                    break;
                                    case(9):
                                    smdArray[k].pivot -= new Vector2(.5f,.5f);
                                    break;
                                }
                                pivot = smdArray[k].pivot ;
                            }
                        }
                        if(textureImporter.spriteImportMode == SpriteImportMode.Single)
                            pivot = textureImporter.spritePivot-new Vector2(.5f,.5f);
                        newUv.x += ((pivot.x)*rec.width)/ spr.texture.width;
                        newUv.y += ((pivot.y)*rec.height)/ spr.texture.height;
                    }

                    uvsLocal.Add(newUv);
                    normalsLocal.Add(new Vector3(0,0,-1));
                    idx++;
                }
                else
                {
                    resultsTriIndexesLocal.Add(resultsLocal.LastIndexOf(v));
                }

            }
        }

        for (int j = resultsTriIndexesLocal.Count-1; j >=0; j--)
        {
            resultsTriIndexesReversedLocal.Add(resultsTriIndexesLocal[j]);
        }

        results.AddRange(resultsLocal);
        resultsTriIndexes.AddRange(resultsTriIndexesLocal);
        resultsTriIndexesReversed.AddRange(resultsTriIndexesReversedLocal);

        uvs.AddRange(uvsLocal);
        normals.AddRange(normalsLocal);

        resultsLocal.Clear();
        resultsTriIndexesLocal.Clear();
        resultsTriIndexesReversedLocal.Clear();
        uvsLocal.Clear();
        normalsLocal.Clear();

        finalVertices = results.ToArray();

        finalNormals = normals.ToArray();
        finalUvs= uvs.ToArray();

        finalTriangles = resultsTriIndexesReversed.ToArray();

        mesh.vertices = finalVertices;
        mesh.triangles = finalTriangles;
        mesh.uv = finalUvs;
        mesh.normals = finalNormals;
        mesh = calculateMeshTangents (mesh);
        return mesh;
    }
Ejemplo n.º 5
0
        private List<Polygon> TriangulatePolyTree(PolyTree tree)
        {
            List<Polygon> polygonsGenerated = new List<Polygon>();
            List<PolygonPoint> AllPoints = new List<PolygonPoint>();
            foreach (PolyNode islands in tree.Childs)
            {
                List<PolygonPoint> floorPoints = new List<PolygonPoint>();
                foreach (IntPoint point in SubdividePolygon(islands.Contour))
                {
                    floorPoints.Add(new PolygonPoint(point.X / GenerationInformation.CalculationScaleFactor, point.Y / GenerationInformation.CalculationScaleFactor));
                }

                AllPoints.AddRange(floorPoints);
                Polygon floorPolygon = new Polygon(floorPoints);

                foreach (PolyNode nextNode in islands.Childs)
                {
                    if (nextNode.IsHole)
                    {
                        List<PolygonPoint> holePoints = new List<PolygonPoint>();
                        foreach (IntPoint point in SubdividePolygon(nextNode.Contour))
                        {
                            holePoints.Add(new PolygonPoint(point.X / GenerationInformation.CalculationScaleFactor, point.Y / GenerationInformation.CalculationScaleFactor));
                        }
                        AllPoints.AddRange(holePoints);
                        floorPolygon.AddHole(new Polygon(holePoints));
                    }
                }
                if (GenerationInformation.UseGrid)
                {
                    List<TriangulationPoint> steinerPoints = new List<TriangulationPoint>();
                    for (float x = (float)floorPolygon.BoundingBox.MinX - ((float)floorPolygon.BoundingBox.MinX % GenerationInformation.GridSize.x); x < floorPolygon.BoundingBox.MaxX; x += GenerationInformation.GridSize.x)
                    {
                        for (float y = (float)floorPolygon.BoundingBox.MinY - ((float)floorPolygon.BoundingBox.MinY % GenerationInformation.GridSize.y); y < floorPolygon.BoundingBox.MaxY; y += GenerationInformation.GridSize.y)
                        {
                            TriangulationPoint p = new TriangulationPoint(x, y);
                            if (floorPolygon.IsPointInside(p))
                                steinerPoints.Add(p);
                        }
                    }

                    CullSteinerPoints(ref steinerPoints, AllPoints, 0.1f);

                    floorPolygon.AddSteinerPoints(steinerPoints);
                }

                floorPolygon.Prepare(P2T.CreateContext(TriangulationAlgorithm.DTSweep));
                P2T.Triangulate(floorPolygon);
                polygonsGenerated.Add(floorPolygon);

            }

            return polygonsGenerated;
        }