Exemplo n.º 1
0
        public NoiseControl()
        {
            InitializeComponent();

            var map = new NoiseMap();
            var builder = new PlaneNoiseMapBuilder()
            {
                DestNoiseMap = map,
            };
            builder.SetDestSize(pictureBox.Width, pictureBox.Height);
            m_noiseBuilder = builder;

            var image = new SharpNoise.Utilities.Imaging.Image();
            var renderer = new ImageRenderer()
            {
                SourceNoiseMap = map,
                DestinationImage = image,
            };

            if (greyRadioButton.Checked)
                renderer.BuildGrayscaleGradient();
            else if (terrainRadioButton.Checked)
                renderer.BuildTerrainGradient();
            else
                throw new Exception();

            m_imageRenderer = renderer;
        }
Exemplo n.º 2
0
        public GraniteTextureTest()
        {
            module = new Turbulence
            {
                Seed = 2,
                Frequency = 4,
                Power = 1.0 / 8.0,
                Roughness = 6,
                Source0 = new Add
                {
                    Source0 = new Billow
                    {
                        Seed = 1,
                        Frequency = 8,
                        Persistence = 0.625,
                        Lacunarity = 2.18359375,
                        OctaveCount = 6,
                    },
                    Source1 = new ScaleBias
                    {
                        Scale = -0.5,
                        Bias = 0,
                        Source0 = new Voronoi
                        {
                            Seed = 1,
                            Frequency = 16,
                            EnableDistance = true,
                        }
                    }
                }
            };

            noiseMap = new NoiseMap();

            textureImage = new Image();

            renderer = new ImageRenderer
            {
                EnableLight = true,
                LightAzimuth = 135,
                LightElevation = 60,
                LightContrast = 2,
                LightColor = new Color(255, 255, 255, 0),
            };
            renderer.AddGradientPoint(-1.0000, new Color(0, 0, 0, 255));
            renderer.AddGradientPoint(-0.9375, new Color(0, 0, 0, 255));
            renderer.AddGradientPoint(-0.8750, new Color(216, 216, 242, 255));
            renderer.AddGradientPoint(0.0000, new Color(191, 191, 191, 255));
            renderer.AddGradientPoint(0.5000, new Color(210, 116, 125, 255));
            renderer.AddGradientPoint(0.7500, new Color(210, 113, 98, 255));
            renderer.AddGradientPoint(1.0000, new Color(255, 176, 192, 255));
        }
Exemplo n.º 3
0
        private NoiseMap GenerateNoiseMap(int width, int height)
        {
            //module::Perlin myModule;
            var module = new LibNoise.Primitive.SimplexPerlin();

            //var module = new LibNoise.Primitive.BevinsGradient();
            //var module = new LibNoise.Primitive.ImprovedPerlin();
            module.Quality = NoiseQuality.Best;
            //module.Seed = PrimitiveModule.DefaultSeed;
            var random = new Random();

            module.Seed = random.Next();

            //ScaleBias scale = null;

            FilterModule fModule = new Pipe();

            fModule.Primitive3D = (IModule3D)module;
            fModule.OctaveCount = random.Next(1, 6);
            // 1;
            // FilterModule.DEFAULT_OCTAVE_COUNT;
            //fModule.Frequency = FilterModule.DEFAULT_FREQUENCY;
            //fModule.Gain = FilterModule.DEFAULT_GAIN;
            //fModule.Lacunarity = FilterModule.DEFAULT_LACUNARITY;
            //fModule.Offset = FilterModule.DEFAULT_OFFSET;
            //fModule.SpectralExponent = FilterModule.DEFAULT_SPECTRAL_EXPONENT;
            fModule.Frequency        = random.Next(1, 5);
            fModule.Gain             = 10;
            fModule.Lacunarity       = 10;
            fModule.Offset           = 10;
            fModule.SpectralExponent = 1;

            NoiseMap heightMap = new NoiseMap();

            heightMap.SetSize(width, height);
            float bound = 2f;
            //NoiseMapBuilderPlane heightMapBuilder = new NoiseMapBuilderPlane(bound, bound * 2, 0.0f, 100.0f, true);
            bool seemless = random.Next(0, 1) == 1;
            NoiseMapBuilderPlane heightMapBuilder = new NoiseMapBuilderPlane(bound, bound * 2, bound, bound * 2, seemless);

            heightMapBuilder.SourceModule = (IModule3D)fModule;
            heightMapBuilder.NoiseMap     = heightMap;
            heightMapBuilder.SetSize(width, height);
            heightMapBuilder.Build();
            return(heightMap);
        }
Exemplo n.º 4
0
    public void GenerateAndDisplayMap()
    {
        noiseMap = NoiseMap.GenerateNoiseMap(worldWidth, worldHeight, scale, octaves, persistance, lacunarity, animationCurve);

        MapDisplay   mapDisplay   = FindObjectOfType <MapDisplay>();
        MeshData     meshData     = MeshGenerator.GenerateMesh(noiseMap, meshMultiplier);
        Mesh         mesh         = meshData.CreateMesh();
        MeshCollider meshCollider = meshObject.GetComponent <MeshCollider>();

        if (meshCollider == null)
        {
            meshCollider = meshObject.AddComponent <MeshCollider>();
        }
        meshCollider.sharedMesh = mesh;
        mapDisplay.DrawMesh(mesh, mapDisplay.CreateTexture(worldWidth, worldHeight));
        textureData.ApplyToMaterial(meshObject.GetComponent <Renderer>().sharedMaterial, meshData.minHeight, meshData.maxHeight);
    }
Exemplo n.º 5
0
    public void SpeedMapGen()
    {
        //StartCoroutine("IE_SpeedMapGen");


        List <BlocToGen> mapBlocks = new List <BlocToGen>();

        mapBlocks = NoiseMap.Create(width, length, scale, xPos, zPos, seed, levels);

        foreach (BlocToGen tile in mapBlocks)
        {
            GameObject cube = Instantiate(Tools.GetMapGenLev(levels, tile.id).model, this.transform);
            cube.transform.position = this.transform.position + new Vector3(tile.x, 0, tile.z);
            cube.GetComponent <Block>().Set(tile.x, tile.z, tile.id, this);
            groundBlocks[(int)tile.x, (int)tile.z] = cube;
        }
    }
