/*
 * wnix, a Unix-like operating system for WebAssembly applications.
 * Copyright (C) 2025  Xavier Del Campo Romero
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <https://www.gnu.org/licenses/>.
 */

#include <gfx/gfx.h>
#include <gfx/private.h>
#include <drv/ps1/dma.h>
#include <drv/ps1/gpu.h>
#include <stddef.h>

static union gfx_sznext *first, *last;

void gfx_add_to_list(union gfx_sznext *const p)
{
    if (!first)
        first = p;
    else if (last)
        last->f.next = (uint32_t)p;

    last = p;
}

int gfx_draw(void)
{
    static union gfx_sznext term = {.cmd_next = 0xffffff};

    gfx_add_to_list(&term);

    if (SCREEN_W != 640)
        gfx_swapenvs();

    gfx_swapheap();

    GP1->mask = (const union drv_ps1_gpu_gp1)
    {
        .dma =
        {
            .cmd = GP1_DMA_DIR,
            .dir = GP1_DMA_DIR_CPU_TO_GP0
        }
    }.mask;

    D2_MADR->mask = (uint32_t)first;
    D2_BCR->syncmode_2.reserved = 0;
    D2_CHCR->mask = (const union chcr)
    {
        .bits =
        {
            .sync_mode = CHCR_SYNC_MODE_LINKED_LIST,
            .dir = CHCR_DIR_FROM_RAM,
            .start_busy = 1
        }
    }.mask;

    first = NULL;
    return 0;
}
