private void InitializeChunks()
    {
        float[,] heightMap = DiamondSquare.GenerateHeightMap(exponentialMapSize, noiseIntensity, seed);
        heightMap          = GaussianBlur.ApplyBlur(heightMap, 5);

        for (int z = 0; z < renderDistance; z++)
        {
            for (int x = 0; x < renderDistance; x++)
            {
                // Create new chunk
                var newChunk = new NChunk(CHUNK_WIDTH, CHUNK_HEIGHT, new Vector3Int(x * CHUNK_WIDTH, 0, z * CHUNK_WIDTH), this.transform);
                _loadedChunks[x, z] = newChunk;

                for (int vZ = 0; vZ < CHUNK_WIDTH; vZ++)
                {
                    for (int vX = 0; vX < CHUNK_WIDTH; vX++)
                    {
                        // TODO: Add cancel condition if v_X + (x * CHUNK_WIDTH) and v_Z + (z * CHUNK_WIDTH) are not inside heightmap
                        // Calculate y-value of voxel
                        int y = Mathf.Abs((int)heightMap[vX + (x * CHUNK_WIDTH), vZ + (z * CHUNK_WIDTH)]);

                        // Add voxels to chunk
                        _loadedChunks[x, z].Add(new NVoxel(new Vector3Int(vX, y, vZ), NBlockType.Grass));
                    }
                }
            }
        }
    }
    private float[,] Generate(int chunkSeed, int generationMethod, float roughness, float offsetX, float offsetY)
    {
        float[,] heightMap;
        switch ((int)generationMethod)
        {
        case 1:
            heightMap = MidpointDisplacement.GenerateHeightMap(chunkSize, chunkSeed, 0.5f, roughness);
            break;

        case 2:
            heightMap = DiamondSquare.GenerateHeightMap(chunkSize, chunkSeed, 0.5f, roughness);
            break;

        case 3:
            heightMap = SquareSquare.GenerateHeightMap(chunkSize, chunkSeed, roughness);
            break;

        /*
         * case 4:
         *      heightMap = Perlin.GenerateHeightMap (chunkSize, chunkSeed, offsetX, offsetY, perlin_Lacunarity, perlin_Persistance, perlin_Scale);
         *      break;
         */
        default:
            heightMap = null;
            break;
        }
        return(heightMap);
    }
Exemple #3
0
        public HeightmapLayerTest()
        {
            var config    = new DiamondSquareConfig(3);
            var generator = new DiamondSquare(config);

            _heightsTask = generator.GenerateAsync();
        }
    // Start is called before the first frame update
    void Start()
    {
        GameObject    terrain = GameObject.Find("LandScape");
        DiamondSquare script  = terrain.GetComponent <DiamondSquare>();

        transform.position = new Vector3(0.0f, 0.0f, script.LandSize);;
    }
	// Use this for initialization
	public static void testDiamondSquareAlg (int size) 
	{
		int size_height_map = size;
		Debug.Log("in start");
		//initialize heightMap
		float[,] heightMap = new float[size_height_map , size_height_map];


		for ( int featureSize = size_height_map / 8; featureSize < size_height_map; featureSize *= 2)
		{
			//seed heightMpa
			for ( int i = 0; i < featureSize; i++)
			{
				for ( int j = 0; j < featureSize; j++)
				{
					heightMap[i,j] = Random.Range(-1f, 1f);
				}
			}

			//use diamond square Algorithm
			heightMap = new DiamondSquare().generateHeightMap(heightMap, size_height_map, size_height_map, featureSize, 1);

			//write texture to disk
			generateTexture(heightMap, featureSize, size_height_map);

			//reset values of heightMap
			heightMap = new float[size_height_map, size_height_map];
		}

		//print to log photos generated
		Debug.Log ("path to file " + Application.dataPath );
	}