Exemplo n.º 6
0
 public static void VaryTileElevation(GameObject tileGameObject, NoiseMap noise)
 {
     MeshFilter[] meshFilters = tileGameObject.GetComponentsInChildren <MeshFilter>();
     Mesh[]       allMeshes   = new Mesh[meshFilters.Length];
     for (int i = 0; i < meshFilters.Length; i++)
     {
         allMeshes[i] = meshFilters[i].sharedMesh;
     }
     for (int i = 0; i < allMeshes.Length; i++)
     {
         Vector3[] vertices = allMeshes[i].vertices;
         for (int j = 0; j < vertices.Length; j++)
         {
             vertices[i] = new Vector3(vertices[i].x, noise.GetLayeredPerlinValueAtPosition(vertices[i].x, vertices[i].z), vertices[i].z);
         }
         allMeshes[i].vertices = vertices;
     }
 }
        private void GenerateTemperatureMap(int height)
        {
            var width   = 2 * height;
            var builder = new SphereNoiseMapBuilder();

            builder.SetDestSize(width, height);
            builder.SetBounds(-90, 90, -180, 180);
            TemperatureNoiseMap  = new NoiseMap();
            builder.SourceModule = TemperatureNoiseModule;
            builder.DestNoiseMap = TemperatureNoiseMap;
            builder.Build();

            var min = 10.0f;
            var max = -10.0f;

            for (var x = 0; x < width; x++)
            {
                for (var y = 0; y < height; y++)
                {
                    var value = TemperatureNoiseMap.GetValue(x, y);
                    if (value < min)
                    {
                        min = value;
                    }
                    else if (value > max)
                    {
                        max = value;
                    }
                }
            }

            for (var x = 0; x < width; x++)
            {
                for (var y = 0; y < height; y++)
                {
                    var value = TemperatureNoiseMap.GetValue(x, y);
                    value  = (value - min) / (max - min);
                    value  = 0.75f + 0.25f * value;
                    value *= (float)EffectiveTemperature;
                    TemperatureNoiseMap.SetValue(x, y, value);
                }
            }
        }
Exemplo n.º 8
0
        /// <summary>
        /// Generate the height map
        /// </summary>
        private void Generate()
        {
            //var bounds = new System.Drawing.RectangleF(6, 1, 3, 3);
            //var bounds = new System.Drawing.RectangleF(6, 1, 4, 4);
            var bounds      = new System.Drawing.RectangleF(6, 1, 5, 5);
            var noiseModule = this.BuildModuleTree();
            var noiseMap    = new NoiseMap();
            var builder     = new PlaneNoiseMapBuilder()
            {
                DestNoiseMap = noiseMap,
                SourceModule = noiseModule
            };

            builder.SetDestSize(this.Dimensions.Width, this.Dimensions.Height);

            builder.SetBounds(bounds.Left, bounds.Right, bounds.Top, bounds.Bottom);
            builder.Build();

            for (var ix = 0; ix < this.Dimensions.Width; ++ix)
            {
                for (var iy = 0; iy < this.Dimensions.Height; ++iy)
                {
                    this.Values[ix, iy] = noiseMap[ix, iy];
                }
            }

            this.Normalize();

            if (this.Parameters.ForceOceanSides)
            {
                this.MaskSides();
            }

            if (this.Parameters.AccentuateHills)
            {
                this.AccentuatePeaks();
                this.Normalize();
            }

            this.FillSinks();

            this.DetermineHeightLevels();
        }
Exemplo n.º 9
0
        public void initializeNoise(String preset, int seed, int noise_resolution, float amplitude, float persistance)
        {
            int noisePreset = 3;

            if (preset.Equals("default"))
            {
                noisePreset = 3;
            }
            else if (preset.Equals("amplified"))
            {
                noisePreset = 1;
            }
            else     // revert to default
            {
                noisePreset = 3;
            }
            noise = new FastPerlinNoise(noise_resolution, seed, amplitude, persistance);
            noise.setNoiseValues(NoiseMap.adjustNoise(noise.getNoiseValues(), noisePreset));
        }
Exemplo n.º 10
0
        /// Temporary method @TODO: Clean this shit.
        public void TempMapGen()
        {
            this.groundNoiseMap = NoiseMap.GenerateNoiseMap(this.size, 11, NoiseMap.GroundWave(42));

            foreach (Vector2Int position in this.rect)
            {
                this.Spawn(
                    position,
                    new Ground(
                        position,
                        Ground.GroundByHeight(this.groundNoiseMap[position.x + position.y * this.size.x])
                        )
                    );

                if (this.grids[Layer.Ground].GetTilableAt(position).def.uid == "rocks")
                {
                    this.Spawn(
                        position,
                        new Mountain(position, Defs.mountains["mountain"])
                        );
                }

                if (this[position].fertility > 0f && !this[position].blockPlant)
                {
                    foreach (TilableDef tilableDef in Defs.plants.Values)
                    {
                        if (
                            this[position].fertility >= tilableDef.plantDef.minFertility &&
                            Random.value <= tilableDef.plantDef.probability
                            )
                        {
                            this.Spawn(
                                position,
                                new Plant(position, tilableDef, true)
                                );
                            break;
                        }
                    }
                }
            }

            this.UpdateConnectedMountains();
        }
Exemplo n.º 11
0
    void Generate()
    {
        Destroy(Buildings);
        Buildings = new GameObject();
        Noise     = NoiseMap.GenerateNoiseMap(resolution, seed, scale, octaves, persistance, lacunarity, offset, size);
        float halfSize = size / 2f;

        for (int z = 0; z <= resolution; z++)
        {
            for (int x = 0; x <= resolution; x++)
            {
                GameObject b = GameObject.CreatePrimitive(PrimitiveType.Cube);
                b.transform.position   = new Vector3(x + x / (int)group.x * group.y, Noise[x, z] / 2, z + z / (int)group.x * group.y);
                b.transform.localScale = new Vector3(1f, Noise[x, z], 1f);
                b.transform.parent     = Buildings.transform;
                b.GetComponent <Renderer>().material = buildingMat[Random.Range(0, buildingMat.Count)];
            }
        }
    }
 public override void Setup()
 {
     if (heightMap == null)
     {
         heightMap = GetComponent <NoiseMap>();
     }
     if (heightMapGenerator == null)
     {
         heightMapGenerator = GetComponent <NoiseGenerator>();
     }
     if (biomeGenerator == null)
     {
         biomeGenerator = GetComponent <BiomeGenerator>();
     }
     if (terrain == null)
     {
         terrain = GetComponent <Terrain>();
     }
 }
Exemplo n.º 13
0
    public bool regenerateVoronoi(bool drawmesh)
    {
        if (GameControl.gameSession == null || (region = GameControl.gameSession.mapGenerator.getRegion()) == null)
        {
            //Debug.Log("Cannot regenerate Voronoi for Water - gameSession is not ready.");
            return(false);
        }

        // prepare noise
        int   noise_seed = (useRandomSeed) ? UnityEngine.Random.Range(int.MinValue, int.MaxValue) : this.seed;
        Noise noise      = new FastPerlinNoise(noiseResolution, noise_seed, noiseAmplitude, noisePersistance);

        noise.setNoiseValues(NoiseMap.adjustNoise(noise.getNoiseValues(), 5));

        // get region parameters
        this.water_elevation = region.getWaterLevelElevation();
        this.size            = region.getViewableSize();
        int halfSize = this.size / 2;

        // generate random coordinates for polygons
        generateXY(out this.X, out this.Y);

        // use voronoi generator
        voronoi = new Voronoi(minDist);
        voronoi.generateVoronoi(X, Y, 0, size, 0, size);

        VoronoiGraph vG = voronoi.getVoronoiGraph();

        foreach (GraphEdge gE in vG.edges)
        {
            gE.x1 -= halfSize;
            gE.x2 -= halfSize;
            gE.y1 -= halfSize;
            gE.y2 -= halfSize;
        }

        if (drawmesh)
        {
            Meshes.WaterMesh.InitializeMesh(region, voronoi.getVoronoiGraph(), mesh, noise, maxWaterLevelDisplacement);
        }
        return(true);
    }
