private static string CheckForTexture(string terrainPath, TerrainObject terrain, out bool exist)
        {
            string terrainTexture = "";

            exist = false;
            var folderPath     = Path.GetDirectoryName(terrainPath);
            var TexturesFolder = Path.Combine(folderPath, Path.GetFileNameWithoutExtension(terrainPath) + "_Textures");
            var texturePath    = Path.Combine(TexturesFolder, "Tile__" + terrain.Number.x.ToString() + "__" + terrain.Number.y.ToString());

            if (Directory.Exists(TexturesFolder))
            {
                if (File.Exists(texturePath + ".png"))
                {
                    texturePath    = texturePath + ".png";
                    terrainTexture = texturePath;
                    exist          = true;
                }
                else
                {
                    texturePath    = texturePath + ".jpg";
                    terrainTexture = texturePath;
                    exist          = true;
                }
            }
            return(terrainTexture);
        }
 private static void SetTreeToTerrain(float TreeScaleFactor, float RandomScaleFactor, TerrainContainerObject container, Vector3 pos)
 {
     for (int x = 0; x < container.terrainCount.x; x++)
     {
         for (int y = 0; y < container.terrainCount.y; y++)
         {
             TerrainObject item    = container.terrains[x, y];
             Terrain       terrain = item.terrain;
             terrain.treeBillboardDistance = BillBoardStartDistance;
             terrain.treeDistance          = TreeDistance;
             TerrainData tData           = terrain.terrainData;
             Vector3     terPos          = terrain.transform.position;
             Vector3     localPos        = pos - terPos;
             float       heightmapWidth  = (tData.heightmapWidth - 1) * tData.heightmapScale.x;
             float       heightmapHeight = (tData.heightmapHeight - 1) * tData.heightmapScale.z;
             if (localPos.x > 0 && localPos.z > 0 && localPos.x < heightmapWidth && localPos.z < heightmapHeight)
             {
                 terrain.AddTreeInstance(new TreeInstance
                 {
                     color          = Color.white,
                     heightScale    = TreeScaleFactor + UnityEngine.Random.Range(-RandomScaleFactor, RandomScaleFactor),
                     lightmapColor  = Color.white,
                     position       = new Vector3(localPos.x / heightmapWidth, 0, localPos.z / heightmapHeight),
                     prototypeIndex = UnityEngine.Random.Range(0, tData.treePrototypes.Length),
                     widthScale     = TreeScaleFactor + UnityEngine.Random.Range(-RandomScaleFactor, RandomScaleFactor)
                 });
                 break;
             }
         }
     }
 }
        private TerrainObject CreateTerrain(TerrainContainerObject parent, int x, int y, Vector3 size, Vector3 scale)
        {
            TerrainData tdata = new TerrainData
            {
                baseMapResolution   = 32,
                heightmapResolution = 32
            };

            tdata.heightmapResolution = heightmapResolution;
            tdata.baseMapResolution   = baseMapResolution;
            tdata.SetDetailResolution(detailResolution, resolutionPerPatch);
            tdata.size = size;

            GameObject GO = Terrain.CreateTerrainGameObject(tdata);

            GO.gameObject.SetActive(true);
            GO.name               = string.Format("{0}-{1}", x, y);
            GO.transform.parent   = parent.gameObject.transform;
            GO.transform.position = new Vector3(size.x * x, 0, size.z * y);
            GO.isStatic           = false;
            TerrainObject item = GO.AddComponent <TerrainObject>();

            item.Number            = new Vector2Int(x, y);
            item.size              = size;
            item.ElevationFilePath = TerrainFilePath;

            string filename = Path.Combine(parent.GeneratedTerrainfolder, GO.name) + ".asset";

            AssetDatabase.CreateAsset(tdata, filename);

            AssetDatabase.SaveAssets();

            return(item);
        }
        private static bool InBounds(TerrainObject terrain, int row, int col)
        {
            float numRows = terrain.terrainData.heightmapWidth - 1;
            float numCols = terrain.terrainData.heightmapHeight - 1;

            return((row >= 0 && row < numRows) &&
                   (col >= 0 && col < numCols));
        }
        public static string CheckForTexture(string TexturePath, TerrainObject terrain, out bool exist)
        {
            string terrainTexture = "";

            exist = false;
            var textureFilePath = Path.Combine(TexturePath, "Tile__" + terrain.Number.x.ToString() + "__" + terrain.Number.y.ToString());

            if (Resources.Load(textureFilePath) as Texture2D)
            {
                terrainTexture = textureFilePath;
                exist          = true;
            }
            return(terrainTexture);
        }
        public void AddTextureToTerrain(string terrainPath, TerrainObject terrainItem)
        {
            var terrain = terrainItem.terrain;

            bool texExist;

            var texPath = Extensions.CheckForTexture(terrainPath, terrainItem, out texExist);

            if (texExist)
            {
#if UNITY_2018_3 || UNITY_2019
                string       path         = Path.Combine(terrainItem.container.GeneratedTerrainfolder, terrainItem.name + ".terrainlayer");
                TerrainLayer terrainLayer = new TerrainLayer();
                AssetDatabase.CreateAsset(terrainLayer, path);

                TerrainData    terrainData   = terrainItem.terrainData;
                TerrainLayer[] terrainLayers = terrainData.terrainLayers;
                for (int i = 0; i < terrainLayers.Length; i++)
                {
                    if ((UnityEngine.Object)terrainLayers[i] == (UnityEngine.Object)terrainLayer)
                    {
                        return;
                    }
                }
                int            num   = terrainLayers.Length;
                TerrainLayer[] array = new TerrainLayer[num + 1];
                Array.Copy(terrainLayers, 0, array, 0, num);
                array[num] = terrainLayer;
                terrainData.terrainLayers = array;

                terrainLayer.diffuseTexture           = (Texture2D)Resources.Load(texPath);// tex;
                terrainLayer.tileSize                 = new Vector2(terrainItem.size.x, terrainItem.size.z);
                terrainLayer.tileOffset               = Vector2.zero;
                terrainItem.terrainData.terrainLayers = array;
#else
                SplatPrototype sp = new SplatPrototype
                {
                    texture    = (Texture2D)Resources.Load(texPath),
                    tileSize   = new Vector2(terrainItem.size.x, terrainItem.size.z),
                    tileOffset = Vector2.zero
                };
                terrain.terrainData.splatPrototypes = new[] { sp };
#endif
            }
            else
            {
                Debug.Log("Texture not found : " + texPath);
            }
        }
        public static void AddTextures(string terrainPath, TerrainObject terrainItem, Vector2 texturedim)
        {
            var terrain = terrainItem.terrain;

            bool texExist;
            var  texPath = CheckForTexture(terrainPath, terrainItem, out texExist);

            if (texExist)
            {
                var textureWidth  = (int)texturedim.x;
                var textureHeight = (int)texturedim.y;

                if (textureWidth <= 128 || textureHeight <= 128)
                {
                    return;
                }
                textureWidth  /= 2;
                textureHeight /= 2;

                Texture2D tex = new Texture2D(textureWidth, textureHeight);
                tex = LoadedTextureTile(texPath);


#if UNITY_2018_1_OR_NEWER
                TerrainLayer[] terrainTexture = new TerrainLayer[1];
                terrainTexture[0] = new TerrainLayer();
                terrainTexture[0].diffuseTexture  = tex;
                terrainTexture[0].tileSize        = new Vector2(terrainItem.size.x, terrainItem.size.z);
                terrainTexture[0].tileOffset      = Vector2.zero;
                terrain.terrainData.terrainLayers = terrainTexture;
#else
                SplatPrototype sp = new SplatPrototype
                {
                    texture    = tex,
                    tileSize   = new Vector2(terrainItem.size.x, terrainItem.size.z),
                    tileOffset = Vector2.zero
                };
                terrain.terrainData.splatPrototypes = new[] { sp };
#endif
            }
            else
            {
                Debug.Log("Texture not found : " + texPath);
            }
        }
        private static float Average(TerrainObject terrain, int row, int col)
        {
            float avg   = 0.0f;
            float total = 0.0f;

            for (int i = row - 1; i < row + 1; i++)
            {
                for (int j = col - 1; j < col + 1; j++)
                {
                    if (InBounds(terrain, i, j))
                    {
                        avg   += heightmap[i, j] * (TerrainHeightSmoothFactor);
                        total += 1.0f;
                    }
                }
            }

            return(avg / total);
        }