Exemple #6
0
        private void GenerateTerrain(int width, int height)
        {
            Tiles = new Tile[width, height];
            double[,] heightmap = new DiamondSquare(RNG, Width, Height, 1, 0.5, false, false).Heightmap;
            double[,] detailmap = new DiamondSquare(RNG, Width, Height, 1, 0.65, false, false).Heightmap;
            double heightmapWidth  = heightmap.GetUpperBound(0);
            double heightmapHeight = heightmap.GetUpperBound(1);
            double widthRatio      = heightmapWidth / (double)Width;
            double heightRatio     = heightmapHeight / (double)Height;
            //int baseHeight = 0; //(int)(-planet.Radius / 10);
            int altitudeModifier = 10000; //(int)(planet.Radius / 2);
            int sealevel         = 0;     // RNG.Next(-10000, 10000);

            for (int x = 0; x < width; x++)
            {
                for (int y = 0; y < height; y++)
                {
                    int    x2       = (int)Math.Round((x) * widthRatio);
                    int    y2       = (int)Math.Round((y) * heightRatio);
                    double altitude = (heightmap[x, y] + detailmap[x, y]) * altitudeModifier;
                    if (altitude > sealevel)
                    {
                        Tiles[x, y] = new Tile(x, y, Tile.TileType.Land);
                    }
                    else
                    {
                        Tiles[x, y] = new Tile(x, y, Tile.TileType.Sea);
                    }
                }
            }
        }
Exemple #7
0
        public void Button_GenerateHeightmap_DiamondSquare()
        {
            ParseInputFields();
            var heightmap = DiamondSquare.Generate(_diamondSquareSize, _diamondSquareNoiseFactor, _diamondSquareNoiseFalloff);

            CreateNewMenuItem(heightmap, "DiamondSquare_" + ++_diamondMapsGenerated);
        }
Exemple #8
0
    // Start is called before the first frame update
    void Start()
    {
        MeshFilter waterMesh = this.gameObject.AddComponent <MeshFilter>();
        Mesh       mesh      = CreateWaterMesh();

        waterMesh.mesh = mesh;

        MeshRenderer renderer = this.gameObject.AddComponent <MeshRenderer>();


        //change size and position of mesh to fit landscape


        renderer.material.shader      = shader;
        renderer.material.mainTexture = texture;

        MeshCollider myMC = this.gameObject.AddComponent <MeshCollider>();

        myMC.sharedMesh = mesh;

        GameObject    terrain   = GameObject.Find("Terrain");
        DiamondSquare script    = terrain.GetComponent <DiamondSquare>();
        Vector2       MinAndMax = script.MinAndMax;
        float         average   = (MinAndMax.x + MinAndMax.y) / 2;

        transform.localPosition = new Vector3(-50.0f, average, -50.0f);
        transform.localScale   += new Vector3(Size, Size, Size);
    }
Exemple #9
0
        private static int[] BuildEmptyMap(List <Transform> markers, VoxelMaterial grass)
        {
            var size = 129;

            while (Map.Instance.CreateMap(null, null).MoveNext())
            {
                ;
            }
            var minX = (int)markers.Min(m => m.position.x) - 10;
            var minY = (int)markers.Min(m => m.position.z) - 10;
            var maxX = (int)markers.Max(m => m.position.x) + 10;
            var maxY = (int)markers.Max(m => m.position.z) + 10;

            var ds     = new DiamondSquare(0.01f, size, size);
            var height = ds.Generate(new System.Random());


            for (var x = Mathf.Max(minX, 0); x < Mathf.Min(maxX, size); x++)
            {
                for (var y = Mathf.Max(minY, 0); y < Mathf.Min(maxY, size); y++)
                {
                    for (var h = 0; h <= (int)((height[x, y] * 3) - 0.01f); h++)
                    {
                        World.At(x, h, y).SetVoxel(grass);
                    }
                }
            }
            return(new[] { maxX - minX, maxY - minY });
        }
        public void DiamondSquare()
        {
            var diamondSquare = new DiamondSquare(TerrainData.heightmapResolution - 1);
            var results       = diamondSquare.Generate(0.23f, 0.43f);

            TerrainData.SetHeights(0, 0, results);
        }