Exemplo n.º 14
0
        public static void PrintNoiseMap(MPos bounds, NoiseMap map)
        {
            using var image = new Bitmap(bounds.X, bounds.Y);

            for (int x = 0; x < bounds.X; x++)
            {
                for (int y = 0; y < bounds.Y; y++)
                {
                    var value = (int)(map[x, y] * 255);
                    var color = System.Drawing.Color.FromArgb(value, value, value);

                    image.SetPixel(x, y, color);
                }
            }
            var path = FileExplorer.Logs + "debugMaps/";

            checkDirectory(path);

            image.Save(path + $"noisemap{map.ID}.png");
        }
Exemplo n.º 15
0
        public NoiseMap Get(ChunkCoordinates coordinates)
        {
            int cx = (coordinates.X * 16);
            int cz = (coordinates.Z * 16);

            NoiseMap noiseMap = new NoiseMap(new float[16 * 16]);

            for (int x = 0; x < 16; x++)
            {
                float rx = cx + x;

                for (int z = 0; z < 16; z++)
                {
                    float rz = cz + z;
                    noiseMap.Set(x, z, Module.GetValue(rx, rz));
                }
            }

            return(noiseMap);
        }
Exemplo n.º 16
0
        public OverworldMap(int width, int height)
        {
            SingletonRandom.DefaultRNG = new Troschuetz.Random.Generators.XorShift128Generator(Data.World.GetSeed());
            Width           = width;
            Height          = height;
            RawOverworldMap = new ArrayMap <bool>(Width, Height);
            voronoiNoiseMap = ZoneGenerator.Generate(width, height);
            OverWorld       = new OverworldTile[Width * Height];
            masterNoise     = new PerlinGenerator(Width, Height);
            masterNoise.ConfigureAll(4, 1, 0.25D, 2);
            CellularAutomataAreaGenerator.Generate(RawOverworldMap, null, 45, 8, 2);
            OrderedMapAreaConnector.Connect(RawOverworldMap, AdjacencyRule.EIGHT_WAY);
            DeadEndTrimmer.Trim(RawOverworldMap);
            RemoveLandmassByVoronoiNoise(RawOverworldMap);
            var perspnoise = masterNoise.Generate();

            rainNoise = perspnoise;
            NormalizePersp();
            BuildOverWorld(RawOverworldMap, OverWorld);
        }
Exemplo n.º 17
0
    Texture2D GetNoiseTexture(NoiseMap noiseMap) //move this?
    {
        Texture2D texture = (Texture2D)material.mainTexture;

        if (texture == null || texture.width != textureResolution)
        {
            texture = new Texture2D(textureResolution, textureResolution);
        }

        for (int y = 0; y < textureResolution; y++)
        {
            for (int x = 0; x < textureResolution; x++)
            {
                float t = Mathf.InverseLerp(noiseMap.minValue, noiseMap.maxValue, noiseMap.GetNoiseValue(x, y));
                texture.SetPixel(x, y, Color.Lerp(Color.black, Color.white, t));
            }
        }
        //texture.filterMode = FilterMode.Trilinear;
        texture.Apply();
        return(texture);
    }
Exemplo n.º 18
0
        private Image getNoise(int startx, int starty, float down)
        {
            Color[,] colors = new Color[800, 600];
            NoiseMap mapr = Utils.getNoiseMap(startx, starty, 3, 3, 2.5, 0.5);
            NoiseMap mapg = Utils.getNoiseMap(startx + 100, starty + 100, 3, 3, 2.5, 0.5);
            NoiseMap mapb = Utils.getNoiseMap(startx + 200, starty + 200, 3, 3, 2.5, 0.5);
            NoiseMap mapa = Utils.getNoiseMap(startx + 700, starty + 700, 2, 2, 0.7, 0.3);

            for (int i = 0; i < 800; i++)
            {
                for (int j = 0; j < 600; j++)
                {
                    byte r = Utils.NormNoise(mapr.GetValue(i, j));
                    byte g = Utils.NormNoise(mapg.GetValue(i, j));
                    byte b = Utils.NormNoise(mapb.GetValue(i, j));
                    byte a = Utils.NormNoise(mapa.GetValue(i, j) - (down));
                    colors[i, j] = new Color(r, g, b, a);
                }
            }
            return(new Image(colors));
        }
        private void GenerateHeightMap(int height)
        {
            var width   = 2 * height;
            var builder = new SphereNoiseMapBuilder();

            builder.SetDestSize(width, height);
            builder.SetBounds(-90, 90, -180, 180);
            HeightNoiseMap       = new NoiseMap();
            builder.SourceModule = HeightNoiseModule;
            builder.DestNoiseMap = HeightNoiseMap;
            builder.Build();

            MinHeight = 10.0f;
            MaxHeight = -10.0f;
            for (var x = 0; x < width; x++)
            {
                for (var y = 0; y < height; y++)
                {
                    var value = HeightNoiseMap.GetValue(x, y);
                    if (value < MinHeight)
                    {
                        MinHeight = value;
                    }
                    else if (value > MaxHeight)
                    {
                        MaxHeight = value;
                    }
                }
            }

            for (var x = 0; x < width; x++)
            {
                for (var y = 0; y < height; y++)
                {
                    var value = HeightNoiseMap.GetValue(x, y);
                    value = (value - MinHeight) / (MaxHeight - MinHeight);
                    HeightNoiseMap.SetValue(x, y, value);
                }
            }
        }
Exemplo n.º 20
0
        protected void initialize()
        {
            Id        = guardIds;
            guardIds += GameMasterOne.dataTypes;

            //myOrientationBehavior = new TileBehaviorSquare();
            MyNPCBehavior = new NPCBehaviorNPC();
            //myKnownNoiseBehavior = new KnownNoiseMapBehaviorAllGuards();

            MyNoiseMap = new NoiseMap();
            myFOV      = new List <IPoint>();

            this.addStat(new Stat("Strength", 0));
            this.addStat(new Stat("Armor", 0));
            this.addStat(new Stat("Weapon Skill", 0));
            this.addStat(new Stat("Perception", 0));
            this.addStat(new Stat("Intelligence", 0));
            this.addStat(new Stat("Dexterity", 0));
            this.addStat(new Stat("Suspicion", 0));
            this.addStat(new Stat("Alert Status", 0));
            this.addStat(new Stat("Field of View", 0));
            this.addStat(new Stat("Suspicion Propensity", 0));
            this.addStat(new Stat("AP", 0));
            this.addStat(new Stat("Knows Map", 0));
            this.addStat(new Stat("Turn Over", 0));
            this.addStat(new Stat("Remaining AP", this.getStat("AP").Value));
            this.addStat(new Stat("Movement Cost", SneakingWorld.getValueByName("movementCost")));
            this.addStat(new Stat("Turns In Place", 0));
            this.addStat(new Stat("Active", 0));
            this.addStat(new Stat("Selected", 0));
            this.addStat(new Stat("Is Visible", 0));
            this.addStat(new Stat("Is Dead", 0));
            this.addStat(new Stat("Health", this.getStat("Strength").BaseValue *3));

            //Status
            this.addStat(new Stat("Status Normal", 5));
            this.addStat(new Stat("Status Suspicious", 10));
            this.addStat(new Stat("Status Alert", 15));
            this.getStat("Alert Status").ItsMax = (int)this.getStat("Status Alert").BaseValue;
        }
