/*
MIT License

Copyright (c) 2020-2022 Rupert Carmichael

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/

#include <stdlib.h>
#include <stdint.h>
#include <string.h>
#include <math.h>

#include "vecx.h"
#include "vecx_render.h"

static int vscale;
static int vwidth;
static int vheight;
static double sdiv;

static uint32_t *vbuf = NULL;

static void (*line_draw)(double, double, double, double, uint8_t);

void vecx_render_set_buf(uint32_t *ptr) {
    vbuf = ptr;
}

static inline void draw_pixel(int x, int y, uint8_t c) {
    c += 64;
    if (x < vwidth && x >= 0 && y < vheight && y >= 0)
        vbuf[(vwidth * y) + x] = (c << 16 | c << 8 | c);
}

// Bresenham's line generation algorithm
static void line_bres(double x0, double y0, double x1, double y1, uint8_t c) {
    long x0l = lround(x0);
    long x1l = lround(x1);
    long y0l = lround(y0);
    long y1l = lround(y1);
    int dx = labs(x1l - x0l);
    int sx = x0l < x1l ? 1 : -1;
    int dy = -labs(y1l - y0l);
    int sy = y0l < y1l ? 1 : -1;
    int err = dx + dy;
    int e2 = 0;

    while (1) {
        draw_pixel(x0l, y0l, c);
        if (x0l == x1l && y0l == y1l)
            break;

        e2 = 2 * err;

        if (e2 >= dy) {
            err += dy;
            x0l += sx;
        }

        if (e2 <= dx) {
            err += dx;
            y0l += sy;
        }
    }
}

// Xiaolin Wu's line algorithm
static inline void plot(int x, int y, double brightness) {
    //plot the pixel at (x, y) with brightness c (where 0 ≤ c ≤ 1)
    if (brightness > 1.0)
        brightness = 1.0;
    else if (brightness < 0.0)
        brightness = 0.0;
    draw_pixel(x, y, (uint8_t)(brightness * 255));
}

// integer part of x
static inline int ipart(double x) {
    return floor(x);
}

// fractional part of x
static inline double fpart(double x) {
    return x - floor(x);
}

static inline double rfpart(double x) {
    return 1 - fpart(x);
}

static inline void fswap(double *a , double *b) {
    double temp = *a;
    *a = *b;
    *b = temp;
}

static void line_wu(double x0, double y0, double x1, double y1, uint8_t c) {
    uint8_t steep = fabs(y1 - y0) > fabs(x1 - x0);

    if (steep) {
        fswap(&x0, &y0);
        fswap(&x1, &y1);
    }

    if (x0 > x1) {
        fswap(&x0, &x1);
        fswap(&y0, &y1);
    }

    double dx = x1 - x0;
    double dy = y1 - y0;
    double gradient = 0.0;

    if (dx == 0)
        gradient = 1.0;
    else
        gradient = dy / (double)dx;

    // handle first endpoint
    double xend = round(x0);
    double yend = y0 + gradient * (xend - x0);
    double xgap = rfpart(x0 + 0.5);
    int xpxl1 = xend; // this will be used in the main loop
    int ypxl1 = ipart(yend);

    if (steep) {
        plot(ypxl1,   xpxl1, rfpart(yend) * xgap);
        plot(ypxl1+1, xpxl1,  fpart(yend) * xgap);
    }
    else {
        plot(xpxl1, ypxl1  , rfpart(yend) * xgap);
        plot(xpxl1, ypxl1+1,  fpart(yend) * xgap);
    }
    double intery = yend + gradient; // first y-intersection for the main loop

    // handle second endpoint
    xend = round(x1);
    yend = y1 + gradient * (xend - x1);
    xgap = fpart(x1 + 0.5);
    int xpxl2 = xend; // this will be used in the main loop
    int ypxl2 = ipart(yend);

    if (steep) {
        plot(ypxl2  , xpxl2, rfpart(yend) * xgap);
        plot(ypxl2+1, xpxl2,  fpart(yend) * xgap);
    }
    else {
        plot(xpxl2, ypxl2,  rfpart(yend) * xgap);
        plot(xpxl2, ypxl2+1, fpart(yend) * xgap);
    }

    // main loop
    if (steep) {
        for (int x = xpxl1; x < xpxl2; ++x) {
            plot(ipart(intery)  , x, rfpart(intery) * (c / 127.0));
            plot(ipart(intery)+1, x,  fpart(intery) * (c / 127.0));
            intery = intery + gradient;
        }
    }
    else {
        for (int x = xpxl1; x < xpxl2; ++x) {
            plot(x, ipart(intery),  rfpart(intery) * (c / 127.0));
            plot(x, ipart(intery)+1, fpart(intery) * (c / 127.0));
            intery = intery + gradient;
        }
    }
}

void vecx_render_set_algo(int algo) {
    line_draw = algo ? &line_wu : &line_bres;
}

void vecx_render_set_scale(int scale) {
    vscale = scale;
    vwidth = VWIDTH * vscale;
    vheight = VHEIGHT * vscale;
    sdiv = 100.0 / vscale;
}

void vecx_render(void) {
    memset(vbuf, 0x00, vwidth * vheight * sizeof(uint32_t));
    for (int i = 0; i < vector_draw_cnt; ++i) {
        line_draw(
            (vectors_draw[i].x0 / sdiv), (vectors_draw[i].y0 / sdiv),
            (vectors_draw[i].x1 / sdiv), (vectors_draw[i].y1 / sdiv),
            vectors_draw[i].color >= VECTREX_COLORS ? 0 : vectors_draw[i].color
        );
    }
}