Exemple #11
0
    public GameObject[,] DrawTerrain()
    {
        int mapwidth = (int)Mathf.Pow(2, heightMapSize) + 1;

        map = new GameObject[mapwidth, mapwidth];
        //seed of 1233 is good
        float[,] heightmap = DiamondSquare.CreateHeightmap(heightMapSize, 12348, 1.0f, 0.5f);
        for (int x = 0; x < heightmap.GetLength(0); x++)
        {
            for (int y = 0; y < heightmap.GetLength(1); y++)
            {
                float height = heightmap[x, y];

                GameObject newTile    = null;
                GameObject tileSprite = GetSprite(height);
                GameObject tileItem   = GetItem(tileSprite.GetComponent <Tile>().Type, x, y);

                newTile = Instantiate(tileSprite, new Vector3(x * tileWidth, y * tileWidth, 0), Quaternion.identity) as GameObject;
                Tile t = newTile.GetComponent <Tile>();
                t.AddItem(tileItem);
                newTile.name = t.Type.ToString() + " (" + x + "," + y + ")";
                t.X          = x;
                t.Y          = y;
                newTile.GetComponent <Node>().X = x;
                newTile.GetComponent <Node>().Y = y;

                map[x, y] = newTile;
            }
        }
        return(map);
    }
Exemple #12
0
        private void LoadFromRandomNoise(int Size, bool isVoronoi)
        {
            DiamondSquare diamondSquare = new DiamondSquare(Size);

            diamondSquare.Execute();

            Voronoi vornoi = new Voronoi(Size, 20);

            if (isVoronoi)
            {
                vornoi.Execute();
            }


            Width    = Size;
            Height   = Size;
            heights  = new float[Size, Size];
            Vertices = new Vbo[Width * Height];

            for (int i = 0; i < Width; i++)
            {
                for (int j = 0; j < Height; j++)
                {
                    if (isVoronoi)
                    {
                        heights[i, j] = (int)(((diamondSquare.Array[i, j] + 1) * 255) + vornoi.Array[i, j]) / 2;
                    }
                    else
                    {
                        heights[i, j] = (int)((diamondSquare.Array[i, j] + 1) * 255);
                    }
                }
            }
        }
Exemple #13
0
    // Use this for initialization
    public static void testDiamondSquareAlg(int size)
    {
        int size_height_map = size;

        Debug.Log("in start");
        //initialize heightMap
        float[,] heightMap = new float[size_height_map, size_height_map];


        for (int featureSize = size_height_map / 8; featureSize < size_height_map; featureSize *= 2)
        {
            //seed heightMpa
            for (int i = 0; i < featureSize; i++)
            {
                for (int j = 0; j < featureSize; j++)
                {
                    heightMap[i, j] = Random.Range(-1f, 1f);
                }
            }

            //use diamond square Algorithm
            heightMap = new DiamondSquare().generateHeightMap(heightMap, size_height_map, size_height_map, featureSize, 1);

            //write texture to disk
            generateTexture(heightMap, featureSize, size_height_map);

            //reset values of heightMap
            heightMap = new float[size_height_map, size_height_map];
        }

        //print to log photos generated
        Debug.Log("path to file " + Application.dataPath);
    }
Exemple #14
0
    // Use this for initialization
    void Start()
    {
        DiamondSquare c = GetComponent <DiamondSquare>();

        c.Reset();
        c.ExecuteDiamondSquare();
    }
Exemple #15
0
        public void DiamondSquareWithFixedValueFuncCreates5X5Plane()
        {
            var map = DiamondSquare.CreateHeightMap(5, 1f);

            DiamondSquare.Apply(ref map, null, () => 0f);

            Assert.That(map, Has.All.EqualTo(1f));
        }
Exemple #16
0
    public void Generate()
    {
        Random.InitState(seed);
        var terrain = CurrentTerrainForGeneration;

        terrain.terrainData = DiamondSquare.GenerateTerrain(terrain.terrainData, this);
        Save();
    }
