IT
games/alis / src / Alis / Machine.php · commit 9c722cf
<?phpnamespace App\Alis;// the VM's plain functions (fn/*.php): the playground's shared engine only autoloads classes (PSR-4)require_once __DIR__ . '/fn/_load.php';/** * Drives the ALIS VM from a JumPHP scene, one call per frame, never blocking. * * The C runs the VM in its own thread (alis_thread → alis_main_V2/V3: an endless loop over the entities * that draws the screen each time the list wraps around) and an SDL timer calling itroutine() at 50 Hz. * Here the same loop is a resumable state machine: frame() runs the entity loop until it draws (the end * of a VM cycle) and returns. A script that busy-waits (a loop polling the keyboard) is cut after * INSTRUCTION_BUDGET opcodes (VmYield between two opcodes) and resumed at the next frame exactly * where it stopped, so the browser never freezes. */final class Machine{    /** opcodes run in one frame before yielding (a frame normally needs a few thousand) */    public const INSTRUCTION_BUDGET = 400000;    private const PHASE_NONE = 0;    private const PHASE_BEFORE = 1;  // in the "before" vector loop (scan/inter)    private const PHASE_MAIN = 2;    // in the main script loop    private const PHASE_AFTER = 3;   // in the "after" vector loop    private const PHASE_SCAN = 4;    // v6: in the scan vector loop (header +0x24)    public bool $running = false;    public ?string $error = null;    public string $gameName = '';    /** opcodes executed in the last frame() (profiling) */    public int $lastOpcodes = 0;    public int $cycles = 0;    private int $phase = self::PHASE_NONE;    private bool $killed = false;    private int $budget = 0;    private float $timerAcc = 0.0;    private float $vmAcc = 0.0;    /** v6: alis_main_V6() has started (its first statement varD5 = alis_first_ent() is done) */    private bool $v6started = false;    /** v6: the local `script_org` of alis_main_V6(), kept across a yield */    private int $v6org = 0;    /**     * The C globals start at zero when the program starts: a second game in the same PHP process (back to the     * list, another game or edition) must not find the state of the first one (its memory offsets, its film...).     */    private static function resetState(): void    {        foreach ([Alis::class, AlisVars::class, Aud::class, AudioVars::class, Deus3dVars::class, Emu8950Vars::class,            EscnamesV6Vars::class, FilmVars::class, Host::class, ImageV6Vars::class, ImageVars::class, Img::class,            MemVars::class, MusicV0Vars::class, MusicV1Vars::class, MusicV2Vars::class, Opcodes2Vars::class,            OpcodesV6bVars::class, OpcodesV6Vars::class, OpcodesVars::class, PlatformVars::class, R3doVars::class,            Rrq3dVars::class, Scr::class, ScriptVars::class, SysAudioVars::class, Tables::class] as $class) {            alis_zero_class($class);        }    }    /** Starts the game whose data files are in $dataPath (folder of the main script). */    public function boot(string $dataPath): bool    {        try {            SysVars::init();            self::resetState();            Hd3d::$size = '';           // its blocks were in the old memory            Hd3d::$tablesFor = '';            Hd3d::$pending = null;            Hd3d::$land = null;            $pl = pl_guess(rtrim($dataPath, '/') . '/', 0);            if (!pl_supported($pl)) {                $this->error = "No ALIS game found in $dataPath";                return false;            }            sys_init($pl, 0, 0);            SysVars::$sys_timeclock_hz = intdiv(1000, $pl->is_little_endian ? 17 : 20);            if (alis_init($pl) == 1) {                $this->error = AlisVars::$alis_fatal ?? 'alis_init failed';                return false;            }            $this->gameName = Alis::$platform->name;            // sys_start() + alis_thread()            Alis::$state = C::eAlisStateRunning;            Alis::$cstopret = 0;            Alis::$varD5 = 0;            $this->phase = self::PHASE_NONE;            $this->v6started = false;            $this->running = true;            return true;        } catch (\Throwable $e) {            $this->fail($e);            return false;        }    }    /** Advances the game by $dt seconds of real time: the 50 Hz timer and at most one VM cycle. */    public function advance(float $dt, int $msec): bool    {        if (!$this->running) {            return false;        }        SysVars::$msec = $msec;        // the timer of the original machine (itroutine: timeclock, palette fades)        $interval = (Alis::$platform->is_little_endian ? 17 : 20) / 1000;        $this->timerAcc = \min($this->timerAcc + $dt, 0.25);        while ($this->timerAcc >= $interval) {            $this->timerAcc -= $interval;            itroutine(0, 0);        }        // a VM cycle every 20 ms * ctiming (C sys_delay_frame)        $period = 0.02 * \max(1, Alis::$ctiming);        $this->vmAcc = \min($this->vmAcc + $dt, $period * 3);        if ($this->vmAcc < $period) {            return false;        }        $this->vmAcc -= $period;        return $this->frame();    }    /** Runs the entity loop until the next draw (true) or a yield (false). */    public function frame(): bool    {        if (!$this->running) {            return false;        }        $this->budget = self::INSTRUCTION_BUDGET;        try {            $drawn = Alis::$platform->version >= 60 ? $this->mainV6()                : (Alis::$platform->version >= 30 ? $this->mainV3() : $this->mainV2());        } catch (VmYield) {            $drawn = false;        } catch (\Throwable $e) {            $this->fail($e);            return false;        }        $this->lastOpcodes = self::INSTRUCTION_BUDGET - $this->budget;        if (!Alis::$state) {            $this->running = false;        }        return $drawn;    }    private function fail(\Throwable $e): void    {        $this->running = false;        $where = Alis::$script !== null ? sprintf(' [script %s pc 0x%06x op 0x%06x]', Alis::$script->name, Alis::$script->pc, Alis::$opcode_pc) : '';        $this->error = $e->getMessage() . $where;        error_log('ALIS: ' . $e::class . ': ' . $e->getMessage() . $where . "\n" . $e->getTraceAsString());    }    /** C alis_loop(), resumable: runs the current script until it stops; VmYield when out of budget. */    private function loop(bool $resume): void    {        $script = Alis::$script;        if (!$resume) {            $script->running = 1;        }        SysVars::$inLoop = true;        $t0 = microtime(true);        try {            // the script compiled to PHP (Compiled\Compiler), else the byte code read here            $compiled = Compiled\Compiler::$on && $script->data !== null ? Compiled\Compiler::for($script->data) : null;            if ($compiled !== null) {                $compiled->run($script, $this->budget);                return;            }            while (Alis::$state && $script->running) {                if (--$this->budget <= 0) {                    throw new VmYield();                }                readexec_opcode();            }        } finally {            SysVars::$inLoop = false;            SysVars::$scriptTime += microtime(true) - $t0;    // the scripts and what they draw (speed checks)        }    }    private function entscr(int $d5): ScriptLive    {        return Alis::$live_scripts[intdiv($d5, ENT_STRIDE())];    }    /** C alis_main_V2() as a resumable state machine. */    private function mainV2(): bool    {        $resume = $this->phase;        while (Alis::$state) {            if ($resume === self::PHASE_BEFORE) {                // finish the script cut by the previous frame's yield, then go on after its loop                $resume = self::PHASE_NONE;                $this->loop(true);                goto resume_before;            }            if ($resume === self::PHASE_MAIN) {                // finish the script cut by the previous frame's yield, then go on after its loop                $resume = self::PHASE_NONE;                $this->loop(true);                goto resume_main;            }            if ($resume === self::PHASE_AFTER) {                // finish the script cut by the previous frame's yield, then go on after its loop                $resume = self::PHASE_NONE;                $this->loop(true);                goto resume_after;            }            if (Alis::$state == C::eAlisStateSave) {                alis_save_state();                Alis::$state = C::eAlisStateRunning;            } elseif (Alis::$state == C::eAlisStateLoad) {                alis_load_state();                Alis::$state = C::eAlisStateRunning;            }            Alis::$restart_loop = 0;            Alis::$script = $this->entscr(Alis::$varD5);            Alis::$fallent = 0;            Alis::$fseq = 0;            Alis::$acc = Alis::$acc_org;            $this->killed = false;            $vram = Alis::$script->vram_org;            if (get_0x24_scan_inter($vram) < 0 && (get_0x24_scan_inter($vram) & 2) == 0) {                $script_offset = swap32(get_0x14_script_org_offset($vram) + 10);                if ($script_offset != 0) {                    Alis::$script->vacc_off = Alis::$saversp = get_0x0a_vacc_offset($vram);                    savecoord($vram);                    Alis::$script->pc = get_0x14_script_org_offset($vram) + 10 + $script_offset;                    $this->phase = self::PHASE_BEFORE;                    $this->loop(false);                    resume_before:                    $this->phase = self::PHASE_NONE;                    $this->killed = Alis::$restart_loop && Alis::$platform->version == 10;                    if (!$this->killed) {                        updtcoord(Alis::$script->vram_org);                    }                }            }            $vram = Alis::$script->vram_org;            if (!$this->killed && get_0x04_cstart_csleep($vram) != 0) {                if (s8(get_0x04_cstart_csleep($vram)) < 0) {                    set_0x04_cstart_csleep($vram, 1);                }                set_0x01_wait_count($vram, get_0x01_wait_count($vram) - 1);                if (get_0x01_wait_count($vram) == 0) {                    savecoord($vram);                    Alis::$script->pc = get_0x08_script_ret_offset($vram);                    Alis::$script->vacc_off = get_0x0a_vacc_offset($vram);                    Alis::$fseq++;                    $this->phase = self::PHASE_MAIN;                    $this->loop(false);                    resume_main:                    $this->phase = self::PHASE_NONE;                    sys_delay_loop();                    if (Alis::$restart_loop == 0) {                        $vram = Alis::$script->vram_org;                        set_0x0a_vacc_offset($vram, Alis::$script->vacc_off);                        set_0x08_script_ret_offset($vram, Alis::$script->pc);                        $script_offset = swap32(get_0x14_script_org_offset($vram) + 6);                        if ($script_offset != 0) {                            Alis::$fseq = 0;                            Alis::$script->vacc_off = Alis::$saversp = get_0x0a_vacc_offset($vram);                            Alis::$script->pc = get_0x14_script_org_offset($vram) + 6 + $script_offset;                            $this->phase = self::PHASE_AFTER;                            $this->loop(false);                            resume_after:                            $this->phase = self::PHASE_NONE;                        }                        if (Alis::$restart_loop == 0) {                            $vram = Alis::$script->vram_org;                            updtcoord($vram);                            set_0x01_wait_count($vram, get_0x02_wait_cycles($vram));                        }                    }                }            }            Alis::$varD5 = xread16(Alis::$atent + 4 + Alis::$varD5) & 0xffff;            if (Alis::$varD5 == 0) {                Alis::$script = $this->entscr(Alis::$varD5);                draw();                sys_poll_event();                $this->cycles++;                return true;            }        }        return false;    }    /** C alis_main_V3() (versions 30/31) as a resumable state machine. */    private function mainV3(): bool    {        $resume = $this->phase;        // set before the resume gotos jump past their assignment below (a yield in the main phase)        $after_vec_off = Alis::$platform->version >= 60 ? 0x1c : 6;        while (Alis::$state) {            if ($resume === self::PHASE_BEFORE) {                // finish the script cut by the previous frame's yield, then go on after its loop                $resume = self::PHASE_NONE;                $this->loop(true);                goto resume_before;            }            if ($resume === self::PHASE_MAIN) {                // finish the script cut by the previous frame's yield, then go on after its loop                $resume = self::PHASE_NONE;                $this->loop(true);                goto resume_main;            }            if ($resume === self::PHASE_AFTER) {                // finish the script cut by the previous frame's yield, then go on after its loop                $resume = self::PHASE_NONE;                $this->loop(true);                goto resume_after;            }            if (Alis::$state == C::eAlisStateSave) {                alis_save_state();                Alis::$state = C::eAlisStateRunning;            } elseif (Alis::$state == C::eAlisStateLoad) {                alis_load_state();                Alis::$state = C::eAlisStateRunning;            }            Alis::$restart_loop = 0;            Alis::$script = $this->entscr(Alis::$varD5);            Alis::$fallent = 0;            Alis::$fseq = 0;            Alis::$acc = Alis::$acc_org;            $before_vec_off = Alis::$platform->version >= 60 ? 0x20 : 10;            $vram = Alis::$script->vram_org;            if (get_0x24_scan_inter($vram) < 0 && (get_0x24_scan_inter($vram) & 2) == 0) {                $script_offset = xread32(get_0x14_script_org_offset($vram) + $before_vec_off);                if ($script_offset != 0) {                    Alis::$script->vacc_off = Alis::$saversp = get_0x0a_vacc_offset($vram);                    savecoord($vram);                    Alis::$script->pc = get_0x14_script_org_offset($vram) + $before_vec_off + $script_offset;                    $this->phase = self::PHASE_BEFORE;                    $this->loop(false);                    resume_before:                    $this->phase = self::PHASE_NONE;                    if (Alis::$restart_loop) {                        // the entity killed itself (cexit / ckill, 0xbb67: add sp,8; jmp 0x37df):                        // no updtcoord, no main / after phase, straight to the next entity                        goto next_entity;                    }                    updtcoord(Alis::$script->vram_org);                }            }            $vram = Alis::$script->vram_org;            if (get_0x04_cstart_csleep($vram) != 0) {                if (s8(get_0x04_cstart_csleep($vram)) < 0) {                    set_0x04_cstart_csleep($vram, 1);                }                if (!ult(Alis::$timeclock, get_0x3e_wait_time($vram))) {                    set_0x3e_wait_time($vram, s32(get_0x3a_wait_cycles($vram) + Alis::$timeclock));                    savecoord($vram);                    Alis::$script->pc = get_0x08_script_ret_offset($vram);                    Alis::$script->vacc_off = get_0x0a_vacc_offset($vram);                    Alis::$fseq++;                    $this->phase = self::PHASE_MAIN;                    $this->loop(false);                    resume_main:                    $this->phase = self::PHASE_NONE;                    if (Alis::$restart_loop == 0) {                        $vram = Alis::$script->vram_org;                        set_0x0a_vacc_offset($vram, Alis::$script->vacc_off);                        set_0x08_script_ret_offset($vram, Alis::$script->pc);                        $script_offset = xread32(get_0x14_script_org_offset($vram) + (Alis::$platform->version >= 60 ? 0x1c : 6));                        if ($script_offset != 0) {                            Alis::$fseq = 0;                            Alis::$script->vacc_off = Alis::$saversp = get_0x0a_vacc_offset($vram);                            Alis::$script->pc = get_0x14_script_org_offset($vram) + (Alis::$platform->version >= 60 ? 0x1c : 6) + $script_offset;                            $this->phase = self::PHASE_AFTER;                            $this->loop(false);                            resume_after:                            $this->phase = self::PHASE_NONE;                        }                        if (Alis::$restart_loop == 0) {                            updtcoord(Alis::$script->vram_org);                        }                    }                }            }            next_entity:            Alis::$varD5 = xread16(Alis::$atent + 4 + Alis::$varD5) & 0xffff;            if (Alis::$varD5 == 0) {                Alis::$script = $this->entscr(Alis::$varD5);                draw();                sys_poll_event();                $this->cycles++;                return true;            }        }        return false;    }    /** C alis_main_V6() (versions >= 60) as a resumable state machine. */    private function mainV6(): bool    {        if (!$this->v6started) {            $this->v6started = true;            Alis::$varD5 = alis_first_ent();        }        $resume = $this->phase;        while (Alis::$state) {            if ($resume === self::PHASE_SCAN) {                // finish the script cut by the previous frame's yield, then go on after its loop                $resume = self::PHASE_NONE;                $this->loop(true);                goto resume_scan;            }            if ($resume === self::PHASE_BEFORE) {                $resume = self::PHASE_NONE;                $this->loop(true);                goto resume_before;            }            if ($resume === self::PHASE_MAIN) {                $resume = self::PHASE_NONE;                $this->loop(true);                goto resume_main;            }            if ($resume === self::PHASE_AFTER) {                $resume = self::PHASE_NONE;                $this->loop(true);                goto resume_after;            }            if (Alis::$state == C::eAlisStateSave) {                alis_save_state();                Alis::$state = C::eAlisStateRunning;            } elseif (Alis::$state == C::eAlisStateLoad) {                alis_load_state();                Alis::$state = C::eAlisStateRunning;            }            Alis::$restart_loop = 0;            Alis::$script = $this->entscr(Alis::$varD5);            xwrite16(Alis::$script->vram_org + 0x20, 0);            if (xread8(V6_FARSLEEP(Alis::$script->vram_org)) & (2 | AlisV6Const::V6_DORMANT)) {                goto v6_next_entity;            }            Alis::$fallent = 0;            Alis::$fseq = 0;            Alis::$acc = Alis::$acc_org;            $this->v6org = get_0x14_script_org_offset(Alis::$script->vram_org);            if (get_0x24_scan_inter(Alis::$script->vram_org) < 0) {                $scan_offset = xread32($this->v6org + 0x24);                if ($scan_offset != 0) {                    Alis::$saversp = get_0x0a_vacc_offset(Alis::$script->vram_org) & 0xffff;                    Alis::$script->vacc_off = s16(s16(Alis::$saversp) - 4);                    savecoord(Alis::$script->vram_org);                    Alis::$script->pc = s32($this->v6org + 0x24 + $scan_offset);                    $this->phase = self::PHASE_SCAN;                    $this->loop(false);                    resume_scan:                    $this->phase = self::PHASE_NONE;                    if (Alis::$restart_loop == 0) {                        Alis::$script->vacc_off = s16(Alis::$saversp);                        set_0x0a_vacc_offset(Alis::$script->vram_org, Alis::$script->vacc_off);                        updtcoord(Alis::$script->vram_org);                    }                }            }            $main_vec = s32($this->v6org + 0x18 + xread32($this->v6org + 0x18));            if (get_0x08_script_ret_offset(Alis::$script->vram_org) != $main_vec) {                $script_offset = xread32($this->v6org + 0x20);                if ($script_offset != 0) {                    Alis::$saversp = get_0x0a_vacc_offset(Alis::$script->vram_org) & 0xffff;                    Alis::$script->vacc_off = s16(s16(Alis::$saversp) - 4);                    savecoord(Alis::$script->vram_org);                    Alis::$script->pc = s32($this->v6org + 0x20 + $script_offset);                    $this->phase = self::PHASE_BEFORE;                    $this->loop(false);                    resume_before:                    $this->phase = self::PHASE_NONE;                    if (Alis::$restart_loop == 0) {                        Alis::$script->vacc_off = s16(Alis::$saversp);                        set_0x0a_vacc_offset(Alis::$script->vram_org, Alis::$script->vacc_off);                        updtcoord(Alis::$script->vram_org);                    }                }            }            if (get_0x04_cstart_csleep(Alis::$script->vram_org) != 0) {                if (s8(get_0x04_cstart_csleep(Alis::$script->vram_org)) < 0) {                    set_0x04_cstart_csleep(Alis::$script->vram_org, 1);                }                if (s32(Alis::$timeclock) >= s32(get_0x3e_wait_time(Alis::$script->vram_org))) {                    set_0x3e_wait_time(Alis::$script->vram_org, s32((get_0x3a_wait_cycles(Alis::$script->vram_org) & 0xffff) + Alis::$timeclock));                    savecoord(Alis::$script->vram_org);                    Alis::$script->pc = get_0x08_script_ret_offset(Alis::$script->vram_org);                    Alis::$script->vacc_off = get_0x0a_vacc_offset(Alis::$script->vram_org);                    Alis::$fseq++;                    $this->phase = self::PHASE_MAIN;                    $this->loop(false);                    resume_main:                    $this->phase = self::PHASE_NONE;                    if (Alis::$restart_loop == 0) {                        set_0x0a_vacc_offset(Alis::$script->vram_org, Alis::$script->vacc_off);                        set_0x08_script_ret_offset(Alis::$script->vram_org, Alis::$script->pc);                        $script_offset = xread32($this->v6org + 0x1c);                        if ($script_offset != 0) {                            Alis::$fseq = 0;                            Alis::$saversp = get_0x0a_vacc_offset(Alis::$script->vram_org) & 0xffff;                            Alis::$script->vacc_off = s16(s16(Alis::$saversp) - 4);                            Alis::$script->pc = s32($this->v6org + 0x1c + $script_offset);                            $this->phase = self::PHASE_AFTER;                            $this->loop(false);                            resume_after:                            $this->phase = self::PHASE_NONE;                            if (Alis::$restart_loop == 0) {                                Alis::$script->vacc_off = s16(Alis::$saversp);                                set_0x0a_vacc_offset(Alis::$script->vram_org, Alis::$script->vacc_off);                            }                        }                        if (Alis::$restart_loop == 0) {                            updtcoord(Alis::$script->vram_org);                        }                    }                }                if (Alis::$restart_loop == 0 && xread8(Alis::$script->vram_org + 0x45)) {                    v6_dirtyelems(Alis::$script->vram_org);                    xwrite8(Alis::$script->vram_org + 0x45, 0);                }            }            v6_next_entity:            Alis::$varD5 = xread16(Alis::$atent + 4 + Alis::$varD5) & 0xffff;            if (Alis::$varD5 == 0) {                Alis::$script = Alis::$main;                draw();                sys_poll_event();                Alis::$varD5 = alis_first_ent();                $this->cycles++;                return true;            }        }        return false;    }}