Пример #1
0
  public void Generate()
  {
      if (generator == Generator.PerlinNoise)
      {
          map = PerlinNoise.Generate(size, scale, octaves, persistence, lacunarity);
      }
      else if (generator == Generator.ExponentiallyDistributedNoise)
      {
          map = ExponentiallyDistributedNoise.Generate(size, scale, octaves, persistence, lacunarity);
      }
      else if (generator == Generator.Geneveaux)
      {
          map = GeneveauxTerrain.Generate(size, riverCount);
      }

      foreach (Modifier mod in modifiers)
      {
          if (mod == Modifier.BeyerHydraulicErosion)
          {
              map = BeyerErosion.Erode(map, erosions);
          }
      }

      if (container == Container.Texture)
      {
          Texture2D tex = HeightMap2Texture(map);
          tex.Apply();
          tex.name = "Texture";
          AssetDatabase.AddObjectToAsset(tex, this);
          AssetDatabase.SetMainObject(this, AssetDatabase.GetAssetPath(this));   // This is disgusting and it is the only way I can get the asset to reload and show the texture
          AssetDatabase.ImportAsset(AssetDatabase.GetAssetPath(this));
      }
      else if (container == Container.Mesh)
      {
          if (obj != null)
          {
              DestroyImmediate(obj);
          }

          /* GameObject obj = new GameObject();
           * Mesh mesh = HeightMap2Mesh(map);
           *
           * MeshFilter filter = obj.AddComponent<MeshFilter>();
           * filter.sharedMesh = mesh;
           *
           * MeshRenderer renderer = obj.AddComponent<MeshRenderer>();
           * renderer.sharedMaterial = new Material(Shader.Find("Specular"));
           *
           * AssetDatabase.AddObjectToAsset(obj, this);
           * AssetDatabase.AddObjectToAsset(mesh, this); */

          obj      = HeightMap2Mesh(map);
          obj.name = "Terrain";

          // PrefabUtility.SaveAsPrefabAsset(obj, "Assets/terrain.prefab");
          // AssetDatabase.AddObjectToAsset(obj, this);

          // AssetDatabase.SetMainObject(obj, AssetDatabase.GetAssetPath(this));
      }
  }
Пример #2
0
        /// <summary>
        /// Applies the filter to the specified image.
        /// </summary>
        /// <param name="image">The image.</param>
        /// <param name="targetLocation">The target location.</param>
        /// <returns>The image</returns>
        public unsafe Image Apply(Image image, Rectangle targetLocation = default(Rectangle))
        {
            targetLocation = targetLocation == default(Rectangle) ? new Rectangle(0, 0, image.Width, image.Height) : targetLocation.Clamp(image);
            var Result = new Color[image.Pixels.Length];

            Array.Copy(image.Pixels, Result, Result.Length);
            var XNoise = PerlinNoise.Generate(image.Width, image.Height, 255, 0, 0.0625f, 1.0f, 0.5f, Roughness, Seed);
            var YNoise = PerlinNoise.Generate(image.Width, image.Height, 255, 0, 0.0625f, 1.0f, 0.5f, Roughness, Seed * 2);

            Parallel.For(targetLocation.Bottom, targetLocation.Top, y =>
            {
                fixed(Color * TargetPointer = &image.Pixels[(y * image.Width) + targetLocation.Left])
                {
                    Color *TargetPointer2 = TargetPointer;
                    for (int x = targetLocation.Left; x < targetLocation.Right; ++x)
                    {
                        float XDistortion = x + (XNoise.Pixels[(y * image.Width) + x].Red * Power);
                        float YDistortion = y + (YNoise.Pixels[(y * image.Width) + x].Red * Power);
                        var X1            = (int)XDistortion.Clamp(0, image.Width - 1);
                        var Y1            = (int)YDistortion.Clamp(0, image.Height - 1);
                        int ResultOffset  = ((y * image.Width) + x);
                        int SourceOffset  = ((Y1 * image.Width) + X1);

                        Result[ResultOffset] = image.Pixels[SourceOffset];
                    }
                }
            });
            return(image.ReCreate(image.Width, image.Height, Result));
        }