Exemple #17
0
        public void Correct_size_depending_on_number_of_iterations(int iterations, int expectedSize)
        {
            var diamondSquare = new DiamondSquare(new NullOffsetGenerator());

            var result = diamondSquare.Create(0, 1, 2, 3, iterations, 0);

            result.Should().HaveCount(expectedSize);
        }
    private void Initialize()
    {
        _mesh         = new Mesh();
        _vertexesList = new List <Vector3>();
        _triangleList = new List <int>();
        this.GetComponent <MeshFilter>().mesh = _mesh;

        _heightMap = DiamondSquare.GenerateHeightMap(8, 34);
        _heightMap = GaussianBlur.ApplyBlur(_heightMap, gaussRepeatAmount);
    }
    // Update is called once per frame
    void Update()
    {
        MeshRenderer renderer = this.gameObject.GetComponent <MeshRenderer>();
        // Pass updated light positions to shader
        GameObject    terrain = GameObject.Find("LandScape");
        DiamondSquare script  = terrain.GetComponent <DiamondSquare>();

        transform.position = new Vector3(0, (script.currMaxHeight + script.currMinHeight) / 2, 0);
        renderer.material.SetColor("_PointLightColor", this.pointLight.color);
        renderer.material.SetVector("_PointLightPosition", this.pointLight.GetWorldPosition());
    }
Exemple #20
0
        public void Has_correct_values_for_zeroth_iteration()
        {
            var diamondSquare = new DiamondSquare(new NullOffsetGenerator());

            var result = diamondSquare.Create(0, 1, 4, 8, 0, 0);

            result.Should().BeEquivalentTo(new double[]
            {
                0, 1,
                4, 8
            });
        }
Exemple #21
0
 private void OnValidate()
 {
     ds = new DiamondSquare(size, roughness);
     testingTextures = new Texture2D(ds.GetSize(), ds.GetSize(), TextureFormat.ARGB32, false);
     for (int i = 0; i < ds.GetSize(); i++)
     {
         for (int j = 0; j < ds.GetSize(); j++)
         {
             testingTextures.SetPixel(j, i, new Color(ds.Get(j, i) * 255, ds.Get(j, i), ds.Get(j, i), 1));
         }
     }
 }
        private void AddOctave()
        {
            float [,] secondOctave = DiamondSquare.GenerateHeightMap(_exponentialMapSize, _noiseIntensity, _seed);

            for (int z = 0; z < _mapSize; z++)
            {
                for (int x = 0; x < _mapSize; x++)
                {
                    _heightMap[x, z] += secondOctave[x, z];
                }
            }
        }
Exemple #23
0
        public void Has_correct_values_for_first_iteration()
        {
            var diamondSquare = new DiamondSquare(new NullOffsetGenerator());

            var result = diamondSquare.Create(0, 1, 4, 8, 1, 0);

            result.Should().ContainInOrder(new[]
            {
                0, 1.0625, 1,
                1.8125, 3.25, 3.0625,
                4, 3.8125, 8
            });
        }
    // Start is called before the first frame update
    private void Start()
    {
        // Get the terrain object and the maxHeight variable in the DiamondSquare script component
        GameObject    terrain = GameObject.Find("LandScape");
        DiamondSquare script  = terrain.GetComponent <DiamondSquare>();

        // Set the initial camera view
        transform.position = new Vector3(0, script.maxHeight * 2, script.LandSize / 2);
        transform.LookAt(new Vector3(10, 0, 0));

        // Get the initial mouse position for later updates
        mousePos = Input.mousePosition;
    }
Exemple #25
0
    public void Generate()
    {
        GameObject  terrain = new GameObject("Terrain");
        Terrain     t       = terrain.AddComponent <Terrain>();
        TerrainData td      = t.terrainData = new TerrainData();

        td.heightmapResolution = (int)Mathf.Pow(2, n);
        td.alphamapResolution  = (int)Mathf.Pow(2, n);
        t.heightmapPixelError  = 0;
        td.SetHeights(0, 0, DiamondSquare.CreateHeightmap(n, seed, spread, spreadReductionRate));
        td.size = new Vector3(td.heightmapWidth, height, td.heightmapHeight);
        terrain.AddComponent <TerrainCollider>();
        GetComponent <TextureTerrain>().DoItBaby();
    }