Exemplo n.º 21
0
        private static void PostProcessing(Size size, NoiseConfig cfg, NoiseMap noiseMap)
        {
            var po = new ParallelOptions()
            {
                CancellationToken = new CancellationToken(),
            };

            Parallel.For(0, size.Height, po, y =>
            {
                for (int x = 0; x < size.Width; x++)
                {
                    var v          = noiseMap[x, y];
                    v             *= cfg.Scale;
                    v              = v < cfg.MinThreshold ? cfg.MinThreshold : v;
                    v              = v > cfg.MaxThreshold ? cfg.MaxThreshold : v;
                    v              = cfg.Invert ? 1f - v : v;
                    v              = cfg.Round ? (int)Math.Round(v) : v;
                    v              = Math.Clamp(Math.Abs(v), 0f, 1f);
                    noiseMap[x, y] = v;
                }
            });
        }
        void generateKey(Piece piece, NoiseMap noise)
        {
            var exitExists = Loader.Exit == CPos.Zero;
            var mapLength  = Bounds.Dist * 256;

            var dist      = Random.Next(8);
            var spawnArea = Bounds - (piece.Size + new MPos(dist, dist));

            MPos             pos;
            WaypointLocation location;
            var success = false;

            do
            {
                pos = getPosNearBorder(spawnArea, out location);

                // Don't spawn near exits
                if (exitExists && (pos.ToCPos() - Loader.Exit).SquaredFlatDist < mapLength)
                {
                    continue;
                }

                if (info.NoiseMapID >= 0 && Random.NextDouble() > noise[pos.X, pos.Y] + 0.1f)
                {
                    continue;
                }

                success = Loader.GenerateCrucialPiece(piece, pos);
                if (success)
                {
                    markDirty(pos, piece);
                }
            }while (!success);

            if (info.IsWaypoint)
            {
                addWaypoint(piece, pos, location);
            }
        }
Exemplo n.º 23
0
        public HeightmapTile GenerateTile(int offsetX, int offsetY)
        {
            var noiseMap = new NoiseMap();

            projection = new NoiseMapBuilderPlane(offsetX * size, (offsetX * size) + size, offsetY * size, (offsetY * size) + size, true);
            projection.SetSize(size, size);
            projection.SourceModule = filter;
            projection.NoiseMap = noiseMap;
            projection.Build();

            var tileData = new double[size * size];

            for (int y = 0; y < size; y++)
            {
                for (int x = 0; x < size; x++)
                {
                    tileData[y * size + x] = projection.NoiseMap.GetValue(x, y);
                }
            }

            return new HeightmapTile(tileData, new Vector2(offsetX, offsetY));
        }
Exemplo n.º 24
0
    /// Handling textures for heightmaps and clipsmaps -----------------------------------------------------------------------------------------------
    #region MapTextureManipulation


    public void CalcNoise(NoiseMap noiseMap)
    {
        // For each pixel in the texture...
        int y = 0;

        while (y < noiseMap.noiseMap.height)
        {
            int x = 0;
            while (x < noiseMap.noiseMap.width)
            {
                float xCoord = ((float)x / noiseMap.noiseMap.width) * noiseMap.scale + noiseMap.offSet.x;
                float yCoord = ((float)y / noiseMap.noiseMap.height) * noiseMap.scale + noiseMap.offSet.y;
                float value  = Mathf.PerlinNoise(xCoord, yCoord);
                noiseMap.noiseMap.SetPixel(x, y, new Color(value, value, value));

                x++;
            }
            y++;
        }

        noiseMap.noiseMap.Apply();
    }
        private void GenerateRingMap(int width)
        {
            var height = 32;

            RingNoiseModule = Random.Perlin("ring noise", 0.25, 2, 1.8, 2.2, 10, 16, 0.65, 0.75);
            RingNoiseModule = new Add
            {
                Source0 = RingNoiseModule,
                Source1 = new Constant {
                    ConstantValue = Random.Uniform("ring offset", -0.5, 0.5)
                }
            };

            var builder = new SphereNoiseMapBuilder();

            RingNoiseMap         = new NoiseMap();
            builder.SourceModule = RingNoiseModule;
            builder.SetDestSize(width, height);
            builder.DestNoiseMap = RingNoiseMap;
            builder.SetBounds(0, 0.00000001, -180, 180);
            builder.Build();
        }
Exemplo n.º 26
0
        private static Bitmap CreateBitmap(Size size, NoiseMap map, NoiseConfig cfg)
        {
            var image    = new SharpNoise.Utilities.Imaging.Image(size.Width, size.Height);
            var renderer = new ImageRenderer
            {
                SourceNoiseMap   = map,
                DestinationImage = image
            };

            if (cfg.OutputGrayscale)
            {
                BuildGrayscaleRenderer(renderer);
            }
            else
            {
                BuildTerrainRenderer(renderer);
            }

            renderer.Render();

            return(image.ToGdiBitmap());
        }
