//TODO: Skip OBJ step and generate directly to .asset
        void GenerateMeshTerrain()
        {
            Done++;
            Debug.Log("Generating Mesh Terrain for " + TileX + "," + TileZ);
            AssetDatabase.Refresh();
            GetContainers();
            CreateFolders();

            Material m = new Material(Shader.Find("Standard"));

            m.EnableKeyword("_BUMPMAP");
            //_DETAIL_MULX2
            m.color = Color.white;
            m.SetFloat("_SpecularHighlights", 0f);
            m.SetFloat("_GlossyReflections", 0f);

            Texture2D t2 = (Texture2D)AssetDatabase.LoadAssetAtPath <Texture2D>(Paths.GetPath(ePATHSPEC.TEXTUREPATH));

            m.mainTexture = t2;
            Texture2D n1 = (Texture2D)AssetDatabase.LoadAssetAtPath <Texture2D>(Paths.GetPath(ePATHSPEC.NORMALMAPPATH));

            m.SetTexture("_BumpMap", n1);
            m.SetFloat("_Glossiness", 0);

            AssetDatabase.CreateAsset(m, Paths.GetPath(ePATHSPEC.MATERIALPATH));
            AssetDatabase.Refresh();

            //TerrainSettings tset = TerrainProto.GetComponent<TerrainSettings>();

            string hpath = Paths.GetPath(ePATHSPEC.HEIGHTMAPCONTPATH);

            Debug.Log("Instantiating HeightmapCont:" + TileX + "," + TileZ);
            HeightMap = Instantiate(AssetDatabase.LoadAssetAtPath <Texture2D>(hpath));

            string outpath  = Paths.GetPath(ePATHSPEC.MESHOBJPATH);
            DRect  TileSize = MapTools.TileBoundsInMeters(new DVector3(TileX, 0, TileZ), ZoomLevel);
            //ExportOBJ.ExportFromHeight(HeightMap, outpath, TileSize);
            //ExportOBJ.ExportMapZenHeight(HeightMap, outpath, TileSize.Size);
            DVector3 TileLatLon = MapTools.TileToWorldPos(new DVector3(TileX, 0, TileZ), ZoomLevel);

            TerrainContainer = new GameObject();
            MassiveTile tile = TerrainContainer.AddComponent <MassiveTile>();

            ExportOBJ.ExportMapZenHeight(tile, HeightMap, outpath, TileSize.Size, TileLatLon);

            AssetDatabase.Refresh();
            AssetDatabase.ImportAsset(Paths.GetPath(ePATHSPEC.MESHOBJPATH));
            GameObject asset = (GameObject)AssetDatabase.LoadMainAssetAtPath(Paths.GetPath(ePATHSPEC.MESHOBJPATH));
            GameObject obj   = Instantiate(asset);

            //Swap OBJ for .Asset to preserve modifications
            Transform  tr = obj.transform.Find("default");
            MeshFilter mf = tr.GetComponent <MeshFilter>();
            Mesh       nm = Instantiate(mf.sharedMesh);

            AssetDatabase.CreateAsset(nm, Paths.GetPath(ePATHSPEC.MESHASSETPATH));
            AssetDatabase.ImportAsset(Paths.GetPath(ePATHSPEC.MESHASSETPATH));
            AssetDatabase.Refresh();
            Mesh masset = (Mesh)AssetDatabase.LoadMainAssetAtPath(Paths.GetPath(ePATHSPEC.MESHASSETPATH));

            GameObject ma  = new GameObject("terrain");
            MeshFilter tmf = ma.AddComponent <MeshFilter>();

            tmf.mesh = masset;
            ma.AddComponent <MeshRenderer>();
            ma.transform.parent = TerrainContainer.transform;

            GameObject.DestroyImmediate(obj);
            AssetDatabase.Refresh();

            //set position
            Vector3  tm  = MapTools.TileToMeters(TileX, TileZ, ZoomLevel).ToVector3();
            Vector3  sp  = MapTools.TileToMeters((int)StartPostion.x, (int)StartPostion.z, ZoomLevel).ToVector3();
            DVector3 dif = new DVector3(TileX, 0, TileZ) - StartPostion;

            TerrainContainer.transform.position = new Vector3(tm.x - sp.x, 0, sp.z - tm.z);

            TerrainContainer.name = TileX + "_" + "0" + "_" + TileZ + "_" + ZoomLevel;
            GameObject   TerGo = TerrainContainer.transform.Find("terrain").gameObject;
            MeshRenderer mr    = TerGo.GetComponent <MeshRenderer>();

            TerGo.AddComponent <MeshCollider>();
            TerGo.layer = LayerMask.NameToLayer("Terrain");

            tile.ZoomLevel = ZoomLevel;
            tile.SetTileIndex(new Vector3(TileX, 0, TileZ), ZoomLevel);

            Material[] temp = new Material[1];
            //temp[0] = Instantiate((Material)AssetDatabase.LoadAssetAtPath<Material>(path + ".mat"));
            temp[0]      = (Material)AssetDatabase.LoadAssetAtPath <Material>(Paths.GetPath(ePATHSPEC.MATERIALPATH));
            temp[0].name = "mat_" + TileX + "_" + TileZ;
            //TextureTools.Bilinear(t2, 512, 512);
            temp[0].mainTexture = t2;
            //temp[1] = Instantiate((Material)AssetDatabase.LoadAssetAtPath<Material>(path + ".mat"));
            //temp[1].name = "hello";
            mr.sharedMaterials = temp;
            AssetDatabase.SaveAssets();
            AssetDatabase.Refresh();
            Debug.Log("Generated Mesh Terrain");
            Done--;
        }
        public void CreateRoads(string sData, DVector3 PositionMeters)
        {
            TileBoundsMeters = this.transform.parent.GetComponent <MassiveTile>().TileBoundsMeters;
            mc = transform.parent.Find("terrain").GetComponent <MeshCollider>();

            Dictionary <string, object> Data     = (Dictionary <string, object>)MiniJSON.Json.Deserialize(sData);
            List <List <Vector3> >      segments = new List <List <Vector3> >();
            IList features = (IList)Data["features"];

            Roads.Clear();
            foreach (IDictionary feature in features)
            {
                IDictionary geometry   = (IDictionary)feature["geometry"];
                IDictionary properties = (IDictionary)feature["properties"];

                string geotype     = (string)geometry["type"];
                string name        = OSMTools.GetProperty(properties, "name");
                string kind        = OSMTools.GetProperty(properties, "kind");
                string kind_detail = OSMTools.GetProperty(properties, "kind_detail");
                //Debug.Log("Processing:" + name);

                if (geotype == "LineString")
                {
                    Road           rs = new Road(name, this.gameObject, kind, kind_detail);
                    MassiveFeature mf = rs.go.AddComponent <MassiveFeature>();
                    mf.SetProperties(properties);
                    rs.is_bridge = mf.is_bridge;

                    for (int i = 0; i < ((IList)geometry["coordinates"]).Count; i++)
                    {
                        IList   piece = (IList)((IList)geometry["coordinates"])[i];
                        double  dx    = (double)piece[0];
                        double  dz    = (double)piece[1];
                        Vector3 v     = MapTools.LatLonToMeters((float)dz, (float)dx).ToVector3();
                        v -= PositionMeters.ToVector3();
                        Node n = new Node(v, name);
                        rs.nodes.Add(n);
                        if (i == 0)
                        {
                            //rs.go.transform.position = v;
                            rs.go.layer = LayerMask.NameToLayer("Roads");
                        }
                    }
                    Roads.Add(rs);
                }


                if (geotype == "MultiLineString")
                {
                    GameObject go = new GameObject();
                    go.transform.parent = this.transform;
                    MassiveFeature mf = go.AddComponent <MassiveFeature>();
                    mf.SetProperties(properties);

                    for (int i = 0; i < ((IList)geometry["coordinates"]).Count; i++)
                    {
                        Road rs = new Road(name, go, kind, kind_detail);
                        rs.is_bridge = mf.is_bridge;
                        go.name      = name;
                        IList segment = (IList)((IList)geometry["coordinates"])[i];
                        for (int j = 0; j < segment.Count; j++)
                        {
                            IList   piece = (IList)segment[j];
                            double  dx    = (double)piece[0];
                            double  dz    = (double)piece[1];
                            Vector3 v     = MapTools.LatLonToMeters((float)dz, (float)dx).ToVector3();
                            v -= PositionMeters.ToVector3();
                            Node n = new Node(v, name);
                            rs.nodes.Add(n);
                            if ((i == 0) && (j == 0))
                            {
                                //rs.go.transform.position = v;
                                rs.go.layer = LayerMask.NameToLayer("Roads");
                            }
                        }
                        Roads.Add(rs);
                    }
                }
            }
            //calculate intersections
            CalculateIntersections();
            CreateRoadGeometry();
            //VisualizeNodes();
        }
        public void CreateTest()
        {
            /*
             * Road r1 = new Road("minor", this.gameObject, Road.KIND_MINOR_ROAD);
             * Roads.Add(r1);
             * Vector3 v1 = new Vector3(100, 0, 0);
             * Vector3 v2 = new Vector3(100, 0, 95);
             * Vector3 v3 = new Vector3(0, 0, 140);
             * r1.nodes.Add(new Node(v1, r1.name));
             * r1.nodes.Add(new Node(v2, r1.name));
             * r1.nodes.Add(new Node(v3, r1.name));
             */

            Road rs = new Road("straight", this.gameObject, Road.KIND_MINOR_ROAD);

            Roads.Add(rs);
            Vector3 v1 = new Vector3(0, 0, 0);
            Vector3 v2 = new Vector3(150, 0, 95);
            Vector3 v3 = new Vector3(250, 0, 140);

            rs.nodes.Add(new Node(v1, rs.name));
            rs.nodes.Add(new Node(v2, rs.name));
            rs.nodes.Add(new Node(v3, rs.name));

            /* Road rss = new Road("bstraight", this.gameObject, Road.KIND_MINOR_ROAD, Road.KIND_SERVICE);
             * Roads.Add(rss);
             * Vector3 v1s = new Vector3(180, 0, 0);
             * Vector3 v2s = new Vector3(180, 0, 95);
             * Vector3 v3s = new Vector3(190, 0, 140);
             * rss.nodes.Add(new Node(v1s, rss.name));
             * rss.nodes.Add(new Node(v2s, rss.name));
             * rss.nodes.Add(new Node(v3s, rss.name));
             */

            //r1.CreateSmoothConnection(v1, v2, v3, v2, Vector3.zero, Vector3.zero);

            /*
             * Bezier b = new Bezier(new Vector3(0, 0, 0),
             * new Vector3( 50, 0, 14 ),
             * new Vector3(50, 0, 14),
             * new Vector3(100, 0, 100));
             *
             * for ( float f = 0; f< 1; f+= 0.1f)
             * {
             * GameObject go = GameObject.CreatePrimitive(PrimitiveType.Sphere);
             * go.transform.position = b.GetPointAtTime(f);
             * go.transform.parent = this.transform;
             * }
             */



            /*
             * Road r1maj = new Road("major", this.gameObject, Road.KIND_MAJOR_ROAD);
             * Roads.Add(r1maj);
             * r1maj.nodes.Add(new Node(new Vector3(300, 0, 0), r1maj.name));
             * r1maj.nodes.Add(new Node(new Vector3(300, 0, 100), r1maj.name));
             * r1maj.nodes.Add(new Node(new Vector3(600, 0, 240), r1maj.name));
             *
             * Road r2 = new Road("path", this.gameObject, Road.KIND_PATH);
             * Roads.Add(r2);
             * r2.nodes.Add(new Node(new Vector3(0, 0, 250), r2.name));
             * r2.nodes.Add(new Node(new Vector3(0, 0, 350), r2.name));
             * r2.nodes.Add(new Node(new Vector3(200, 0, 350), r2.name));
             *
             * Road r3 = new Road("rail", this.gameObject, Road.KIND_RAIL);
             * Roads.Add(r3);
             * r3.nodes.Add(new Node(new Vector3(0, 0, 350), r3.name));
             * r3.nodes.Add(new Node(new Vector3(0, 0, 450), r3.name));
             * r3.nodes.Add(new Node(new Vector3(400, 0, 550), r3.name));
             */

            TileBoundsMeters = this.transform.parent.GetComponent <MassiveTile>().TileBoundsMeters;
            mc = transform.parent.Find("terrain").GetComponent <MeshCollider>();
            // GridSplit(true);
            CalculateIntersections();
            CreateRoadGeometry();
            //VisualizeNodes();
        }
        public void Generate(string sData, DVector3 PositionMeters, string AssetPath)
        {
            mc = transform.parent.Find("terrain").GetComponent <MeshCollider>();
            TileBoundsMeters = this.transform.parent.GetComponent <MassiveTile>().TileBoundsMeters;
            Data             = (Dictionary <string, object>)MiniJSON.Json.Deserialize(sData);

            IList features = (IList)Data["features"];

            foreach (IDictionary feature in features)
            {
                IDictionary geometry = (IDictionary)feature["geometry"];
                string      geotype  = (string)geometry["type"];

                IDictionary properties = (IDictionary)feature["properties"];
                string      kind       = "";
                string      kinddetail = "";
                string      name       = "_";
                string      id         = "";
                name       = OSMTools.GetProperty(properties, "name");
                kind       = OSMTools.GetProperty(properties, "kind");
                kinddetail = OSMTools.GetProperty(properties, "kind_detail");
                id         = OSMTools.GetProperty(properties, "id");

                //if (name == "_") continue;

                if (!CanWeInclude(AllowKinds, kind))
                {
                    continue;
                }


                List <List <Vector3> > segments = new List <List <Vector3> >();

                if (geotype == "LineString" &&
                    CanWeInclude(AllowShapes, "LineString"))
                {
                    List <Vector3> list = new List <Vector3>();
                    foreach (IList piece in (IList)geometry["coordinates"])
                    {
                        double  dx = (double)piece[0];
                        double  dz = (double)piece[1];
                        Vector3 v  = MapTools.LatLonToMeters((float)dz, (float)dx).ToVector3();
                        v -= PositionMeters.ToVector3();
                        list.Add(v);
                    }

                    list = OSMTools.InsertPoints(list, InterpolateRoadMeters);

                    segments.Add(list);
                }

                if (geotype == "MultiLineString" &&
                    CanWeInclude(AllowShapes, "MultiLineString"))
                {
                    foreach (IList piecelist in (IList)geometry["coordinates"])
                    {
                        List <Vector3> list = new List <Vector3>();
                        foreach (IList piece in (IList)piecelist)
                        {
                            double  dx = (double)piece[0];
                            double  dz = (double)piece[1];
                            Vector3 v  = MapTools.LatLonToMeters((float)dz, (float)dx).ToVector3();
                            v -= PositionMeters.ToVector3();
                            list.Add(v);
                        }
                        list = OSMTools.InsertPoints(list, InterpolateRoadMeters);
                        segments.Add(list);
                    }
                }

                if (segments.Count > 0)
                {
                    MeshData md = new MeshData();
                    Run(segments, md, GetWidthForKind(kind));

                    GameObject go = new GameObject(name);
                    go.layer = LayerMask.NameToLayer("Roads");
                    MassiveFeature f = go.AddComponent <MassiveFeature>();
                    f.SetSegments(segments);
                    f.SetProperties(properties);
                    f.SetType(geotype);
                    f.SetID(id);
                    go.transform.parent        = this.transform;
                    go.transform.localPosition = Vector3.zero;
                    // Create the mesh
                    CreateGameObject(md, go, kind);
                    //WriteAsset(go, AssetPath);
                }
            }

#if UNITY_EDITOR
            AssetDatabase.SaveAssets();
#endif
        }