Perlin Noise

CSharp · Console

/Program.cs

using System;

public class Program
{
	
	public static void Main()
	{
		int size = 25;
		int definition = 7;
		Random rng = new Random();//generates a random seed
		PerlinNoise p = new PerlinNoise(size, definition, rng.Next(1,100));
	}
	
	public class PerlinNoise{
		private int seed;
		public PerlinNoise(int size,int definition,int seed) {
			this.seed = seed;
			float[,] values = new float[size,size];
	
		
			for (float a = 0; a < size*definition; a++) { 
				Console.WriteLine(" ");
			for (float i = 0; i < size*definition; i++) { 
				float val = getValue(new V2(i/definition,a/definition));
				Console.Write(getChar(val));
				}
			} 
			
		}
		private float gradient(V2 point,V2 edge) {//finds where the point lands on the gradient
			Random rng = new Random(Convert.ToInt32(edge.x*seed)^Convert.ToInt32(edge.y*seed));//keeps the random number consistent to for each edge 
			int angle = rng.Next(1,360);
			return (float)((point.y - edge.y) * Math.Sin(angle) + (point.x - edge.x)* Math.Cos(angle));
		}
	
		private float getValue(V2 point) {
		
				V2 bl = new V2(Convert.ToInt32(Math.Floor(point.x)),Convert.ToInt32(Math.Floor(point.y)));//gets the position of the bottem left edge
				V2 tr = new V2(bl.x+1,bl.y+1);//gets the position of the top right edge
		
		
				float a1 = gradient(point,bl);// gets gradient from the bottom left edge
				float a2 = gradient(point,new V2(tr.x,bl.y));// gets gradient from the bottom right edge
				float i1 = (a2 - a1) * (point.x - bl.x) + a1;//interpolates horizontaly along bottom
			
				a1 = gradient(point, new V2(bl.x,tr.y));// gets gradient from the top left edge
				a2 = gradient(point,tr);// gets gradient from the top right edge
				float i2 = (a2 - a1) * (point.x - bl.x) + a1;//interpolates horizontaly along top
			
				float a_return = (i2 - i1) * (point.y - bl.y) + (float)i1;//interpolates verticaly
				return(a_return);
		}
	
	
		private char getChar(float val) {//prints a character to indicate the value
			if (val < -0.3) {
				return '`';
			} else if (val < -0.10) { 
				return ("'")[0];
			} else if (val <= 0) {
				return '"';
			
			} else if (val < 0.10) {
				return '*';
			}else if (val < 0.3) {
		    	return '^';
			}
			return '#';
		
		}
	
		private class V2 {
			public V2(float x,float y) {
				this.x=x;
				this.y=y;
			}
			public float x;
			public float y;
		}
	}
}
;