Exemplo n.º 27
0
        public Bitmap Render()
        {
            NoiseMap noise = new NoiseMap(this.Map.MapWidth, this.Map.MapHeight);

            // Copy map data to noise map.
            for (int z = 0; z < noise.Height; z++)
            {
                for (int x = 0; x < noise.Width; x++)
                {
                    noise.SetValue(x, z, this.Map.HeightMap[x, z] * this.Map.Resolution);
                }
            }

            this.Renderer.NoiseMap = noise;

            BitmapAdaptater adapter = new BitmapAdaptater(noise.Width, noise.Height);

            this.Renderer.Image = adapter;
            this.Renderer.Render();
            this.Image = adapter.Bitmap;
            return(this.Image);
        }
        public NoiseMap Get(ChunkCoordinates coordinates)
        {
            int minX = ((coordinates.X) * 16);
            int minZ = ((coordinates.Z) * 16);
            var maxX = ((coordinates.X + 1) << 4);
            var maxZ = ((coordinates.Z + 1) << 4);

            int cx = (coordinates.X * 16);
            int cz = (coordinates.Z * 16);

            float q11 = Module.GetValue(minX, minZ);
            float q12 = Module.GetValue(minX, maxZ);

            float q21 = Module.GetValue(maxX, minZ);
            float q22 = Module.GetValue(maxX, maxZ);

            NoiseMap noiseMap = new NoiseMap(new float[16 * 16]);

            for (int x = 0; x < 16; x++)
            {
                float rx = cx + x;

                for (int z = 0; z < 16; z++)
                {
                    float rz = cz + z;

                    noiseMap.Set(x, z, MathUtils.BilinearCmr(
                                     rx, rz,
                                     q11,
                                     q12,
                                     q21,
                                     q22,
                                     minX, maxX, minZ, maxZ));
                }
            }

            return(noiseMap);
        }
    public void MapGeneration()
    {
        float[,] noiseMap = NoiseMap.GenerateNoiseMap(mapWidth, mapHeight, seed, noiseScale, octaves, persistance, lacunarity, offSet);

        Color[] colorMap = new Color[mapWidth * mapHeight];

        for (int yy = 0; yy < mapHeight; yy++)
        {
            for (int xx = 0; xx < mapWidth; xx++)
            {
                float currentHeight = noiseMap[xx, yy];

                for (int ii = 0; ii < regions.Length; ii++)
                {
                    if (currentHeight <= regions[ii].height)
                    {
                        colorMap[yy * mapWidth + xx] = regions[ii].color;
                        break;
                    }
                }
            }
        }

        MapDisplay display = FindObjectOfType <MapDisplay>();

        if (drawMode == DrawMode.NoiseMap)
        {
            display.DrawTexture(TextureGenerator.TextureFromHeightMap(noiseMap));
        }
        else if (drawMode == DrawMode.colorMap)
        {
            display.DrawTexture(TextureGenerator.TextureFromHeightMap(noiseMap));
        }
        else if (drawMode == DrawMode.Mesh)
        {
            display.DrawMesh(MapMeshGenerator.GenerateMapMesh(noiseMap, meshHeightMulti, meshHeightCurve), TextureGenerator.TextureFromColorMap(colorMap, mapWidth, mapHeight));
        }
    }
Exemplo n.º 30
0
        private Image getPlanetSurface(int startx, int starty)
        {
            Color[,] colors = new Color[800, 600];
            NoiseMap mapr = Utils.getNoiseMap(startx, starty, 12, 12, 2.7, 0.8);

            for (int i = 0; i < 800; i++)
            {
                for (int j = 0; j < 600; j++)
                {
                    byte r = Utils.NormNoise(mapr.GetValue(i, j));
                    colors[i, j] = new Color(r, r, r);
                }
            }
            GradientBuilder grad = new GradientBuilder();

            grad.AddGradient(new Gradient(0, Color.Blue));
            grad.AddGradient(new Gradient(50, Color.Yellow));
            grad.AddGradient(new Gradient(140, Color.Green));
            grad.AddGradient(new Gradient(255, Color.White));
            grad.PrepareGradients();
            grad.SourceImage = new Image(colors);
            return(grad.Render());
        }
Exemplo n.º 31
0
        private void SetBiomeBlocks(ChunkColumn chunk, ChunkLandscape landscape)
        {
            int worldX = chunk.X * 16;
            int worldZ = chunk.Z * 16;

            var coords = new BlockCoordinates(worldX, 0, worldZ);

            for (int x = 0; x < 16; x++)
            {
                coords.X = worldX + x;
                for (int z = 0; z < 16; z++)
                {
                    coords.Z = worldZ + z;

                    var index = NoiseMap.GetIndex(x, z);
                    var river = landscape.River[index];
                    int depth = -1;

                    landscape.Biome[index].Replace(chunk, coords, x, z, depth, this, landscape.Noise, river, landscape.Biome);
                    chunk.biomeId[index] = (byte)landscape.Biome[index].Id;
                }
            }
        }
    public void TileGenerator()
    {
        if (randomSeed)
        {
            seed = Random.Range(0, 100000);
        }
        noiseMap             = new float[mapSize, mapSize];
        float [,] falloffMap = FalloffGenerator.GenerateFalloffMap(mapSize);

        for (int y = 0; y < mapSize; y++)
        {
            for (int x = 0; x < mapSize; x++)
            {
                noiseMap[x, y] = NoiseMap.fBM(x, y, seed, scale, octaves, persistence);
            }
        }

        tilemap.ClearAllTiles();

        if (tilemode == Tilemode.LandscapeMap)
        {
            GenerateLandscape(noiseMap, falloffMap);
        }
        else if (tilemode == Tilemode.NoiseMap)
        {
            NoiseMapGenerator(noiseMap);
        }
        else if (tilemode == Tilemode.FalloffMap)
        {
            NoiseMapGenerator(falloffMap);
        }
        else if (tilemode == Tilemode.CaveGeneration)
        {
            GenerateCave();
        }
        RuleTileGenerator(dirtRuleTile);
    }
Exemplo n.º 33
0
        public async void SameAsync()
        {
            OverworldTerrainSettings generatorSettings = new OverworldTerrainSettings();

            generatorSettings.Seed = 137;
            OverworldTerrain noiseGen = new OverworldTerrain(generatorSettings, true);

            var map = new NoiseMap();

            PlaneNoiseMapBuilder builder = new PlaneNoiseMapBuilder()
            {
                DestNoiseMap = map,
                SourceModule = noiseGen.Result
            };

            var image    = new SharpNoise.Utilities.Imaging.Image();
            var renderer = new ImageRenderer()
            {
                SourceNoiseMap   = map,
                DestinationImage = image
            };

            //renderer.BuildGrayscaleGradient();
            renderer.BuildTerrainGradient();

            builder.SetBounds(-2024, 2024, -2024, 2024);
            builder.SetDestSize(1024, 1024);
            builder.Build();

            renderer.Render();

            var bmp = renderer.DestinationImage.ToGdiBitmap();

            bmp.Save("terrain.bmp");

            Assert.Equal(0, 0);
        }
