cimagestb-imagesimplex-noisenoise-generator

Why is no data getting written to image?


I'm trying to create procedural textures, and for that, I'm generating noise, and then writing that data to an image file, to be displayed. So far I generated the noise, and now I'm trying to write that to an image file, to display the noise. I expect my image to look like this, but instead it is entirely black.

enter image description here

Here's my code where I'm writing to the image file

    void write_noise_2d(int w, int h, int channels_num)
    {
        // initialize noise
        fnl_state noise = fnlCreateState();
        noise.noise_type = FNL_NOISE_OPENSIMPLEX2;

        // create data array for noise
        uint8_t* noise_data = malloc(w * h * channels_num * sizeof(uint8_t));
        int index = 0;
        // create noise throughout the entire image
        for(int x=0; x<w; x++)
        {
            for(int y=0; y<h; y++)
            {
                noise_data[index++] = fnlGetNoise2D(&noise, x, y);
            }
        }

        stbi_write_jpg("textures/noisemap.jpg", w, h, channels_num, noise_data, w * channels_num);
        free(noise_data);
    }

    write_noise_2d(512, 512, 3);

I did diligent research on this topic and even found some example source code, that worked when I just copied and pasted it, but when I implemented the noise functions, it no longer worked. Instead of displaying the noise data like I expected it to (as shown in the example image provided). Instead, it's nothing more than just a black square.

EDIT: For reference, this is the main resource I was using for this. Copying and pasting this code actually displays the data on the file, while my implementation doesn't.

http://chanhaeng.blogspot.com/2018/12/how-to-use-stbimagewrite.html


Solution

  • As per @Ian Abbott's suggestion, I took the sample code provided, and now the image displays proper noise as shown below

    enter image description here

    Looks a little bit wonky but I can change that with the noise options provided by FNL (fastnoise lite for those wondering)

    For future viewers, this is the new proper code that actually worked.

        void write_noise_2d(int w, int h, int channels_num)
    {
        // initialize noise
        fnl_state noise = fnlCreateState();
        noise.noise_type = FNL_NOISE_OPENSIMPLEX2;
        noise.octaves = 8;
        // create data array for noise
        float* noise_data = malloc(w * h * channels_num * sizeof(float));
        int index = 0;
        // create noise throughout the entire image
        for(int x=0; x<w; x++)
        {
            for(int y=0; y<h; y++)
            {
                noise_data[index++] = (1 + fnlGetNoise2D(&noise, x, y)) * 127.999;
            }
        }
    
        stbi_write_jpg("textures/noisemap.jpg", w, h, channels_num, noise_data, w * channels_num);
        free(noise_data);
    }
    
    write_noise_2d(512, 512, 1);