Пример #3
0
        private Bitmap FillBitmap(int width, int height, double scale, double offsetX, double offsetY, double offsetZ, double persistence, int octaves)
        {
            PerlinNoise perlinNoise = new PerlinNoise {
                scale       = scale,
                offsetX     = offsetX,
                offsetY     = offsetY,
                offsetZ     = offsetZ,
                octaves     = octaves,
                persistence = persistence
            };
            DirectBitmap directBitmap = new DirectBitmap(width, height);

            Parallel.For(0, width, (x, state) => {
                if (generateToken.IsCancellationRequested)
                {
                    state.Break();
                }
                for (int y = 0; y < height; y++)
                {
                    int value = (int)(perlinNoise.Generate((double)x / width, (double)y / height) * 255);
                    directBitmap.SetPixel(x, y, Color.FromArgb(value, value, value));
                }
            });
            if (generateToken.IsCancellationRequested)
            {
                directBitmap.Dispose();
                throw new TaskCanceledException();
            }
            Bitmap result = directBitmap.Bitmap;

            directBitmap.Dispose();
            return(result);
        }
Пример #4
0
        private void Start()
        {
            heightmap = PerlinNoise.Generate(width, height, scale, octaves, persistance, lacunarity);

            Terrain.terrainData.SetHeights(0, 0, heightmap);

            Debug.Log(LocalToWorldFlat(IndicesToLocalFlat(512, 512)));
        }
Пример #5
0
        public void KeyMoreThanDataTest()
        {
            const int _keyLength  = 25;
            const int _dataLength = 12;

            var _noiser     = new PerlinNoise();
            var _secretData = _noiser.Generate(_dataLength);

            var _crypter = new CryptoProvider();

            _crypter.Key = _noiser.Generate(_keyLength);

            var _crypted   = _crypter.Encode(_secretData);
            var _deCrypted = _crypter.Decode(_crypted);

            CollectionAssert.AreEqual(_secretData, _deCrypted);
        }
Пример #6
0
        private bool GenerateIronSample(BlockSpacePosition blockPosition)
        {
            double calcX = blockPosition.x * 0.1 + 20.0;
            double calcY = blockPosition.y * 0.05 - 20.0;
            double calcZ = blockPosition.z * 0.1;

            double noiseSample = PerlinNoise.Generate(calcX, calcY + 0.01, calcZ);

            return(noiseSample < -7.5);
        }
Пример #7
0
        private bool GenerateCoalSample(BlockSpacePosition blockPosition)
        {
            double calcX = blockPosition.x * 0.20;
            double calcY = blockPosition.y * 0.20 + 5.0;
            double calcZ = blockPosition.z * 0.20;

            double noiseSample = PerlinNoise.Generate(calcX, calcY + 0.01, calcZ);

            return(noiseSample < -0.465);
        }
Пример #8
0
        private bool GenerateRockSample(BlockSpacePosition blockPosition)
        {
            double calcX = blockPosition.x * 0.018;
            double calcY = blockPosition.y * 0.020;
            double calcZ = blockPosition.z * 0.018;

            double noiseSample = PerlinNoise.Generate(calcX, calcY + 0.01, calcZ);

            return((1.0 + noiseSample - ((double)blockPosition.y / 32.0)) > -1.45 ||
                   noiseSample < -0.3);
        }