Exemplo n.º 34
0
        /// <summary>
        /// 
        /// </summary>
        protected void GenerateNoise()
        {
            EnabledInterface(false);

            // Parse input ------------------------------------------------------------------------------------
            int seed = ParseInt(_tbxSeed.Text, PrimitiveModule.DEFAULT_SEED);
            float frequency = ParseFloat(_tbxFrequency.Text, FilterModule.DEFAULT_FREQUENCY);
            float lacunarity = ParseFloat(_tbxLacunarity.Text, FilterModule.DEFAULT_LACUNARITY);
            float gain = ParseFloat(_tbxGain.Text, FilterModule.DEFAULT_GAIN);
            float offset = ParseFloat(_tbxOffset.Text, FilterModule.DEFAULT_OFFSET);
            float exponent = ParseFloat(_tbxExponent.Text, FilterModule.DEFAULT_SPECTRAL_EXPONENT);
            var octaveCount = (int) _nstpOctave.Value;
            bool seamless = _chkbx.Checked;

            GradientColor gradient = GradientColor.GRAYSCALE;
            NoiseQuality quality = PrimitiveModule.DEFAULT_QUALITY;
            var primitive = NoisePrimitive.ImprovedPerlin;
            var filter = NoiseFilter.SumFractal;

            try
            {
                quality = (NoiseQuality) Enum.Parse(typeof (NoiseQuality), _cbxQuality.Text);
            }
            catch
            {
                MessageBox.Show(
                    String.Format("Unknown quality '{0}'", _cbxQuality.Text),
                    "Libnoise Error",
                    MessageBoxButtons.OK,
                    MessageBoxIcon.Error
                    );

                EnabledInterface(true);

                return;
            }

            try
            {
                primitive = (NoisePrimitive) Enum.Parse(typeof (NoisePrimitive), _cbxPrimitive.Text);
            }
            catch
            {
                MessageBox.Show(
                    String.Format("Unknown primitive '{0}'", _cbxPrimitive.Text),
                    "Libnoise Error",
                    MessageBoxButtons.OK,
                    MessageBoxIcon.Error
                    );

                EnabledInterface(true);

                return;
            }

            try
            {
                filter = (NoiseFilter) Enum.Parse(typeof (NoiseFilter), _cbxFilter.Text);
            }
            catch
            {
                MessageBox.Show(
                    String.Format("Unknown filter '{0}'", _cbxFilter.Text),
                    "Libnoise Error",
                    MessageBoxButtons.OK,
                    MessageBoxIcon.Error
                    );

                EnabledInterface(true);

                return;
            }

            switch (_cbxGradient.Text)
            {
                case "Grayscale":
                    gradient = GradientColor.GRAYSCALE;
                    break;

                case "Terrain":
                    gradient = GradientColor.TERRAIN;
                    break;
            }

            // Create module tree ------------------------------------------------------------------------------------

            PrimitiveModule pModule = null;

            switch (primitive)
            {
                case NoisePrimitive.Constant:
                    pModule = new Constant(offset);
                    break;

                case NoisePrimitive.Cylinders:
                    pModule = new Cylinders(offset);
                    seamless = false;
                    break;

                case NoisePrimitive.Spheres:
                    pModule = new Spheres(offset);
                    seamless = false;
                    break;

                case NoisePrimitive.BevinsGradient:
                    pModule = new BevinsGradient();
                    break;

                case NoisePrimitive.BevinsValue:
                    pModule = new BevinsValue();
                    break;

                case NoisePrimitive.ImprovedPerlin:
                    pModule = new ImprovedPerlin();
                    break;

                case NoisePrimitive.SimplexPerlin:
                    pModule = new SimplexPerlin();
                    break;
            }

            pModule.Quality = quality;
            pModule.Seed = seed;

            FilterModule fModule = null;
            ScaleBias scale = null;

            switch (filter)
            {
                case NoiseFilter.Pipe:
                    fModule = new Pipe();
                    break;

                case NoiseFilter.SumFractal:
                    fModule = new SumFractal();
                    break;

                case NoiseFilter.SinFractal:
                    fModule = new SinFractal();
                    break;

                case NoiseFilter.MultiFractal:
                    fModule = new MultiFractal();
                    // Used to show the difference with our gradient color (-1 + 1)
                    scale = new ScaleBias(fModule, 1f, -0.8f);
                    break;

                case NoiseFilter.Billow:
                    fModule = new Billow();
                    ((Billow) fModule).Bias = -0.2f;
                    ((Billow) fModule).Scale = 2f;
                    break;

                case NoiseFilter.HeterogeneousMultiFractal:
                    fModule = new HeterogeneousMultiFractal();
                    // Used to show the difference with our gradient color (-1 + 1)
                    scale = new ScaleBias(fModule, -1f, 2f);
                    break;

                case NoiseFilter.HybridMultiFractal:
                    fModule = new HybridMultiFractal();
                    // Used to show the difference with our gradient color (-1 + 1)
                    scale = new ScaleBias(fModule, 0.7f, -2f);
                    break;

                case NoiseFilter.RidgedMultiFractal:
                    fModule = new RidgedMultiFractal();
                    // Used to show the difference with our gradient color (-1 + 1)
                    scale = new ScaleBias(fModule, 0.9f, -1.25f);
                    break;

                case NoiseFilter.Voronoi:
                    fModule = new Voronoi();
                    break;
            }

            fModule.Frequency = frequency;
            fModule.Lacunarity = lacunarity;
            fModule.OctaveCount = octaveCount;
            fModule.Offset = offset;
            fModule.Offset = offset;
            fModule.Gain = gain;
            fModule.Primitive3D = (IModule3D) pModule;

            IModule3D finalModule;

            if (scale == null)
                finalModule = (IModule3D) fModule;
            else
                finalModule = scale;

            NoiseMapBuilder projection;

            switch (_cbxProjection.Text)
            {
                case "Spherical":
                    projection = new NoiseMapBuilderSphere();
                    ((NoiseMapBuilderSphere) projection).SetBounds(-90f, 90f, -180f, 180f); // degrees
                    break;

                case "Cylindrical":
                    projection = new NoiseMapBuilderCylinder();
                    ((NoiseMapBuilderCylinder) projection).SetBounds(-180f, 180f, -10f, 10f);
                    break;

                case "Planar":
                default:
                    float bound = 2f;
                    projection = new NoiseMapBuilderPlane(bound, bound*2, bound, bound*2, seamless);
                    //projection = new NoiseMapBuilderPlane(-bound, bound, -bound, bound, seamless);
                    //projection = new NoiseMapBuilderPlane(0, bound, 0, bound, seamless);
                    break;
            }

            int width = 0;
            int height = 0;

            switch (_cbxSize.Text)
            {
                case "256 x 256":
                    width = 256;
                    height = 256;
                    break;

                case "512 x 512":
                    width = 512;
                    height = 512;
                    break;

                case "1024 x 1024":
                    width = 1024;
                    height = 1024;
                    break;

                case "256 x 128":
                    width = 256;
                    height = 128;
                    break;

                case "512 x 256":
                    width = 512;
                    height = 256;
                    break;

                case "1024 x 512":
                    width = 1024;
                    height = 512;
                    break;

                case "2048 x 1024":
                    width = 2048;
                    height = 1024;
                    break;
                default:

                case "128 x 128":
                    width = 128;
                    height = 128;
                    break;
            }

            // ------------------------------------------------------------------------------------------------
            // 0 - Initializing
            _prbarRenderProgression.Visible = true;
            _lblProgressPercent.Visible = true;
            _prbarRenderProgression.Value = 0;
            ;
            _lblProgressPercent.Text = "";

            _lblLog.Text = String.Format("Create a {0} image with a {1} projection\n", _cbxSize.Text,
                _cbxProjection.Text);

            var watchDog = new Stopwatch();
            TimeSpan ts;
            double elaspedTime = 0;

            //
            // ------------------------------------------------------------------------------------------------
            // 1 - Build the noise map
            watchDog.Reset();

            _prbarRenderProgression.Value = 0;
            _lblLog.Text += "Building noise map ... ";

            var noiseMap = new NoiseMap();

            /*
            // ShapeFilter test
            Bitmap bmpShape = new Bitmap("smileyShape.bmp");
            BitmapAdaptater bmShapeAdaptater = new BitmapAdaptater(bmpShape);

            ShapeFilter shapeFilter = new ShapeFilter();
            shapeFilter.Shape = bmShapeAdaptater;

            projection.Filter = shapeFilter;
            */

            projection.SetSize(width, height);
            projection.SourceModule = finalModule;
            projection.NoiseMap = noiseMap;
            projection.CallBack = delegate(int line)
            {
                line++;

                watchDog.Stop();

                //Process message
                Application.DoEvents();

                _prbarRenderProgression.Value = (line*100/height);
                _lblProgressPercent.Text = String.Format("{0} % - {1} line(s)", _prbarRenderProgression.Value, line);

                watchDog.Start();
            };

            watchDog.Start();
            projection.Build();
            watchDog.Stop();

            ts = watchDog.Elapsed;
            elaspedTime += ts.TotalMilliseconds;

            _lblLog.Text += String.Format("{0:00}:{1:00} {2:00},{3:0000}\n",
                ts.Hours, ts.Minutes,
                ts.Seconds, ts.Milliseconds*10
                );

            // ------------------------------------------------------------------------------------------------
            // 2 - Render image
            // Create a renderer, BitmapAdaptater create a System.Drawing.Bitmap on the fly
            watchDog.Reset();
            _prbarRenderProgression.Value = 0;
            _lblLog.Text += "Rendering image ... ";

            var renderer = new ImageRenderer();
            renderer.NoiseMap = noiseMap;
            renderer.Gradient = gradient;
            renderer.LightBrightness = 2;
            renderer.LightContrast = 8;
            //renderer.LightEnabled = true;

            // Libnoise image struct strategy
            //Graphics.Tools.Noise.Renderer.Image image = new Graphics.Tools.Noise.Renderer.Image();
            //renderer.Image = image;

            // Dotnet Bitmap Strategy
            var bmpAdaptater = new BitmapAdaptater(width, height);
            renderer.Image = bmpAdaptater;

            renderer.CallBack = delegate(int line)
            {
                line++;

                watchDog.Stop();

                //Process message
                Application.DoEvents();

                _prbarRenderProgression.Value = (line*100/height);
                _lblProgressPercent.Text = String.Format("{0} % - {1} line(s)", _prbarRenderProgression.Value, line);

                watchDog.Start();
            };

            // Render the texture.
            watchDog.Start();
            renderer.Render();
            watchDog.Stop();

            ts = watchDog.Elapsed;
            elaspedTime += ts.TotalMilliseconds;

            _lblLog.Text += String.Format("{0:00}:{1:00} {2:00},{3:0000}\n",
                ts.Hours, ts.Minutes,
                ts.Seconds, ts.Milliseconds*10
                );

            //----------------------------------------
            // Normalmap rendering test
            //
            /*
            BitmapAdaptater nmapAdaptater = new BitmapAdaptater(width, height);
            NormalMapRenderer nmap = new NormalMapRenderer();
            nmap.Image = nmapAdaptater;
            nmap.BumpHeight = 30.0f;
            nmap.NoiseMap = noiseMap;
            nmap.Render();
            nmapAdaptater.Bitmap.Save("normalMap.png", ImageFormat.Png);
            */
            //----------------------------------------

            /*
            Heightmap8 heightmap8 = new Heightmap8();
            Heightmap8Renderer heightmapRenderer = new Heightmap8Renderer();
            heightmapRenderer.Heightmap = heightmap8;
            */

            /*
            Heightmap16 heightmap16 = new Heightmap16();
            Heightmap16Renderer heightmapRenderer = new Heightmap16Renderer();
            heightmapRenderer.Heightmap = heightmap16;
            */

            /*
            Heightmap32 heightmap32 = new Heightmap32();
            Heightmap32Renderer heightmapRenderer = new Heightmap32Renderer();
            heightmapRenderer.Heightmap = heightmap32;
            */

            /*
            heightmapRenderer.NoiseMap = noiseMap;
            heightmapRenderer.ExactFit();
            heightmapRenderer.Render();
            */

            /*
            Heightmap16RawWriter rawWriter = new Heightmap16RawWriter();
            rawWriter.Heightmap = heightmap16;
            rawWriter.Filename = "heightmap16.raw";
            rawWriter.WriteFile();
            */

            // ------------------------------------------------------------------------------------------------
            // 3 - Painting

            // Save the file
            //bmpAdaptater.Bitmap.Save("rendered.png",ImageFormat.Png);
            _imageRendered.Width = width;
            _imageRendered.Height = height;

            //_imageRendered.Image = _bitmap;
            _imageRendered.Image = bmpAdaptater.Bitmap;

            if (_imageRendered.Width > _panImageViewport.Width)
                _imageRendered.Left = 0;
            else
                _imageRendered.Left = (_panImageViewport.Width - _imageRendered.Width)/2;

            if (_imageRendered.Height > _panImageViewport.Height)
                _imageRendered.Top = 0;
            else
                _imageRendered.Top = (_panImageViewport.Height - _imageRendered.Height)/2;

            if (_imageRendered.Width > _panImageViewport.Width || _imageRendered.Height > _panImageViewport.Height)
            {
                _imageRendered.Anchor = (AnchorStyles.Left | AnchorStyles.Top);
                _panImageViewport.AutoScroll = true;
            }
            else
                _panImageViewport.AutoScroll = false;

            // ----------------------------------------------------------------

            ts = TimeSpan.FromMilliseconds(elaspedTime);

            // Format and display the TimeSpan value.
            _lblLog.Text += String.Format("Duration : {0:00}:{1:00} {2:00},{3:0000}\n",
                ts.Hours, ts.Minutes,
                ts.Seconds, ts.Milliseconds*10
                );

            EnabledInterface(true);

            _prbarRenderProgression.Value = 0;
            _lblProgressPercent.Text = "";
            _prbarRenderProgression.Visible = false;
            _lblProgressPercent.Visible = false;
        }
