// Pyre GPU — the API
// Our own graphics API. Simple, no committee.
// Submit geometry -> vertex transform -> rasterize -> framebuffer.
// N8toriousAi, 2026.

#ifndef PYRE_API_H
#define PYRE_API_H

#include "pyre_math.h"
#include "pyre_raster.h"

// ---- vertex: position + color ----
typedef struct {
    vec3 pos;
    pyre_rgb color;
} pyre_vertex;

typedef struct {
    pyre_fb fb;
    mat4 model, view, proj;
    mat4 mvp;  // cached
    int mvp_dirty;
} pyre_ctx;

static inline void pyre_init(pyre_ctx *ctx, int w, int h,
                             pyre_rgb *color_buf, float *depth_buf) {
    ctx->fb.width = w; ctx->fb.height = h;
    ctx->fb.color = color_buf; ctx->fb.depth = depth_buf;
    ctx->model = m4_identity();
    ctx->view  = m4_identity();
    ctx->proj  = m4_identity();
    ctx->mvp_dirty = 1;
}

static inline void pyre_set_model(pyre_ctx *ctx, mat4 m) {
    ctx->model = m; ctx->mvp_dirty = 1;
}
static inline void pyre_set_view(pyre_ctx *ctx, mat4 m) {
    ctx->view = m; ctx->mvp_dirty = 1;
}
static inline void pyre_set_proj(pyre_ctx *ctx, mat4 m) {
    ctx->proj = m; ctx->mvp_dirty = 1;
}

static inline void pyre_clear(pyre_ctx *ctx, pyre_rgb c) {
    pyre_fb_clear(&ctx->fb, c);
}

// transform one vertex to screen space. Returns 0 if behind camera.
static inline int pyre_project(pyre_ctx *ctx, vec3 p,
                               float *sx, float *sy, float *sz) {
    if (ctx->mvp_dirty) {
        ctx->mvp = m4_mul(ctx->proj, m4_mul(ctx->view, ctx->model));
        ctx->mvp_dirty = 0;
    }
    vec4 v = {p.x, p.y, p.z, 1.0f};
    vec4 c = m4_mul_v4(ctx->mvp, v);
    if (c.w <= 0.0f) return 0;
    float ndc_x = c.x / c.w;
    float ndc_y = c.y / c.w;
    float ndc_z = c.z / c.w;
    *sx = (ndc_x * 0.5f + 0.5f) * (float)ctx->fb.width;
    *sy = (0.5f - ndc_y * 0.5f) * (float)ctx->fb.height;
    *sz = ndc_z * 0.5f + 0.5f;
    return 1;
}

// Draw a triangle list. Returns triangles drawn.
static inline int pyre_draw_tris(pyre_ctx *ctx,
                                 const pyre_vertex *verts, int nverts) {
    int drawn = 0;
    for (int i = 0; i + 2 < nverts; i += 3) {
        float x0, y0, z0, x1, y1, z1, x2, y2, z2;
        int ok0 = pyre_project(ctx, verts[i+0].pos, &x0, &y0, &z0);
        int ok1 = pyre_project(ctx, verts[i+1].pos, &x1, &y1, &z1);
        int ok2 = pyre_project(ctx, verts[i+2].pos, &x2, &y2, &z2);
        if (!ok0 || !ok1 || !ok2) continue;
        if (pyre_tri_gouraud(&ctx->fb,
                x0, y0, z0, verts[i+0].color,
                x1, y1, z1, verts[i+1].color,
                x2, y2, z2, verts[i+2].color) > 0)
            drawn++;
    }
    return drawn;
}

#endif
