protected void paintTerrain(MapCell[,] map, Door d) { terrain = this.gameObject.GetComponent<Terrain>(); float[,,] splatmapData = new float[terrain.terrainData.alphamapWidth, terrain.terrainData.alphamapHeight, terrain.terrainData.alphamapLayers]; float[] splatWallWeights = new float[terrain.terrainData.alphamapLayers]; splatWallWeights[0] = 0f; splatWallWeights[1] = 1f; float[] splatFloorWeights = new float[terrain.terrainData.alphamapLayers]; splatFloorWeights[0] = 1f; splatFloorWeights[1] = 0f; int indexXmap, indexYmap; for (int i = 0; i < splatmapData.GetLength(0); i++) { for (int j = 0; j < splatmapData.GetLength(1); j++) { indexXmap = Mathf.Clamp(i/factor, 0, map.GetLength(0) - 1); indexYmap = Mathf.Clamp(j/factor, 0, map.GetLength(0) - 1); if (map[indexXmap, indexYmap].cellKind == MapCell.CellKind.WALL || map[indexXmap, indexYmap].cellKind == MapCell.CellKind.UNUSED) { splatmapData = setSplatWeights(i, j, splatWallWeights, splatmapData); } else { splatmapData = setSplatWeights(i, j, splatFloorWeights, splatmapData); } } } terrain.terrainData.SetAlphamaps(0, 0, splatmapData); terrain.Flush(); }
public static void RefreshTreeTextures(UnityEngine.Terrain terrain) { if (terrain == null) { throw new NullReferenceException(); } if (!RanOnce) { RanOnce = true; if (AbleToLocateOnTerrainChanged) { try { OnTerrainChanged.Invoke(terrain, TriggerTreeChangeValues); Working = true; return; } catch (Exception exception) { Debug.LogException(exception); Working = false; } } } if (Working) { OnTerrainChanged.Invoke(terrain, TriggerTreeChangeValues); } else { terrain.Flush(); } }
public void CreateTerrain() { //Het maken van een nieuw terrein met daarbijbehorende resolutie. TerrainData terrainData = new TerrainData(); terrainData.heightmapResolution = Settings.HeightmapResolution; terrainData.alphamapResolution = Settings.AlphamapResolution; //Het maken van het terrein hoogte / lengte. var heightmap = GetHeightMap(); terrainData.SetHeights(0, 0, heightmap); terrainData.size = new Vector3(Settings.Length, Settings.Height, Settings.Length); var newTerrainGameObject = Terrain.CreateTerrainGameObject(terrainData); newTerrainGameObject.transform.position = new Vector3(X * Settings.Length, 0, Z * Settings.Length); Terrain = newTerrainGameObject.GetComponent<Terrain>(); Terrain.Flush(); }
private void SetNeighbors(TerrainNeighbor ignoreNeighbor = TerrainNeighbor.neighborTotal) { for (TerrainNeighbor n = TerrainNeighbor.neighborPositionLeft; n <= TerrainNeighbor.neighborPositionTop; n++) { uint terr = WorldMapBindings_GetNeighbor(instaneId, (int)n); var t = UnityCppBindings.GetTerrain(terr); SetNeighbor(t, n); //prevent dead loop if (null != t && n != ignoreNeighbor) { t.SetNeighbors((TerrainNeighbor)((int)(n + 2) % (int)TerrainNeighbor.neighborTotal)); } } terrain.SetNeighbors(GetNeighbor(TerrainNeighbor.neighborPositionLeft), GetNeighbor(TerrainNeighbor.neighborPositionTop), GetNeighbor(TerrainNeighbor.neighborPositionRight), GetNeighbor(TerrainNeighbor.neighborPositionBottom)); terrain.Flush(); }
private void OnHeightMapLoaded() { terrainData = new TerrainData(); //地形设置 int size = _heightMap.GetLength(0); Vector3 terrainSize = new Vector3(_mapWidth, TerrainConst.MaxTerrainHeight, _mapWidth); //地形的大小,最高、最低点的差值 //Debug.LogFormat("Terrain {0} Size {1}", terrainInstance, terrainSize); terrainData.size = terrainSize; terrainData.heightmapResolution = size + 1; terrainData.SetHeights(0, 0, _heightMap); //一切都是为了这个方法... var tmp = new SplatPrototype[splatCount]; var splat0 = new SplatPrototype(); splat0.texture = texture2s[0]; splat0.normalMap = texture2s[1]; splat0.smoothness = 0.5f; var splat1 = new SplatPrototype(); splat1.texture = texture2s[2]; splat1.normalMap = texture2s[3]; splat1.smoothness = 0.5f; tmp[0] = splat0; tmp[1] = splat1; terrainData.splatPrototypes = tmp; Debug.LogFormat("splat of terrain {0},{1},{2},{3}", instaneId, _splatMap.GetLength(0), _splatMap.GetLength(1), _splatMap.GetLength(2)); terrainData.SetAlphamaps(0, 0, _splatMap); var t = UnityEngine.Terrain.CreateTerrainGameObject(terrainData); t.name = terrainInstance.ToString(); terrain = t.GetComponent <UnityEngine.Terrain>(); terrain.heightmapMaximumLOD = SkyDream.Terrain.maxLod; SetNeighbors(); terrain.terrainData.size = terrainSize; terrain.Flush(); Debug.LogFormat("terrain {0} create success ", instaneId); }
private void startTerrainUpdate(Terrain t) { int mLayer = 1 << meshLayer; raycastDistance = maxBounds.y - t.transform.position.y + 10; Vector3 vScale = t.terrainData.heightmapScale; Vector3 beginPoint = t.transform.position; beginPoint.y += raycastDistance; float[,] heights = new float[t.terrainData.heightmapWidth, t.terrainData.heightmapHeight]; float tdist = raycastDistance; RaycastHit hit; Vector3 curPoint; for (int i = 0; i < t.terrainData.heightmapWidth; i++) { for (int j = 0; j < t.terrainData.heightmapHeight; j++) { curPoint = beginPoint + new Vector3(i * vScale.x, 0, j * vScale.z); if (Physics.Raycast(curPoint, -Vector3.up, out hit, raycastDistance, mLayer)) heights[j, i] = (tdist - hit.distance) / vScale.y; else heights[j, i] = 0; } } t.terrainData.SetHeights(0, 0, heights); if (textureType == MeshToTerrainTextureType.bakeMainTextures) { Texture2D texture = new Texture2D(textureWidth, textureHeight); vScale.x = vScale.x * t.terrainData.heightmapWidth / textureWidth; vScale.z = vScale.z * t.terrainData.heightmapHeight / textureHeight; Color[] colors = new Color[textureWidth * textureHeight]; Renderer lastRenderer = null; Mesh m = null; Vector2[] uv = null; int []triangles = null; Vector3[] verticles = null; for (int i = 0; i < textureWidth; i++) { for (int j = 0; j < textureHeight; j++) { curPoint = beginPoint + new Vector3(i * vScale.x, 0, j * vScale.z); int cPos = j * textureWidth + i; if (Physics.Raycast(curPoint, -Vector3.up, out hit, raycastDistance, mLayer)) { Renderer renderer = hit.collider.GetComponent<Renderer>(); if (renderer != null && renderer.sharedMaterial != null) { if (lastRenderer != renderer) { lastRenderer = renderer; m = renderer.GetComponent<MeshFilter>().sharedMesh; triangles = m.triangles; verticles = m.vertices; uv = m.uv; } Material mat = renderer.sharedMaterial; if (mat.mainTexture != null) { Texture2D mainTexture = (Texture2D)mat.mainTexture; Vector3 localPoint = renderer.transform.InverseTransformPoint(hit.point); int triangle = hit.triangleIndex * 3; Vector3 v1 = verticles[triangles[triangle]]; Vector3 v2 = verticles[triangles[triangle + 1]]; Vector3 v3 = verticles[triangles[triangle + 2]]; Vector3 f1 = v1 - localPoint; Vector3 f2 = v2 - localPoint; Vector3 f3 = v3 - localPoint; float a = Vector3.Cross(v1 - v2, v1 - v3).magnitude; float a1 = Vector3.Cross(f2, f3).magnitude / a; float a2 = Vector3.Cross(f3, f1).magnitude / a; float a3 = Vector3.Cross(f1, f2).magnitude / a; Vector3 textureCoord = uv[triangles[triangle]] * a1 + uv[triangles[triangle + 1]] * a2 + uv[triangles[triangle + 2]] * a3; colors[cPos] = mainTexture.GetPixelBilinear(textureCoord.x, textureCoord.y); } else { colors[cPos] = mat.color; } } else { colors[cPos] = textureEmptyColor; } } else colors[cPos] = textureEmptyColor; } } texture.SetPixels(colors); texture.Apply(); string textureFilename = Path.Combine("Assets", t.name + ".png"); int index = 1; while(File.Exists(textureFilename) && !overwriteExists) { textureFilename = Path.Combine("Assets", t.name + " " + index.ToString() + ".png"); index++; } File.WriteAllBytes(textureFilename, texture.EncodeToPNG()); AssetDatabase.Refresh(); texture = (Texture2D)AssetDatabase.LoadAssetAtPath(textureFilename, typeof(Texture2D)); List<SplatPrototype> sps = new List<SplatPrototype>(); SplatPrototype sp = new SplatPrototype(); sp.tileSize = new Vector2(t.terrainData.heightmapWidth * t.terrainData.heightmapScale.x, t.terrainData.heightmapHeight * t.terrainData.heightmapScale.z); sp.texture = texture; sps.Add(sp); t.terrainData.splatPrototypes = sps.ToArray(); } t.Flush(); }
public static void RefreshTreeTextures(Terrain terrain) { if (!terrain) { throw new NullReferenceException(); } if (!TerrainHack.RanOnce) { TerrainHack.RanOnce = true; if (TerrainHack.AbleToLocateOnTerrainChanged) { try { TerrainHack.OnTerrainChanged.Invoke(terrain, TerrainHack.TriggerTreeChangeValues); TerrainHack.Working = true; return; } catch (Exception exception) { Debug.LogException(exception); TerrainHack.Working = false; } } } if (!TerrainHack.Working) { terrain.Flush(); } else { TerrainHack.OnTerrainChanged.Invoke(terrain, TerrainHack.TriggerTreeChangeValues); } }
public void CreateTerrain() { var data = new TerrainData(); data.alphamapResolution = Settings.AlphaMapResolution; data.heightmapResolution = Settings.HeightMapResolution; var heightmap = GetHeightmap(); data.SetHeights(0, 0, heightmap); ApplyTextures(data); data.size = new Vector3(Settings.Length, Settings.Height, Settings.Length); var terrain = Terrain.CreateTerrainGameObject(data); terrain.transform.position = new Vector3(-0.5f * Settings.Length, 0, -0.5f * Settings.Length); _terrain = terrain.GetComponent<Terrain>(); _terrain.heightmapPixelError = 8; _terrain.materialType = Terrain.MaterialType.Custom; _terrain.materialTemplate = Settings.TerrainMaterial; _terrain.reflectionProbeUsage = UnityEngine.Rendering.ReflectionProbeUsage.Off; _terrain.Flush(); }
/// <summary> /// Places random trees on the terrain. /// </summary> /// <param name="terrain"> /// The terrain to place trees on. /// </param> /// <param name="mtp"> /// The settings for the tree placement. /// </param> public static void PlaceRandomTrees(Terrain terrain, MassTreePlacement mtp) { var data = terrain.terrainData; var num = data.treePrototypes.Length; if (num == 0) { Debug.LogWarning("Can't place trees because no prototypes are defined. Process aborted."); return; } Undo.RegisterCompleteObjectUndo(data, "Mass Place Trees"); var start = DateTime.Now; var array = new TreeInstance[mtp.Count]; var i = 0; while (i < array.Length) { // stop if process have run for over X seconds var delta = DateTime.Now - start; if (delta.TotalSeconds >= mtp.MaxTime) { Debug.LogWarning("Process was taking too much time to run"); return; } var position = new Vector3(Random.value, 0.0f, Random.value); // don't allow placement of trees below minWorldY and above maxWorldY var y = data.GetInterpolatedHeight(position.x, position.z); var worldY = y + terrain.transform.position.y; if (worldY < mtp.MinWorldY || worldY > mtp.MaxWorldY) { continue; } // don't allow placement of trees on surfaces flatter than minSlope and steeper than maxSlope var steepness = data.GetSteepness(position.x, position.z); if (steepness < mtp.MinSlope || steepness > mtp.MaxSlope) { continue; } var color = Color.Lerp(Color.white, Color.gray * 0.7f, Random.value); color.a = 1f; var treeInstance = default(TreeInstance); treeInstance.position = position; treeInstance.color = color; treeInstance.lightmapColor = Color.white; treeInstance.prototypeIndex = Random.Range(0, num); treeInstance.widthScale = Random.Range(mtp.MinWidthScale, mtp.MaxWidthScale); treeInstance.heightScale = Random.Range(mtp.MinHeightScale, mtp.MaxHeightScale); array[i] = treeInstance; i++; } data.treeInstances = array; RecalculateTreePositions(data); terrain.Flush(); }
/// <summary> /// Clears the terrain of all trees. /// </summary> /// <param name="terrain"> /// The terrain who's trees to remove. /// </param> public static void Clear(Terrain terrain) { terrain.terrainData.treeInstances = new TreeInstance[0]; RecalculateTreePositions(terrain.terrainData); terrain.Flush(); }
void MakeTerrainWithHeightMap(Terrain t, float[,] heightMap) { heightMap = t.GetComponent<MakeTerrainBlocks>().GetPoints(); t.terrainData.SetHeights(0, 0, heightMap); t.Flush(); }
void Start() { Screen.showCursor = false; terrain = this.GetComponent<Terrain>(); foreach (AnimationState state in thelight.animation) { state.time = 1.5f; state.speed *= 1/120.0f; } alphas = terrain.terrainData.GetAlphamaps(0,0,512,512); restoreTerrain(); original_alphas = terrain.terrainData.GetAlphamaps(0,0,512,512); doDetails(); terrain.Flush(); }
// Use this for initialization void Start() { t = terrain.GetComponent<Terrain>(); td = t.terrainData; float[,] heights = new float[(int)td.size.x, (int)td.size.z]; System.Random rand = new System.Random(); for(int i = 0 ; i < td.size.x; i++) { for(int j = 0 ; j < td.size.z; j++) { // heights[i, j] += ((float) SimplexNoise.noise(i, j))>0?(float) SimplexNoise.noise(i, j):0; } } normalizePerlin(ref heights, new Vector2(td.size.x - 1, td.size.z - 1)); td.SetHeights(0, 0, heights); td.RefreshPrototypes(); t.Flush(); }