Exemple #26
0
        public void Has_correct_values_for_second_iteration()
        {
            var diamondSquare = new DiamondSquare(new NullOffsetGenerator());

            var result = diamondSquare.Create(0, 1, 4, 8, 2, 0);

            result.Should().BeEquivalentTo(new[]
            {
                0, 0.6484375, 1.0625, 1.0390625, 1,
                0.8359375, 1.53125, 1.984375, 2.09375, 1.5390625,
                1.8125, 2.453125, 3.25, 3.234375, 3.0625,
                2.2578125, 3.21875, 3.703125, 4.53125, 3.8984375,
                4, 2.7578125, 3.8125, 4.0859375, 8
            });
        }
Exemple #27
0
    private void SetHeightMap()
    {
        float[,] tmpHeightMap = DiamondSquare.GenerateHeightMap(world);

        heightMap = new int[world.WorldAttributes.WorldSizeInBlocks, world.WorldAttributes.WorldSizeInBlocks];

        for (int x = 0; x < world.WorldAttributes.WorldSizeInBlocks; ++x)
        {
            for (int z = 0; z < world.WorldAttributes.WorldSizeInBlocks; ++z)
            {
                heightMap[x, z] = Mathf.RoundToInt(tmpHeightMap[x, z]
                                                   * world.WorldAttributes.BiomeAttributes[world.Bioms[x, z]].BiomeHeight
                                                   + world.WorldAttributes.BiomeAttributes[world.Bioms[x, z]].SolidGroundHeight);
            }
        }
    }
Exemple #28
0
    public void Tests()
    {
        DiamondSquare ds        = new DiamondSquare(9, 2);
        int           pixelGapX = Mathf.RoundToInt(ds.GetSize() / Mathf.Sqrt(vertices.Length));
        int           pixelGapY = Mathf.RoundToInt(ds.GetSize() / Mathf.Sqrt(vertices.Length));
        int           y         = 0;

        for (var i = 0; i < vertices.Length; i++)
        {
            vertices[i] *= ds.Get(Mathf.RoundToInt(i - (y * Mathf.Sqrt(vertices.Length))) * pixelGapX, y * pixelGapY);
            if (i - (y * Mathf.Sqrt(vertices.Length)) >= Mathf.Sqrt(vertices.Length))
            {
                y += 1;
            }
        }
    }
Exemple #29
0
        public IRelief GetRelief()
        {
            var diamondSquare = new DiamondSquare
            {
                sizeBlock = SizeBlock,
                MainBiome = new Biome
                {
                    Colors = LandscapeGradient.ToListOfMyColor()
                },
                SmoothCount = SmoothCount,
                minp        = GetRepPoints(-1),
                maxp        = GetRepPoints(+1),
            };

            return(diamondSquare);
        }
