: AyaanScript+ — Adaptive 3D demo.
: Starts with GPU (gl_*) rendering. If frame rate drops below 30fps for
: several frames (another app stealing GPU time, etc), automatically
: falls back to CPU (gui_3d_*) at lower detail.

const W = 800
const H = 800

set use_gpu = 1
gl_init W H "AyaanScript+ - Adaptive 3D"

set ay = 0
set running = 1
set frame = 0

while running == 1
    if use_gpu == 1
        gl_open running
    endif
    if running == 0
        break
    endif

    set ay = {ay + 0.018}

    if use_gpu == 1
        gl_clear "#0a0a25"
        gl_rotate 0.4 ay 0
        gl_camera 6
        : 9 cubes in a grid
        set i = 0
        repeat 3 i
            set j = 0
            repeat 3 j
                set x = {(i - 2) * 1.7}
                set y = {(j - 2) * 1.7}
                set hue = {(i + j * 3) * 40}
                hsv_to_rgb hue 0.85 1.0 -> col
                gl_cube x y 0 1.2 col
            endrepeat
        endrepeat
        gl_swap

        : check if we should fall back
        gl_should_fallback fb
        gl_fps_actual fps
        if fb == 1
            psyska -/ "GPU running slow (fps={fps}), switching to CPU"
            gl_close
            set use_gpu = 0
            gui_native "AyaanScript+ - CPU Fallback" W H
            gui_fps 30
        endif
    endif

    if use_gpu == 0
        gui_open running
        if running == 0
            break
        endif
        gui_3d_clear "#0a0a25"
        gui_3d_rotate 0.4 ay 0
        gui_3d_camera 6
        : fewer cubes on CPU
        gui_3d_cube -1.5 0 0 1.5 "#ff5577"
        gui_3d_cube 1.5 0 0 1.5 "#55ccff"
        gui_3d_cube 0 -1.5 0 1.2 "#ffcc44"
        gui_update
    endif

    set frame = {frame + 1}
    if frame > 1000
        set running = 0
    endif
endwhile

if use_gpu == 1
    gl_close
else
    gui_close
endif

sys_cpu -> c
psyska -/ "final CPU load: {c}%"
psyska -/ "frames rendered: {frame}"
