c # – Wonky perlin noise

I am quite new to the wonderful world of "Procedural textures," and I am trying to create a double precision noise perlin algorithm.


I'm almost done, except for the fact that the coordinates seem to be off, any idea what I've done wrong? Here is the code:

public static class Noise {
    static int() p = new int(Convert.ToInt32(Math.Pow(2,16)));
    public static vector2dDouble v1i;
    public static vector2dDouble v2i;
    public static vector2dDouble v3i;
    public static vector2dDouble v4i;

    public static double(,) GenerateNoiseMap(int mapWidth, int mapHeight, int seed, float scale, int octaves, float persistance, float lacunarity, Vector3 offset) {
        double(,) noiseMap = new double(mapWidth, mapHeight);

        System.Random prng = new System.Random(seed);
        Vector2() octaveOffsets = new Vector2(octaves);
        for (int i = 0; i < octaves; i++) {
            float offsetX = prng.Next(-100000, 100000) + offset.x;
            float offsetY = prng.Next(-100000, 100000) + offset.z;
            octaveOffsets(i) = new Vector2(offsetX, offsetY);

        if (scale <= 0) {
            scale = 0.0001f;

        float maxNoiseHeight = float.MinValue;
        float minNoiseHeight = float.MaxValue;

        float halfWidth = mapWidth / 2f;
        float halfHeight = mapHeight / 2f;

        for (int y = 0; y < mapHeight; y++) {
            for (int x = 0; x < mapWidth; x++) {

                float amplitude = 1;
                float frequency = 1;
                double noiseHeight = 0;

                for (int i = 0; i < octaves; i++) {
                    double sampleX = (double)(x - halfWidth) / scale * frequency + octaveOffsets(i).x + 0.001;
                    double sampleY = (double)(y - halfHeight) / scale * frequency + octaveOffsets(i).y + 0.001;

                    double perlinValue = Noise2d(sampleX, sampleY);
                    noiseHeight += perlinValue * amplitude;

                    amplitude *= persistance;
                    frequency *= lacunarity;

                if (noiseHeight > maxNoiseHeight) {
                    maxNoiseHeight = (float)noiseHeight;
                else if (noiseHeight < minNoiseHeight) {
                    minNoiseHeight = (float)noiseHeight;
                noiseMap(x, y) = noiseHeight;

        for (int y = 0; y < noiseMap.GetLength(1); y++) {
            for (int x = 0; x < noiseMap.GetLength(0); x++) {
                noiseMap(x, y) = (double)Mathf.InverseLerp(minNoiseHeight, maxNoiseHeight, (float)noiseMap(x, y));

(!(enter image description here)(1))(1)
        return noiseMap;

    public static void init(int seed) {
        createGradients(p, seed);

    public static int() createGradients(int() p, int seed) {
        System.Random prng = new System.Random(seed);
        for (int i = 0; i < p.GetLength(0) / 2; i++) {
            p(i) = prng.Next(0, 256);
            p(i + ((int)p.GetLength(0) / 2)) = p(i);

        return p;

    static vector2dDouble generateGradient(int val) {
        int hash = val & 3;
        switch (hash) {
            case 0:
                return new vector2dDouble(1.0, 1.0);
            case 1:
                return new vector2dDouble(-1.0, 1.0);
            case 2:
                return new vector2dDouble(-1.0, -1.0);
            case 3:
                return new vector2dDouble(1.0, -1.0);
            default: return new vector2dDouble(0, 0);

    static double Noise2d(double x, double y) {

        int ix = Convert.ToInt32(Math.Floor(x)) & (p.GetLength(0) / 2 - 1);
        int iy = Convert.ToInt32(Math.Floor(y)) & (p.GetLength(0) / 2 - 1);

        x -= Math.Floor(x);
        y -= Math.Floor(y);

        vector2dDouble v1 = new vector2dDouble(x - 1, y),
                       v2 = new vector2dDouble(x - 1, y - 1),
                       v3 = new vector2dDouble(x, y), 
                       v4 = new vector2dDouble(x, y - 1);

        int g1 = p(p(ix + 1) + iy + 1),
            g2 = p(p(ix) + iy + 1),
            g3 = p(p(ix + 1) + iy), 
            g4 = p(p(ix)  + iy);

        double u = fade(x);
        double v = fade(y);

        double f1 = v1.dot(generateGradient(g1)), 
               f2 = v2.dot(generateGradient(g2)), 
               f3 = v3.dot(generateGradient(g3)), 
               f4 = v4.dot(generateGradient(g4));

        return lerp(u, lerp(v, f2, f4), lerp(v ,f1, f3));

    static double lerp(double t, double argc, double argv) { return argc + t * (argv - argc); }

    static double fade(double t) { return t * t * t * (t * (t * 6 - 15) + 10); }

public struct vector2dDouble {
    public double x, y;

    public vector2dDouble(double argx, double argy) {
        x = argx;
        y = argy;

    public double dot(vector2dDouble argc) {
        argc.x *= x;
        argc.y *= y;

        return argc.x + argc.y;

    public void print() {
        Debug.Log(x + "," + y);

procedure generation: how to generate a softer Perlin noise?

So, recently I have been learning things of procedure generation (specifically Perlin noise) and I have run into a wall.
enter the description of the image here
This is the result that I have seen everyone, but this is what I am getting,
enter the description of the image here

This is my code, (I am using python):

import random
import math
import PIL.Image

class Noise:

    def __init__(self, x, y):
        self.x = x
        self.y = y

    def lerp(self, start, stop, t):
        return start*(1-t) + (stop*t)

    def smoothstep(self, t):
        return 3*(t**2) - 2*(t**3)

    def gradients(self):
        grads = ()
        for _ in range(4):
            x = random.randrange(0, 361)
            y = random.randrange(0, 361)
            grads.append((math.cos(x), math.sin(y)))
        return grads

    def cvectors(self):
        botleft = (self.x, self.y)
        botright = (self.x-1, self.y)
        topleft = (self.x, self.y-1)
        topright = (self.x-1, self.y-1)
        cvecs = (botleft, botright, topleft, topright)
        return cvecs

    def makenoise(self):
        dot = ()
        grads = self.gradients()
        cvecs = self.cvectors()
        for i in range(4):
            (x, y) = cvecs(i)
            (a, b) = grads(i)
        st = self.lerp(dot(0), dot(1), self.smoothstep(x))
        uv = self.lerp(dot(2), dot(3), self.smoothstep(x))
        stuv = self.lerp(st, uv, self.smoothstep(self.y))
        return stuv

    size = 128
    img = PIL.Image.new('L', (size, size))
    for x in range(size):
        for y in range(size):
            perlin = Noise(random.uniform(0, 1), random.uniform(0, 1))
            img.putpixel(tuple((x, y)), perlin.makenoise())

This is only an assumption, but I feel it is a problem of scale. Thanks in advance and apologies also for the horrible code.

Procedural generation: deformation of the domain with Perlin noise

It seems that the extent of deformation of your domain is too small.

Start your q at approximately 20 times its current value and you will get a very pronounced domain deformation:

Deformed Domain Sign

I made this image by modifying its code to replace the 4.0* with 80.0*:

function pattern(x, y, scale, octaves, lacunarity, gain){
    var q = (
            fbm(x, y, scale, octaves, lacunarity, gain), 
            fbm(x+5.2, y+1.3, scale, octaves, lacunarity, gain), 

    return fbm(x+80.0*q(0), y+80.0*q(1), scale, octaves, lacunarity, gain);

Detailed explanation of the algorithmic complexity of perlin noise

I'm doing an algorithm analysis project and I've been looking for something more complex than Perlin Noise is $ O (n cdot 2 ^ n) $ due to duplication in $ n $ matrix dimensions and operations. Anyone know where there is more information? I have another month before our group makes the presentation.

procedure generation: Perlin noise ground, how to add features (rivers, etc.)

I am new to gamedev.

I am currently working on a small peaceful low poly game with LWJGL3, following the ThinMatrix tutorials.

So far, I am using Perlin noise to generate the height map. This is what I got with a 200×200 map: https://puu.sh/EqHpn/26d95a343e.png

I would like to have biomes, rivers, mountains not so often and other characteristics.

For biomes:
I have read, to generate biomes, we often use the height map, a humidity map and a temporary one based on height. But imagine that you can have a forest at the same level as a desert, but the toundra will only be on top of the mountains. Should the biome define height?

For other features:
Should I generate a perlin noise layer for each characteristic? If so, would they only affect the height map?

How should I do it? What are the steps of a good land generation?

EDIT: How should my biomes be structured? Currently, my biomes have only 1 color and, depending on the height, the color varies. But the transition between biomes is bad. Yellow to green, green to brown, etc.

TLDR: Am I generating land with only heights? How should I add more features in my terrain using Perlin noise?

c # – Generating 2D perlin procedural noise

I have been searching for a week after a C # implementation of a 2D seed based procedure noise generation function. I am trying to implement a way to generate orespawns in a 2D plane. The plane is based on fragments (21×21 pieces) that originate in 0.0 and can expand in both directions (negative and positive).

I looked at Perlin to get a general understanding about noise. I tried to convert the implementation of Hugo Elias to C # but without any results. I've also seen Ken Perlin's improved noise, but it uses 3 coordinates for the input that I don't know how to use. Other implementations that I have seen online use php, javascript or C. The general consensus is that I find it difficult to implement a noise function with lack of documentation and different languages.

What I am looking for is a way to generate procedural noise in an expanding 2D plane with few scattered groups of high noise and the majority of low noise to collect high areas for ore generation.

What would be a good way to implement this function?

Unit: How do I use this Perlin noise texture to change the mesh?

First, I recommend that the noise calculation come into its own function:

float SampleNoise(Vector2 normalizedPoint) {
    Vector2 samplePoint = origin + normalizedPoint * scale;
    return Mathf.PerlinNoise(samplePoint.x, samplePoint.y);

Then, you can easily reuse the same function both in the generation of texture and in the displacement of vertices, without writing it twice (with the risk of changing one copy while forgetting to change the other). Inside your texture loop it would look like this:

Vector2 normalized = new Vector2(x / noiseTex.width, y / noiseTex.height);
float sample = SampleNoise(normalized);

Then you can make a second pass to update your vertices:

// Do this part once, in Start, so you're not allocating new vertex arrays constantly.
var mesh = ((MeshRenderer)rend).mesh;
var vertices = mesh.vertices;

// Update your vertex heights anytime your noise changes.
for(int i = 0; i < vertices.Length; i++) {
    var vertex = vertices(i);
    // The default plane goes from -5 to +5, so remap it to 0...1:
    var normalized = (new Vector2(vertex.x, vertex.z))/10f + Vector2.one * 0.5f;
    vertex.height = heightScale * SampleNoise(normalized);

mesh.vertices = vertices;

You can also apply this offset in the vertex shader, reading the texture itself. But modifying the CPU side of the source mesh also allows you to use it for things like lightning and collisions.

Improving the speed of creation for three Perlin noise maps in Python?

I am interested in learning how I can improve the speed of the code in this pygame file. I itero more than 6400 * 1800 * 3 elements of several matrices numpy here to apply values ​​of noise. The noise library that I am using can be found on GitHub here. All others are self-explanatory noise maps.

I'm calling static variables of a class called S T here. ST.MAP_WIDTH = 6400 and ST.MAP_HEIGHT = 1800

of __future__ import division
of singleton import ST
import numpy as np
import noise
import time
import randomly
import mathematics

def __noise (noise_x, noise_y, octaves = 1, persistence = 0.5, lacunarity = 2.0):
It generates and returns a noise value.

: param noise_x: The noise value of x
: param noise_y: The noise value of y
: returns: numpy.float32

value = noise.pnoise2 (noise_x, noise_y,
octaves, persistence, lacunarity,
random.randint (1, 9999))

returns np.float32 (value)

def __elevation_mapper (noise_x, noise_y):
Find and return the elevation noise for the noise_x and
Parameters of noise_y.

: param noise_x: noise_x = x / ST.MAP_WIDTH - scrambler
: param noise_y: noise_y = y / ST.MAP_HEIGHT - scrambler
: return: float
return __noise (noise_x, noise_y, 8, 0.9)

def __climate_mapper (and, noise_x, noise_y):
Find and return the climate noise for the given noise_x and
Parameters of noise_y.

: param noise_x: noise_x = x / ST.MAP_WIDTH - scrambler
: param noise_y: noise_y = y / ST.MAP_HEIGHT - scrambler
: return: float
# find the distance from the bottom of the map and normalize to the range [0, 1]
    distance = math.sqrt ((and - (ST.MAP_HEIGHT >> 1)) ** 2) / ST.MAP_HEIGHT

value = __noise (noise_x, noise_y, 8, 0.7)

return (1 + value - distance) / 2

def __rainfall_mapper (noise_x, noise_y):
Find and return the rain noise for the noise_x and
Parameters of noise_y.

: param noise_x: noise_x = x / ST.MAP_WIDTH - scrambler
: param noise_y: noise_y = y / ST.MAP_HEIGHT - scrambler
: return: float
return __noise (noise_x, noise_y, 4, 0.65, 2.5)

def create_map_arr ():
This function creates elevation maps, weather and rain noise,
normalizes them to the rank [0, 1], and then assign them to their
Appropriate attributes in the ST singleton.

start = timeit.default_timer ()

elevation_arr = np.zeros ([ST.MAP_HEIGHT, ST.MAP_WIDTH], np.float32)
clim_arr = np.zeros ([ST.MAP_HEIGHT, ST.MAP_WIDTH], np.float32)
rain_arr = np.zeros ([ST.MAP_HEIGHT, ST.MAP_WIDTH], np.float32)

randomizer = random.uniform (0.0001, 0.9999)

# assign noise map values
for and in range (ST.MAP_HEIGHT):
for x in the range (ST.MAP_WIDTH):
noise_x = x / ST.MAP_WIDTH - scrambler
noise_y = y / ST.MAP_HEIGHT - scrambler

elevation_arr[y][x]    = __elevation_mapper (noise_x, noise_y)
climate_arr[y][x]    = __climate_mapper (and, noise_x, noise_y)
rain_arr[y][x]    = __rainfall_mapper (noise_x, noise_y)

# normalize to the range [0, 1] and assign to the relevant ST attributes
ST.ELEVATIONS = (elevation_arr - elevation_arr.min ()) / 
(elevation_arr.max () - elevation_arr.min ())

ST.CLIMATES = (Climate_arr - Climate_arr.min ()) / 
(Climate_arr.max () - Climate_arr.min ())

ST.RAINFALLS = (Rainier_arr - Rain_arr.min ()) / 
(Rainage_arr.max () - Rain_arr.min ())

stop = timeit.default_timer ()
print ("GENERATION TIME:" + str (stop - start))

Python – Perlin Noise generation always returns zero

A quick summary of how Perlin noise works:

Start by finding the cell in which the sample point is located within a network of integers. From that he determines the whole points that define the corners of that cell. For each corner, it generates a pseudorandom gradient vector, and then calculates the displacement projection of its sample point from the corner along this gradient vector. By interpolating these projections according to the position of the sample, the final soft noise value is obtained.

Diagram showing how Perlin noise works using gradient vectors at corner points

So, let's consider how this works when your sample lands directly in One of these corner points. The interpolation weight for all the other corners will be zero, and the projection on the gradient vector of this corner will also be zero, so the result is: zero.

In each set of integer coordinates, the Perlin noise will give you a value of zero.

So, easy solution: do not sample in whole coordinates. Sampling in (x + 0.5, y + 0.5) for the integers x and y will move your sample point from the corner to the center of the cell. However, you will not see much benefit from using a continuous noise function such as Perlin noise. Adjacent samples will have little correlation. If you only want one random number per tile, you could use a hashing function such as Perlin, which uses noise internally to select a random gradient for each corner: skip the overload to do it four times, calculate point products, and interpolate the results.

Or, if you want continuity between multiple tiles, you must scale your sampling locations smaller than the size of the function of the noise function. For example, if you want large-scale functions on the order of approximately 30 tiles wide, divide x and y by 30 to obtain a fractional sampling location that will gradually increase and decrease the hills and valleys within each grid cell of the noise function .

Generation of procedures: generation of different maps using Perlin Noise with a seed

I'm developing a 2D game in python and I could have Perlin Noise work with this code:

import time
import noise


BLOCK = "#"

WATER = "-"
WATER_LIMITS = (0.3, -0.4)

GRASS = ""

oct = 1
outputString = str ()

global output chain

for and in range (1000):
outputString + = "["
        for x in range(165):
            i = round(noise.pnoise2(x / 15, y / 15, octaves = oct), 5)
                if i > 0.4:
                    outputString += BLOCK
                elif i < -0.5:
                    outputString += WATER
                    outputString += GRASS
        outputString += "]north"

time = timeit.timeit (GENERATE_MAP, number = 1)
print (outputString)
print ("time =" + str (time))

But this creates the same terrain every time, so I thought to use seeds, but I do not know how to do it.
I am using python 3.6 with noise.