void Awake () { if (s_Instance == null) s_Instance = this; undestructible = new Vector3[4]; if (seed != 0) { Random.seed = seed; } terrainMap = new Dictionary<Vector3, GameObject>(); obstacleMap = new Dictionary<Vector3, GameObject>(); buildingMap = new Dictionary<GameObject, Vector3>(); yScale = Mathf.Round(basicCube.GetComponent<Renderer>().bounds.size.y * 10) / 10; xScale = basicCube.GetComponent<Renderer>().bounds.size.x; zScale = basicCube.GetComponent<Renderer>().bounds.size.z; undestructible[0] = new Vector3(xMax / 2, 0, zMax / 2); undestructible[1] = new Vector3(xMax / 2 + 1, 0, zMax / 2); undestructible[2] = new Vector3(xMax / 2, 0, zMax / 2 + 1); undestructible[3] = new Vector3(xMax / 2 + 1, 0, zMax / 2 + 1); Generate(); }
// Use this for initialization void Start() { dispoTP = true; ObjectifsManager.nbAnimauxTot = ObjectifsManager.nbAnimauxTot + 1; //Debug.Log("Animaux Actuels = " + ObjectifsManager.nbAnimauxTot); old = state; terrain = GameObject.FindObjectOfType<TerrainGenerator>(); if (state == "Fly") { } else if (state == "GoToCenter") { GameObject CaseActual = terrain.getCaseByPosition(transform.position); if (CaseActual.GetComponent<TerrainScript>().getType() == Type.Eau) { Destroy(gameObject); } else if (CaseActual.GetComponent<TerrainScript>().getType() == Type.Sable) { } } AllreadyInstance++; StartCoroutine(changeOrder()); }
private void Awake() { _agent = GetComponent <NavMeshAgent>(); _genes = GetComponent <Genes>(); _model = GetComponentInChildren <MeshRenderer>().transform; _terrainGenerator = FindObjectOfType <TerrainGenerator>(); }
// Use this for initialization void Start2() { Chunk.setSize (chunkSize); Chunk.setDiscretization (voxelsPerUnit); NoiseSampleManager sampleManager = new NoiseSampleManager (groundLevel); NoisedFlatDensity density = new NoisedFlatDensity (groundLevel, sampleManager); foreach (NoiseSample noiseSample in noiseSamples) { SampleRepository.registerSample (noiseSample.getPersistentSample ()); sampleManager.addSample (noiseSample); } TerrainGenerator generator = new TerrainGenerator (density, horizontalChunks, verticalChunks); generator.generate (); /*NoiseSample noiseSample1 = new NoiseSample ( SampleRepository.getSample ("sample1"), weightFirstSample, new DefaultSaturation (noiseSaturation1.x, noiseSaturation1.y), firstSampleScale); NoiseSample noiseSample2 = new NoiseSample ( SampleRepository.getSample ("sample2"), weightSecondSample, new DefaultSaturation (noiseSaturation2.x, noiseSaturation2.y), secondSampleScale);*/ /*ChunkProcessor processor = new ChunkProcessor (); for (int i = 0; i < horizontalChunks; i++) { for (int j = 0; j < verticalChunks; j++) { for (int k = 0; k < horizontalChunks; k++) { Chunk chunk = Chunk.Instantiate (new Vector3 (chunkSize*i, chunkSize*j, chunkSize*k)); chunk.applyDensity (density); processor.process (chunk); } } }*/ }
public ErosionManager(TerrainGenerator terrain) { this.terrain = terrain; vertices = terrain.vertices; terrainSize = terrain.terrainSize; terrain.erosionManager = this; }
public override void AgentReset() { base.AgentReset(); BodyParts["pelvis"] = GetComponentsInChildren <Rigidbody>().FirstOrDefault(x => x.name == "torso"); BodyParts["foot"] = GetComponentsInChildren <Rigidbody>().FirstOrDefault(x => x.name == "foot"); SetCenterOfMass(); if (_terrainGenerator == null) { _terrainGenerator = GetComponent <TerrainGenerator>(); } _lastXPosInMeters = (int)BodyParts["foot"].transform.position.x; _terrainGenerator.Reset(); _stepCountAtLastMeter = 0; // set to true this to show monitor while training Monitor.SetActive(true); StepRewardFunction = StepRewardHopper101; TerminateFunction = LocalTerminate; ObservationsFunction = ObservationsDefault; OnTerminateRewardValue = 0f; _pain = 0f; _modeRecover = false; base.SetupBodyParts(); SetCenterOfMass(); }
public TerrainChunk(TerrainGenerator generator, Vector2 coord, LODInfo[] detailLevels, int size, Transform parent, Material material) { _detailLevels = detailLevels; _generator = generator; _position = coord * size; _bounds = new Bounds(_position, Vector2.one * size); Vector3 position3d = new Vector3(_position.x, 0, _position.y); _meshObject = new GameObject($"Terrain Chunk ({coord.x}, {coord.y})"); _meshRenderer = _meshObject.AddComponent <MeshRenderer>(); _meshFilter = _meshObject.AddComponent <MeshFilter>(); _meshCollider = _meshObject.AddComponent <MeshCollider>(); _meshRenderer.material = material; _meshObject.transform.position = position3d; _meshObject.transform.parent = parent; SetVisible(false); _lodMeshes = new LODMesh[_detailLevels.Length]; for (int i = 0; i < _detailLevels.Length; i++) { _lodMeshes[i] = new LODMesh(_generator, _detailLevels[i].lod, Update); } _generator.RequestMapData(_position, OnMapDataReceived); }
// Choose terrain generator void SetTerrain(byte terrainId) { switch (terrainId) { case 0: terrainGenerator = new DefaultTerrainGenerator(this); break; case 1: terrainGenerator = new AlienTerrainGenerator(this); break; case 2: terrainGenerator = new CaveTerrainGenerator(this); break; default: SetTerrain(0); break; } // TODO: reset environment and set terrain properties like gravity and lights.. parentOfChunks = GameObject.Find("/Environment/World").transform; // Init save save = new WorldSave(worldName, seed, terrainId); }
static void Main(string[] args) { Console.WriteLine("Do you want to see the whole process? (Y/N):"); string showcase = Console.ReadLine(); bool continuous_save = false; if (showcase.ToUpper() == "Y") { Console.WriteLine("Do you want to save the whole process? (Y/N):"); string continuous_save_text = Console.ReadLine(); if (continuous_save_text.ToUpper() == "Y") { continuous_save = true; } } TerrainGenerator tg = new TerrainGenerator(); tg.continuous_save = continuous_save; Form form = new Form(); form.Width = 400; form.Height = 400; if (showcase.ToUpper() == "Y") { tg.showcase = true; tg.form = form; Task.Run(() => { Application.Run(tg.form); tg.form.BringToFront(); tg.form.Activate(); }); tg.form.Text = "Generation Showcase"; } while (!tg.finished) { try { tg.Update(); } catch (Exception e) { Console.WriteLine(e.ToString()); } if (tg.finished) { Console.WriteLine("FINISHED"); Console.WriteLine("Do you want to repeat it? (Y/N):"); string repeat = Console.ReadLine(); if (repeat.ToUpper() == "Y") { tg = new TerrainGenerator(); tg.continuous_save = continuous_save; if (showcase.ToUpper() == "Y") { tg.showcase = true; tg.form = form; } } } } }
void Start() { _manager = this; database = _database; #if !UNITY_EDITOR toucControl = true; #endif if (!toucControl) { CrossPlatformInputManager.useHardwareInput(); } else { CrossPlatformInputManager.useTouchInput(); } UIHandler = _UIHandler; path = Application.persistentDataPath; Debug.Log("Game started at " + path); mainThread = Thread.CurrentThread; Timer.start("Loading Materials"); for (int i = 0; i <= Enum.GetValues(typeof(MyMaterial)).Length - 1; i++) { ((MyMaterial)i).loadMaterial(); } Timer.endAndPrint("Loading Materials"); halfMaxChunkCount = (maxChunkCount / 2); chunkPrefab = _chunkPrefab; chunks = new Chunk[maxChunkCount, 50, maxChunkCount]; currentTerrainGenerator = new TerrainGenerator(); //INITIATIONS ItemMeshCreator.init(); IconRenderer.init(); if (startGame) { //LOAD SAVE FILE save = SaveLoader.load(saveFileName); currentTerrainGenerator.initiateMap(); //INITIALIZE PLAYER if (save.player == null) { save.player = new Player(spawnPoint); } save.player.init(playerPrefab); //INITIALIZE UI _UIHandler.init(); } //START BACKGOUND THREAD if (startGame) { Thread thread = new Thread(Timer.doAsycTick); thread.IsBackground = true; thread.Start(); } }
public GameObject LoadTerrainMeshes(McData data) { var gameObject = TerrainGenerator.GenerateMeshes(data); gameObject.name = McConsts.TerrainPrefix + data.Guid.ToString(); return(gameObject); }
private void Start() { human = GetComponent <Human>(); dayNightCycle = Camera.main.GetComponent <DayNightCycle>(); terrainGenerator = Camera.main.GetComponent <TerrainGenerator>(); human.woodAmount = Random.Range(1, 4); }
public AddConform(TerrainGenerator tg) { Debug.Log("is add conf opt type: " + tg.gen_opts.GetType()); this.gen_opts = (AddConformOpt)tg.gen_opts; this.noise_store = tg.noise_store; this.gen_type = GeneratorType.AddConform; this.draw_editor = true; }
public void Start() { terrainDataThreadInfoQueue = new ConcurrentQueue <MapThreadInfo <TileData> >(); terrainGenerator = GameObject.Find("Level").GetComponent <TerrainGenerator>(); caveBuilder = GameObject.Find("Level").GetComponent <CaveBuilder>(); cityGenerator = GameObject.Find("CityPoints").GetComponent <CityGenerator>(); decorationGenerator = GameObject.Find("Decorations").GetComponent <DecorationGenerator>(); }
public tileGenCoro(TerrainGenerator parent, Vector2 pos, int sx, int sy, Action <TileData, Vector2> callback) { p = parent; this.pos = pos; this.sx = sx; this.sy = sy; this.callback = callback; }
// Use this for initialization void Start() { //BoxCollider2D playerCollider = player.GetComponent<BoxCollider2D>(); //Physics2D.IgnoreCollision() //LayerMask mask = 8; playerCamera = playerCameraObject.GetComponent<Camera>(); terrainGenScript = terrainGen.GetComponent<TerrainGenerator>(); }
private static void DrawDimensionErrorMessage(TerrainGenerator instance) { if (!string.IsNullOrEmpty(instance.inspector.errorMessage) && instance.inspector.errorMessage.Equals(TerrainGenerator.InspectorUtilities.LARGE_DIMENSION_ERROR_MSG)) { EditorGUILayout.HelpBox(TerrainGenerator.InspectorUtilities.LARGE_DIMENSION_ERROR_MSG, MessageType.None, false); } }
public InverseLerp( TerrainGenerator source, float lowerBound, float upperBound ) { _generator = new InverseLerpGenerator(source.GetGenerator(), lowerBound, upperBound); }
// Start is called before the first frame update void Start() { chunks = new Dictionary <Vector3Int, Chunk>(); chunkList = new List <Chunk>(); chunkThreader = GetComponent <ChunkThreader>(); visualChunkManager = GetComponent <VisualChunkManager>(); tg = GetComponent <TerrainGenerator>(); }
public void Generate( object o = null, EventArgs args = null) { GetReferences(); pos = transform.position; mesh = TerrainGenerator.Generate(ref datas, pos); }
public Blend( TerrainGenerator source1, TerrainGenerator source2, TerrainGenerator weight ) { _generator = new CoherentNoise.Generation.Combination.Blend(source1.GetGenerator(), source2.GetGenerator(), weight.GetGenerator()); }
private void generateWorldData() { this.terrainGenerator = GameObject.Find("Terrain").GetComponent <TerrainGenerator>(); this.terrainGenerator.GenerateTerrain(); this.worldData = this.terrainGenerator.GetVoxelData(); }
void Awake() { Target = (TerrainGenerator)target; if (Target.TerrainSystem != null) { Resolution = Target.TerrainSystem.Resolution; } }
void Start() { mapImage = GetComponent <Image>(); TerrainGenerator tg = GameObject.FindGameObjectWithTag("GameController").GetComponent <TerrainGenerator>(); wallScale = tg.GetWallSize(); texture = new Texture2D(0, 0); }
public RocksModifier(ISectionData sectionData, EZObjectPool[] pools, TerrainGenerator terrainChunksParent, Vector3 origin) : base("Rocks_", pools) { this.sectionData = sectionData; this.terrainChunksParent = terrainChunksParent; this.origin = origin; }
public MultiplyConform(TerrainGenerator tg) { Debug.Log("is mul conf opt: " + tg.gen_opts.GetType()); this.gen_opts = (MultiplyConformOpt)tg.gen_opts; this.noise_store = tg.noise_store; this.gen_type = GeneratorType.MultiplyConform; this.draw_editor = true; }
void Awake() { if (instance != null) { Debug.LogError("Multiple instances of " + this + " found"); } instance = this; }
private static void DisplayContextMenuForPrefab(Rect r, TerrainGenerator instance, int i) { int childCount = instance.EnvironmentalPainter.GetGroupChildCount(i); bool active = instance.EnvironmentalPainter.IsGroupActive(i); GameObject prefab = instance.EnvironmentalPainterSettings.GetPrefabs()[i]; bool hasCombination = instance.EnvironmentalPainter.GetCombinationsGroup(prefab).childCount > 0; GenericPopup menu = new GenericPopup(); if (childCount > 0 && active) { menu.AddItem(new GUIContent("Group"), false, () => { GroupPrefabInstancesContextHandler(instance, i); }); } else { menu.AddDisabledItem(new GUIContent("Group"), false); } if (childCount > 0 && active && hasCombination) { menu.AddItem(new GUIContent("UnGroup"), false, () => { UnGroupPrefabInstancesContextHandler(instance, i); }); } else { menu.AddDisabledItem(new GUIContent("UnGroup"), false); } menu.AddSeparator(); if (childCount > 0 && !active) { menu.AddItem(new GUIContent("Show All"), false, () => { ShowAllPrefabInstancesContextHandler(instance, i); }); } else { menu.AddDisabledItem(new GUIContent("Show All"), false); } if (childCount > 0 && active) { menu.AddItem(new GUIContent("Hide All"), false, () => { HideAllPrefabInstancesContextHandler(instance, i); }); } else { menu.AddDisabledItem(new GUIContent("Hide All"), false); } menu.AddSeparator(); menu.AddItem(new GUIContent("Export Distribution Map"), false, () => { ExportDistributionMapContextHandler(instance, i); }); menu.AddItem(new GUIContent("Mass Placement"), false, () => { MassPlacementContextHandler(instance, i); }); menu.AddSeparator(); if (childCount > 0) { menu.AddItem(new GUIContent("Clear All"), false, () => { ClearAllPrefabInstancesContextHandler(instance, i); }); } else { menu.AddDisabledItem(new GUIContent("Clear All"), false); } menu.Show(r); }
public static string SaveGame() { CameraController cameraController = Camera.main.GetComponent <CameraController>(); string saveName = DateTime.Now.ToString("MM_dd_yyyy_HH_mm_ss"); QuickSaveWriter quickSaveWriter = QuickSaveWriter.Create(saveName); quickSaveWriter.Write(GameInfo.MAP_SEED, GameInfo.mapSeed); quickSaveWriter.Write(GameInfo.MAP_SIZE, GameInfo.mapSize); quickSaveWriter.Write("playerTeam", GameInfo.playerTeam); quickSaveWriter.Write("cameraPosition", Camera.main.transform.position); quickSaveWriter.Write("cameraRotation", Camera.main.transform.rotation); quickSaveWriter.Write("gold", cameraController.resources[BaseBehavior.ResourceType.Gold]); quickSaveWriter.Write("wood", cameraController.resources[BaseBehavior.ResourceType.Wood]); quickSaveWriter.Write("food", cameraController.resources[BaseBehavior.ResourceType.Food]); quickSaveWriter.Write("favor", cameraController.resources[BaseBehavior.ResourceType.Favor]); int index = 0; foreach (GameObject unitObject in GameObject.FindGameObjectsWithTag("Building").Concat(GameObject.FindGameObjectsWithTag("Unit"))) { BaseBehavior unitBaseBehavior = unitObject.GetComponent <BaseBehavior>(); unitBaseBehavior.Save(ref quickSaveWriter, index); index++; } quickSaveWriter.Write("indexCount", index); TerrainGenerator terrainGenerator = Terrain.activeTerrain.GetComponent <TerrainGenerator>(); // Blind texture Color[] colors = terrainGenerator.blindTexture2D.GetPixels(); int[] blindInfo = new int[colors.Length]; for (int i = 0; i < colors.Length; i++) { blindInfo[i] = colors[i] == Color.black ? 1 : 0; } quickSaveWriter.Write("blindTextureData", blindInfo); // Binds for (int number = 1; number <= 9; number++) { int[] binds = new int[cameraController.unitsBinds[KeyCode.Alpha0 + number].Count]; int i = 0; foreach (GameObject bindObject in cameraController.unitsBinds[KeyCode.Alpha0 + number]) { BaseBehavior bindObjectBaseBehavior = bindObject.GetComponent <BaseBehavior>(); binds[i] = bindObjectBaseBehavior.uniqueId; i++; } quickSaveWriter.Write(new StringBuilder(15).AppendFormat("{0}_{1}", number, "bind").ToString(), binds); } quickSaveWriter.Commit(); return(saveName); }
private static void DrawCombinationsGroup(TerrainGenerator instance) { instance.inspector.isCombinationsGroupExpanded = EditorCommon.GroupFoldout(instance.inspector.isCombinationsGroupExpanded, "Combinations"); instance.EnvironmentalPainterSettings.drawCombinationsBounds = instance.inspector.isCombinationsGroupExpanded; if (instance.inspector.isCombinationsGroupExpanded) { EditorGUI.indentLevel += 1; List <GameObject> prefabs = instance.EnvironmentalPainterSettings.GetPrefabs(); List <Transform> combinationGroups = GetAllCombinationGroups(instance); bool hasNonEmptyGroup = combinationGroups.Find(t => t.childCount != 0) != null; if (!hasNonEmptyGroup) { EditorGUILayout.HelpBox("No combination created yet!", MessageType.None); } else { Vector2 tileSize = new Vector2(50, 50); for (int i = 0; i < combinationGroups.Count; ++i) { if (combinationGroups[i].childCount == 0) { continue; } EditorGUILayout.BeginHorizontal(); Rect tileRect = EditorGUILayout.GetControlRect(GUILayout.Width(tileSize.x), GUILayout.Height(tileSize.y)); Texture t = AssetPreview.GetAssetPreview(prefabs[i]); if (AssetPreview.IsLoadingAssetPreview(prefabs[i].GetInstanceID())) { int dotCount = System.DateTime.Now.Millisecond / 300; GUI.Label(tileRect, EditorCommon.DOT_ANIM[dotCount], EditorCommon.CenteredLabel); } else if (t == null) { string assetPath = AssetDatabase.GetAssetPath(prefabs[i]); if (!string.IsNullOrEmpty(assetPath)) { AssetDatabase.ImportAsset(assetPath, ImportAssetOptions.ForceSynchronousImport); } } else { EditorGUI.DrawPreviewTexture(tileRect, t); } EditorGUILayout.BeginVertical(); EditorGUILayout.LabelField(prefabs[i].name); EditorGUILayout.LabelField("Count: " + combinationGroups[i].childCount, EditorCommon.ItalicLabel); EditorGUILayout.EndVertical(); EditorGUILayout.EndHorizontal(); } } EditorGUI.indentLevel -= 1; } EditorGUILayout.GetControlRect(GUILayout.Height(1)); }
public GeometryPainter(TerrainGenerator terrain) { if (terrain == null) { throw new System.ArgumentException("Terrain cannot be null"); } this.terrain = terrain; settings = new ToolsSettings(); }
void Awake() { if (Instance) { Destroy(gameObject); return; } Instance = this; }
// Update is called once per frame void Update() { if (Input.GetKeyDown(KeyCode.Space)) { TerrainGenerator terrgen = transform.GetComponent <TerrainGenerator>(); terrgen.seed = Random.Range(-10000, 10000); terrgen.GenerateMap(); } }
public RiverInfo(TerrainGenerator terrain) { riverPath = new List<Vertex>(); reachTop = false; reachRight = false; reachBot = false; reachLeft = false; this.terrain = terrain; }
private static void DrawLibraryGroup(TerrainGenerator instance, ref int libraryObjectPickerControlId) { instance.inspector.isLibraryGroupExpanded = EditorCommon.GroupFoldout(instance.inspector.isLibraryGroupExpanded, "Library"); List <GameObject> prefabs = instance.EnvironmentalPainterSettings.GetPrefabs(); if (instance.inspector.isLibraryGroupExpanded) { EditorGUILayout.Space(); if (prefabs != null && prefabs.Count > 0) { float width = EditorGUIUtility.currentViewWidth - EditorGUI.indentLevel * EditorGUIUtility.singleLineHeight; Vector2 tileSize = new Vector2(75, 75); int itemPerRow = (int)(width / tileSize.x); itemPerRow = Mathf.Clamp(itemPerRow, 1, prefabs.Count); int numberOfRow = Mathf.CeilToInt(prefabs.Count * 1.0f / itemPerRow); for (int i = 0; i < itemPerRow * numberOfRow; ++i) { if (i % itemPerRow == 0) { EditorGUILayout.BeginHorizontal(GUILayout.ExpandWidth(false)); } DrawPrefabTile(instance, tileSize, i); if ((i + 1) % itemPerRow == 0) { EditorGUILayout.EndHorizontal(); EditorGUILayout.Space(); } } } else { EditorGUILayout.HelpBox("Try adding a prefab!", MessageType.None); } EditorGUILayout.BeginHorizontal(); GUILayout.FlexibleSpace(); if (GUILayout.Button("Add", GUILayout.Width(EditorCommon.standardWidth), GUILayout.Height(EditorCommon.standardHeight))) { HandleAddPrefabButtonClicked(ref libraryObjectPickerControlId); } GUI.enabled = prefabs != null && prefabs.Count > 0; if (GUILayout.Button("Remove", GUILayout.Width(EditorCommon.standardWidth), GUILayout.Height(EditorCommon.standardHeight))) { HandleRemovePrefabButtonClicked(instance); } GUI.enabled = true; if (GUILayout.Button("Reset", GUILayout.Width(EditorCommon.standardWidth), GUILayout.Height(EditorCommon.standardHeight))) { HandleResetButtonClicked(instance); } EditorGUILayout.EndHorizontal(); } EditorGUILayout.GetControlRect(GUILayout.Height(1)); }
void Awake () { if (Instance) { Destroy(gameObject); return; } Instance = this; }
private void Awake() { TerrainGenerator generator = GetComponent <TerrainGenerator>(); Assert.IsNotNull(generator); terrainData = generator.TerrainData; ecosystem = FindObjectOfType <Ecosystem>(); }
public void AssignFunctions(TerrainGenerator terrainGenerator, FilterGenerator filterGenerator, RiverGenerator riverGenerator, ErosionGenerator erosionGenerator) { tg = terrainGenerator; fg = filterGenerator; rg = riverGenerator; eg = erosionGenerator; lt = tg.localTerrain; UpdateLayers(); }
public void AssignFunctions(GlobalCoordinates globalTerrainC, TerrainGenerator terrainGenerator, FilterGenerator filterGenerator, RiverGenerator riverGenerator, ErosionGenerator erosionGenerator) { this.globalTerrainC = globalTerrainC; tg = terrainGenerator; fg = filterGenerator; rg = riverGenerator; eg = erosionGenerator; lm.AssignFunctions(tg, fg, rg, eg); }
public GUIExport(GUIManager gm) { this.gm = gm; tg = gm.cm.terrainGenerator; menuWidth = gm.menuWidth; rightMenuOffset = gm.rightOffset; topOffset = gm.topOffset; buttonHeight = gm.menuButtonHeight; sideOffset = 10; scaleY = gm.scaleY; //path = "C:\\Users\\Vukmir\\Dropbox\\ŠKOLA\\SBAPR\\Fractal Nature II\\Assets\\Export"; path = "C:"; name = ""; }
void Start() { generator = GetComponent<TerrainGenerator>(); filter = GetComponent<MeshFilter>(); if (terrainMesh != null) { graph = new Graph(terrainMesh); terrain = generator.GenerateTerrain(graph); if (water != null) { water.sharedMesh = graph.BuildMesh(false, (vertex) => { return vertex.position + vertex.normal * waterGrow; } ); } GenerateMesh(); } }
public BiomeMap(TerrainGenerator newTerrainData) { m_terrainData = newTerrainData; m_data = new BiomeMapPixel[Size, Size]; //Set biome weights for all pixels Point position; for (int x = 0; x < Size; ++x) { for (int y = 0; y < Size; ++y) { position = new Point(x, y); float heightAboveSeaLevel = m_terrainData.GetHeightAboveSeaLevelAt(position); float latitude = Mathf.Clamp(position.y / (float)m_terrainData.Heightmap.size, 0f, 1f); float precipitation = m_terrainData.Rainmap.GetValueAt(position); m_data[y, x] = new BiomeMapPixel(latitude, heightAboveSeaLevel, precipitation); } } //Iterate through all pixels, setting their parent Biome for (int x = 0; x < Size; ++x) { for (int y = 0; y < Size; ++y) { //Ignore pixels that have already had their parent biome set. if (m_data[y, x].ParentBiome != null) { continue; } //Generate a new Biome object from the primary biome type of this pixel. Biome biome = new Biome(m_data[y, x].GetPrimaryBiome()); //Flood fill the map with that biome. floodFill(new Point(x, y), biome); //Generate a name for that biome, now that it knows how big it is. biome.GenerateName(); } } }
public void changeWorld() { foreach(GameObject go in _terrainGameObjects) { go.GetComponent<MeshCollider>().enabled = false; go.GetComponent<MeshRenderer>().enabled = false; } foreach(GameObject[] goa in _undergroundGameObjects) { foreach(GameObject go in goa) { go.GetComponent<MeshRenderer>().enabled = false; } } terrainGenerator = new TerrainGenerator(_camera); ResetTerrain(); ChangeTerrainColor(new Color(Random.value/2+0.5f,Random.value/2+0.5f,Random.value/2+0.5f,1.0f)); }
//***********<RIVER...>************* public RiverGenerator(TerrainGenerator terrain) { this.terrain = terrain; filtermanager = terrain.filterManager; terrain.riverGenerator = this; vertices = terrain.vertices; terrainSize = terrain.terrainSize; heightMap = terrain.heightMap; frp = new FunctionRiverPlanner(this); frd = new FunctionRiverDigger(this); fmc = new FunctionMathCalculator(this); ftm = new FunctionTerrainManager(this); fd = new FunctionDebugger(this); currentRiver = new RiverInfo(terrain); AssignFunctions(); }
protected virtual void Init(int wSize) { worldSize = wSize; worldTree = new HybridTree((sbyte)worldSize); worldTree.Init(); discoveryWorkTree = new HybridTree((sbyte)worldSize); discoveryWorkTree.Init(); mainThreadSyncedTree = new WorldTree((sbyte)worldSize); mainThreadSyncedTree.Init(); wtSyncingTree = new WorldTree((sbyte)worldSize); wtSyncingTree.Init(); terrainGenerator = new TerrainGenerator(Mathf.Pow(2, worldSize)); }
public void DiscoverPointsWork() { discoveredPoints = new List<Vector3>(); discoveredValues = new List<sbyte>(); List<Vector3> openList = new List<Vector3>(); openList.AddRange(pendingDiscoveryWork); pendingDiscoveryWork.Clear(); TerrainGenerator tgen = new TerrainGenerator(Mathf.Pow(2, worldSize)); Vector3 offset; int jindex; sbyte value; Stopwatch stopwatch1 = new Stopwatch(); stopwatch1.Start(); for (int i = openList.Count - 1; i >= 0; i--) { //jindex = discoveryWorkTree.GetIndexAtWorldPoint(openList[i]); value = discoveryWorkTree.GetValueAt(openList[i]); if (value == 1) { openList.RemoveAt(i); } else { //discoveryWorkTree.SetValueAt(jindex, 1); } } stopwatch1.Stop(); int index = 0; int debugCounter = 0; int discoveredNonVoid = 0; int faultychecks = 0; Stopwatch stopwatch2 = new Stopwatch(); Stopwatch stopwatch3generation = new Stopwatch(); Stopwatch stopwatch4setvalue = new Stopwatch(); while (index < openList.Count) { for (int i = 0; i < 6; i++) { offset = openList[index]; offset[(int)(i / 2)] += -1 + ((i % 2) * 2); //sixaxis stopwatch2.Start(); // jindex = discoveryWorkTree.GetIndexAtWorldPointSimple(offset); value = discoveryWorkTree.GetValueAt(offset); stopwatch2.Stop(); if (value < 1) { stopwatch3generation.Start(); value = tgen.GetPointValue(offset); stopwatch3generation.Stop(); //discoveryWorkTree.SetValueAt(jindex, value); if (value > 1) { discoveredPoints.Add(offset); discoveredValues.Add(value); } if (value == 1) { if (!openList.Contains(offset)) { openList.Add(offset); } } else { discoveredNonVoid++; stopwatch4setvalue.Start(); discoveryWorkTree.SetValueAtPoint(offset, value); stopwatch4setvalue.Stop(); } } else { faultychecks++; } /*//int jindex = discoveryWorkTree.GetIndexAtWorldPointSimple(offset); //sbyte value = discoveryWorkTree.GetValueAt(jindex); if (value <= 0) { if(!openList.Contains(offset)) { value = tgen.GetPointValue(offset); discoveredPoints.Add(offset); discoveredValues.Add(value); if (value == 1) { openList.Add(offset); } } }*/ } stopwatch4setvalue.Start(); discoveryWorkTree.SetValueAtPoint(openList[index], 1); stopwatch4setvalue.Stop(); index++; if (discoveredNonVoid >= 40) {/* DebugOutput.Shout(openList.Count.ToString() + " and faulty checks " + faultychecks.ToString() + "indiceCount = " + discoveryWorkTree.GetIndiceCount().ToString()); DebugOutput.Shout("cleanup: " + stopwatch1.ElapsedMilliseconds.ToString() + " getindex: " + stopwatch2.ElapsedMilliseconds.ToString() + " generation: " + stopwatch3generation.ElapsedMilliseconds.ToString() + " setvalue: " + stopwatch4setvalue.ElapsedMilliseconds.ToString());*/ for (int k = index; k < openList.Count; k++) { pendingDiscoveryWork.Add(openList[k]); } break; } } }
/// <summary> /// Sets up the terrain functions /// </summary> /// <param name="heightFunction">The terrain height function</param> /// <param name="groundFunction">The terrain ground offset function</param> public void SetupTerrain( TerrainFunction heightFunction, TerrainFunction groundFunction ) { if ( Planet == null ) { throw new InvalidOperationException( "Terrain model does not have an associated planet. Cannot setup terrain" ); } float radius = SpherePlanet.PlanetModel.Radius.ToRenderUnits; float height = MaximumHeight.ToRenderUnits; // NOTE: AP: Patch scale is irrelevant, because vertices are projected onto the function sphere anyway m_Gen = new TerrainGenerator( TerrainGeometry.Sphere, heightFunction, groundFunction ); m_Gen.Setup( 1024, radius, radius + height ); m_Gen.SetSmallestStepSize( MinimumStepSize, MinimumStepSize ); OnModelChanged( false, true ); }
// Use this for initialization void Start() { thi = this; player = GameObject.Find("PlayerTest").transform; seed = Random.Range(1000f, 100000f); colorWave = new Texture2D(waveGradientLength, 1); heightWave = new Texture2D(heightGradientLength, 1); chromaticAbberation = Camera.main.GetComponent<UnityStandardAssets.ImageEffects.VignetteAndChromaticAberration>(); randomSkyHueOffset = Random.value; if (textures.Length > 0) mat.SetTexture(Shader.PropertyToID("_MainTex"), textures[textureIndex]); }
// Use this for initialization void Start () { playerCamera = Camera.main; //the following lines should be their own class "PlayerViewManager"? border = (Transform)Instantiate(selectionBorder, new Vector2(0, 0), Quaternion.identity); //Terrain Generation will not be part of player class this.terrainGenerator = tg.gameObject.GetComponent<TerrainGenerator>(); this.terrainGenerator.init(); //player cursor this.border_x = (this.terrainGenerator.terrain_width / 2) - 1; this.border_y = (this.terrainGenerator.terrain_height / 2) - 1; }
// START: /// <summary> /// Start this instance. /// </summary> public void Start() { // Get the components dungeonGenerator = GetComponent<DungeonGenerator> (); sceneryGenerator = GetComponent<SceneryGenerator> (); stairsGenerator = GetComponent<StairsGenerator> (); roomGenerator = GetComponent<RoomGenerator> (); perimeterGenerator = GetComponent<PerimeterGenerator> (); entranceGenerator = GetComponent<EntranceGenerator> (); corridorGenerator = GetComponent<CorridorGenerator> (); voidGenerator = GetComponent<VoidGenerator> (); pitGenerator = GetComponent<PitGenerator> (); chestGenerator = GetComponent<ChestGenerator> (); caveGenerator = GetComponent<CaveGenerator> (); terrainCarver = GetComponent<TerrainCarver> (); terrainGenerator = GetComponent<TerrainGenerator> (); textureGenerator = GetComponent<TerrainTextureGenerator> (); // Initialize the instances stairsGenerator.Start (); roomGenerator.Start (); perimeterGenerator.Start (); entranceGenerator.Start (); corridorGenerator.Start (); voidGenerator.Start (); pitGenerator.Start (); chestGenerator.Start (); caveGenerator.Start (); terrainCarver.Start (); terrainGenerator.Start (); textureGenerator.Start (); // Initialize the floor array allFloors = new Floor[dungeonGenerator.numFloors]; }
public FilterManager(TerrainGenerator terrain) { terrainSize = terrain.terrainSize; vertices = terrain.vertices; terrain.filterManager = this; }
// Use this for initialization public void Start() { dungeonGenerator = GetComponent<DungeonGenerator> (); terrainGenerator = GetComponent<TerrainGenerator> (); textureGenerator = GetComponent<TerrainTextureGenerator> (); terrainToolkit = terrain.GetComponent<TerrainToolkit> (); }
void Start() { // Initialise main Class object terrain = new TerrainGenerator(); // Calling the constructor (Unity's C# does not allow conventional constructors) terrain.initialise(patchSize, patchMatrixSize); // Updating end-point of main mesh endPoint = new Vector3(terrain.terrainSize - 1, 0, terrain.terrainSize - 1); // Generate fractal Diamond-Square turbulence terrain.applyDiamondSquare(diSqStrength); // Initialise procedural texture variables terrain.applyProceduralTex(true, sandColor, sandLimit, sandStrength, sandCoverage, true, grassColor, grassStrength, true, snowColor, snowLimit, snowStrength, snowCoverage, true, rockColor, slopeLimit, slopeStrength, noiseTexValue); // Build mesh terrain.build(); // erosionManager has to be created when erosionManager = new ErosionManager(terrain); erosionManager.initHydraulicMaps(); filterManager = new FilterManager(terrain); //riverGenerator has to be after filterManager! riverGenerator = new RiverGenerator(terrain); //doesn't work well with on-fly generation riverGenerator.ftm.PerserveMountains(5, 30, 20); }
void TerrainTest() { int testSize = 100; int stepSize = 1; //int octaves,double persistence TerrainGenerator tg = new TerrainGenerator(16384); Vector3 testVector = new Vector3(0, 0, 0); testSize = testSize / 2; double moreThan = 0.44; double lessThan = 0.58; for (int i = -testSize; i < testSize; i+=stepSize) { for (int j = -testSize; j < testSize; j += stepSize) { for (int k = -10; k < 10; k++) { testVector.x = i; testVector.y = j; testVector.z = k; if (tg.hollowTube(testVector)) { //double d = tg.OctavePerlin(testVector, 11, 2.5); //Color col = UtilityColor.hsv2rgb(1.0f - (float)d, 1, 1); Color col = Color.green; UnityEngine.Debug.DrawLine(testVector, testVector + Vector3.up, col,40.0f); UnityEngine.Debug.DrawLine(testVector + (Vector3.up * 0.5f) + (Vector3.left * 0.5f), testVector + (Vector3.up * 0.5f) + (Vector3.right * 0.5f), col, 40.0f); UnityEngine.Debug.DrawLine(testVector + (Vector3.up * 0.5f) + (Vector3.forward * 0.5f), testVector + (Vector3.up * 0.5f) + (Vector3.back * 0.5f), col, 40.0f); } else if (tg.PlatVeines(testVector)) { double d = tg.OctavePerlin(testVector, 11, 2.5); Color col = UtilityColor.hsv2rgb(1.0f - (float)d, 1, 1); UnityEngine.Debug.DrawLine(testVector, testVector + Vector3.up, col, 40.0f); UnityEngine.Debug.DrawLine(testVector + (Vector3.up * 0.5f) + (Vector3.left * 0.5f), testVector + (Vector3.up * 0.5f) + (Vector3.right * 0.5f), col, 40.0f); UnityEngine.Debug.DrawLine(testVector + (Vector3.up * 0.5f) + (Vector3.forward * 0.5f), testVector + (Vector3.up * 0.5f) + (Vector3.back * 0.5f), col, 40.0f); } else if (tg.PallasiteDeposit(testVector)) { Color col = Color.red; UnityEngine.Debug.DrawLine(testVector, testVector + Vector3.up, col,40.0f); UnityEngine.Debug.DrawLine(testVector + (Vector3.up * 0.5f) + (Vector3.left * 0.5f), testVector + (Vector3.up * 0.5f) + (Vector3.right * 0.5f), col, 40.0f); UnityEngine.Debug.DrawLine(testVector + (Vector3.up * 0.5f) + (Vector3.forward * 0.5f), testVector + (Vector3.up * 0.5f) + (Vector3.back * 0.5f), col, 40.0f); } else if (tg.IceDeposit(testVector)) { Color col = Color.white; UnityEngine.Debug.DrawLine(testVector, testVector + Vector3.up, col, 20.0f); UnityEngine.Debug.DrawLine(testVector + (Vector3.up * 0.5f) + (Vector3.left * 0.5f), testVector + (Vector3.up * 0.5f) + (Vector3.right * 0.5f), col, 20.0f); } else if (tg.subIceDeposit(testVector)) { Color col = Color.cyan; UnityEngine.Debug.DrawLine(testVector, testVector + Vector3.up, col, 20.0f); UnityEngine.Debug.DrawLine(testVector + (Vector3.up * 0.5f) + (Vector3.left * 0.5f), testVector + (Vector3.up * 0.5f) + (Vector3.right * 0.5f), col, 20.0f); } /* else { double d = tg.OctavePerlin(testVector, 12, 15.5); Color col = UtilityColor.hsv2rgb((1.0f - (float)d)*0.66f, 1, 1); // Color col = Color.green; UnityEngine.Debug.DrawLine(testVector, testVector + Vector3.up, col, 20.0f); UnityEngine.Debug.DrawLine(testVector + (Vector3.up * 0.5f) + (Vector3.left * 0.5f), testVector + (Vector3.up * 0.5f) + (Vector3.right * 0.5f), col, 20.0f); }*/ /* if (tg.subIceDeposit(testVector)) { Color col = Color.cyan; UnityEngine.Debug.DrawLine(testVector, testVector + Vector3.up, col, 20.0f); UnityEngine.Debug.DrawLine(testVector + (Vector3.up * 0.5f) + (Vector3.left * 0.5f), testVector + (Vector3.up * 0.5f) + (Vector3.right * 0.5f), col, 20.0f); } */ /*if (tg.doubleANDVectorV1(testVector, 0.78, 0.88, 10, 10.5)) { double d = tg.OctavePerlin(testVector, 10, 10.5); Color col = UtilityColor.hsv2rgb((float)d, 1, 1); //Color col = Color.gray; //UnityEngine.Debug.DrawLine(testVector, testVector + Vector3.up, col, 20.0f); //UnityEngine.Debug.DrawLine(testVector + (Vector3.up * 0.5f) + (Vector3.left * 0.5f), testVector + (Vector3.up * 0.5f) + (Vector3.right * 0.5f), col, 20.0f); }*/ /*if (d > moreThan && d < lessThan ) { UnityEngine.Debug.DrawLine(testVector, testVector + Vector3.up, UtilityColor.hsv2rgb(1.0f - (float)d, 1, 1), 20.0f); UnityEngine.Debug.DrawLine(testVector + (Vector3.up * 0.5f) + (Vector3.left * 0.5f), testVector + (Vector3.up * 0.5f) + (Vector3.right * 0.5f), UtilityColor.hsv2rgb(1.0f - (float)d, 1, 1), 20.0f); }*/ /* if (d>0.45 && d < 0.55) { UnityEngine.Debug.DrawLine(testVector, testVector + Vector3.up,Color.blue,23.0f); } else if (d > 0.45) { UnityEngine.Debug.DrawLine(testVector, testVector + Vector3.up,Color.red,23.0f); } else if (d > 0.40) { UnityEngine.Debug.DrawLine(testVector, testVector + Vector3.up, Color.green, 23.0f); }*/ } } } }
public Terrain( GameObject originGameObject, TerrainGenerator mterrainGenerator) { _originGameObject = originGameObject; terrainGenerator = mterrainGenerator; }
IEnumerator terrainTestNew() { int testSize = 400; int stepSize = 1; //int octaves,double persistence TerrainGenerator tg = new TerrainGenerator(16384); Vector3 testVector = new Vector3(0, 0, 0); testSize = testSize / 2; double moreThan = 0.44; double lessThan = 0.58; for (int i = -testSize; i < testSize; i += stepSize) { yield return 0; for (int j = -testSize; j < testSize; j += stepSize) { int height = 30; int kstep = 1; if (i > -height && i < height) { height = testSize; } for (int k = -height; k < height; k+=kstep) { testVector.x = i; testVector.z = j; testVector.y = k; if (tg.MediumCavern(testVector)) { Color col = Color.blue; drawPoint(testVector, col); } else if (tg.SmallCavern(testVector)) { Color col = Color.cyan; drawPoint(testVector, col); } /* else if (tg.TestDeposit(testVector)) { Color col = Color.grey; drawPoint(testVector, col); }*/ } } } }
public void recalculateDestination() { if (state == "GoToCenter") { if (terrain == null) terrain = GameObject.FindObjectOfType<TerrainGenerator>(); List<Vector3> e = terrain.getListCase(transform.position, typetogo); if (e.Count == 0) { Vector2 newPos = Vector3.left * 999f; Vector3 pos2 = Vector3.left * 999f; while (pos2.x > 20f || pos2.x < 0f || pos2.z > 20f || pos2.z < 0f) { newPos = Random.insideUnitCircle * 4f; pos2 = transform.position + new Vector3(newPos.x, 0f, newPos.y); } pos2.y = 0f; GetComponent<NavMeshAgent>().SetDestination(pos2); return; } Vector3 test = new Vector3(500, 500, 500); foreach (Vector3 entry in e) { if (Vector3.Distance(transform.position, test) > Vector3.Distance(transform.position, entry)) { test = entry; } } cible = new Vector3(test.x, 0f, test.z); if (!GetComponent<NavMeshAgent>().isOnNavMesh) { NavMeshHit posTogo; NavMesh.SamplePosition(transform.position, out posTogo, 1000f, NavMesh.AllAreas); GetComponent<NavMeshAgent>().nextPosition = posTogo.position; return ; } GetComponent<NavMeshAgent>().SetDestination(cible); } }
/// <summary> /// Sets up the terrain functions /// </summary> /// <param name="heightFunction">The terrain height function</param> /// <param name="groundFunction">The terrain ground offset function</param> public void SetupTerrain( TerrainFunction heightFunction, TerrainFunction groundFunction ) { if ( PlanetModel == null ) { throw new InvalidOperationException( "Terrain model does not have an associated planet. Cannot setup terrain" ); } float height = MaximumHeight.ToRenderUnits; m_Gen = new TerrainGenerator( TerrainGeometry.Plane, heightFunction, groundFunction ); m_Gen.Setup( 1024, 0, height ); m_Gen.SetSmallestStepSize( 0.001f, 0.001f ); OnModelChanged( ); }
public RandomTerrain(TerrainGenerator tg) { this.tg = tg; }
void Awake() { transform.position = Vector3.zero; _camera = Camera.main; _camera.orthographicSize = Screen.height / 2; _cameraTransform = _camera.transform; //terrain setup terrainGenerator = new TerrainGenerator(_camera); ResetTerrain(); ChangeTerrainColor(new Color(Random.value/2+0.5f,Random.value/2+0.5f,Random.value/2+0.5f,1.0f)); for(var i = 0; i <= 1; i++) { var go = new GameObject( "mesh " + i); go.transform.parent = transform; go.isStatic = true; go.AddComponent<MeshFilter>(); var collider = go.AddComponent<MeshCollider>(); collider.material = physicsMaterial; collider.smoothSphereCollisions = true; var meshRenderer = go.AddComponent<MeshRenderer>(); meshRenderer.sharedMaterial = terrainMaterialBorder; _terrainGameObjects[i] = go; } for(var i = 0; i < 2; i++) { _undergroundGameObjects[i] = new GameObject[numberOfSUndergroundTile]; _undergroundMeshFilter[i] = new MeshFilter[numberOfSUndergroundTile]; _objs[i] = new List<GameObject>(); for(var j = 0; j < numberOfSUndergroundTile; j++) { var go = new GameObject( "undergound " + i + " " + j); go.transform.parent = transform; _undergroundMeshFilter[i][j] = go.AddComponent<MeshFilter>(); var meshRenderer = go.AddComponent<MeshRenderer>(); meshRenderer.sharedMaterial = terrainMaterialInside; _undergroundGameObjects[i][j] = go; } } }