Generating Perlin Noise in C#


Noise textures are often very important in lots of algorithms used in computer graphics.

This post will show a simple implementation of the classic Perlin Noise technique.

The code below shows a class responsible for generating each point of the noise texture. The implementation is simple, we used the perlin formula to generate the point, and after we make a bilinear interpolation to smooth a little the sample:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace PloobsEngine.Utils
{
    /// Perlin Noise
    public class PerlinNoise
    {
        /// Perlin Noise Constructot
        public PerlinNoise(int width, int height)
        {
            this.MAX_WIDTH = width;
            this.MAX_HEIGHT = height;                
        }

        public int MAX_WIDTH = 256;
        public int MAX_HEIGHT = 256;
                
        /// Gets the value for a specific X and Y coordinate
        /// results in range [-1, 1] * maxHeight
        public float GetRandomHeight(float X, float Y, float MaxHeight,
            float Frequency, float Amplitude, float Persistance,
            int Octaves)
        {
            GenerateNoise();
            float FinalValue = 0.0f;
            for (int i = 0; i < Octaves; ++i)
            {
                FinalValue += GetSmoothNoise(X * Frequency, Y * Frequency) * Amplitude;
                Frequency *= 2.0f;
                Amplitude *= Persistance;
            }
            if (FinalValue < -1.0f)
            {
                FinalValue = -1.0f;
            }
            else if (FinalValue > 1.0f)
            {
                FinalValue = 1.0f;
            }
            return FinalValue * MaxHeight;
        }

        //This function is a simple bilinear filtering function which is good (and easy) enough.        
        private float GetSmoothNoise(float X, float Y)
        {
            float FractionX = X - (int)X;
            float FractionY = Y - (int)Y;
            int X1 = ((int)X + MAX_WIDTH) % MAX_WIDTH;
            int Y1 = ((int)Y + MAX_HEIGHT) % MAX_HEIGHT;
            //for cool art deco looking images, do +1 for X2 and Y2 instead of -1...
            int X2 = ((int)X + MAX_WIDTH - 1) % MAX_WIDTH;
            int Y2 = ((int)Y + MAX_HEIGHT - 1) % MAX_HEIGHT;
            float FinalValue = 0.0f;
            FinalValue += FractionX * FractionY * Noise[X1, Y1];
            FinalValue += FractionX * (1 - FractionY) * Noise[X1, Y2];
            FinalValue += (1 - FractionX) * FractionY * Noise[X2, Y1];
            FinalValue += (1 - FractionX) * (1 - FractionY) * Noise[X2, Y2];
            return FinalValue;
        }

        float[,] Noise;
        bool NoiseInitialized = false;
        /// create a array of randoms
        private void GenerateNoise()
        {
            if (NoiseInitialized)                //A boolean variable in the class to make sure we only do this once
                return;
            Noise = new float[MAX_WIDTH, MAX_HEIGHT];    //Create the noise table where MAX_WIDTH and MAX_HEIGHT are set to some value>0            
            for (int x = 0; x < MAX_WIDTH; ++x)
            {
                for (int y = 0; y < MAX_HEIGHT; ++y)
                {
                    Noise[x, y] = ((float)(StaticRandom.Random()) - 0.5f) * 2.0f;  //Generate noise between -1 and 1
                }
            }
            NoiseInitialized = true;
        }

    }
}

To transform the sampled points in a texture you could use the following code:

