public SetDetailResolution ( int detailResolution, int resolutionPerPatch ) : void | ||
detailResolution | int | Specifies the number of pixels in the detail resolution map. A larger detailResolution, leads to more accurate detail object painting. |
resolutionPerPatch | int | Specifies the size in pixels of each individually rendered detail patch. A larger number reduces draw calls, but might increase triangle count since detail patches are culled on a per batch basis. A recommended value is 16. If you use a very large detail object distance and your grass is very sparse, it makes sense to increase the value. |
리턴 | void |
void CopyTerrainDataFromTo(TerrainData tDataFrom, ref TerrainData tDataTo) { tDataTo.SetDetailResolution(tDataFrom.detailResolution, 8); tDataTo.heightmapResolution = tDataFrom.heightmapResolution; tDataTo.alphamapResolution = tDataFrom.alphamapResolution; tDataTo.baseMapResolution = tDataFrom.baseMapResolution; tDataTo.size = tDataFrom.size; tDataTo.splatPrototypes = tDataFrom.splatPrototypes; }
private TerrainData CreateTerrain() { TerrainData terrainData = new TerrainData (); terrainData.size = terrainPrefab.terrainData.size; terrainData.heightmapResolution = terrainPrefab.terrainData.heightmapHeight; terrainData.baseMapResolution = terrainPrefab.terrainData.baseMapResolution; terrainData.SetDetailResolution (terrainPrefab.terrainData.detailResolution, 1); return terrainData; }
private static void ResizeDetailResolution(TerrainData terrainData, int resolution, int resolutionPerPatch) { if (resolution == terrainData.detailResolution) { List<int[,]> list = new List<int[,]>(); for (int i = 0; i < terrainData.detailPrototypes.Length; i++) { list.Add(terrainData.GetDetailLayer(0, 0, terrainData.detailWidth, terrainData.detailHeight, i)); } terrainData.SetDetailResolution(resolution, resolutionPerPatch); for (int j = 0; j < list.Count; j++) { terrainData.SetDetailLayer(0, 0, j, list[j]); } } else { terrainData.SetDetailResolution(resolution, resolutionPerPatch); } }
private static void CreateTerrain(MenuCommand menuCommand) { TerrainData terrainData = new TerrainData(); terrainData.heightmapResolution = 1025; terrainData.size = new Vector3(1000f, 600f, 1000f); terrainData.heightmapResolution = 512; terrainData.baseMapResolution = 1024; terrainData.SetDetailResolution(1024, terrainData.detailResolutionPerPatch); AssetDatabase.CreateAsset(terrainData, AssetDatabase.GenerateUniqueAssetPath("Assets/New Terrain.asset")); GameObject gameObject = Terrain.CreateTerrainGameObject(terrainData); GameObjectUtility.SetParentAndAlign(gameObject, menuCommand.context as GameObject); Selection.activeObject = gameObject; Undo.RegisterCreatedObjectUndo(gameObject, "Create terrain"); }
private static void CreateTerrain(MenuCommand menuCommand) { TerrainData asset = new TerrainData { heightmapResolution = 0x401, size = new Vector3(1000f, 600f, 1000f), heightmapResolution = 0x200, baseMapResolution = 0x400 }; asset.SetDetailResolution(0x400, asset.detailResolutionPerPatch); AssetDatabase.CreateAsset(asset, AssetDatabase.GenerateUniqueAssetPath("Assets/New Terrain.asset")); GameObject child = Terrain.CreateTerrainGameObject(asset); GameObjectUtility.SetParentAndAlign(child, menuCommand.context as GameObject); Selection.activeObject = child; Undo.RegisterCreatedObjectUndo(child, "Create terrain"); }
/// <summary> /// Clone TerrainData object /// </summary> /// <param name="source"> /// A <see cref="TerrainData"/> /// </param> /// <param name="detailResolutionPerPatch"> /// A <see cref="System.Int32"/> /// </param> /// <returns> /// A <see cref="TerrainData"/> /// </returns> public static TerrainData Clone(TerrainData source, int detailResolutionPerPatch) { TerrainData dest = new TerrainData(); dest.alphamapResolution = source.alphamapResolution; dest.baseMapResolution = source.baseMapResolution; dest.SetDetailResolution(source.detailResolution, detailResolutionPerPatch); DetailPrototype[] dp = new DetailPrototype[source.detailPrototypes.Length]; for (int i=0; i<dp.Length; i++) dp[i] = new DetailPrototype(); dest.detailPrototypes = dp; for (int i=0; i<dp.Length; i++) { dest.detailPrototypes[i].bendFactor = source.detailPrototypes[i].bendFactor; dest.detailPrototypes[i].dryColor = source.detailPrototypes[i].dryColor; dest.detailPrototypes[i].healthyColor = source.detailPrototypes[i].healthyColor; dest.detailPrototypes[i].maxHeight = source.detailPrototypes[i].maxHeight; dest.detailPrototypes[i].maxWidth = source.detailPrototypes[i].maxWidth; dest.detailPrototypes[i].minHeight = source.detailPrototypes[i].minHeight; dest.detailPrototypes[i].minWidth = source.detailPrototypes[i].minWidth; dest.detailPrototypes[i].noiseSpread = source.detailPrototypes[i].noiseSpread; dest.detailPrototypes[i].prototype = source.detailPrototypes[i].prototype; dest.detailPrototypes[i].prototypeTexture = source.detailPrototypes[i].prototypeTexture; dest.detailPrototypes[i].renderMode = source.detailPrototypes[i].renderMode; dest.detailPrototypes[i].usePrototypeMesh = source.detailPrototypes[i].usePrototypeMesh; dest.SetDetailLayer(0,0,i,source.GetDetailLayer(0,0,source.detailWidth,source.detailHeight,i)); } dest.RefreshPrototypes(); dest.heightmapResolution = source.heightmapResolution; dest.SetHeights(0,0,source.GetHeights(0,0,source.heightmapWidth,source.heightmapHeight)); dest.hideFlags = source.hideFlags; dest.name = source.name+" (Clone)"; dest.size = source.size; dest.splatPrototypes = source.splatPrototypes; dest.treeInstances = source.treeInstances; dest.treePrototypes = source.treePrototypes; dest.wavingGrassAmount = source.wavingGrassAmount; dest.wavingGrassSpeed = source.wavingGrassSpeed; dest.wavingGrassStrength = source.wavingGrassStrength; dest.wavingGrassTint = source.wavingGrassTint; return dest; }
void finalizeHeightmap(RenderedHeightmap rh) { TerrainData tData = new TerrainData(); tData.heightmapResolution = chunkResolution; tData.alphamapResolution = chunkResolution; tData.SetDetailResolution(chunkResolution*2, 1); tData.size = new Vector3(chunkWidth, terrainHeight, chunkWidth); tData.splatPrototypes = splats; tData.detailPrototypes = grassProto; tData.treePrototypes = treeProto; tData.RefreshPrototypes(); // tree placement tData.treeInstances = rh.treeInstances.ToArray(); /* Create and position the terrain */ GameObject terrain = Terrain.CreateTerrainGameObject(tData); terrain.transform.position = new Vector3 ( chunkWidth * rh.coord.x, 0.0f, chunkWidth * rh.coord.z); /* Set the heightmap data from the background thread. */ tData.SetHeights(0, 0, rh.heightmap); stitchTerrain(tData, rh.coord); chunks[rh.coord] = tData; // texturing tData.SetAlphamaps(0, 0, rh.splatmap); // grass placement /*if (texturesToAffect.Length != 0) { var detailedLayer = grassPlacement (tData.detailResolution, tData.GetAlphamaps (0, 0, tData.alphamapWidth, tData.alphamapHeight)); tData.SetDetailLayer (0, 0, grassType, detailedLayer); }*/ }
// these are copied from UnityEditor.dll private void CreateTerrain(string name, int size) { TerrainData theAsset = new TerrainData(); // theAsset.heightmapResolution = 0x201; theAsset.heightmapResolution = size + 1; theAsset.size = new Vector3(2000f, 1000f, 2000f); // AssetUtility.CreateAsset(theAsset, name); AssetDatabase.CreateAsset(theAsset, name + ".asset"); // theAsset.heightmapResolution = 0x200; theAsset.heightmapResolution = size; theAsset.baseMapResolution = 0x400; // theAsset.SetDetailResolution(0x400, theAsset.detailResolutionPerPatch); theAsset.SetDetailResolution(0x400, 16); // recommended value from documentation // AssetUtility.SaveAsset(theAsset); Selection.activeObject = Terrain.CreateTerrainGameObject(theAsset); AssetDatabase.SaveAssets(); }
void makeTerrain(int x, int z) { EditorUtility.DisplayProgressBar("Expand Terrain", "Creating GameObject...", 0.5f); TerrainData terrainData = new TerrainData(); TerrainData selTerrainData = Selection.activeGameObject.GetComponent<Terrain>().terrainData; terrainData.heightmapResolution = selTerrainData.heightmapResolution; terrainData.alphamapResolution = selTerrainData.alphamapResolution; terrainData.baseMapResolution = selTerrainData.baseMapResolution; terrainData.SetDetailResolution(selTerrainData.detailResolution, 8); terrainData.name = "Terrain" + x + "_" + z; Vector3 pos; pos.x = selTerrainData.size.x * x; pos.y = 0.0f; pos.z = selTerrainData.size.z * z; terrainData.size = selTerrainData.size; terrainData.RefreshPrototypes(); GameObject terrObj = Terrain.CreateTerrainGameObject(terrainData); terrObj.transform.position = pos; terrObj.name = "t" + x + "." + z; terrObj.GetComponent<Terrain>().Flush(); AssetDatabase.CreateAsset(terrainData, "Assets/Terrain" + x + "_" + z + ".asset"); if (teExpandOpts[0] == true) { EditorUtility.DisplayProgressBar("Expand Terrain", "Generating Heightmap...", 0.5f); TENoiseLab.genIt(terrObj); } if (teExpandOpts[1] == true) { EditorUtility.DisplayProgressBar("Expand Terrain", "Generating Textures...", 0.5f); terrainData.splatPrototypes = selTerrainData.splatPrototypes; TETextures.genIt(terrObj); } if (teExpandOpts[2] == true) { EditorUtility.DisplayProgressBar("Expand Terrain", "Generating Detail...", 0.5f); terrainData.detailPrototypes = selTerrainData.detailPrototypes; TEDetail.genIt(terrObj); } if (teExpandOpts[3] == true) { EditorUtility.DisplayProgressBar("Expand Terrain", "Generating Foliage...", 0.5f); terrainData.treePrototypes = selTerrainData.treePrototypes; TETrees.genIt(terrObj); } EditorUtility.ClearProgressBar(); TerrainEdge.getNeighbors(Selection.activeGameObject); }
public static void reRes(GameObject go,int detailRes, int heightRes, int alphaRes) { TerrainData tdat = go.GetComponent<Terrain>().terrainData; TerrainData terrainData = new TerrainData(); string goName = go.name+"_new"; string terName = tdat.name; terrainData.heightmapResolution = heightRes; terrainData.alphamapResolution = alphaRes; terrainData.SetDetailResolution(detailRes,8); terrainData.baseMapResolution = tdat.baseMapResolution; terrainData.detailPrototypes = tdat.detailPrototypes; terrainData.splatPrototypes = tdat.splatPrototypes; terrainData.treePrototypes = tdat.treePrototypes; terrainData.treeInstances = tdat.treeInstances; terrainData.size = tdat.size; terrainData.RefreshPrototypes(); GameObject terrObj = Terrain.CreateTerrainGameObject(terrainData); terrObj.transform.position=new Vector3(0f,0f,0f); terrObj.name = goName; terrObj.GetComponent<Terrain>().Flush(); float mult = 0.0f; int destres = 0; destres = detailRes; int[,] detaildatasource = new int[tdat.detailResolution,tdat.detailResolution]; int[,] detaildatadest = new int[destres,destres]; for(int layer=0; layer<tdat.detailPrototypes.Length; layer++){ detaildatasource = tdat.GetDetailLayer(0,0,tdat.detailResolution,tdat.detailResolution,layer); mult=(float)tdat.detailResolution/(float)destres; for(int y=0;y<destres;y++){ for(int x=0;x<destres;x++){ int xold = (int)(mult * (float)x); int yold = (int)(mult * (float)y); detaildatadest[x,y]=detaildatasource[xold,yold]; } } terrainData.SetDetailLayer(0,0,layer,detaildatadest); } destres = heightRes; float[,] heightdatasource = new float[tdat.heightmapResolution,tdat.heightmapResolution]; float[,] heightdatadest = new float[destres,destres]; heightdatasource = tdat.GetHeights(0,0,tdat.heightmapResolution,tdat.heightmapResolution); mult=((float)tdat.heightmapResolution-1.0f)/((float)destres-1.0f); for(int y=0;y<destres;y++){ for(int x=0;x<destres;x++){ int xold = (int)(mult * (float)x); int yold = (int)(mult * (float)y); heightdatadest[x,y]=heightdatasource[xold,yold]; } } destres = alphaRes; float[,,] alphadata = tdat.GetAlphamaps(0,0,tdat.alphamapResolution,tdat.alphamapResolution); float[,,] alphadatadest = new float[destres,destres,tdat.splatPrototypes.Length]; mult=(float)tdat.alphamapResolution/(float)destres; for(int i=0;i<tdat.splatPrototypes.Length;i++){ for(int y=0;y<destres;y++){ for(int x=0;x<destres;x++){ int xold = (int)(mult * (float)x); int yold = (int)(mult * (float)y); alphadatadest[x,y,i] = alphadata[xold,yold,i]; } } } terrObj.GetComponent<Terrain>().terrainData.SetHeights(0,0,heightdatadest); AssetDatabase.CreateAsset(terrainData, "Assets/"+terName+"_new.asset"); AssetDatabase.SaveAssets(); TerrainData terrainData2Splat = (TerrainData)AssetDatabase.LoadAssetAtPath("Assets/"+terName+"_new.asset", typeof(TerrainData)); terrainData2Splat.splatPrototypes = tdat.splatPrototypes; terrainData2Splat.RefreshPrototypes(); terrainData2Splat.SetAlphamaps (0, 0, alphadatadest); AssetDatabase.SaveAssets(); go.active = false; }
/// <summary> /// Promote data to live terrain. /// This must be called after other processing complete. /// </summary> public void PromoteTerrainData() { // Basemap not used and is just pushed far away const float basemapDistance = 10000f; // Ensure TerrainData is created Terrain terrain = GetComponent<Terrain>(); if (terrain.terrainData == null) { // Calculate width and length of terrain in world units float terrainSize = (MapsFile.WorldMapTerrainDim * MeshReader.GlobalScale); // Setup terrain data // Must set terrainData.heightmapResolution before size (thanks Nystul!) TerrainData terrainData = new TerrainData(); terrainData.name = "TerrainData"; terrainData.heightmapResolution = heightmapResolution; terrainData.size = new Vector3(terrainSize, TerrainHelper.maxTerrainHeight, terrainSize); terrainData.SetDetailResolution(detailResolution, resolutionPerPatch); terrainData.alphamapResolution = detailResolution; terrainData.baseMapResolution = detailResolution; // Apply terrain data terrain.terrainData = terrainData; terrain.GetComponent<TerrainCollider>().terrainData = terrainData; terrain.basemapDistance = basemapDistance; } // Promote tileMap tileMapTexture.SetPixels32(TileMap); tileMapTexture.Apply(false); // Promote material terrain.materialTemplate = terrainMaterial; terrain.materialType = Terrain.MaterialType.Custom; // Promote heights Vector3 size = terrain.terrainData.size; terrain.terrainData.size = new Vector3(size.x, TerrainHelper.maxTerrainHeight * TerrainScale, size.z); terrain.terrainData.SetHeights(0, 0, heights); // Raise event RaiseOnPromoteTerrainDataEvent(terrain.terrainData); }
private void ResizeDetailResolution(TerrainData terrainData, int resolution, int resolutionPerPatch) { if (resolution == terrainData.detailResolution) { List<int[,]> numArrayList = new List<int[,]>(); for (int layer = 0; layer < terrainData.detailPrototypes.Length; ++layer) numArrayList.Add(terrainData.GetDetailLayer(0, 0, terrainData.detailWidth, terrainData.detailHeight, layer)); terrainData.SetDetailResolution(resolution, resolutionPerPatch); for (int layer = 0; layer < numArrayList.Count; ++layer) terrainData.SetDetailLayer(0, 0, layer, numArrayList[layer]); } else terrainData.SetDetailResolution(resolution, resolutionPerPatch); }
private void createTerrain(){ TerrainData terrainData = new TerrainData(); terrainData.alphamapResolution = alphaMapSize; terrainData.heightmapResolution = heightMapSize; terrainData.SetDetailResolution (detailMapSize, m_detailResolutionPerPatch); terrainData.size = new Vector3((float)terrainSizeX, (float)terrainHeight, (float)terrainSizeY); terrainData.splatPrototypes = texturePrototypes.ToArray(); terrainData.treePrototypes = treePrototypes.ToArray(); terrainData.detailPrototypes = detailPrototypes.ToArray(); //p_terrain.transform.position = new Vector3(-terrainSizeX*0.5f, 0,-terrainSizeY*0.5f); p_terrain = Terrain.CreateTerrainGameObject(terrainData).GetComponent<Terrain>(); p_terrain.terrainData.wavingGrassStrength = m_wavingGrassStrength; p_terrain.terrainData.wavingGrassAmount = m_wavingGrassAmount; p_terrain.terrainData.wavingGrassSpeed = m_wavingGrassSpeed; p_terrain.terrainData.wavingGrassTint = m_wavingGrassTint; p_terrain.detailObjectDensity = m_detailObjectDensity; p_terrain.detailObjectDistance = m_detailObjectDistance; p_terrain.treeDistance = m_treeDistance; p_terrain.treeBillboardDistance = m_treeBillboardDistance; p_terrain.treeCrossFadeLength = m_treeCrossFadeLength; p_terrain.treeMaximumFullLODCount = m_treeMaximumFullLODCount; p_terrain.castShadows = false; }
/// <summary> /// Create terrain for the given tile /// </summary> private Terrain CreateTerrainTile(int x, int z) { float height = _terrainSettings.TerrainHeight; var centerTile = x == (_tilesX / 2) && z == (_tilesZ / 2); //Create terrain data and set prototypes var data = new TerrainData { heightmapResolution = _terrainSettings.HeightmapSize, alphamapResolution = _terrainSettings.AlphamapSize, size = new Vector3(_terrainSize, height, _terrainSize), splatPrototypes = _splatPrototypes, treePrototypes = _treePrototypes, detailPrototypes = _detailPrototypes }; //Generate heightmap data.SetHeights(0, 0, GenerateHeightMap(x, z)); //create terrain gameobject and position it correctly var xPos = _terrainSize * x + _terrainOffset.x; var zPos = _terrainSize * z + _terrainOffset.y; var terrain = Terrain.CreateTerrainGameObject(data).GetComponent<Terrain>(); terrain.transform.position = new Vector3(xPos, 0, zPos); terrain.gameObject.SetParent(_terrainGameObject); terrain.name = string.Format("tile{0}x{1}", x, z); terrain.castShadows = false; terrain.detailObjectDensity = _terrainSettings.GrassDensity; terrain.detailObjectDistance = 200.0f; terrain.treeDistance = 1000.0f; terrain.treeBillboardDistance = 400.0f; terrain.treeCrossFadeLength = 20.0f; terrain.treeMaximumFullLODCount = 400; //Generate trees if (!centerTile) { //Possibly generate some lakes var rng = Random.value; if (_terrainSettings.GenerateLake && rng < 0.75f) { var it = Random.Range(1, 4); for (int i = 0; i < it; i++) { //add a lake o the terrain with a random size AddLake(terrain, x, z, Random.Range(25, 60)); } } var trees = GenerateTrees(data, x, z); if (trees != null) { foreach (var tree in trees) { terrain.AddTreeInstance(tree); } } } //Generate alphamap if valid var alphamap = GenerateAlphaMap(data); if (alphamap != null) { data.SetAlphamaps(0, 0, alphamap); } //Generate Detailsmap if valid for every layer var detailLayers = GenerateDetailLayers(data, x, z); if (detailLayers != null) { //set some detail settings data.SetDetailResolution(_terrainSettings.DetailMapSize, _terrainSettings.DetailResolution); data.wavingGrassStrength = 0.1f; data.wavingGrassAmount = 0.1f; data.wavingGrassSpeed = 0.2f; data.wavingGrassTint = Color.white; for (int layer = 0; layer < detailLayers.Count; ++layer) { data.SetDetailLayer(0, 0, layer, detailLayers[layer]); } } //make sure the changes are updated terrain.Flush(); return terrain; }
// Add Grass private void AddGrass(DaggerfallTerrain daggerTerrain, TerrainData terrainData) { // Used to check performance // Stopwatch stopwatch = new Stopwatch(); // stopwatch.Start(); details = new int[256, 256]; //Get the current season currentSeason = DaggerfallUnity.Instance.WorldTime.Now.SeasonValue; //Proceed if it's NOT winter, and if the worldClimate contains grass, which is everything above 225, with the exception of 229 if (currentSeason != DaggerfallDateTime.Seasons.Winter && (daggerTerrain.MapData.worldClimate > 225 && daggerTerrain.MapData.worldClimate != 229)) { //Switch the grass texture based on the climate if (daggerTerrain.MapData.worldClimate == 226 || daggerTerrain.MapData.worldClimate == 227 || daggerTerrain.MapData.worldClimate == 228 || daggerTerrain.MapData.worldClimate == 230) detailPrototype[0].prototypeTexture = brownGrass; else detailPrototype[0].prototypeTexture = greenGrass; tilemap = daggerTerrain.TileMap; terrainData.detailPrototypes = detailPrototype; terrainData.wavingGrassTint = Color.gray; terrainData.SetDetailResolution(256, 8); int colorValue; //Check all the tiles, Daggerfall uses the red color value to draw tiles for (int i = 0; i < 128; i++) { for (int j = 0; j < 128; j++) { colorValue = tilemap[(i * 128) + j].r; //For easier checking switch (colorValue) { //Four corner tiles case 8: case 9: case 10: case 11: details[i * 2, j * 2] = Random.Range(thickLower, thickHigher); details[i * 2, (j * 2) + 1] = Random.Range(thickLower, thickHigher); details[(i * 2) + 1, j * 2] = Random.Range(thickLower, thickHigher); details[(i * 2) + 1, (j * 2) + 1] = Random.Range(thickLower, thickHigher); break; //Upper left corner case 40: case 224: case 164: case 176: case 181: details[(i * 2) + 1, j * 2] = Random.Range(thinLower, thinHigher); break; //Lower left corner case 41: case 221: case 165: case 177: case 182: details[i * 2, j * 2] = Random.Range(thinLower, thinHigher); break; //Lower right corner case 42: case 222: case 166: case 178: case 183: details[i * 2, (j * 2) + 1] = Random.Range(thinLower, thinHigher); break; //Upper right corner case 43: case 223: case 167: case 179: case 180: details[(i * 2) + 1, (j * 2) + 1] = Random.Range(thinLower, thinHigher); break; //Left side case 44: case 66: case 84: case 160: case 168: details[(i * 2) + 1, j * 2] = Random.Range(thinLower, thinHigher); details[i * 2, j * 2] = Random.Range(thinLower, thinHigher); break; //lower side case 45: case 67: case 85: case 161: case 169: details[i * 2, (j * 2) + 1] = Random.Range(thinLower, thinHigher); details[i * 2, j * 2] = Random.Range(thinLower, thinHigher); break; //right side case 46: case 64: case 86: case 162: case 170: details[(i * 2) + 1, (j * 2) + 1] = Random.Range(thinLower, thinHigher); details[i * 2, (j * 2) + 1] = Random.Range(thinLower, thinHigher); break; //upper side case 47: case 65: case 87: case 163: case 171: details[(i * 2) + 1, (j * 2) + 1] = Random.Range(thinLower, thinHigher); details[(i * 2) + 1, j * 2] = Random.Range(thinLower, thinHigher); break; //All expect lower right case 48: case 62: case 88: case 156: details[i * 2, j * 2] = Random.Range(thinLower, thinHigher); details[(i * 2) + 1, j * 2] = Random.Range(thinLower, thinHigher); details[(i * 2) + 1, (j * 2) + 1] = Random.Range(thinLower, thinHigher); break; //All expect upper right case 49: case 63: case 89: case 157: details[i * 2, j * 2] = Random.Range(thinLower, thinHigher); details[i * 2, (j * 2) + 1] = Random.Range(thinLower, thinHigher); details[(i * 2) + 1, j * 2] = Random.Range(thinLower, thinHigher); break; //All expect upper left case 50: case 60: case 90: case 158: details[i * 2, j * 2] = Random.Range(thinLower, thinHigher); details[i * 2, (j * 2) + 1] = Random.Range(thinLower, thinHigher); details[(i * 2) + 1, (j * 2) + 1] = Random.Range(thinLower, thinHigher); break; //All expect lower left case 51: case 61: case 91: case 159: details[i * 2, (j * 2) + 1] = Random.Range(thinLower, thinHigher); details[(i * 2) + 1, j * 2] = Random.Range(thinLower, thinHigher); details[(i * 2) + 1, (j * 2) + 1] = Random.Range(thinLower, thinHigher); break; //Left to right case 204: case 206: case 214: details[i * 2, j * 2] = Random.Range(thinLower, thinHigher); details[(i * 2) + 1, (j * 2) + 1] = Random.Range(thinLower, thinHigher); break; //Right to left case 205: case 207: case 213: details[(i * 2) + 1, j * 2] = Random.Range(thinLower, thinHigher); details[i * 2, (j * 2) + 1] = Random.Range(thinLower, thinHigher); break; } } } } terrainData.SetDetailLayer(0, 0, 0, details); // stopwatch.Stop(); // // Write result // UnityEngine.Debug.Log("Time elapsed: " + // stopwatch.Elapsed); }
void CreateTerrain() { //fire up the progress bar ShowProgressBar (1, 100); TerrainData terrain = new TerrainData (); terrain.heightmapResolution = resolution; terrain.SetDetailResolution(resolution, 8); GameObject terrainObject = Terrain.CreateTerrainGameObject (terrain); Undo.RegisterCreatedObjectUndo (terrainObject, "Object to Terrain"); MeshCollider collider = Selection.activeGameObject.GetComponent<MeshCollider> (); CleanUp cleanUp = null; //Add a collider to our source object if it does not exist. //Otherwise raycasting doesn't work. if (!collider) { collider = Selection.activeGameObject.AddComponent<MeshCollider> (); cleanUp = () => DestroyImmediate (collider); } Bounds bounds = collider.bounds; float sizeFactor = collider.bounds.size.y / (collider.bounds.size.y + addTerrain.y); terrain.size = collider.bounds.size + addTerrain; bounds.size = new Vector3 (terrain.size.x, collider.bounds.size.y, terrain.size.z); // Do raycasting samples over the object to see what terrain heights should be float[,] heights = new float[terrain.heightmapWidth, terrain.heightmapHeight]; Ray ray = new Ray (new Vector3 (bounds.min.x, bounds.max.y + bounds.size.y, bounds.min.z), -Vector3.up); RaycastHit hit = new RaycastHit (); float meshHeightInverse = 1 / bounds.size.y; Vector3 rayOrigin = ray.origin; int maxHeight = heights.GetLength (0); int maxLength = heights.GetLength (1); Vector2 stepXZ = new Vector2 (bounds.size.x / maxLength, bounds.size.z / maxHeight); for (int zCount = 0; zCount < maxHeight; zCount++) { ShowProgressBar (zCount, maxHeight); for (int xCount = 0; xCount < maxLength; xCount++) { float height = 0.0f; if (collider.Raycast (ray, out hit, bounds.size.y * 3)) { height = (hit.point.y - bounds.min.y) * meshHeightInverse; height += shiftHeight; //bottom up if (bottomTopRadioSelected == 0) { height *= sizeFactor; } //clamp if (height < 0) { height = 0; } } heights [zCount, xCount] = height; rayOrigin.x += stepXZ [0]; ray.origin = rayOrigin; } rayOrigin.z += stepXZ [1]; rayOrigin.x = bounds.min.x; ray.origin = rayOrigin; } terrain.SetHeights (0, 0, heights); terrainObject.transform.position = Selection.activeGameObject.transform.position; string name = Selection.activeGameObject.name; AssetDatabase.CreateAsset (terrain, "Assets/" + name + " - Terrain.asset"); EditorUtility.ClearProgressBar (); if (cleanUp != null) { cleanUp (); } }
private void CreateLand() { #region Preparations var mapData = Data.Battle["gamebody"]["map_info"]["types"]; var worldSize = realMapSize * Settings.DimensionScaleFactor; var resolution = Mathf.RoundToInt(Mathf.Sqrt(realMapSize.x * realMapSize.y) * Settings.Terrain.Smoothness); var terrainData = new TerrainData { heightmapResolution = Mathf.ClosestPowerOfTwo(resolution) + 1, size = new Vector3(worldSize.y, Settings.Map.HeightOfLevel[2], worldSize.x), alphamapResolution = resolution, baseMapResolution = resolution }; #endregion #region Set Heights float landArea = 0; var heights = new float[terrainData.heightmapHeight, terrainData.heightmapWidth]; var mapRect = new Rect(0, 0, Data.MapSize.x, Data.MapSize.y); for (int bumpNum = Mathf.RoundToInt(realMapSize.x * realMapSize.y / 10), i = 0; i < bumpNum; ++i) { var sigmaX = Random.Range(0.8f, 2) * terrainData.heightmapHeight / realMapSize.x; var sigmaY = Random.Range(0.8f, 2) * terrainData.heightmapWidth / realMapSize.y; var muX = Random.Range(0, terrainData.heightmapHeight); var muY = Random.Range(0, terrainData.heightmapWidth); var h = Random.Range(-0.6f, 0.4f); for (var x = Mathf.Max(-muX, -Mathf.RoundToInt(sigmaX * 3)); x < Mathf.Min(terrainData.heightmapHeight - muX, Mathf.RoundToInt(sigmaX * 3)); ++x) for (var y = Mathf.Max(-muY, -Mathf.RoundToInt(sigmaY * 3)); y < Mathf.Min(terrainData.heightmapWidth - muY, Mathf.RoundToInt(sigmaY * 3)); ++y) heights[muX + x, muY + y] += h * Mathf.Exp(-Mathf.Pow(x / sigmaX, 2) - Mathf.Pow(y / sigmaY, 2)); } var threshold = Settings.Map.HeightOfLevel[0] / Settings.Map.HeightOfLevel[2] * 0.8f; for (var x = 0; x < terrainData.heightmapHeight; ++x) for (var y = 0; y < terrainData.heightmapWidth; ++y) { if ((heights[x, y] += threshold / 2) > threshold) heights[x, y] = threshold; var i = (float)x / (terrainData.heightmapHeight - 1) * realMapSize.x - Settings.Map.MapSizeOffset.top; var j = (1 - (float)y / (terrainData.heightmapWidth - 1)) * realMapSize.y - Settings.Map.MapSizeOffset.left; int i0 = Mathf.FloorToInt(i), j0 = Mathf.FloorToInt(j); float ul = 0, ur = 0, br = 0, bl = 0, di = i - i0, dj = j - j0; if (mapRect.Contains(new Vector2(i0, j0))) ul = mapData[i0][j0].n; if (mapRect.Contains(new Vector2(i0, j0 + 1))) ur = mapData[i0][j0 + 1].n; if (mapRect.Contains(new Vector2(i0 + 1, j0 + 1))) br = mapData[i0 + 1][j0 + 1].n; if (mapRect.Contains(new Vector2(i0 + 1, j0))) bl = mapData[i0 + 1][j0].n; var height = (1 - di) * (1 - dj) * ul + (1 - di) * dj * ur + di * (1 - dj) * bl + di * dj * br; if (Math.Abs(height) < Mathf.Epsilon) continue; heights[x, y] = Mathf.Max(heights[x, y], height = Mathf.Sign(height - 0.5f) * Mathf.Pow(Mathf.Abs(height * 2 - 1), 0.25f) / 2 + 0.5f); landArea += height; } terrainData.SetHeights(0, 0, heights); landArea *= realMapSize.x * realMapSize.y / (terrainData.heightmapHeight * terrainData.heightmapWidth); #endregion #region Paint Texture var splatPrototypes = new SplatPrototype[splatTextures.Length]; for (var i = 0; i < splatPrototypes.Length; i++) { var splatPrototype = new SplatPrototype { texture = splatTextures[i], tileSize = Vector2.one * Settings.DimensionScaleFactor * 4 }; splatPrototypes[i] = splatPrototype; } terrainData.splatPrototypes = splatPrototypes; var alphamapResolution = terrainData.alphamapResolution; var alphamaps = new float[alphamapResolution, alphamapResolution, splatPrototypes.Length]; for (var i = 0; i < alphamapResolution; i++) for (var j = 0; j < alphamapResolution; j++) { var height = heights[Mathf.RoundToInt((float)i / (alphamapResolution - 1) * (terrainData.heightmapHeight - 1)), Mathf.RoundToInt((float)j / (alphamapResolution - 1) * (terrainData.heightmapWidth - 1))]; alphamaps[i, j, 0] = height; alphamaps[i, j, 1] = 1 - height; } terrainData.SetAlphamaps(0, 0, alphamaps); #endregion #region Place Trees var treePrototypes = new TreePrototype[treePrefabs.Length]; for (var i = 0; i < treePrototypes.Length; i++) { var treePrototype = new TreePrototype { prefab = treePrefabs[i], bendFactor = 1 }; treePrototypes[i] = treePrototype; } terrainData.treePrototypes = treePrototypes; var treeInstances = new TreeInstance[Mathf.RoundToInt(landArea * Settings.Terrain.Tree.Density)]; var range = new Vector4(Settings.Map.MapSizeOffset.right / realMapSize.y, 1 - Settings.Map.MapSizeOffset.left / realMapSize.y, Settings.Map.MapSizeOffset.top / realMapSize.x, 1 - Settings.Map.MapSizeOffset.bottom / realMapSize.x); for (var i = 0; i < treeInstances.Length; i++) { var treeScale = Random.Range(0.08f, 0.16f) * Settings.DimensionScaleFactor; Vector3 treePosition; do treePosition = new Vector3(Random.Range(range.x, range.y), 0, Random.Range(range.z, range.w)); while ((treePosition.y = heights[Mathf.RoundToInt(treePosition.z * (terrainData.heightmapHeight - 1)), Mathf.RoundToInt(treePosition.x * (terrainData.heightmapWidth - 1))]) < Mathf.Lerp(Settings.Map.HeightOfLevel[1] / Settings.Map.HeightOfLevel[2], 1, 0.6f) || Methods.Coordinates.IsOccupied(Methods.Coordinates.InternalToExternal(Vector3.Scale(treePosition, new Vector3(worldSize.y, 0, worldSize.x))))); var treeInstance = new TreeInstance { prototypeIndex = Random.Range(0, treePrototypes.Length), position = treePosition + Vector3.up * Settings.Terrain.Tree.VerticalPositionOffset * treeScale, color = new Color(0, 0.8f, 0, 1), lightmapColor = new Color(1, 1, 1, 1), heightScale = treeScale, widthScale = treeScale }; treeInstances[i] = treeInstance; } terrainData.treeInstances = treeInstances; #endregion #region Paint Details var detailPrototypes = new DetailPrototype[detailTextures.Length]; for (var i = 0; i < detailPrototypes.Length; i++) { var detailPrototype = new DetailPrototype { prototypeTexture = detailTextures[i], minWidth = Settings.Terrain.Detail.MinDimension, minHeight = Settings.Terrain.Detail.MinDimension, maxWidth = Settings.Terrain.Detail.MaxDimension, maxHeight = Settings.Terrain.Detail.MaxDimension, renderMode = DetailRenderMode.GrassBillboard }; detailPrototypes[i] = detailPrototype; } terrainData.detailPrototypes = detailPrototypes; terrainData.SetDetailResolution(resolution, Mathf.Clamp(resolution, 8, 128)); var detailLayers = new int[detailPrototypes.Length][,]; for (var i = 0; i < detailPrototypes.Length; i++) detailLayers[i] = new int[terrainData.detailResolution, terrainData.detailResolution]; for (var i = 0; i < terrainData.detailResolution; i++) for (var j = 0; j < terrainData.detailResolution; j++) { var layer = Random.Range(0, detailPrototypes.Length); var height = heights[Mathf.RoundToInt((float)i / (terrainData.detailResolution - 1) * (terrainData.heightmapHeight - 1)), Mathf.RoundToInt((float)j / (terrainData.detailResolution - 1) * (terrainData.heightmapWidth - 1))]; if (height > Mathf.Lerp(Settings.Map.HeightOfLevel[1] / Settings.Map.HeightOfLevel[2], 1, 0.4f)) detailLayers[layer][i, j] = 1; } for (var i = 0; i < detailPrototypes.Length; i++) terrainData.SetDetailLayer(0, 0, i, detailLayers[i]); terrainData.wavingGrassAmount = Settings.Terrain.Detail.Waving.Amount; terrainData.wavingGrassSpeed = Settings.Terrain.Detail.Waving.Speed; terrainData.wavingGrassStrength = Settings.Terrain.Detail.Waving.Strength; #endregion #region Final Settings var terrain = Terrain.CreateTerrainGameObject(terrainData).GetComponent<Terrain>(); terrain.treeBillboardDistance = Settings.Terrain.Tree.BillboardDistance; terrain.detailObjectDistance = Settings.Terrain.Detail.MaxVisibleDistance; terrain.detailObjectDensity = Settings.Terrain.Detail.Density; #endregion }
void SplitIt() { if ( Selection.activeGameObject == null ) { Debug.LogWarning("No terrain was selected"); return; } parentTerrain = Selection.activeGameObject.GetComponent(typeof(Terrain)) as Terrain; if ( parentTerrain == null ) { Debug.LogWarning("Current selection is not a terrain"); return; } //Split terrain for ( int i=0; i< terrainsCount; i++) { EditorUtility.DisplayProgressBar("Split terrain","Process " + i, (float) i / terrainsCount ); TerrainData td = new TerrainData(); GameObject tgo = Terrain.CreateTerrainGameObject( td ); tgo.name = parentTerrain.name + " " + i; terrainData.Add( td ); terrainGo.Add ( tgo ); Terrain genTer = tgo.GetComponent(typeof(Terrain)) as Terrain; genTer.terrainData = td; AssetDatabase.CreateAsset(td, "Assets/" + genTer.name+ ".asset"); // Assign splatmaps genTer.terrainData.splatPrototypes = parentTerrain.terrainData.splatPrototypes; // Assign detail prototypes genTer.terrainData.detailPrototypes = parentTerrain.terrainData.detailPrototypes; // Assign tree information genTer.terrainData.treePrototypes = parentTerrain.terrainData.treePrototypes; // Copy parent terrain propeties #region parent properties genTer.basemapDistance = parentTerrain.basemapDistance; genTer.castShadows = parentTerrain.castShadows; genTer.detailObjectDensity = parentTerrain.detailObjectDensity; genTer.detailObjectDistance = parentTerrain.detailObjectDistance; genTer.heightmapMaximumLOD = parentTerrain.heightmapMaximumLOD; genTer.heightmapPixelError = parentTerrain.heightmapPixelError; genTer.treeBillboardDistance = parentTerrain.treeBillboardDistance; genTer.treeCrossFadeLength = parentTerrain.treeCrossFadeLength; genTer.treeDistance = parentTerrain.treeDistance; genTer.treeMaximumFullLODCount = parentTerrain.treeMaximumFullLODCount; #endregion //Start processing it // Translate peace to position #region translate peace to right position Vector3 parentPosition = parentTerrain.GetPosition(); int terraPeaces = (int) Mathf.Sqrt( terrainsCount ); float spaceShiftX = parentTerrain.terrainData.size.z / terraPeaces; float spaceShiftY = parentTerrain.terrainData.size.x / terraPeaces; float xWShift = (i % terraPeaces ) * spaceShiftX; float zWShift = ( i / terraPeaces ) * spaceShiftY; tgo.transform.position = new Vector3( tgo.transform.position.x + zWShift, tgo.transform.position.y, tgo.transform.position.z + xWShift ); // Shift last position tgo.transform.position = new Vector3( tgo.transform.position.x + parentPosition.x, tgo.transform.position.y + parentPosition.y, tgo.transform.position.z + parentPosition.z ); #endregion // Split height #region split height Debug.Log ( "Split height" ); //Copy heightmap td.heightmapResolution = parentTerrain.terrainData.heightmapResolution / terraPeaces; //Keep y same td.size = new Vector3( parentTerrain.terrainData.size.x / terraPeaces, parentTerrain.terrainData.size.y, parentTerrain.terrainData.size.z / terraPeaces ); float[,] parentHeight = parentTerrain.terrainData.GetHeights(0,0, parentTerrain.terrainData.heightmapResolution, parentTerrain.terrainData.heightmapResolution ); float[,] peaceHeight = new float[ parentTerrain.terrainData.heightmapResolution / terraPeaces + 1, parentTerrain.terrainData.heightmapResolution / terraPeaces + 1 ]; // Shift calc int heightShift = parentTerrain.terrainData.heightmapResolution / terraPeaces; int startX = 0; int startY = 0; int endX = 0; int endY = 0; if ( i==0 ) { startX = startY = 0; endX = endY = parentTerrain.terrainData.heightmapResolution / terraPeaces + 1; } if ( i==1 ) { startX = startY = 0; endX = parentTerrain.terrainData.heightmapResolution / terraPeaces + 1; endY = parentTerrain.terrainData.heightmapResolution / terraPeaces + 1; } if ( i==2 ) { startX = startY = 0; endX = parentTerrain.terrainData.heightmapResolution / terraPeaces + 1; endY = parentTerrain.terrainData.heightmapResolution / terraPeaces + 1; } if ( i==3 ) { startX = startY = 0; endX = parentTerrain.terrainData.heightmapResolution / terraPeaces + 1; endY = parentTerrain.terrainData.heightmapResolution / terraPeaces + 1; } // iterate for ( int x=startX;x< endX;x++) { EditorUtility.DisplayProgressBar("Split terrain","Split height", (float) x / ( endX - startX )); for ( int y=startY;y< endY;y++) { int xShift=0; int yShift=0; // if ( i==0 ) { xShift = 0; yShift = 0; } // if ( i==1 ) { xShift = heightShift; yShift = 0; } // if ( i==2 ) { xShift = 0; yShift = heightShift; } if ( i==3 ) { xShift = heightShift; yShift = heightShift; } float ph = parentHeight[ x + xShift,y + yShift]; peaceHeight[x ,y ] = ph; } } EditorUtility.ClearProgressBar(); // Set heightmap to child genTer.terrainData.SetHeights( 0,0, peaceHeight ); #endregion // Split splat map #region split splat map td.alphamapResolution = parentTerrain.terrainData.alphamapResolution / terraPeaces; float[,,] parentSplat = parentTerrain.terrainData.GetAlphamaps(0,0, parentTerrain.terrainData.alphamapResolution, parentTerrain.terrainData.alphamapResolution ); float[,,] peaceSplat = new float[ parentTerrain.terrainData.alphamapResolution / terraPeaces , parentTerrain.terrainData.alphamapResolution / terraPeaces, parentTerrain.terrainData.alphamapLayers ]; // Shift calc int splatShift = parentTerrain.terrainData.alphamapResolution / terraPeaces; if ( i==0 ) { startX = startY = 0; endX = endY = parentTerrain.terrainData.alphamapResolution / terraPeaces; } if ( i==1 ) { startX = startY = 0; endX = parentTerrain.terrainData.alphamapResolution / terraPeaces; endY = parentTerrain.terrainData.alphamapResolution / terraPeaces; } if ( i==2 ) { startX = startY = 0; endX = parentTerrain.terrainData.alphamapResolution / terraPeaces; endY = parentTerrain.terrainData.alphamapResolution / terraPeaces; } if ( i==3 ) { startX = startY = 0; endX = parentTerrain.terrainData.alphamapResolution / terraPeaces; endY = parentTerrain.terrainData.alphamapResolution / terraPeaces; } // iterate for ( int s=0;s<parentTerrain.terrainData.alphamapLayers;s++) { for ( int x=startX;x< endX;x++) { EditorUtility.DisplayProgressBar("Split terrain","Split splat", (float) x / ( endX - startX )); for ( int y=startY;y< endY;y++) { int xShift=0; int yShift=0; // if ( i==0 ) { xShift = 0; yShift = 0; } // if ( i==1 ) { xShift = splatShift; yShift = 0; } // if ( i==2 ) { xShift = 0; yShift = splatShift; } if ( i==3 ) { xShift = splatShift; yShift = splatShift; } float ph = parentSplat[x + xShift,y + yShift, s]; peaceSplat[x ,y, s] = ph; } } } EditorUtility.ClearProgressBar(); // Set heightmap to child genTer.terrainData.SetAlphamaps( 0,0, peaceSplat ); #endregion // Split detail map #region split detail map td.SetDetailResolution( parentTerrain.terrainData.detailResolution / terraPeaces, 8 ); for ( int detLay=0; detLay< parentTerrain.terrainData.detailPrototypes.Length; detLay++) { int[,] parentDetail = parentTerrain.terrainData.GetDetailLayer(0,0, parentTerrain.terrainData.detailResolution, parentTerrain.terrainData.detailResolution, detLay ); int[,] peaceDetail = new int[ parentTerrain.terrainData.detailResolution / terraPeaces, parentTerrain.terrainData.detailResolution / terraPeaces ]; // Shift calc int detailShift = parentTerrain.terrainData.detailResolution / terraPeaces; if ( i==0 ) { startX = startY = 0; endX = endY = parentTerrain.terrainData.detailResolution / terraPeaces; } if ( i==1 ) { startX = startY = 0; endX = parentTerrain.terrainData.detailResolution / terraPeaces; endY = parentTerrain.terrainData.detailResolution / terraPeaces; } if ( i==2 ) { startX = startY = 0; endX = parentTerrain.terrainData.detailResolution / terraPeaces; endY = parentTerrain.terrainData.detailResolution / terraPeaces; } if ( i==3 ) { startX = startY = 0; endX = parentTerrain.terrainData.detailResolution / terraPeaces; endY = parentTerrain.terrainData.detailResolution / terraPeaces; } // iterate for ( int x=startX;x< endX;x++) { EditorUtility.DisplayProgressBar("Split terrain","Split detail", (float) x / (endX - startX )); for ( int y=startY;y< endY;y++) { int xShift=0; int yShift=0; // if ( i==0 ) { xShift = 0; yShift = 0; } // if ( i==1 ) { xShift = detailShift; yShift = 0; } // if ( i==2 ) { xShift = 0; yShift = detailShift; } if ( i==3 ) { xShift = detailShift; yShift = detailShift; } int ph = parentDetail[x + xShift,y + yShift]; peaceDetail[x ,y] = ph; } } EditorUtility.ClearProgressBar(); // Set heightmap to child genTer.terrainData.SetDetailLayer( 0,0, detLay, peaceDetail ); } #endregion // Split tree data #region split tree data for( int t=0; t< parentTerrain.terrainData.treeInstances.Length;t++) { EditorUtility.DisplayProgressBar("Split terrain","Split trees " , (float) t / parentTerrain.terrainData.treeInstances.Length ); // Get tree instance TreeInstance ti = parentTerrain.terrainData.treeInstances[t]; // First section if ( i==0 && ti.position.x > 0f && ti.position.x < 0.5f && ti.position.z > 0f && ti.position.z < 0.5f ) { // Recalculate new tree position ti.position = new Vector3( ti.position.x * 2f, ti.position.y, ti.position.z * 2f ); // Add tree instance genTer.AddTreeInstance( ti ); } // Second section if ( i==1 && ti.position.x > 0.0f &&ti.position.x < 0.5f && ti.position.z >= 0.5f && ti.position.z <= 1.0f ) { // Recalculate new tree position ti.position = new Vector3( (ti.position.x ) * 2f, ti.position.y, ( ti.position.z - 0.5f ) * 2f ); // Add tree instance genTer.AddTreeInstance( ti ); } // Third section if ( i==2 && ti.position.x >= 0.5f && ti.position.x <= 1.0f && ti.position.z > 0.0f && ti.position.z < 0.5f ) { // Recalculate new tree position ti.position = new Vector3( (ti.position.x - 0.5f ) * 2f, ti.position.y, ( ti.position.z ) * 2f ); // Add tree instance genTer.AddTreeInstance( ti ); } // Fourth section if ( i==3 && ti.position.x >= 0.5f && ti.position.x <= 1.0f && ti.position.z >= 0.5f && ti.position.z <= 1.0f ) { // Recalculate new tree position ti.position = new Vector3( (ti.position.x - 0.5f ) * 2f, ti.position.y, ( ti.position.z - 0.5f ) * 2f ); // Add tree instance genTer.AddTreeInstance( ti ); } } #endregion AssetDatabase.SaveAssets(); } EditorUtility.ClearProgressBar(); }
private void generateWorldTerrain() { // Create Unity Terrain game object GameObject terrainGameObject = Terrain.CreateTerrainGameObject(null); terrainGameObject.name = string.Format("WorldTerrain"); terrainGameObject.gameObject.transform.localPosition = Vector3.zero; // assign terrainGameObject to layer "WorldTerrain" if available (used for rendering with secondary camera to prevent floating-point precision problems with huge clipping ranges) int layerExtendedTerrain = LayerMask.NameToLayer("WorldTerrain"); if (layerExtendedTerrain != -1) terrainGameObject.layer = layerExtendedTerrain; int worldMapResolution = Math.Max(worldMapWidth, worldMapHeight); if (worldHeights == null) { worldHeights = new float[worldMapResolution, worldMapResolution]; } for (int y = 0; y < worldMapHeight; y++) { for (int x = 0; x < worldMapWidth; x++) { // get height data for this map pixel from world map and scale it to approximately match StreamingWorld's terrain heights float sampleHeight = Convert.ToSingle(dfUnity.ContentReader.WoodsFileReader.GetHeightMapValue(x, y)); sampleHeight *= (ImprovedWorldTerrain.computeHeightMultiplier(x, y) * ImprovedTerrainSampler.baseHeightScale + ImprovedTerrainSampler.noiseMapScale); // make ocean elevation the lower limit if (sampleHeight < ImprovedTerrainSampler.scaledOceanElevation) { sampleHeight = ImprovedTerrainSampler.scaledOceanElevation; } // normalize with TerrainHelper.maxTerrainHeight worldHeights[worldMapHeight - 1 - y, x] = Mathf.Clamp01(sampleHeight / ImprovedTerrainSampler.maxTerrainHeight); } } // Basemap not used and is just pushed far away const float basemapDistance = 1000000f; // Ensure TerrainData is created Terrain terrain = terrainGameObject.GetComponent<Terrain>(); if (terrain.terrainData == null) { // Setup terrain data TerrainData terrainData = new TerrainData(); terrainData.name = "TerrainData"; // this is not really an assignment! you tell unity terrain what resolution you want for your heightmap and it will allocate resources and take the next power of 2 increased by 1 as heightmapResolution... terrainData.heightmapResolution = worldMapResolution; float heightmapResolution = terrainData.heightmapResolution; // Calculate width and length of terrain in world units float terrainSize = ((MapsFile.WorldMapTerrainDim * MeshReader.GlobalScale) * (heightmapResolution - 1.0f)); terrainData.size = new Vector3(terrainSize, ImprovedTerrainSampler.maxTerrainHeight, terrainSize); //terrainData.size = new Vector3(terrainSize, TerrainHelper.maxTerrainHeight * TerrainScale * worldMapResolution, terrainSize); terrainData.SetDetailResolution(worldMapResolution, 16); terrainData.alphamapResolution = worldMapResolution; terrainData.baseMapResolution = worldMapResolution; // Apply terrain data terrain.terrainData = terrainData; terrain.basemapDistance = basemapDistance; } terrain.heightmapPixelError = 0; // 0 ... prevent unity terrain lod approach, set to higher values to enable it //terrain.castShadows = true; // Promote heights Vector3 size = terrain.terrainData.size; terrain.terrainData.size = new Vector3(size.x, ImprovedTerrainSampler.maxTerrainHeight * streamingWorld.TerrainScale, size.z); terrain.terrainData.SetHeights(0, 0, worldHeights); // update world terrain position - do this before terrainGameObject.transform invocation, so that object2world matrix is updated with correct values Vector3 offset = new Vector3(0.0f, 0.0f, 0.0f); updatePositionWorldTerrain(ref terrainGameObject, offset); textureAtlasDesertSummer = dfUnity.MaterialReader.TextureReader.GetTerrainTilesetTexture(2).albedoMap; textureAtlasDesertSummer.filterMode = FilterMode.Point; textureAtlasWoodlandSummer = dfUnity.MaterialReader.TextureReader.GetTerrainTilesetTexture(302).albedoMap; textureAtlasWoodlandSummer.filterMode = FilterMode.Point; textureAtlasMountainSummer = dfUnity.MaterialReader.TextureReader.GetTerrainTilesetTexture(102).albedoMap; textureAtlasMountainSummer.filterMode = FilterMode.Point; textureAtlasSwampSummer = dfUnity.MaterialReader.TextureReader.GetTerrainTilesetTexture(402).albedoMap; textureAtlasSwampSummer.filterMode = FilterMode.Point; textureAtlasDesertWinter = dfUnity.MaterialReader.TextureReader.GetTerrainTilesetTexture(3).albedoMap; textureAtlasDesertWinter.filterMode = FilterMode.Point; textureAtlasWoodlandWinter = dfUnity.MaterialReader.TextureReader.GetTerrainTilesetTexture(303).albedoMap; textureAtlasWoodlandWinter.filterMode = FilterMode.Point; textureAtlasMountainWinter = dfUnity.MaterialReader.TextureReader.GetTerrainTilesetTexture(103).albedoMap; textureAtlasMountainWinter.filterMode = FilterMode.Point; textureAtlasSwampWinter = dfUnity.MaterialReader.TextureReader.GetTerrainTilesetTexture(403).albedoMap; textureAtlasSwampWinter.filterMode = FilterMode.Point; textureAtlasDesertRain = dfUnity.MaterialReader.TextureReader.GetTerrainTilesetTexture(4).albedoMap; textureAtlasDesertRain.filterMode = FilterMode.Point; textureAtlasWoodlandRain = dfUnity.MaterialReader.TextureReader.GetTerrainTilesetTexture(304).albedoMap; textureAtlasWoodlandRain.filterMode = FilterMode.Point; textureAtlasMountainRain = dfUnity.MaterialReader.TextureReader.GetTerrainTilesetTexture(104).albedoMap; textureAtlasMountainRain.filterMode = FilterMode.Point; textureAtlasSwampRain = dfUnity.MaterialReader.TextureReader.GetTerrainTilesetTexture(404).albedoMap; textureAtlasSwampRain.filterMode = FilterMode.Point; terrainMaterial = new Material(Shader.Find("Daggerfall/IncreasedTerrainTilemap")); terrainMaterial.name = string.Format("world terrain material"); // Assign textures and parameters terrainMaterial.SetTexture("_TileAtlasTexDesert", textureAtlasDesertSummer); terrainMaterial.SetTexture("_TileAtlasTexWoodland", textureAtlasWoodlandSummer); terrainMaterial.SetTexture("_TileAtlasTexMountain", textureAtlasMountainSummer); terrainMaterial.SetTexture("_TileAtlasTexSwamp", textureAtlasSwampSummer); //terrainMaterial.SetTexture("_FarTerrainTilemapTex", textureTerrainInfoTileMap); terrainMaterial.SetInt("_TextureSetSeasonCode", 0); updateMaterialSeasonalTextures(ref terrainMaterial, currentSeason); // change seasonal textures if necessary terrainMaterial.SetInt("_PlayerPosX", this.playerGPS.CurrentMapPixel.X); terrainMaterial.SetInt("_PlayerPosY", this.playerGPS.CurrentMapPixel.Y); terrainMaterial.SetInt("_TerrainDistance", streamingWorld.TerrainDistance); Vector3 vecWaterHeight = new Vector3(0.0f, (ImprovedTerrainSampler.scaledOceanElevation + 1.0f) * streamingWorld.TerrainScale, 0.0f); // water height level on y-axis (+1.0f some coastlines are incorrect otherwise) Vector3 vecWaterHeightTransformed = terrainGameObject.transform.TransformPoint(vecWaterHeight); // transform to world coordinates terrainMaterial.SetFloat("_WaterHeightTransformed", vecWaterHeightTransformed.y); terrainMaterial.SetTexture("_SkyTex", renderTextureSky); setMaterialFogParameters(ref terrainMaterial); //terrainMaterial.SetFloat("_BlendFactor", blendFactor); terrainMaterial.SetFloat("_BlendStart", blendStart); terrainMaterial.SetFloat("_BlendEnd", blendEnd); #if REFLECTIONSMOD_CODE_AVAILABLE if (isActiveReflectionsMod) { reflectionSeaTexture = GameObject.Find("ReflectionsMod").GetComponent<ReflectionsMod.UpdateReflectionTextures>().getSeaReflectionRenderTexture(); if (reflectionSeaTexture != null) { terrainMaterial.EnableKeyword("ENABLE_WATER_REFLECTIONS"); terrainMaterial.SetTexture("_SeaReflectionTex", reflectionSeaTexture); terrainMaterial.SetInt("_UseSeaReflectionTex", 1); } else { terrainMaterial.SetInt("_UseSeaReflectionTex", 0); } } #else terrainMaterial.SetInt("_UseSeaReflectionTex", 0); #endif // Promote material terrain.materialType = Terrain.MaterialType.Custom; terrain.materialTemplate = terrainMaterial; terrainGameObject.SetActive(true); worldTerrainGameObject = terrainGameObject; }
private void CreateTerrain() { var parent = (GameObject) Instantiate(new GameObject("Terrain")); parent.transform.position = new Vector3(0, 0, 0); for (int x = 1; x <= tileAmount.x; x++) { for (int y = 1; y <= tileAmount.y; y++) { var terrainData = new TerrainData(); alphabet = (Alphabet) x; string name = alphabet + "-" + y; terrainData.size = new Vector3(width/16f, height, lenght/16f); terrainData.baseMapResolution = baseTextureReolution; terrainData.heightmapResolution = heightmapResoltion; terrainData.alphamapResolution = controlTextureResolution; terrainData.SetDetailResolution(detailResolution, detailResolutionPerPatch); terrainData.name = name; GameObject terrain = Terrain.CreateTerrainGameObject(terrainData); terrain.name = name; terrain.transform.parent = parent.transform; terrain.transform.position = new Vector3(lenght*(x - 1), 0, width*(y - 1)); AssetDatabase.CreateAsset(terrainData, "Assets/" + path + name + ".asset"); } } }
void CopyTerrainDataFromTo(TerrainData tDataFrom, ref TerrainData tDataTo) { //TerrainCollider tc = terrainBlock.gameObject.GetComponent<TerrainCollider>(); //tc.terrainData = terrainBlock.terrainData; tDataTo.SetDetailResolution(tDataFrom.detailResolution, 8); tDataTo.heightmapResolution = tDataFrom.heightmapResolution; tDataTo.alphamapResolution = tDataFrom.alphamapResolution; tDataTo.baseMapResolution = tDataFrom.baseMapResolution; tDataTo.size = tDataFrom.size; tDataTo.splatPrototypes = tDataFrom.splatPrototypes; tDataTo.treePrototypes = tDataFrom.treePrototypes; tDataTo.treeInstances = tDataFrom.treeInstances; float[,] heights = tDataFrom.GetHeights(0, 0, tileWidth, tileHeight); tDataTo.SetHeights(0,0, heights); }
TerrainData InitializeTerrain(float[,] noise) { TerrainData t = new TerrainData(); t.heightmapResolution = terrainSizePOT; t.alphamapResolution = textureRes; t.SetDetailResolution(textureRes, 16); t.baseMapResolution = textureRes; t.size = new Vector3(terrainSizePOT, terrainHeight, terrainSizePOT); t.SetHeights(0,0,noise); t.splatPrototypes = splatProto; return t; }
void Awake() { splat[0] = Resources.Load("Textures/" + "rock_2048") as Texture2D; splat[1] = Resources.Load("Textures/" + "forst_1024") as Texture2D; splat[2] = Resources.Load("Textures/" + "snow_512") as Texture2D; splat[3] = Resources.Load("Textures/" + "GoodDirt") as Texture2D; detailTexture[0] = Resources.Load("Details/SimpleGrass/" + "Grass") as Texture2D; detailTexture[1] = Resources.Load("Details/SimpleGrass/" + "WhiteFlowers") as Texture2D; trees[0] = Resources.Load("Trees/" + "Tree4Master") as GameObject; trees[1] = Resources.Load("Trees/" + "Tree5") as GameObject; trees[2] = Resources.Load("Trees/" + "Tree4Master") as GameObject; trees[3] = Resources.Load("Trees/" + "Bush1") as GameObject; Vector2[] splatTileSize = new Vector2[4] { new Vector2(Tile0, Tile0), new Vector2(Tile1, Tile1), new Vector2(Tile2, Tile2), new Vector2(Tile3, Tile3) }; for (int i = 0; i < numOfSplatPrototypes; i++) m_splatPrototypes[i] = new SplatPrototype(); for (int i = 0; i < numOfSplatPrototypes; i++) { m_splatPrototypes[i].texture = splat[i]; m_splatPrototypes[i].tileOffset = Vector2.zero; m_splatPrototypes[i].tileSize = splatTileSize[i]; m_splatPrototypes[i].texture.Apply(true); } for (int i = 0; i < numOfDetailPrototypes; i++) { m_detailProtoTypes[i] = new DetailPrototype(); m_detailProtoTypes[i].prototypeTexture = detailTexture[i]; m_detailProtoTypes[i].renderMode = detailMode; m_detailProtoTypes[i].healthyColor = m_grassHealthyColor; m_detailProtoTypes[i].dryColor = m_grassDryColor; m_detailProtoTypes[i].maxHeight = 0.5f; m_detailProtoTypes[i].maxWidth = 0.2f; } for (int i = 0; i < numOfTreePrototypes; i++) { m_treeProtoTypes[i] = new TreePrototype(); m_treeProtoTypes[i].prefab = trees[i]; } for (int i = 0; i < dim; i++) { for (int j = 0; j < dim; j++) { TerrainData terrainData = new TerrainData(); terrainData.wavingGrassStrength = m_wavingGrassStrength; terrainData.wavingGrassAmount = m_wavingGrassAmount; terrainData.wavingGrassSpeed = m_wavingGrassSpeed; terrainData.wavingGrassTint = m_wavingGrassTint; terrainData.heightmapResolution = m_heightMapSize; terrainData.size = new Vector3(m_landScapeSize, m_terrainHeight, m_landScapeSize); terrainData.alphamapResolution = m_alphaMapSize; terrainData.splatPrototypes = m_splatPrototypes; terrainData.treePrototypes = m_treeProtoTypes; terrainData.SetDetailResolution(m_detailMapSize, m_detailResolutionPerPatch); terrainData.detailPrototypes = m_detailProtoTypes; m_terrainGrid[i, j] = Terrain.CreateTerrainGameObject(terrainData).GetComponent<Terrain>(); } } for (int i = 0; i < dim; i++) { for (int j = 0; j < dim; j++) { m_terrainGrid[i, j].gameObject.AddComponent<TerrainScript>(); m_terrainGrid[i, j].transform.parent = gameObject.transform; m_terrainGrid[i, j].transform.position = new Vector3( m_terrainGrid[1, 1].transform.position.x + (i - 1) * m_landScapeSize, m_terrainGrid[1, 1].transform.position.y, m_terrainGrid[1, 1].transform.position.z + (j - 1) * m_landScapeSize); m_terrainGrid[i, j].treeDistance = m_treeDistance; m_terrainGrid[i, j].treeBillboardDistance = m_treeBillboardDistance; m_terrainGrid[i, j].treeCrossFadeLength = m_treeCrossFadeLength; m_terrainGrid[i, j].treeMaximumFullLODCount = m_treeMaximumFullLODCount; m_terrainGrid[i, j].detailObjectDensity = m_detailObjectDensity; m_terrainGrid[i, j].detailObjectDistance = m_detailObjectDistance; m_terrainGrid[i, j].GetComponent<Collider>().enabled = false; m_terrainGrid[i, j].basemapDistance = 4000; m_terrainGrid[i, j].castShadows = false; PatchManager.AddTerrainInfo(curGlobalIndexX + i - 1, curGlobalIndexZ + j - 1, m_terrainGrid[i, j], m_terrainGrid[i, j].transform.position); } } PatchManager.MakePatches(); int patchCount = PatchManager.patchQueue.Count; for(int i = 0; i < patchCount; i++) PatchManager.patchQueue.Dequeue().ExecutePatch(); UpdateIndexes(); UpdateTerrainNeighbors(); StartCoroutine(FlushTerrain()); terrainIsFlushed = true; m_terrainGrid[curCyclicIndexX, curCyclicIndexZ].GetComponent<Collider>().enabled = false; m_terrainGrid[curCyclicIndexX, curCyclicIndexZ].GetComponent<Collider>().enabled = true; }
private void createNewTerrains() { terrain = new List<Terrain>(); const string containerName = "Generated terrains"; string cName = containerName; int index = 1; while (GameObject.Find(cName) != null) { cName = containerName + " " + index.ToString(); index++; } container = new GameObject(cName); container.transform.position = new Vector3(0, minBounds.y - 5, 0); float w = maxBounds.x - minBounds.x; float h = maxBounds.z - minBounds.z; int sW = Mathf.FloorToInt(w / newTerrainCountX); int sH = Mathf.FloorToInt(h / newTerrainCountY); int sY = Mathf.FloorToInt((maxBounds.y - minBounds.y) * 1.5f); float offX = (w - sW * newTerrainCountX) / 2; float offY = (h - sH * newTerrainCountY) / 2; for (int j = 0; j < newTerrainCountY; j++) { for (int i = 0; i < newTerrainCountX; i++) { TerrainData tdata = new TerrainData(); tdata.SetDetailResolution(detailResolution, resolutionPerPatch); tdata.baseMapResolution = baseMapResolution; tdata.heightmapResolution = heightmapResolution; tdata.size = new Vector3(sW, sY, sH); string terrainName = string.Format("Generated Terrain {0}x{1}", i, j); string filename = Path.Combine("Assets", terrainName + ".asset"); index = 1; while(File.Exists(filename) && !overwriteExists) { filename = Path.Combine("Assets", terrainName + " " + index.ToString() + ".asset"); index++; } AssetDatabase.CreateAsset(tdata, filename); GameObject terrainGO = Terrain.CreateTerrainGameObject(tdata); terrainGO.name = terrainName; terrainGO.transform.parent = container.transform; terrainGO.transform.localPosition = new Vector3(minBounds.x + i * sW + offX, 0, minBounds.z + j * sH + offY); terrain.Add(terrainGO.GetComponent<Terrain>()); } } if (terrain.Count > 1) { for (int i = 0; i < terrain.Count; i++) { int leftIndex = (i % newTerrainCountX != 0)? i - 1: -1; int rightIndex = (i % newTerrainCountX != newTerrainCountX - 1)? i + 1: -1; int topIndex = i - newTerrainCountX; int bottomIndex = i + newTerrainCountX; Terrain left = (newTerrainCountX > 1 && leftIndex != -1)? terrain[leftIndex]: null; Terrain right = (newTerrainCountX > 1 && rightIndex != -1)? terrain[rightIndex]: null; Terrain top = (newTerrainCountY > 1 && topIndex >= 0)? terrain[topIndex]: null; Terrain bottom = (newTerrainCountY > 1 && bottomIndex < terrain.Count)? terrain[bottomIndex]: null; terrain[i].SetNeighbors(left, bottom, right, top); } } }
public static void newTerrainAutoName(int x, int z, float hMapWidth, float hMapHeight, int hMapRes, int aMapRes, int bMapRes, int dRes, int dResPP){ TerrainData terrainData = new TerrainData(); terrainData.heightmapResolution = hMapRes; terrainData.alphamapResolution = aMapRes; terrainData.baseMapResolution = bMapRes; terrainData.SetDetailResolution(dRes,dResPP); terrainData.name = "Terrain"+x+"_"+z; Vector3 size; size.x = hMapWidth; size.y = hMapHeight; size.z = hMapWidth; Vector3 pos; pos.x = hMapWidth * x; pos.y = 0.0f; pos.z = hMapWidth * z; terrainData.size = size; terrainData.RefreshPrototypes(); GameObject terrObj = Terrain.CreateTerrainGameObject(terrainData); terrObj.transform.position=pos; terrObj.name = "t"+x+"."+z; terrObj.GetComponent<Terrain>().Flush(); AssetDatabase.CreateAsset(terrainData, "Assets/Terrain"+x+"_"+z+".asset"); }