Exemplo n.º 35
0
        void SetupNoiseMapBuilder()
        {
            // Set up noise module tree
            // TranslatePoint is used to shift the generated noise over time
            TimeTranslator = new TranslatePoint
            {
                // Scales the generated noise values down to 80%
                Source0 = new ScaleBias
                {
                    Scale = 0.8,
                    Bias = 0,
                    // Scale coordinates down to get some rougher structures
                    Source0 = new ScalePoint
                    {
                        // Scale down xz-plane
                        XScale = 0.0375,
                        ZScale = 0.0375,
                        // Scale down "time"
                        YScale = 0.625,
                        Source0 = new Billow(),
                    },
                },
            };

            // Set up target noise map and noise map builder
            NoiseMap = new NoiseMap();
            NoiseMapBuilder = new PlaneNoiseMapBuilder
            {
                DestNoiseMap = NoiseMap,
                SourceModule = TimeTranslator,
            };
            NoiseMapBuilder.SetBounds(0, LongitudeBands, 0, LatitudeBands);
            NoiseMapBuilder.SetDestSize(LongitudeBands, LatitudeBands);
        }
Exemplo n.º 36
0
 public MapTests()
 {
     map = new NoiseMap(2, 2);
 }
Exemplo n.º 37
0
        public WoodTextureTest()
        {
            module = new Turbulence
            {
                Seed = 2,
                Frequency = 2,
                Power = 1.0 / 64.0,
                Roughness = 4,
                Source0 = new RotatePoint
                {
                    XAngle = 84,
                    Source0 = new TranslatePoint
                    {
                        ZTranslation = 1.48,
                        Source0 = new Turbulence
                        {
                            Seed = 1,
                            Frequency = 4,
                            Power = 1.0 / 256.0,
                            Roughness = 4,
                            Source0 = new Add
                            {
                                Source0 = new Cylinders
                                {
                                    Frequency = 16,
                                },
                                Source1 = new ScaleBias
                                {
                                    Scale = 0.25,
                                    Bias = 0.125,
                                    Source0 = new ScalePoint
                                    {
                                        YScale = 0.25,
                                        Source0 = new Perlin
                                        {
                                            Seed = 2135,
                                            Frequency = 48,
                                            Persistence = 0.5,
                                            Lacunarity = 2.20703125,
                                            OctaveCount = 3,
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            };

            noiseMap = new NoiseMap();

            textureImage = new Image();

            renderer = new ImageRenderer
            {
                EnableLight = false,
            };
            renderer.AddGradientPoint(-1.00, new Color(189, 94, 4, 255));
            renderer.AddGradientPoint(0.50, new Color(144, 48, 6, 255));
            renderer.AddGradientPoint(1.00, new Color(60, 10, 8, 255));
        }
Exemplo n.º 38
0
        static NoiseMap CreateTerrainNoiseMap(Module noise, IntSize2 size)
        {
            var map = new NoiseMap();

            var build = new SharpNoise.Builders.PlaneNoiseMapBuilder()
            {
                DestNoiseMap = map,
                EnableSeamless = false,
                SourceModule = noise,
            };

            double x = 1;
            double y = 1;
            double w = size.Width / 256.0;
            double h = size.Height / 256.0;

            build.SetDestSize(size.Width, size.Height);
            build.SetBounds(x, x + w, y, y + h);
            build.Build();

            //map.BorderValue = 1;
            //map = NoiseMap.BilinearFilter(map, this.Width, this.Height);

            return map;
        }
Exemplo n.º 39
0
        private async void startButton_Click(object sender, EventArgs e)
        {
            timeLabel.Text = string.Empty;

            var cts = new CancellationTokenSource();

            var dialog = new ProgressDialog();
            dialog.Owner = this;
            dialog.cancelButton.Click += (s, ea) => cts.Cancel();
            dialog.Show();

            var stopwatch = new Stopwatch();
            stopwatch.Start();

            var generatorModule = new PlanetGenerator(GeneratorSettings).CreatePlanetModule();

            var planetBuilder = new SphereNoiseMapBuilder();
            var planetElevationMap = new NoiseMap();

            planetBuilder.SetBounds(GeneratorSettings.SouthCoord, GeneratorSettings.NorthCoord,
                GeneratorSettings.WestCoord, GeneratorSettings.EastCoord);
            planetBuilder.SetDestSize(GeneratorSettings.GridWidth, GeneratorSettings.GridHeight);

            planetBuilder.SourceModule = generatorModule;
            planetBuilder.DestNoiseMap = planetElevationMap;

            bool cancelled = false;

            try
            {
                await planetBuilder.BuildAsync(cts.Token);
            }
            catch (OperationCanceledException)
            {
                cancelled = true;
            }

            stopwatch.Stop();

            dialog.Close();

            if (cancelled)
                return;
            
            timeLabel.Text = String.Format("Planet generated in {0}", stopwatch.Elapsed.ToString());

            var degExtent = GeneratorSettings.EastCoord - GeneratorSettings.WestCoord;
            var gridExtent = (double)GeneratorSettings.GridWidth;
            var metersPerDegree = (GeneratorSettings.PlanetCircumference / 360.0);
            var resInMeters = (degExtent / gridExtent) * metersPerDegree;
            var seaLevelInMeters = (((GeneratorSettings.SeaLevel + 1) / 2.0) *
                (GeneratorSettings.MaxElev - GeneratorSettings.MinElev)) + GeneratorSettings.MinElev;

            var planetImage = new Image();
            var planetRenderer = new ImageRenderer();
            planetRenderer.SourceNoiseMap = planetElevationMap;
            planetRenderer.DestinationImage = planetImage;
            planetRenderer.AddGradientPoint (-16384.0 + seaLevelInMeters, new Color (  0,   0,   0, 255));
            planetRenderer.AddGradientPoint (    -256 + seaLevelInMeters, new Color (  6,  58, 127, 255));
            planetRenderer.AddGradientPoint (    -1.0 + seaLevelInMeters, new Color ( 14, 112, 192, 255));
            planetRenderer.AddGradientPoint (     0.0 + seaLevelInMeters, new Color ( 70, 120,  60, 255));
            planetRenderer.AddGradientPoint (  1024.0 + seaLevelInMeters, new Color (110, 140,  75, 255));
            planetRenderer.AddGradientPoint (  2048.0 + seaLevelInMeters, new Color (160, 140, 111, 255));
            planetRenderer.AddGradientPoint (  3072.0 + seaLevelInMeters, new Color (184, 163, 141, 255));
            planetRenderer.AddGradientPoint (  4096.0 + seaLevelInMeters, new Color (255, 255, 255, 255));
            planetRenderer.AddGradientPoint (  6144.0 + seaLevelInMeters, new Color (128, 255, 255, 255));
            planetRenderer.AddGradientPoint ( 16384.0 + seaLevelInMeters, new Color (  0,   0, 255, 255));
            planetRenderer.EnableLight = true;
            planetRenderer.LightContrast = 1.0 / resInMeters;
            planetRenderer.LightIntensity = 2;
            planetRenderer.LightElevation = 45;
            planetRenderer.LightAzimuth = 135;
            planetRenderer.Render();

            string filename;
            using(var sfd = new SaveFileDialog())
            {
                sfd.Filter = "PNG Image (*.png)|*.png";
                DialogResult result;
                do
                {
                    result = sfd.ShowDialog();
                } while (result != DialogResult.OK);
                filename = sfd.FileName;
            }

            planetImage.SaveGdiBitmap(filename, System.Drawing.Imaging.ImageFormat.Png);
        }