public Texture2D CreatePerlinNoiseTexture(int sizex, int sizey,float frequencia, float amplitude, float persistence, int octave,bool mipmap = false)
        {
            PerlinNoise pn = new PerlinNoise(sizex, sizey);
            Texture2D t = factory.CreateTexture2D(sizex, sizey,mipmap); ///helper that creates a simple empty texture
            Color[] cor = new Color[sizex * sizey];
            for (int i = 0; i < sizex; i++)
            {
                for (int j = 0; j < sizey; j++)
                {
                    float value = pn.GetRandomHeight(i, j, 1, frequencia, amplitude, persistence, octave);
                    value =  0.5f * (1 + value);
                    cor[i + j * sizex] = new Color(value,value,value);
                }
            }

            t.SetData(cor);
            return t;            
        }

  1. #1 by book flight and hotel on 30 de abril de 2017 - 2:00 pm

    I am just commenting to make you be aware of of the incredible experience my wife’s princess developed reading your blog. She came to understand several things, not to mention what it’s like to have an amazing teaching spirit to make other individuals smoothly grasp specified extremely tough subject areas. You actually did more than readers’ expected results. Thank you for churning out the essential, dependable, revealing and also fun thoughts on this topic to Gloria.

  2. #2 by dating on 30 de abril de 2017 - 2:22 pm

    Every the moment in a though we opt for blogs that we study. Listed below would be the most recent web pages that we pick

  3. #3 by free google play codes on 30 de abril de 2017 - 2:39 pm

    Hi there. I discovered your web site by the use of Google even as looking for a related topic, your website got here up. It appears good. I have bookmarked it in my google bookmarks to come back then.

  4. #4 by Alat pemadam api on 30 de abril de 2017 - 3:13 pm

    This is really interesting, You are a very skilled blogger. I have joined your feed and look forward to seeking more of your great post. Also, I’ve shared your web site in my social networks!

  5. #5 by review ibosport on 30 de abril de 2017 - 3:26 pm

    Now i’m excellent in financial planning, and offering advice regarding weather to buy particular items or cut back. how can i start a internet site giving out this advice?.

  6. #6 by ways to tell your partner you have an std on 30 de abril de 2017 - 3:30 pm

    Here are a number of the web sites we advise for our visitors

  7. #7 by bandarQ on 30 de abril de 2017 - 3:31 pm

    Hiya, I am really glad I have found this info. Today bloggers publish only about gossip and internet stuff and this is actually frustrating. A good blog with interesting content, that is what I need. Thanks for making this web-site, and I’ll be visiting again. Do you do newsletters by email?

  8. #8 by cantiksehatgue on 30 de abril de 2017 - 3:32 pm

    Hiya, I’m really glad I’ve found this info. Today bloggers publish just about gossip and internet stuff and this is really frustrating. A good site with interesting content, that’s what I need. Thanks for making this web-site, and I’ll be visiting again. Do you do newsletters by email?

  9. #9 by sex problem on 30 de abril de 2017 - 3:33 pm

    the time to read or go to the material or sites we have linked to below the

  10. #10 by Puisi on 30 de abril de 2017 - 3:48 pm

    Awesome write-up. I am a normal visitor of your site and appreciate you taking the time to maintain the excellent site. I will be a frequent visitor for a long time.

  11. #11 by small business on 30 de abril de 2017 - 4:09 pm

    I cling on to listening to the reports speak about receiving free online grant applications so I have been looking around for the best site to get one. Could you tell me please, where could i acquire some?

  12. #12 by lowe's home improvement on 30 de abril de 2017 - 4:09 pm

    I was suggested this web site by my cousin. I’m not sure whether this post is written by him as nobody else know such detailed about my difficulty. You’re incredible! Thanks!

  13. #13 by medical school on 30 de abril de 2017 - 4:27 pm

    Good website! I truly love how it is easy on my eyes and the data are well written. I am wondering how I could be notified when a new post has been made. I have subscribed to your RSS feed which must do the trick! Have a nice day!

  14. #14 by www.krogerfeedback.com on 30 de abril de 2017 - 4:40 pm

    I am truly grateful to the owner of this website who has shared this
    enormous article at here.

  15. #15 by sbobet on 30 de abril de 2017 - 4:54 pm

    Awesome post. I am a normal visitor of your web site and appreciate you taking the time to maintain the nice site. I’ll be a frequent visitor for a really long time.

  16. #16 by home on 30 de abril de 2017 - 5:05 pm

    I was just looking for this info for a while. After 6 hours of continuous Googleing, at last I got it in your web site. I wonder what’s the lack of Google strategy that do not rank this type of informative web sites in top of the list. Usually the top websites are full of garbage.

  17. #17 by cheap plane tickets on 30 de abril de 2017 - 5:30 pm

    Wow! This could be one particular of the most useful blogs We have ever arrive across on this subject. Basically Great. I’m also an expert in this topic therefore I can understand your hard work.

  18. #18 by Home Improvement on 30 de abril de 2017 - 5:45 pm

    I have to express thanks to this writer for bailing me out of this type of setting. Just after scouting through the world wide web and meeting recommendations that were not beneficial, I figured my entire life was gone. Being alive minus the solutions to the issues you have sorted out all through this posting is a crucial case, as well as the ones which could have badly damaged my career if I hadn’t discovered your web page. Your primary understanding and kindness in dealing with all the things was tremendous. I don’t know what I would have done if I hadn’t come across such a point like this. I can also at this point relish my future. Thanks so much for the reliable and results-oriented help. I will not think twice to recommend your web site to any person who should get tips about this issue.

  19. #19 by www.krogerfeedback.com on 30 de abril de 2017 - 5:47 pm

    I used to be able to find good information from your articles.

  20. #20 by togel online on 30 de abril de 2017 - 5:50 pm

    Hello there. I discovered your site via Google even as looking for a similar subject, your website got here up. It looks good. I’ve bookmarked it in my google bookmarks to visit then.

  21. #21 by buy viagra cheap on 30 de abril de 2017 - 7:03 pm

    Ha ha. Hvor er det cool! Jeg elsker ogsÃ¥ Mandrillen. Mit nuværende profilbillede er broder Salsa, da vi næsten har samme frisure – jeg sveder bare ikke nær sÃ¥ meget og er heller ikke ligesÃ¥ god til at folde ting i tæpper.Ellers er Bjarne Goldbæk altid en vinder hos mig!

  22. #22 by generic viagra on 30 de abril de 2017 - 7:25 pm

    They’re are sooooooo cute together. And she has such a sweet voice. I love listening to her sing.. Does anyone know when this was taped? It looks like it’s at a wedding or something??

  23. #23 by viagra online on 30 de abril de 2017 - 8:12 pm

    Just wish to say your article is as surprising. The clarity in your post is simply nice and i could assume you’re an expert on this subject. Fine with your permission let me to grab your RSS feed to keep updated with forthcoming post. Thanks a million and please continue the gratifying work.

  24. #24 by Tantric Satin on 30 de abril de 2017 - 9:15 pm

    Wonderful story, reckoned we could combine several unrelated information, nonetheless seriously worth taking a look, whoa did one particular discover about Mid East has got a lot more problerms too

  25. #25 by purchase viagra on 30 de abril de 2017 - 11:14 pm

    30+ blowout and we can’t play starters less than 30 minutes.Worse, the Pistons’ starters played less than 30 minutes, 26 mins tops. One minute here and there probably don’t amount to much, but it is worrisome that we can’t even play our bench guys 15 minutes on a blowout.

1 324 325 326
(não será publicado)