Exemple #9
0
        private TerrainObject CreateTerrain(Transform parent, int x, int y, Vector3 size, Vector3 scale)
        {
            TerrainData tdata = new TerrainData
            {
                baseMapResolution   = 32,
                heightmapResolution = 32
            };

            tdata.SetDetailResolution(prefs.detailResolution, prefs.resolutionPerPatch);
            tdata.size = size;


            GameObject GO = Terrain.CreateTerrainGameObject(tdata);

            GO.gameObject.SetActive(true);
            GO.name               = string.Format("{0}-{1}", x, y);
            GO.transform.parent   = parent;
            GO.transform.position = new Vector3(size.x * x, 0, size.z * y);

            TerrainObject item = GO.AddComponent <TerrainObject>();

            item.Number            = new Vector2Int(x, y);
            item.size              = size;
            item.ElevationFilePath = FilePath;
            item.prefs             = prefs;

            item.terrain.basemapDistance = prefs.BaseMapDistance;


            float prog = ((terrains.GetLength(0) * terrains.GetLength(1) * 100f) / (prefs.terrainCount.x * prefs.terrainCount.y)) / 100f;

            if (OnProgression != null)
            {
                OnProgression("Generating Terrains", prog);
            }


            return(item);
        }
Exemple #10
0
        /// <summary>
        /// Generate HeightMaps by spliting Single terrain file to tiles
        /// </summary>
        /// <param name="prefs"></param>
        /// <param name="item"></param>
        public void GenerateHeightMap(Prefs prefs, TerrainObject item)
        {
            tdata = item.terrain.terrainData;

            if (tdataHeightmap == null)
            {
                tdataHeightmap = new float[tdata.heightmapHeight, tdata.heightmapWidth];
            }
            //
            if (tdata == null)
            {
                tdata = item.terrain.terrainData;
                tdata.baseMapResolution = prefs.baseMapResolution;
                tdata.SetDetailResolution(prefs.detailResolution, prefs.resolutionPerPatch);
                tdata.size = item.size;

                if (tdataHeightmap == null)
                {
                    tdataHeightmap = new float[tdata.heightmapHeight, tdata.heightmapWidth];
                }
            }

            float elevationRange = MaxElevation - MinElevation;

            long startTime = DateTime.Now.Ticks;

            float thx = tdata.heightmapWidth - 1;
            float thy = tdata.heightmapHeight - 1;


            var y_Terrain_Col_num = (mapSize_row_y / prefs.terrainCount.x);
            var x_Terrain_row_num = (mapSize_col_x / prefs.terrainCount.y);

            // heightmap rotation
            int tw = tdata.heightmapWidth;
            int th = tdata.heightmapHeight;

            for (int x = lastX; x < tw; x++)
            {
                for (int y = 0; y < th; y++)
                {
                    var x_from = item.Number.x * x_Terrain_row_num;
                    var x_To   = item.Number.x * x_Terrain_row_num + x_Terrain_row_num - 1;

                    var y_from = item.Number.y * y_Terrain_Col_num;
                    var y_To   = item.Number.y * y_Terrain_Col_num + y_Terrain_Col_num - 1;

                    float px = Mathf.Lerp(x_from, x_To, x / thx);
                    float py = Mathf.Lerp(y_from, y_To, y / thy);

                    var el = _floatheightData[(int)((px)), (int)(py)];

                    tdataHeightmap[y, x] = (el - MinElevation) / elevationRange;
                }
                lastX = x;
                if (new TimeSpan(DateTime.Now.Ticks - startTime).TotalSeconds > 1)
                {
                    return;
                }
            }

            lastX = 0;
            tdata.SetHeights(0, 0, tdataHeightmap);

            tdata            = null;
            generateComplete = true;
        }
