/*
 * 3D Engine 
 * texture.c: 
 * Based on pikuma.com 3D software renderer in C
 * Copyright (c) 2021 986-Studio. All rights reserved.
 *
 * Created by Manoël Trapier on 07/03/2021.
 */
#include <stdlib.h>
#include <upng.h>

#include <texture.h>

/***********************************************************************************************************************
 * Public functions
 **********************************************************************************************************************/

void loadTextureDateFromPng(texture_t *tex, const char *filepath)
{
    if (tex->png != NULL)
    {
        upng_free(tex->png);
        tex->png = NULL;
    }

    tex->png = upng_new_from_file(filepath);
    if (tex->png != NULL)
    {
        upng_decode(tex->png);
        if (upng_get_error(tex->png)  == UPNG_EOK)
        {
            tex->data = (colour_t *)upng_get_buffer(tex->png);
            tex->width = upng_get_width(tex->png);
            tex->height = upng_get_height(tex->png);
        }
    }
}

void textureCleanup(texture_t *tex)
{
    if (tex->png != NULL)
    {
        upng_free(tex->png);
        tex->png = NULL;
    }

    /* uPNG do free the buffer for us. */
    tex->data = NULL;
}

colour_t getTextureColour(texture_t *texture, tex2_t *position)
{
    colour_t ret = 0;
    int32_t texX = FP_GET_INT(position->u);
    int32_t texY = FP_GET_INT(position->v);

    while(texX < 0) { texX += texture->width; }
    while(texY < 0) { texY += texture->height; }
    texX = texX % texture->width;
    texY = texY % texture->height;

    switch(upng_get_format(texture->png))
    {
    case UPNG_LUMINANCE8:
        ret = ((uint8_t *)texture->data)[(texY * texture->width) + texX];
        break;

    case UPNG_RGBA8:
        ret = ((colour_t *)texture->data)[(texY * texture->width) + texX];
        break;

    default:
        break;
    }

    return ret;
}