Exemple #30
0
        private void GenerateMap()
        {
            double[,] heightmap = new DiamondSquare(RNG, SizeX, SizeY, 1, 0.55, false, false).GenerateHeightmap();
            //heightmap = HydraulicErosion(heightmap, 2);
            double heightmapWidth = heightmap.GetUpperBound(0);
            double heightmapDepth = heightmap.GetUpperBound(1);
            double widthRatio     = heightmapWidth / (double)SizeX;
            double heightRatio    = heightmapDepth / (double)SizeY;
            int    baseHeight     = 5;
            int    altitudeScale  = 10;
            int    sealevel       = 5;// RNG.Next(-10000, 10000);

            for (int x = 0; x < SizeX; x++)
            {
                for (int y = 0; y < SizeX; y++)
                {
                    int    x2          = (int)Math.Round((x) * widthRatio);
                    int    y2          = (int)Math.Round((y) * heightRatio);
                    double altitude    = baseHeight + heightmap[x2, y2] * altitudeScale;
                    double temperature = 30 - 0.01 * altitude;

                    for (int z = 0; z < SizeZ; z++)
                    {
                        Tile tile = TileGrid[x, y, z];
                        if (z <= altitude)
                        {
                            tile.IsSolid  = true;
                            tile.IsLiquid = false;
                            tile.Texture  = BorderlessBlock;
                            tile.Color    = Color.ForestGreen;
                        }
                        else if (z <= sealevel)
                        {
                            tile.IsLiquid = true;
                            tile.IsSolid  = false;
                            tile.Texture  = BorderlessFloor;
                            tile.Color    = Color.Navy * 0.35f;
                        }
                        else
                        {
                            tile.IsSolid  = false;
                            tile.IsLiquid = false;
                        }
                    }
                }
            }
        }