Exemple #11
0
        public static void StitchTerrain(List <TerrainObject> newterrains, float m_Smoothlevel, int m_StitcheLength)
        {
            m_stitchelenght = m_StitcheLength;
            Smoothlevel     = m_Smoothlevel;

            m_stitchelenght = StitcheLength;

            errorLength = false;
            if (_terrainDict == null)
            {
                _terrainDict = new Dictionary <int[], TerrainObject>(new IntArrayComparer());
            }
            else
            {
                _terrainDict.Clear();
            }

            _terrains = newterrains.ToArray();

            foreach (var item in newterrains)
            {
                if (item.terrainData.heightmapWidth < StitcheLength)
                {
                    errorLength = true;
                    return;
                }
            }

            if (_terrains.Length > 0)
            {
                firstPosition = new Vector2(_terrains[0].transform.position.x, _terrains[0].transform.position.z);

                int sizeX = (int)_terrains[0].terrainData.size.x;
                int sizeZ = (int)_terrains[0].terrainData.size.z;

                foreach (var m_terrain in _terrains)
                {
                    int[] posTer = new int[] {
                        (int)(Mathf.RoundToInt((m_terrain.terrain.transform.position.x - firstPosition.x) / sizeX)),
                        (int)(Mathf.RoundToInt((m_terrain.transform.position.z - firstPosition.y) / sizeZ))
                    };
                    _terrainDict.Add(posTer, m_terrain);
                }
                //Checks neighbours and stitches them

                for (int i = 0; i < _terrainDict.Count; i++)
                {
                    var   item   = _terrainDict.ElementAt(i);
                    int[] posTer = item.Key;

                    TerrainObject top    = null;
                    TerrainObject left   = null;
                    TerrainObject right  = null;
                    TerrainObject bottom = null;

                    Terrain t_top    = null;
                    Terrain t_left   = null;
                    Terrain t_right  = null;
                    Terrain t_bottom = null;

                    _terrainDict.TryGetValue(new int[] { posTer[0], posTer[1] + 1 }, out top);
                    _terrainDict.TryGetValue(new int[] { posTer[0] - 1, posTer[1] }, out left);
                    _terrainDict.TryGetValue(new int[] { posTer[0] + 1, posTer[1] }, out right);
                    _terrainDict.TryGetValue(new int[] { posTer[0], posTer[1] - 1 }, out bottom);


                    if (top)
                    {
                        t_top = top.terrain;
                    }
                    if (left)
                    {
                        t_left = left.terrain;
                    }
                    if (right)
                    {
                        t_right = right.terrain;
                    }
                    if (bottom)
                    {
                        t_bottom = bottom.terrain;
                    }


                    item.Value.terrain.SetNeighbors(t_left, t_top, t_right, t_bottom);

                    item.Value.terrain.Flush();

                    if (stitcheMethod == StitchMethod.AveragePower || StitcheLength == 0)
                    {
                        if (right != null)
                        {
                            StitchTerrains(item.Value.terrain, right.terrain, TerrainSide.Right);
                        }

                        if (top != null)
                        {
                            StitchTerrains(item.Value.terrain, top.terrain, TerrainSide.Top);
                        }
                    }
                }
                //Repairs corners
                for (int i = 0; i < _terrainDict.Count; i++)
                {
                    var           item   = _terrainDict.ElementAt(i);
                    int[]         posTer = item.Key;
                    TerrainObject top    = null;
                    TerrainObject left   = null;
                    TerrainObject right  = null;
                    TerrainObject bottom = null;
                    _terrainDict.TryGetValue(new int[] {
                        posTer [0],
                        posTer [1] + 1
                    }, out top);
                    _terrainDict.TryGetValue(new int[] {
                        posTer [0] - 1,
                        posTer [1]
                    }, out left);
                    _terrainDict.TryGetValue(new int[] {
                        posTer [0] + 1,
                        posTer [1]
                    }, out right);
                    _terrainDict.TryGetValue(new int[] {
                        posTer [0],
                        posTer [1] - 1
                    }, out bottom);


                    StitcheLength = 0;

                    if (right != null)
                    {
                        StitchTerrains(item.Value.terrain, right.terrain, TerrainSide.Right);
                    }

                    if (top != null)
                    {
                        StitchTerrains(item.Value.terrain, top.terrain, TerrainSide.Top);
                    }

                    StitcheLength = m_stitchelenght;

                    if (right != null && bottom != null)
                    {
                        TerrainObject rightBottom = null;
                        _terrainDict.TryGetValue(new int[] {
                            posTer [0] + 1,
                            posTer [1] - 1
                        }, out rightBottom);
                        if (rightBottom != null)
                        {
                            StitchTerrainsRepair(item.Value.terrain, right.terrain, bottom.terrain, rightBottom.terrain);
                        }
                    }
                }
            }
        }