texture.cpp

C++ software renderer

src/texture.cpp

1.4 KB
#include "texture.h"

#include "globals.h"

#define STB_IMAGE_IMPLEMENTATION
#include "stb_image.h"

Texture load_texture(const char *filename) {
    int            width, height, channels;
    unsigned char *data = stbi_load(filename, &width, &height, &channels, 4);

    if (!data) {
        fprintf(stderr, "Failed to load image: %s\n", filename);
        return textures[0];  // can see this being annoying to debug, change
    }

    Texture tex;
    tex.width  = width;
    tex.height = height;
    tex.pixels = (u32 *)malloc(sizeof(u32) * width * height);
    for (int y = 0; y < height; ++y) {
        for (int x = 0; x < width; ++x) {
            int pixel_idx         = y * width + x;
            int flipped_y         = height - 1 - y;
            u8  r                 = data[flipped_y * width * 4 + x * 4 + 0];
            u8  g                 = data[flipped_y * width * 4 + x * 4 + 1];
            u8  b                 = data[flipped_y * width * 4 + x * 4 + 2];
            u8  a                 = data[flipped_y * width * 4 + x * 4 + 3];
            tex.pixels[pixel_idx] = (r << 24) | (g << 16) | (b << 8) | a;
        }
    }
    stbi_image_free(data);
    return tex;
}

u32 sample_texture(int texture_index, vec2f uv) {
    const Texture &tex = textures[texture_index];
    int            x   = (int)(uv.x * tex.width);
    int            y   = (int)(uv.y * tex.height);
    return tex.pixels[y * tex.width + x];
}