Exemple #31
0
        private void diamond_Click(object sender, EventArgs e)
        {
            DiamondSquare ds = new DiamondSquare(
                (int)num_iter_fract.Value,
                0,
                512f,
                (float)shoroh.Value
                );

            ds.Iterate();
            Graphics graphics;

            graphics = Graphics.FromImage(pictureBox.Image);
            graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
            graphics.Clear(pictureBox.BackColor);

            ds.Draw(graphics);
            pictureBox.Refresh();
        }
        public PlasmaTexture(GraphicsDevice device, DiamondSquareSeed seed)
            : base(device, seed.size, seed.size)
        {
            var generator = new DiamondSquare();
            var values = generator.Generate(seed);
            Color[] colorData = new Color[seed.size * seed.size];

            var range = generator.MaxValue - generator.MinValue;
            var min = generator.MinValue;

            for (int x = 0; x < seed.size; ++x)
            {
                for (int y = 0; y < seed.size; ++y)
                {
                    var value = Math.Min(Math.Max(values.Get(seed.size + 1, x, y), 0.0f), 1.0f);
                    //int value = (int)(((values.Get(size + 1, x, y) - min) / range) * 255);
                    colorData[y * seed.size + x] = new Color(value, value, value, 1);
                }
            }

            this.SetData<Color>(colorData);
        }
	//iterates over all meshes in the array
	void generateMissingMeshes()
	{
		Debug.Log ("meshes in currently generating : ");

		//iterate over all generating meshes
		foreach ( string meshName in meshesCurrentlyGenerating)
		{
			Debug.Log("strint key " + meshName);
			//get discrete mesh position
			string[] param = meshName.Split(',');
			int x = int.Parse(param[0]), z = int.Parse(param[1]);
			Debug.Log("in generate missing meshes parsed x : " + x + " z " + z);
			int seed_x_start = 0, seed_z_start = 0, seed_x_end = generator.meshSideLength, seed_z_end = generator.meshSideLength;

			//check if we share any sides with current meshes in scene, if so get their heigths on there shared border
			float[,] heigthMap = new float[generator.meshSideLength, generator.meshSideLength];
			
			/*Debug.Log ("printing heightmap BEFORE SEEDING ");
			for(int i = 0; i < generator.meshSideLength; i++)
			{
				string s= "";
				for ( int j = 0; j < generator.meshSideLength; j++)
				{
					s += heigthMap[i, j];
				}
				Debug.Log (s);
				s = "";
			}*/


			#region update HeightMap with shared borders
			ArrayList borders = new ArrayList(4);
			//north face shared
			try
			{
				//try and get mesh
				Mesh sharedBorder = meshesInScene[(x+1) + "," + z];
				Debug.Log ("north values ");
				string s = "";
				//iterate over all heights of current existing mesh
				for ( int xx = 0; xx < generator.meshSideLength; xx++)
				{
					//Debug.Log ("index in loop " + (xx * generator.meshSideLength));
					//heigthMap[xx, generator.meshSideLength - 1 ] = sharedBorder.vertices[xx * generator.meshSideLength].y;
					heigthMap[generator.meshSideLength - 1, xx] = sharedBorder.vertices[xx * generator.meshSideLength].y;
					s += heigthMap[generator.meshSideLength - 1, xx] + " ";
				}
				Debug.Log (s);
				s = "";
				seed_x_end -= generator.featureSize;
				borders.Add(0);
			}
			catch ( System.Exception e) {}
			//south face shared
			try
			{
				//try and get mesh
				Mesh sharedBorder = meshesInScene[(x-1) + "," + z];

				//iterate over all heights of current existing mesh
				for ( int xx = 0; xx < generator.meshSideLength; xx++)
				{
					heigthMap[0 , xx] = sharedBorder.vertices[(generator.meshSideLength - 1) + xx * generator.meshSideLength].y;
				}

				seed_x_start += generator.featureSize;
				borders.Add(1);
			}
			catch ( System.Exception e) {}
			//east face shared
			try
			{
				//try and get mesh
				Mesh sharedBorder = meshesInScene[(x) + "," + (z + 1)];
				
				//iterate over all heights of current existing mesh
				for ( int zz = 0; zz < generator.meshSideLength; zz++)
				{
					heigthMap[zz , generator.meshSideLength - 1] = sharedBorder.vertices[zz].y;
				}

				seed_z_start += generator.featureSize;
				borders.Add(2);
			}
			catch ( System.Exception e) {}
			//west face shared
			try
			{
				//try and get mesh
				Mesh sharedBorder = meshesInScene[(x) + "," + (z - 1)];
				
				//iterate over all heights of current existing mesh
				for ( int zz = 0; zz < generator.meshSideLength; zz++)
				{
					heigthMap[zz, 0] = sharedBorder.vertices[ (generator.meshSideLength - 1) * generator.meshSideLength + zz].y;
				}
				seed_z_end -= generator.featureSize;
				borders.Add(3);
			}
			catch ( System.Exception e) {}
			#endregion


			Debug.Log ("x start " + seed_x_start + " x end " + seed_x_end + " z start " + seed_z_start + " z end " + seed_z_end);


			//randomly seed the terrain
			for ( int i = seed_x_start; i < seed_x_end; i += generator.featureSize)
			{
				for ( int j = seed_z_start; j < seed_z_end; j += generator.featureSize)
				{
					heigthMap[i, j] = Random.Range(-1f, 1f) * generator.randomDisplacement * generator.step;
				}
			}



			Debug.Log ("printing heightmap after seeding");
			for(int i = 0; i < generator.meshSideLength; i++)
			{
				string s= "";
				for ( int j = 0; j < generator.meshSideLength; j++)
				{
					s += heigthMap[i, j] + " ";
				}
				Debug.Log (s);
				s = "";
			}
	
			//generate noise on heigthMap
			//for ( int c = 1; c <= generator.nNoiseIterations; c++) //((int[]) borders.ToArray(typeof(int)))
			Debug.Log ("sizex = size _z = " + generator.meshSideLength);
				heigthMap = new DiamondSquare().generateHeightMap(heigthMap, generator.meshSideLength, generator.meshSideLength, /*generator.sizeX /*/ generator.featureSize/** generator.meshSideLength*/, generator.randomDisplacement * generator.step / (6 /** c*/));

			/*Debug.Log ("printing heightmap after noise");
			for(int i = 0; i < generator.meshSideLength; i++)
			{
				string s= "";
				for ( int j = 0; j < generator.meshSideLength; j++)
				{
					s += heigthMap[i, j] + " ";
				}
				Debug.Log (s);
				s = "";
			}*/

			//generate mesh based on heigthMap
			generator.generateMesh(x, z, heigthMap);
		}

		//delete meshesCurrentlyBeingGenerated
		meshesCurrentlyGenerating = new ArrayList(10);
	}
    public TerrainGenerator(int patchSize)
    {
        //initialize(64,3);
        ds = new DiamondSquare(this, patchSize);
        rt = new RandomTerrain(this);
        this.patchSize = patchSize;
        try
        {
            GUIterrainPlannerMenu tpMenu = GameObject.Find("TerrainPlanner").GetComponent<GUIterrainPlannerMenu>();
            pm = tpMenu.patch.pm;
            gtp = tpMenu.patch;
            extraPatchCount = tpMenu.patch.extraPatchCount;
        }
        catch (Exception e)
        {
            Debug.Log("TerrainPlanner not found");
            //pm = new PatchManager(patchSize);
            gtp = new GUIterrainPatch(patchSize);
            gtp.SetDefaultPatch(DefaultTerrain.valleys);
            pm = gtp.pm;

            extraPatchCount = 0;
        }
    }
 // Use this for initialization
 void Start()
 {
     diamondSquare = new DiamondSquare ();
 }
    // Use this for initialization
    void Start()
    {
        RenderSettings.fog = false;
        diamondSquare = new DiamondSquare ();
        diamondSquare.flat = true;

        perlin = new PerlinNoise ();

        worldScript = this.GetComponent<World> ();

        diamondSquareChunk = (int)worldScript.viewDistance*2;

        seed = Random.Range(0.5f, 0.6f);

        //generateTerrain ();

        //generateCanyon (new Vector3(300,300,300));

        print ("Total Cubes - " + numCubes);
    }
	//generates a texture depending on the height map for a given mesh
	Texture2D generateTexture(Vector3[] vertices, int featSize, float maxHeightRangeChange) 
	{
		//featSize is the featureSize for the given array
		//maxHeightRangeChange is the maximum height that can be changed in the noise generation

		//create new texture with detail specified by user
		Texture2D texture = new Texture2D(textureDetail, textureDetail);

		//get noise from height of each vertex in mesh
		float[,] noise = new float[meshSideLength, meshSideLength];
	
		//iterate over all points in the mesh
		for ( int z = 0; z < meshSideLength ; z++ )
		{
			for ( int x = 0 ; x < meshSideLength ; x++)
			{
				//get height value of given vertex
				float height = vertices[ (x ) + meshSideLength * (z)].y;

				//update noise height value
				noise[x, z] = height;
			}
		}

		//get noise value for terrain height
		noise = new DiamondSquare().generateHeightMap(noise, meshSideLength, meshSideLength, featSize, maxHeightRangeChange);
		
		//ratio to convert from mesh coordinates to pixel coordinates
		float step_ratio = meshSideLength / ((float) textureDetail);
	
		//iterate over all pixels in texture
		for ( int z = 0; z < textureDetail ; z++)
		{
			for ( int x = 0 ; x < textureDetail ; x++)
			{
				//get height of noise value at given point
				float height = noise[ (int) (step_ratio * x), (int) (step_ratio* z)];

				//boolean to tell if we filled pixel (x,z)
				bool filled = false;

				//iterate over all heights thresholds
				for ( int i = 0 ; i < textureHeightThresholds.Length; i++)
				{
					//check if we satisfay height threshold
					if ( height < textureHeightThresholds[i])
					{
						//set pixxel in texture
						texture.SetPixel(x, z, textureHeightValues[i].GetPixel(Random.Range(0, textureHeightValues[i].width ), Random.Range(0, textureHeightValues[i].height)));

						//update bool
						filled = true;

						//break to prevent multiple pixel overwrites
						break; 
					}
				}

				//check if pixel was filled, if not assign default texture color
				if ( !filled)
					texture.SetPixel(x, z, textureHeightValues[textureHeightValues.Length - 1].GetPixel(Random.Range(0, textureHeightValues[textureHeightValues.Length - 1].width ), Random.Range(0, textureHeightValues[textureHeightValues.Length - 1].height)));
			}
		}

		//set texture parameters
		texture.wrapMode = TextureWrapMode.Clamp;
		texture.filterMode = FilterMode.Bilinear;
		
		//apply texture
		texture.Apply();

		//return newly created texture
		return texture;
	}