Пример #9
0
 /// <summary>
 /// Generate Perlin Noise procedurally
 /// /// </summary>
 /// <param name="width"></param>
 /// <param name="height"></param>
 /// <param name="octavesPercent"></param>
 /// <param name="percentFrequency"></param>
 /// <returns>Bitmap stream in jpg format</returns>
 public async Task <Stream> GetPerlinNoise(int width, int height, int octavesPercent, int percentFrequency)
 {
     if ((octavesPercent < 1) || (octavesPercent > 100))
     {
         throw new ArgumentException(nameof(octavesPercent) + " must between 1 and 100");
     }
     if ((percentFrequency < 1) || (percentFrequency > 100))
     {
         throw new ArgumentException(nameof(percentFrequency) + " must between 1 and 100");
     }
     return(await Task.Run(() => { return GetStreamFromBitmap(PerlinNoise.Generate(Width: width, Height: height, Octaves: (int)Math.Ceiling(octavesPercent / 33d), Frequency: (float)new Random().NextDouble() + new Random().Next((int)Math.Ceiling(percentFrequency / 25d)), Amplitude: 1f, Persistance: 1f, MinRGBValue: 0, MaxRGBValue: 255, Seed: Guid.NewGuid().GetHashCode())); }));
 }
        public override ChunkData[,] Generate(World world, int seed)
        {
            var size  = world.WorldWidth * world.ChunkSize;
            var noise = PerlinNoise.Generate(size, size, octaveCount, amplitude, seed);

            for (int exp = 0; exp < ExplosionsCount; exp++)
            {
                int randomExpX = Random.Range(0, size);
                int randomExpZ = Random.Range(0, size);


                var selection = Selections.SelectSphere(
                    new Vector3Int(randomExpX, (int)(world.ChunkHeight * 0.25f), randomExpZ), ExplosionsSize).ToList();

                for (int i = 0; i < selection.Count; i++)
                {
                    if (selection[i].x < 0 || selection[i].x >= size || selection[i].z < 0 || selection[i].z >= size)
                    {
                        continue;
                    }

                    noise[selection[i].x, selection[i].z] = 0;
                }
            }



            for (int x = 0; x < size; x++)
            {
                for (int z = 0; z < size; z++)
                {
                    noise[x, z] *= CurveX.Evaluate((float)x / size) * CurveZ.Evaluate((float)z / size);
                }
            }

            var data = new ChunkData[world.WorldWidth, world.WorldDepth];

            for (byte i = 0; i < world.WorldWidth; i++)
            {
                for (byte j = 0; j < world.WorldDepth; j++)
                {
                    var chunk = new ChunkData(world.ChunkSize, world.ChunkHeight);
                    FillChunk(world, chunk, noise, i, j);
                    data[i, j] = chunk;
                }
            }

            return(data);
        }
Пример #11
0
        public HeightMap(bool pPerlin, int pSize)
        {
            _size = pSize;
            if (pPerlin)
            {
                var n = new PerlinNoise(pSize);
                _map = n.Generate(4, .7f, .4f, .3f, .1f);
            }
            else
            {
                var n = new DiamondSquareNoise(pSize);
                _map = n.Generate(0, 5, .5f);

                float maxHeight = 0;
                float maxDepth  = 1;
                for (int x = 0; x < pSize; x++)
                {
                    for (int y = 0; y < pSize; y++)
                    {
                        if (_map[x, y] > maxHeight)
                        {
                            maxHeight = _map[x, y];
                        }
                        if (_map[x, y] < maxDepth)
                        {
                            maxDepth = _map[x, y];
                        }
                    }
                }

                //Scale all points so they are within max/min
                maxDepth = Math.Abs(maxDepth);
                for (int x = 0; x < pSize; x++)
                {
                    for (int y = 0; y < pSize; y++)
                    {
                        if (_map[x, y] < 0)
                        {
                            _map[x, y] = _map[x, y] / maxDepth;
                        }
                        else if (_map[x, y] > 0)
                        {
                            _map[x, y] = _map[x, y] / maxHeight;
                        }
                    }
                }
            }
        }
Пример #12
0
        private void Reload()
        {
            var matrix = PerlinNoise.Generate(Width, Height, OctavesCount, Amplitude, 0);
            var maxX   = matrix.GetLength(0);
            var maxY   = matrix.GetLength(1);

            perlin = new float[maxX * maxY];
            for (var i = 0; i < maxX; i++)
            {
                for (var j = 0; j < maxY; j++)
                {
                    var index = j * maxX + i;
                    perlin[index] = matrix[i, j];
                }
            }
        }
Пример #13
0
        public void CryptStringTest()
        {
            const int _keyLength = 12;

            var _noiser     = new PerlinNoise();
            var _secretData = "Однажды, в студеную зимнюю пору я из лесу вышел; был сильный мороз.";

            var _crypter = new CryptoProvider();

            _crypter.Key = _noiser.Generate(_keyLength);

            var _crypted   = _crypter.Encode(_secretData);
            var _deCrypted = _crypter.DecodeToString(_crypted);

            Assert.AreEqual(_secretData, _deCrypted);
        }
Пример #14
0
    //public float z = 0.5f;

    private void OnDrawGizmosSelected()
    {
        Gizmos.color = Color.blue;
        for (float x = 0.0f; x < 5; x += 0.1f)
        {
            for (float z = 0.0f; z < 5; z += 0.1f)
            {
            }
        }
        for (int i = 0; i < 10000; i++)
        {
            var p = UnityEngine.Random.insideUnitSphere;

            var noise = PerlinNoise.Generate(p.x + 0.5f, p.y + 0.5f, p.z + 0.5f);

            p = p * (20 + noise);
            Gizmos.DrawSphere(p, 0.1f);
        }
    }
Пример #15
0
 void Generate()
 {
     perlinGenerator.Generate();
     gridSpawner.Generate();
 }
Пример #16
0
 public void GenerateReturnsArrayOfData()
 {
     PerlinNoise tm = new PerlinNoise();
       float[][] data = tm.Generate(0, 10, 0, 20, 10, 8, 128, 4);
 }
Пример #17
0
        // генерирует карту высот с размером SizeX, SizeY, по методу LandGenMethod c коэффициентами Convs, со сглаживанием или нет (Smoothing) с долинизацией (Valley)
        public void GenerateHeightmap(int SizeX, int SizeY, GenMethod LandGenMethod, Convolution[] Convs, bool Smoothing, bool Valley, bool Island)
        {
            this.SizeX = SizeX;
            this.SizeY = SizeY;
            Heightmap  = new double[SizeX, SizeY];
            PerlinNoise Noise = new PerlinNoise(256);

            double min = 99999;
            double max = -99999;

            double[,] ar = new double[SizeX, SizeY];

            if (LandGenMethod == GenMethod.Perlin)
            {
                for (int i = 0; i < SizeX; i++)
                {
                    for (int j = 0; j < SizeY; j++)
                    {
                        for (int l = 0; l < Convs.Length; l++)
                        {
                            if (Convs[l].Operation == Operation.Plus)
                            {
                                if (Convs[l].Coef != 0)
                                {
                                    ar[i, j] += Noise.Generate(i, j, Convs[l].Coef);
                                }
                                else
                                if (Convs[l].Coef != 0)
                                {
                                    ar[i, j] *= Noise.Generate(i, j, Convs[l].Coef);
                                }
                            }
                        }

                        if (max < ar[i, j])
                        {
                            max = ar[i, j];
                        }
                        if (min > ar[i, j])
                        {
                            min = ar[i, j];
                        }
                    }
                }
            }
            else
            {
                Random rand = new Random();
                double theta;
                double distanceX, distanceY;
                double Radius;
                double x, y;
                double t;

                min = 0;
                for (int k = 0; k < Convs[0].Coef; k++)
                {
                    Radius = rand.NextDouble() * (SizeX * Convs[1].Coef);

                    if (Island)
                    {
                        theta     = rand.NextDouble() * Math.PI * 2;
                        t         = rand.NextDouble();
                        distanceX = t * (SizeX * Convs[2].Coef - Radius);
                        distanceY = t * (SizeY * Convs[2].Coef - Radius);
                        x         = SizeX / 2.0 + Math.Cos(theta) * distanceX;
                        y         = SizeY / 2.0 + Math.Sin(theta) * distanceY;
                    }
                    else
                    {
                        x = SizeX * rand.NextDouble();
                        y = SizeY * rand.NextDouble();
                    }

                    for (int i = 0; i < SizeX; i++)
                    {
                        for (int j = 0; j < SizeY; j++)
                        {
                            t = Radius * Radius - ((i - x) * (i - x) + (j - y) * (j - y));
                            if (t > 0)
                            {
                                ar[i, j] += t;
                            }

                            if (max < ar[i, j])
                            {
                                max = ar[i, j];
                            }
                            //if (min > ar[i, j]) min = ar[i, j];
                        }
                    }
                }
            }


            double coef = 1 / ((max - min));

            for (int i = 1; i < SizeX - 1; i++)
            {
                for (int j = 1; j < SizeY - 1; j++)
                {
                    if (Smoothing)
                    {
                        Heightmap[i, j] = (ar[i - 1, j - 1] + ar[i - 1, j] + ar[i - 1, j + 1] +
                                           ar[i, j - 1] + ar[i, j] + ar[i, j + 1] +
                                           ar[i + 1, j - 1] + ar[i + 1, j] + ar[i + 1, j + 1] - 9.0 * min) / (9.0 * (max - min));
                    }
                    else
                    {
                        Heightmap[i, j] = (ar[i, j] - min) * coef;
                    }
                    if (Valley)
                    {
                        Heightmap[i, j] = Math.Sqrt(Heightmap[i, j]);
                    }
                }
            }
        }