TR
games/alis / src / Alis / fn / alis.php · commit 9c722cf
<?phpnamespace App\Alis;// Port of alis/src/alis.c (MIT, Olivier Huguenot, Vadim Kindl), with the NDEBUG readexec_* macros and the// object-like / function-like macros of alis.h.// C globals: sAlisVM alis -> Alis, sHost host -> Host, alis_arena_size / alis_fatal / errors -> AlisVars,// tab_opcodes & co. -> Tables.// =============================================================================// MARK: - alis.h macros// =============================================================================/** ENT_STRIDE: entity id = byte offset into atent; v6 uses 0x18-byte memory nodes (DOS io_malloc table) */function ENT_STRIDE(): int{    return Alis::$platform->version >= 60 ? 0x18 : 6; // (int)sizeof(sScriptLoc)}/** ENTSCR(x) */function ENTSCR(int $x): ?ScriptLive{    return Alis::$live_scripts[intdiv($x, ENT_STRIDE())] ?? null;}/** ELEMIDX(x): return comparable number to what we see in ST debugger */function ELEMIDX(int $x): int{    return (intdiv($x - 0x78, 0x30) * 0x28) + 0x8078;}function ALIS_SCR_WCY(): int{    return Alis::$platform->version >= 30 ? 8 : 2;}function ALIS_SCR_WCZ(): int{    return Alis::$platform->version >= 30 ? 16 : 4;}function ALIS_SCR_WCAX(): int{    return Alis::$platform->version >= 30 ? 0x18 : -1;}function ALIS_SCR_WCAY(): int{    return Alis::$platform->version >= 30 ? 0x20 : -1;}function ALIS_SCR_WCAZ(): int{    return Alis::$platform->version >= 30 ? 0x28 : -1;}function ALIS_SCR_ADDR(): int{    return Alis::$platform->version >= 30 ? 0x32 : 0x8;}function ALIS_SCR_GROUP(): int{    return Alis::$platform->version >= 30 ? 0x30 : 0x6;}function ALIS_SCR_WCX2(): int{    return Alis::$platform->version >= 30 ? 0x34 : 0x9;}function ALIS_SCR_WCY2(): int{    return Alis::$platform->version >= 30 ? 0x38 : 0xa;}function ALIS_SCR_WCZ2(): int{    return Alis::$platform->version >= 30 ? 0x3c : 0xb;}/** ALIS_SET_SCRIPT(x) */function ALIS_SET_SCRIPT(?ScriptLive $x): void{    Alis::$script = $x;}/** PL_CGA(): PC CGA art: 4-colour sprites and the fixed CGA palette (not the 16-colour re-release) */function PL_CGA(): bool{    return Alis::$platform->kind == C::EPlatformPC && Alis::$platform->version <= 11 && !Alis::$platform->ega;}/** ATPROG(i): program table at atprog: data_org of each loaded program, game byte order */function ATPROG(int $i): int{    return xread32(Alis::$atprog + $i * 4);}function ATPROG_SET(int $i, int $v): void{    xwrite32(Alis::$atprog + $i * 4, $v);}/** V6_FARSLEEP(vram) (v6 layout, kept for completeness) */function V6_FARSLEEP(int $vram): int{    return $vram - 0x65;}// =============================================================================// MARK: - Opcode dispatch (NDEBUG READEXEC_FAST macros)// =============================================================================function readexec(array $table, string $name, int $identation): void{    $opcode = $table[ord(Alis::$mem[Alis::$script->pc++])];    $opcode();}function readexec_opcode(): void{    if (Alis::$platform->version >= 60) {        readexec_opcode_v6();        return;    }    $s = Alis::$script;    Alis::$opcode_pc = $s->pc;    (Tables::$tab_opcodes[ord(Alis::$mem[$s->pc++])])();}function readexec_codesc1name(): void{    (Tables::$tab_codesc1[ord(Alis::$mem[Alis::$script->pc++])])();}function readexec_codesc2name(): void{    (Tables::$codesc2names[ord(Alis::$mem[Alis::$script->pc++])])();}function readexec_codesc3name(): void{    (Tables::$codesc3names[ord(Alis::$mem[Alis::$script->pc++])])();}function readexec_opername(): void{    (Tables::$tab_opernames[ord(Alis::$mem[Alis::$script->pc++])])();    if (Alis::$platform->version < 60) {        Alis::$varD7 = ((Alis::$varD7 & 0xffff) ^ 0x8000) - 0x8000; // s16(), inlined: called for every operand    }}function readexec_storename(): void{    (Tables::$tab_storenames[ord(Alis::$mem[Alis::$script->pc++])])();}function readexec_addname(): void{    (Tables::$tab_addnames[ord(Alis::$mem[Alis::$script->pc++])])();}function readexec_addname_swap(): void{    $_tmp = Alis::$sd7;    Alis::$sd7 = Alis::$oldsd7;    Alis::$oldsd7 = $_tmp;    readexec_addname();}function readexec_opername_saveD7(): void{    Alis::$varD6 = Alis::$varD7;    readexec_opername();}function readexec_opername_saveD6(): void{    $_tmp = s16(Alis::$varD7);    readexec_opername_saveD7();    Alis::$varD6 = Alis::$varD7;    Alis::$varD7 = $_tmp;}function readexec_opername_swap(): void{    $_tmp = Alis::$sd7;    Alis::$sd7 = Alis::$sd6;    Alis::$sd6 = $_tmp;    readexec_opername();}// =============================================================================// MARK: - Private// =============================================================================function set_dispatch_tables(): void{    Tables::$opcodes = table_opcodes();    Tables::$codesc1names = table_codesc1names();    Tables::$codesc2names = table_codesc2names();    Tables::$codesc3names = table_codesc3names();    Tables::$opernames = table_opernames();    Tables::$storenames = table_storenames();    Tables::$addnames = table_addnames();    Tables::$tab_opcodes    = alis_tab_opcodes();    Tables::$tab_codesc1    = Alis::$platform->version >= 60 ? table_codesc1names_v40() : Tables::$codesc1names;    Tables::$tab_opernames  = alis_tab_opernames();    Tables::$tab_storenames = alis_tab_storenames();    Tables::$tab_addnames   = alis_tab_addnames();}/** PORT: memset(&struct, 0, sizeof struct) of a generated singleton class: every static property back to its default, then ::init(). */function alis_zero_class(string $class): void{    $rc = new \ReflectionClass($class);    foreach ($rc->getProperties(\ReflectionProperty::IS_STATIC) as $prop) {        if ($prop->hasDefaultValue()) {            $prop->setValue(null, $prop->getDefaultValue());        }    }    if (method_exists($class, 'init')) {        $class::init();    }}function alis_load_main(): void{    // 22400    = atprog > 2edd8 (22400 > 34ba8) ALIS_VM_RAM_ORG    // 224f0    = atent    // 2261c    = finent    // 22690    = header    Alis::$nbprog = 0;    Alis::$main = null;    // packed main script contains vm specs in the header    $fp = sys_fopen(Alis::$platform->main, 'rb');    if ($fp) {        Alis::$vprotect = 0;        if (Alis::$platform->version >= 60) {            $v60_header = (string)fread($fp, 0x18);            $v60_header = str_pad($v60_header, 0x18, "\0");            // swap16(v60_header + 0x10): game byte order            $sprite_count = Alis::$xle ? (ord($v60_header[0x10]) | (ord($v60_header[0x11]) << 8))                                       : ((ord($v60_header[0x10]) << 8) | ord($v60_header[0x11]));            Alis::$specs->script_data_tab_len = 512; // MAX_SCRIPTS            Alis::$specs->script_vram_tab_len = ($sprite_count + 0x10) & 0xffff;  // node count (DOS inisprit 0000e28f)            Alis::$specs->mem_cap = 0;            Alis::$specs->max_allocatable_vram = Alis::$platform->uid == C::EGameDeus ? 0x40000 : (Alis::$platform->kind == C::EPlatform3DO ? 0x30000 : 0x200000);            Alis::$specs->vram_to_data_offset = ($sprite_count + 3) * 0x30;        } else {            // skip 6 bytes (magic + check)            fseek($fp, 6, SEEK_CUR);            // read raw specs header            Alis::$specs->script_data_tab_len = fread16($fp);            Alis::$specs->script_vram_tab_len = fread16($fp);            Alis::$specs->mem_cap = fread32($fp);            Alis::$specs->max_allocatable_vram = fread32($fp);            Alis::$specs->vram_to_data_offset = fread32($fp);            Alis::$specs->vram_to_data_offset = s32(Alis::$specs->vram_to_data_offset + 3);            Alis::$specs->vram_to_data_offset = mul32(Alis::$specs->vram_to_data_offset, 0x30);        }        // set the location of scripts' vrams table        Alis::$atprog = Alis::$basemem;        Alis::$atent = s32(Alis::$atprog + Alis::$specs->script_data_tab_len * 4);        Alis::$atent_ptr = Alis::$vram_org + Alis::$specs->script_data_tab_len * 4;        Alis::$maxent = Alis::$specs->script_vram_tab_len;        Alis::$debent = s32(Alis::$atent + Alis::$maxent * ENT_STRIDE());        Alis::$finent = Alis::$debent;        Img::$debsprit = s32(((Alis::$debent + Alis::$specs->max_allocatable_vram) | 0xf) + 1);        Img::$finsprit = s32(Img::$finsprit + Img::$debsprit + Alis::$specs->vram_to_data_offset);        Alis::$debprog = Img::$finsprit;        Alis::$finprog = Alis::$debprog;        Alis::$dernprog = Alis::$atprog;        Alis::$maxprog = Alis::$specs->script_data_tab_len;        Alis::$finmem = s32(Alis::$platform->ram_sz - 0x9168);        if (Alis::$specs->mem_cap && ult(s32(Alis::$debprog + Alis::$specs->mem_cap), Alis::$finmem)) {            Alis::$finmem = s32(Alis::$debprog + Alis::$specs->mem_cap);   // as the original        }        inisprit();        if (Alis::$platform->version >= 60) {            // v6 node table            mem_set(Alis::$atent, 0, Alis::$maxent * 0x18);            for ($idx = 6; $idx < Alis::$maxent - 1; $idx++) {                xwrite16(Alis::$atent + $idx * 0x18 + 0x10, ($idx + 1) * 0x18);            }            Alis::$nodefree = 6 * 0x18;            Alis::$nodetail = ((Alis::$maxent - 1) * 0x18) & 0xffff;            xwrite16(Alis::$atent + C::NODE_BLKHEAD + 0xe, C::NODE_BLKTAIL);            xwrite16(Alis::$atent + C::NODE_BLKTAIL + 0xe, C::NODE_BLKTAIL);        } else {            // populate the script vrams table with the offsets (routine at $18cd8)            for ($idx = 0; $idx < Alis::$specs->script_vram_tab_len; $idx++) {                $offset = xswap16((1 + $idx) * 6) & 0xffff;                $p = Alis::$atent_ptr + $idx * 6;   // alis.atent_ptr[idx] = (sScriptLoc){0, offset}                hwrite32($p, 0);                hwrite16($p + 4, $offset);            }        }        Alis::$specs->script_vram_max_addr = s32(((Alis::$debent + Alis::$specs->max_allocatable_vram) | 0xf) + 1);        fclose($fp);        // load main scripts as an usual script...        $script = script_load(Alis::$platform->main);        if ($script === null) {            return;        }        Alis::$main = script_live($script);        Alis::$basemain = Alis::$main->vram_org;        if (Alis::$platform->version == 10) {            // NOTE: v1.0 default direction table: last index, then 26 unit vectors            $dirtab = [                0x19,                1,0,0, 1,1,0, 0,1,0, -1,1,0, -1,0,0, -1,-1,0, 0,-1,0, 1,-1,0, 1,0,1,                1,1,1, 0,1,1, -1,1,1, -1,0,1, -1,-1,1, 0,-1,1, 1,-1,1, 0,0,1, 1,0,-1,                1,1,-1, 0,1,-1, -1,1,-1, -1,0,-1, -1,-1,-1, 0,-1,-1, 1,-1,-1, 0,0,-1];            mem_write(Alis::$vstandard, pack('c*', ...$dirtab));        }        if (Alis::$platform->version < 60) {            // legacy model            Alis::$dernent = s16(xswap16(hread16(Alis::$atent_ptr + 4)));            hwrite16(Alis::$atent_ptr + 4, 0);        }    }}function alis_first_ent(): int{    // v6: entry 0 is the reserved null sentinel; the chain head is its next-link.    return Alis::$platform->version >= 60 ? (xread16(Alis::$atent + 4) & 0xffff) : 0;}// =============================================================================// MARK: - VM API// =============================================================================/** * Returns 0 on success, 1 on failure (C u8). */function alis_init(Platform $platform): int{    // PORT: the C globals alis / audio / host are zero-initialised at program start: initialise the    // singletons here unless the host already did (sys_init() may fill audio.host_freq before alis_init()).    if (!isset(Alis::$header)) {        Alis::init();    }    if (count(Aud::$channels) < 4) {        Aud::init();    }    if (!isset(Host::$pixelbuf)) {        Host::init();    }    Alis::$platform = clone $platform;    Alis::$cdspeed = 0x493e0;    Alis::$pays = 0;       // pays: keymode=Q=>0; keymode=A=>1 (France); keymode=Z=>2 (Germany)                           // cf. Z=QWERTZU=2, Q=QWERTY=1, A=AZERTY=0 -> keyboard_current    vram_init();    render3d_init();    script_guess_game($platform->main);    if (Alis::$platform->uid == 0) {        return 1;    }    set_dispatch_tables();    // PORT: C static initialisers of the image.c v6 globals (image agent)    if (Alis::$platform->version >= 60) {        ImageV6Vars::init();    }    // VM heap: the native pre-flight sizes it to the machine, else the game's preferred tier.    $floor = 0;    $pref = 0;    pl_arena_range(Alis::$platform, $floor, $pref);    Alis::$platform->ram_sz = AlisVars::$alis_arena_size ? AlisVars::$alis_arena_size : $pref;    Alis::$memclass = Alis::$platform->ram_sz < $pref ? pl_model_memclass(Alis::$platform->ram_sz) : 0;    Alis::$timeclock = 0;    Aud::$fsound = 1;    Aud::$fmusic = 1;    Aud::$musicId = 0xffff;    if (Alis::$platform->version >= 60) {        v6snd_init();                   // v6 voice-channel table    }    // memset(audio.tabinst, 0, sizeof(audio.tabinst));    Aud::$tabinst = array_map(fn () => new sAudioInstrument(), range(1, 128));    Alis::$restart_loop = 0;    Alis::$automode = 0;    // DOS platform config: bits encode detected hardware capabilities.    // Bit 0: joystick A, Bit 1: joystick B, Bit 2: mouse, Bit 6: CD speed >= 200000.    // Bit 7 is never set by the original executable.    // Scripts use oconfig / 0x40 to detect film replay capability.    if (Alis::$platform->kind == C::EPlatformPC) {        // Robinson's Requiem DOS (version 31): mouse + fast CD = 0x44 (config()/64 == 1)        Alis::$theconfig = (Alis::$platform->version == 31) ? 0x44 : 0x87;    }    Alis::$v6ips = 0x10;  // static init (oips reads it +1)    $pal_format = Img::$pal_format;    alis_zero_class(Img::class);        // memset(&image, 0, sizeof(image))    Img::$pal_format = $pal_format;    dos_pal_reset();    if (Alis::$platform->kind == C::EPlatformPC && PL_CGA()) {        // CGA-art games; the VGA ones start black like the original DAC (first fade from black)        for ($i = 0; $i < 4; $i++) {            $c = (ImageVars::$cga_palette[$i * 4 + 0] << 16) | (ImageVars::$cga_palette[$i * 4 + 1] << 8) | ImageVars::$cga_palette[$i * 4 + 2];            Img::$tpalet[$i] = $c;            Img::$mpalet[$i] = $c;        }    } else {        Img::$tpalet = array_fill(0, 256, 0);        Img::$mpalet = array_fill(0, 256, 0);    }    for ($i = 0; $i < 768; $i++) {        Img::$dkpalet[$i] = 0x100;    }    Img::$atpalet = 0; // image.tpalet (element offset into Img::$tpalet, see image.php)    Img::$ampalet = 0; // image.mpalet    Img::$flinepal = 0;    Img::$tlinepal[0] = 0;    Img::$tlinepal[1] = 0;    Img::$tlinepal[2] = 0xff;    Img::$tlinepal[3] = 0;    Img::$ptabfen = 0; // image.tabfen    Img::$fmouse = 0xff;    Img::$fonum = 0xffff;    Img::$loglarg = 0xa0; // 0x50 for st    // VM heap, sized by pl_compute_ram_size.    Alis::$mem = str_repeat("\0", Alis::$platform->ram_sz);    Alis::$xle = Alis::$platform->is_little_endian ? 1 : 0;    MemVars::$_xwc = (Alis::$platform->version >= 30 && Alis::$platform->is_little_endian) ? 1 : 0;    // image.spritemem = malloc(kSpriteMemSize): the sprite records are Sprite objects (sprite_var())    Img::$sprites = [];    Img::$buffer_alloc_size = Alis::$platform->width * (Alis::$platform->height + 2 * Host::$pixelbuf->surface_h);    ImageVars::$image_buf_cap = Img::$buffer_alloc_size;    if (Alis::$platform->version >= 60) {        // v6 switches 320 <-> 640x480 (cvideo)        // allocate the largest once, resize_screen reuses it        $big = 640 * (480 + 2 * Host::$pixelbuf->surface_h) + 640 + 2;        if (ImageVars::$image_buf_cap < $big) {            ImageVars::$image_buf_cap = $big;        }    }    // PORT: no platform framebuffer (sys_get_framebuffer() is NULL on desktop builds): host buffers    Img::$physic_alloc = host_alloc(ImageVars::$image_buf_cap);    Img::$logic_alloc = Img::$physic_alloc;    if (Alis::$platform->dbl_buf) {        Img::$logic_alloc = host_alloc(ImageVars::$image_buf_cap);    }    Img::$physic = Img::$physic_alloc + Host::$pixelbuf->surface_h * Alis::$platform->width;    Img::$logic  = Img::$logic_alloc  + Host::$pixelbuf->surface_h * Alis::$platform->width;    rgb_alloc(Alis::$platform->width, Alis::$platform->height);    Img::$logx1 = 0;    Img::$logx2 = Alis::$platform->width - 1;    Img::$logy1 = 0;    Img::$logy2 = Alis::$platform->height - 1;    // cswitching is never called by older games (see cswitching for the PC caveat).    Alis::$fswitch = Alis::$platform->dbl_buf;    Alis::$flagmain = 0;    Alis::$fallent = 0;    Alis::$fseq = 0;    Alis::$fmuldes = 0;    Alis::$fadddes = 0;    Alis::$ferase = 0;    Alis::$saversp = 0;    Alis::$basevar = 0;    Alis::$finmem = Alis::$basemem - 0x400; // 0x22000 + 0x3600;    Alis::$nbprog = 0;    Alis::$maxprog = 0;    Alis::$atprog = Alis::$basemem;    Alis::$nbent = 0;    Alis::$ptrent = 0; // alis.tablent    Alis::$tablent = array_fill(0, 256, 0);    Alis::$matent = array_fill(0, 256, 0);    Alis::$buffer = array_fill(0, 1024, 0);    Alis::$ctiming = 0;    Alis::$prevkey = 0;    // init virtual registers    Alis::$varD6 = Alis::$varD7 = 0;    // init temp chunks    Alis::$bsd7 = 0x1a1e6;    Alis::$bsd6 = 0x1a2e6;    Alis::$bsd7bis = 0x1a3e6;    // NOTE: random address that should be empty    Alis::$vstandard = 0x19d16; // 0x153C6;    mem_set(Alis::$vstandard, 0, 256);    // Work areas sit below every game's basemem (lowest 0x1f300): at 0x212ee/0x22880 they    // overlapped the entity contexts of low-basemem games (Arborea: the expression stack    // overwrote another entity's wait reload).    Alis::$tabptr = 0x19c00; // tab containing 2 * 16 pointers    mem_set(Alis::$tabptr, 0, 2 * 16 * 4);    Alis::$sd7 = Alis::$bsd7;    Alis::$sd6 = Alis::$bsd6;    Alis::$oldsd7 = Alis::$bsd7bis;    // init helpers    Alis::$fp = null;    // set the vram origin at some abitrary location (same as atari, to ease debug)    Alis::$vram_org = Alis::$basemem;    // the script data address table is located at vram start    Alis::$script_data_orgs = Alis::$vram_org;    Alis::$acc = Alis::$acc_org = (Alis::$platform->version >= 60 ? AlisVars::$kAccOrgV6 : AlisVars::$kAccOrg);    Alis::$pretrlinetra = 0x1ef7c;    Alis::$pretglinetra = 0x1f58e;    Alis::$tlinetra  = 0x1e602;    Alis::$itlinetra = 0x1e802;    Alis::$trlinetra = 0x1f07e;    Alis::$tglinetra = 0x1f690;    Alis::$fmouse = 0xff;    // init host system stuff    Host::$pixelbuf->w = Alis::$platform->width;    Host::$pixelbuf->h = Alis::$platform->height;    Host::$pixelbuf->data = Img::$physic;    Host::$pixelbuf->palette = 0; // image.mpalet (the host reads Img::$mpalet)    Alis::$load_delay = 0;    Alis::$unload_delay = 0;    // load main script    alis_load_main();    if (Alis::$main === null) {        return 1;    }    ALIS_SET_SCRIPT(Alis::$main);    Alis::$basemain = Alis::$main->vram_org;    Alis::$desmouse = 0;    // Robinsons Requiem    Img::$fdoland = 0;    Img::$scdirect = 0;    Img::$tlpix = 0;    Img::$atalti = 0;    Img::$atlpix = 0;    Img::$atalias = 0;    Img::$tlland = 0;    Img::$atlland = 0;    Img::$landone = 0;    Img::$purey = 0;    Img::$purey2 = 0;    Img::$fhorizon = 0;    Img::$zoombid = 0x20de2;    Img::$landdata = 0x1ccc2;    return 0;}function alis_deinit(): void{    // free scripts    // TODO: use real script table / cunload    Alis::$mem = '';    Img::$sprites = [];    Img::$physic_alloc = 0;    Img::$logic_alloc = 0;    Img::$physic = 0;    Img::$logic = 0;    rgb_alloc(0, 0);    Img::$buffer_alloc_size = 0;    ImageVars::$image_buf_cap = 0;}/** PORT: name of the function a callable refers to (to map audio.soundrout to the C audio_type). */function alis_callable_name($f): string{    if ($f === null) {        return '';    }    if (is_string($f)) {        return strtolower(ltrim($f, '\\'));    }    try {        return strtolower((new \ReflectionFunction(\Closure::fromCallable($f)))->getName());    } catch (\Throwable) {        return '';    }}/** PORT: the static properties of a class, minus $skip. */function alis_class_state(string $class, array $skip = []): array{    $state = [];    foreach ((new \ReflectionClass($class))->getStaticProperties() as $k => $v) {        if (!in_array($k, $skip, true)) {            $state[$k] = $v;        }    }    return $state;}/** PORT: restores static properties saved by alis_class_state(), minus $skip. */function alis_class_restore(string $class, array $state, array $skip = []): void{    $rc = new \ReflectionClass($class);    foreach ($state as $k => $v) {        if (!in_array($k, $skip, true) && $rc->hasProperty($k)) {            $class::$$k = $v;        }    }}/** PORT: reads another translator's static property (null when the class / property does not exist). */function alis_static_get(string $class, string $prop): mixed{    return class_exists($class) && property_exists($class, $prop) ? $class::$$prop : null;}/** PORT: writes another translator's static property when it exists. */function alis_static_set(string $class, string $prop, mixed $value): void{    if ($value !== null && class_exists($class) && property_exists($class, $prop)) {        $class::$$prop = $value;    }}/** Host buffer pointers of image that a state load keeps (runtime allocations, not saved). */const ALIS_IMG_HOST_PTRS = ['spritemem', 'physic', 'logic', 'physic_alloc', 'logic_alloc', 'backmap', 'atpalet', 'ampalet',    'ptabfen', 'bufpack', 'wlogic', 'bgcache_alloc', 'wdraw', 'rgblogic', 'rgbphysic', 'depthbuf', 'depthrows', 'omask',    'terrgba', 'terrgbarows'];/** * PORT: the C dumps the raw structs (alis, image, audio, mv1a, mv2a, mv0a...) with fwrite. Here the static * properties of Alis / Img / Aud and the player objects are serialize()d in one blob (which keeps the * ScriptLive -> ScriptData links, so the C relinking by script id is not needed), together with the VM RAM * (Alis::$mem up to ram_sz), the sprite objects (image.spritemem) and the physic/logic screens. * Layout: "ALIS\0", kSaveStateVersion + "\0", 8 hex digits = blob size, blob, cdtrack_save(), 14 PSG bytes. * FLI/FLC video and v6 state are not saved (dropped features). */function alis_save_state(): void{    $path = Alis::$platform->path . 'alis.state';    $fp = sys_fopen($path, 'wb');    if ($fp === null || $fp === false) {        return;    }    $ram_sz = Alis::$platform->ram_sz;    $scr_sz = Alis::$platform->width * Alis::$platform->height;    $main_idx = 0;    $script_idx = 0;    for ($i = 0; $i < C::MAX_SCRIPTS; $i++) {        if (Alis::$live_scripts[$i] === Alis::$main) {            $main_idx = $i;        }        if (Alis::$live_scripts[$i] === Alis::$script) {            $script_idx = $i;        }    }    $audio_type = 0;    $rout = property_exists(Aud::class, 'soundrout') ? alis_callable_name(Aud::$soundrout) : '';    $types = [1 => 'mv1_soundrout', 2 => 'mv2_soundrout', 3 => 'mv2_chiprout', 4 => 'mv2_opl2rout', 5 => 'mv0_soundrout'];    foreach ($types as $t => $fname) {        if ($rout === strtolower(__NAMESPACE__ . '\\' . $fname)) {            $audio_type = $t;            break;        }    }    $mouse = sys_get_mouse();    $state = [        'alis' => alis_class_state(Alis::class, ['mem', 'fp']),        'ram' => substr(Alis::$mem, 0, $ram_sz),        'main_idx' => $main_idx,        'script_idx' => $script_idx,        'mouse_enabled' => $mouse->enabled,        'image' => alis_class_state(Img::class),        'physic' => substr(Alis::$mem, Img::$physic, $scr_sz),        'logic' => Img::$logic != Img::$physic ? substr(Alis::$mem, Img::$logic, $scr_sz) : null,        'audio' => alis_class_state(Aud::class, ['soundrout']),        'audio_type' => $audio_type,        'mv1a' => alis_static_get(MusicV1Vars::class, 'mv1a'),        'mv2a' => alis_static_get(MusicV2Vars::class, 'mv2a'),        'opl_sfx_initialized' => alis_static_get(SysAudioVars::class, 'opl_sfx_initialized'),        'opl_sfx_type' => alis_static_get(SysAudioVars::class, 'opl_sfx_type'),        'ptscreen' => Scr::$ptscreen,        'mv0a' => alis_static_get(MusicV0Vars::class, 'mv0a'),        'film' => film_save_state(),                                   // FLI/FLC video (video.php)        'v6voices' => alis_static_get(AudioVars::class, 'v6voices'),   // v6 voices (alis.mem offsets)    ];    $blob = serialize($state);    fwrite($fp, "ALIS\0");    fwrite($fp, AlisConst::kSaveStateVersion . "\0");    fwrite($fp, sprintf('%08x', strlen($blob)));    fwrite($fp, $blob);    cdtrack_save($fp);    $psg = '';    for ($r = 0; $r < 14; $r++) {        $psg .= chr(sys_read_psg($r) & 0xff);    }    fwrite($fp, $psg);    sys_fclose($fp); // PORT: sys_fclose() commits the write stream to the JumPHP storage}/** PORT: see alis_save_state() for the file layout. */function alis_load_state(): void{    $path = Alis::$platform->path . 'alis.state';    $fp = sys_fopen($path, 'rb');    if ($fp === null || $fp === false) {        return;    }    $buffer = fread_bytes($fp, 5);    if ($buffer !== "ALIS\0") {        fclose($fp);        return;    }    $buffer = fread_bytes($fp, 5);    $ver = (int)$buffer;    $ver_current = (int)AlisConst::kSaveStateVersion;    if ($ver != $ver_current) {        fclose($fp);        return;    }    $alis_size = (int)hexdec(fread_bytes($fp, 8));    $state = $alis_size > 0 ? @unserialize(fread_bytes($fp, $alis_size)) : false;    if (!is_array($state)) {        fclose($fp);        return;    }    $savepath = Alis::$platform->path;    $savemain = Alis::$platform->main;    sys_isr_pause(1);    $oldmem = Alis::$mem;    $oldmem_size = Alis::$platform->ram_sz;    $cur_w = Alis::$platform->width;    $cur_h = Alis::$platform->height;    // memset(&alis, 0, alis_size); fread(&alis, ...)    Alis::init();    alis_class_restore(Alis::class, $state['alis'], ['mem', 'fp']);    Alis::$fp = null;    // v6 can save in another resolution: buffers keep the current size until resized below    $save_w = Alis::$platform->width;    $save_h = Alis::$platform->height;    Alis::$platform->width = $cur_w;    Alis::$platform->height = $cur_h;    Alis::$platform->path = $savepath;    Alis::$platform->main = $savemain;    // Reuse the arena (VM RAM followed by the host buffers)    $ram = $state['ram'];    $vram_size = strlen($ram);    if ($vram_size == $oldmem_size) {        Alis::$mem = $ram . substr($oldmem, $oldmem_size);    } else {        // PORT: another arena size: the host buffers keep their offsets past the old RAM size        Alis::$mem = $ram . ($vram_size < $oldmem_size ? substr($oldmem, $vram_size) : substr($oldmem, $oldmem_size));    }    Alis::$xle = Alis::$platform->is_little_endian ? 1 : 0;    MemVars::$_xwc = (Alis::$platform->version >= 30 && Alis::$platform->is_little_endian) ? 1 : 0;    Alis::$vram_org = Alis::$basemem;    // The string buffers are offsets already (the C rebases the saving process's host pointers)    $bufs = [0x1a1e6, 0x1a2e6, 0x1a3e6];    $ps = ['sd7', 'sd6', 'oldsd7'];    $used = [0, 0, 0];    $ok = [0, 0, 0];    for ($i = 0; $i < 3; $i++) {        $off = Alis::${$ps[$i]};        for ($b = 0; $b < 3; $b++) {            if ($off == $bufs[$b] && !$used[$b]) {                Alis::${$ps[$i]} = $bufs[$b];                $used[$b] = $ok[$i] = 1;            }        }    }    for ($i = 0; $i < 3; $i++) {        for ($b = 0; $b < 3 && !$ok[$i]; $b++) {            if (!$used[$b]) {                Alis::${$ps[$i]} = $bufs[$b];                $used[$b] = $ok[$i] = 1;            }        }    }    Alis::$bsd7 = $bufs[0];    Alis::$bsd6 = $bufs[1];    Alis::$bsd7bis = $bufs[2];    Alis::$atent_ptr = Alis::$vram_org + Alis::$specs->script_data_tab_len * 4;    // host text buffers belong to the saving process    Alis::$text_data = 0;    Alis::$text_sz = 0;    v6text_reload();    // (alis.acc / acc_org were restored with the Alis state)    if (Alis::$platform->version < 60) {        Alis::$acc = Alis::$acc_org = AlisVars::$kAccOrg;   // older saves stored 0x22880    }    // loaded_scripts / live_scripts come back with their links (serialize() keeps object identity)    for ($i = 0; $i < C::MAX_SCRIPTS; $i++) {        $live = Alis::$live_scripts[$i] ?? null;        if ($live !== null && $live->data === null) {            $live->name = '';        }    }    Alis::$main = Alis::$live_scripts[$state['main_idx']] ?? null;    ALIS_SET_SCRIPT(Alis::$live_scripts[$state['script_idx']] ?? null);    // mouse    $enable_mouse = $state['mouse_enabled'];    // image: runtime-allocated pointers (not into alis.mem) must survive the restore.    $keep = [];    foreach (ALIS_IMG_HOST_PTRS as $k) {        $keep[$k] = Img::$$k;    }    alis_zero_class(Img::class);    alis_class_restore(Img::class, $state['image'], ALIS_IMG_HOST_PTRS);    foreach ($keep as $k => $v) {        Img::$$k = $v;    }    if ($save_w != $cur_w || $save_h != $cur_h) {        $saved = alis_class_state(Img::class);        resize_screen($save_w, $save_h);        Img::$logx1 = $saved['logx1'];        Img::$logx2 = $saved['logx2'];        Img::$logy1 = $saved['logy1'];        Img::$logy2 = $saved['logy2'];        Img::$loglarg = $saved['loglarg'];        Img::$wdraw = $saved['wdraw'] == $saved['backmap'] ? Img::$backmap : Img::$logic;    }    // image.spritemem and the screens    $scr_sz = Alis::$platform->width * Alis::$platform->height;    if ($state['physic'] !== '' && $scr_sz > 0) {        mem_write(Img::$physic, substr($state['physic'], 0, $scr_sz));    }    // Single-buffered: logic == physic and only one buffer was saved (mirror alis_save_state).    if (Img::$logic != Img::$physic && $state['logic'] !== null && $scr_sz > 0) {        mem_write(Img::$logic, substr($state['logic'], 0, $scr_sz));    }    // audio    alis_class_restore(Aud::class, $state['audio'], ['soundrout']);    // PORT: audio.soundrout (function pointer) must exist as Aud::$soundrout (?callable)    switch (property_exists(Aud::class, 'soundrout') ? $state['audio_type'] : -1) {        case 1:  Aud::$soundrout = __NAMESPACE__ . '\\mv1_soundrout';  break;        case 2:  Aud::$soundrout = __NAMESPACE__ . '\\mv2_soundrout';  break;        case 3:  Aud::$soundrout = __NAMESPACE__ . '\\mv2_chiprout';   break;        case 4:  Aud::$soundrout = __NAMESPACE__ . '\\mv2_opl2rout';   break;        case 5:  Aud::$soundrout = __NAMESPACE__ . '\\mv0_soundrout'; mv0_reset(); break;        case -1: break;        default: Aud::$soundrout = '';                break;    }    alis_static_set(MusicV1Vars::class, 'mv1a', $state['mv1a']);    alis_static_set(MusicV2Vars::class, 'mv2a', $state['mv2a']);    // OPL2 SFX channel state (non-Atari builds)    alis_static_set(SysAudioVars::class, 'opl_sfx_initialized', $state['opl_sfx_initialized']);    alis_static_set(SysAudioVars::class, 'opl_sfx_type', $state['opl_sfx_type']);    // FLI/FLC video    film_load_state($state['film'] ?? null);    Scr::$ptscreen = $state['ptscreen'];    // 3D renderer host state is not saved: reopen the 3D screens on their saved arenas    if (Alis::$platform->version >= 60) {        // PORT: v6xdirty is an image.c global (image agent): set where it exists        alis_static_set(ImageVars::class, 'v6xdirty', 1);        for ($o = Scr::$ptscreen & 0xffff; $o != 0; $o = xread16(Alis::$basemain + $o + 0x5c) & 0xffff) {            $scr = Alis::$basemain + $o;            if (xread8($scr + 0x5a) == 6 && !(xread8($scr + 0x58) & 0x40)) {                v6x3d_open($scr);            }        }    }    cdtrack_load($fp);    // v6 voices (PORT: v6 games only: the voices are idle in the older ones)    if (Alis::$platform->version >= 60) {        if (isset($state['v6voices'])) {            alis_static_set(AudioVars::class, 'v6voices', $state['v6voices']);        } else {            v6snd_init();        }    }    // mv0 player and YM registers (older files: mv0 stays reset)    if (!isset($state['mv0a'])) {        mv0_reset();    } else {        alis_static_set(MusicV0Vars::class, 'mv0a', $state['mv0a']);        $psg = fread_bytes($fp, 14);        if (strlen($psg) == 14) {            for ($r = 0; $r < 14; $r++) {                sys_write_psg($r, ord($psg[$r]));            }        }    }    fclose($fp);    Host::$pixelbuf->palette = 0; // image.mpalet (the host reads Img::$mpalet)    dos_pal_sync_from_image();    if (Alis::$platform->version >= 60) {        v6_worldhead_rebuild();    }    sys_init_timers();    sys_enable_mouse($enable_mouse);    set_update_cursor();    // requiem    Alis::$pretrlinetra = 0x1ef7c;    Alis::$pretglinetra = 0x1f58e;    Alis::$tlinetra  = 0x1e602;    Alis::$itlinetra = 0x1e802;    Alis::$trlinetra = 0x1f07e;    Alis::$tglinetra = 0x1f690;    sys_isr_pause(0);}function alis_loop(): void{    Alis::$script->running = 1;    while (Alis::$state && Alis::$script->running) {        readexec_opcode();    }    // alis loop was stopped by 'cexit', 'cstop', or user event}function savecoord(int $addr): void{    Img::$oldcx = xread16($addr + C::ALIS_SCR_WCX);    Img::$oldcy = xread16($addr + ALIS_SCR_WCY());    Img::$oldcz = xread16($addr + ALIS_SCR_WCZ());    // ishar 3    if (Alis::$platform->version >= 30) {        Img::$oldacx = xread16($addr + ALIS_SCR_WCAX());        Img::$oldacy = xread16($addr + ALIS_SCR_WCAY());        Img::$oldacz = xread16($addr + ALIS_SCR_WCAZ());    }}/** Ishar 3 angle wrap of updtcoord(). */function updtcoord_angle(int $angle): int{    if ((0x168 < $angle) && 0x168 < ($angle = s16($angle - 0x168))) {        $angle = s16($angle % 0x168);    }    if ($angle < -0x168 && ($angle = s16($angle + 0x168)) < -0x168) {        $angle = s16($angle % 0x168);    }    return $angle;}function updtcoord(int $addr): void{    // v6: angles are RAW 16-bit (65536 per circle): no Ishar 3 degree normalisation    if (Alis::$platform->version >= 60) {        return;    }    if (Alis::$platform->version < 30) {        // ishar 1&2        $addx = s16(xread16($addr + 0) - Img::$oldcx);        $addy = s16(xread16($addr + 2) - Img::$oldcy);        $addz = s16(xread16($addr + 4) - Img::$oldcz);        if ($addz != 0 || $addx != 0 || $addy != 0) {            if (Alis::$platform->version == 10) {                scalaire_v10(get_0x16_screen_id(Alis::$script->vram_org), $addx, $addy, $addz);            }            for ($sprite = sprite_var(get_0x18_unknown(Alis::$script->vram_org)); $sprite !== null; $sprite = sprite_var($sprite->to_next)) {                if ($sprite->state == 0) {                    $sprite->state = 2;                }                $sprite->depx = s16($sprite->depx + $addx);                $sprite->depy = s16($sprite->depy + $addy);                $sprite->depz = s16($sprite->depz + $addz);            }        }    } else {        // ishar 3        $angle = xread16($addr + ALIS_SCR_WCAX());        if ($angle != Img::$oldacx) {            $angle = updtcoord_angle($angle);            xwrite16($addr + ALIS_SCR_WCAX(), $angle);        }        $angle = xread16($addr + ALIS_SCR_WCAY());        if ($angle != Img::$oldacy) {            $angle = updtcoord_angle($angle);            xwrite16($addr + ALIS_SCR_WCAY(), $angle);        }        $angle = xread16($addr + ALIS_SCR_WCAZ());        if ($angle != Img::$oldacz) {            $angle = updtcoord_angle($angle);            xwrite16($addr + ALIS_SCR_WCAZ(), $angle);        }        $addx = s16(xread16($addr + C::ALIS_SCR_WCX) - Img::$oldcx);        $addy = s16(xread16($addr + ALIS_SCR_WCY()) - Img::$oldcy);        $addz = s16(xread16($addr + ALIS_SCR_WCZ()) - Img::$oldcz);        $wcaz = xread16($addr + ALIS_SCR_WCAZ()) & 0xffff;        if ($angle != Img::$oldacz || $addz != 0 || $addx != 0 || $addy != 0) {            for ($sprite = sprite_var(get_0x18_unknown(Alis::$script->vram_org)); $sprite !== null; $sprite = sprite_var($sprite->to_next)) {                if ($sprite->state == 0) {                    $sprite->state = 2;                }                $sprite->depx = s16($sprite->depx + $addx);                $sprite->depy = s16($sprite->depy + $addy);                $sprite->depz = s16($sprite->depz + $addz);                // Angle stored at memory offset 0x26 within u32 at 0x24:                // on LE that's the HIGH word, on BE it's the LOW word                if (Alis::$platform->is_little_endian) {                    $sprite->sprite_0x28 = s32(($sprite->sprite_0x28 & 0xFFFF) | ($wcaz << 16));                } else {                    $sprite->sprite_0x28 = s32(($sprite->sprite_0x28 & ~0xFFFF) | ($wcaz & 0xFFFF));                }            }        }    }}function alis_main_V2(): void{    while (Alis::$state) {        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_SET_SCRIPT(ENTSCR(Alis::$varD5));        Alis::$fallent = 0;        Alis::$fseq = 0;        Alis::$acc = Alis::$acc_org;        $killed = 0;        if (get_0x24_scan_inter(Alis::$script->vram_org) < 0 && (get_0x24_scan_inter(Alis::$script->vram_org) & 2) == 0) {            $script_offset = read32(get_0x14_script_org_offset(Alis::$script->vram_org) + 10);   // C swap32()            if ($script_offset != 0) {                Alis::$script->vacc_off = Alis::$saversp = get_0x0a_vacc_offset(Alis::$script->vram_org);                Alis::$saversp &= 0xffff;                savecoord(Alis::$script->vram_org);                Alis::$script->pc = s32(get_0x14_script_org_offset(Alis::$script->vram_org) + 10 + $script_offset);                alis_loop();                $killed = Alis::$restart_loop && Alis::$platform->version == 10;                if (!$killed) {                    updtcoord(Alis::$script->vram_org);                }            }        }        if (!$killed && 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);            }            set_0x01_wait_count(Alis::$script->vram_org, get_0x01_wait_count(Alis::$script->vram_org) - 1);            if (get_0x01_wait_count(Alis::$script->vram_org) == 0) {                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 = (Alis::$fseq + 1) & 0xff;                alis_loop();                sys_delay_loop();                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 = read32(get_0x14_script_org_offset(Alis::$script->vram_org) + 6);   // C swap32()                    if ($script_offset != 0) {                        Alis::$fseq = 0;                        Alis::$script->vacc_off = Alis::$saversp = get_0x0a_vacc_offset(Alis::$script->vram_org);                        Alis::$saversp &= 0xffff;                        Alis::$script->pc = s32(get_0x14_script_org_offset(Alis::$script->vram_org) + 6 + $script_offset);                        alis_loop();                    }                    if (Alis::$restart_loop == 0) {                        updtcoord(Alis::$script->vram_org);                        set_0x01_wait_count(Alis::$script->vram_org, get_0x02_wait_cycles(Alis::$script->vram_org));                    }                }            }        }        Alis::$varD5 = xread16(Alis::$atent + 4 + Alis::$varD5) & 0xffff;        if (Alis::$varD5 == 0) {            ALIS_SET_SCRIPT(ENTSCR(Alis::$varD5));            draw();            sys_poll_event();        }    }}function alis_main_V3(): void{    while (Alis::$state) {        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_SET_SCRIPT(ENTSCR(Alis::$varD5));        Alis::$fallent = 0;        Alis::$fseq = 0;        Alis::$acc = Alis::$acc_org;        // old format script vectors: "before" at +10, "after" at +6        $before_vec_off = Alis::$platform->version >= 60 ? 0x20 : 10;        $after_vec_off  = Alis::$platform->version >= 60 ? 0x1c : 6;        if (get_0x24_scan_inter(Alis::$script->vram_org) < 0 && (get_0x24_scan_inter(Alis::$script->vram_org) & 2) == 0) {            $script_offset = xread32(get_0x14_script_org_offset(Alis::$script->vram_org) + $before_vec_off);            if ($script_offset != 0) {                Alis::$script->vacc_off = Alis::$saversp = get_0x0a_vacc_offset(Alis::$script->vram_org);                Alis::$saversp &= 0xffff;                savecoord(Alis::$script->vram_org);                Alis::$script->pc = s32(get_0x14_script_org_offset(Alis::$script->vram_org) + $before_vec_off + $script_offset);                alis_loop();                if (Alis::$restart_loop == 0) { // killed itself: no updtcoord on its old vram                    updtcoord(Alis::$script->vram_org);                }            }        }        if (Alis::$restart_loop == 0 && 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 (ule(get_0x3e_wait_time(Alis::$script->vram_org), Alis::$timeclock)) {                set_0x3e_wait_time(Alis::$script->vram_org, s32(get_0x3a_wait_cycles(Alis::$script->vram_org) + 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 = (Alis::$fseq + 1) & 0xff;                alis_loop();                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(get_0x14_script_org_offset(Alis::$script->vram_org) + $after_vec_off);                    if ($script_offset != 0) {                        Alis::$fseq = 0;                        Alis::$script->vacc_off = Alis::$saversp = get_0x0a_vacc_offset(Alis::$script->vram_org);                        Alis::$saversp &= 0xffff;                        Alis::$script->pc = s32(get_0x14_script_org_offset(Alis::$script->vram_org) + $after_vec_off + $script_offset);                        alis_loop();                    }                    if (Alis::$restart_loop == 0) {                        updtcoord(Alis::$script->vram_org);                    }                }            }        }        Alis::$varD5 = xread16(Alis::$atent + 4 + Alis::$varD5) & 0xffff;        if (Alis::$varD5 == 0) {            ALIS_SET_SCRIPT(ENTSCR(Alis::$varD5));            draw();            sys_poll_event();        }    }}function alis_thread($data = null): int{    Alis::$cstopret = 0;    Alis::$varD5 = 0;    if (alis_static_get(SysVars::class, 'opt_load_state')) {        Alis::$state = C::eAlisStateLoad;    }    if (Alis::$platform->version < 30) {        alis_main_V2();    } elseif (Alis::$platform->version >= 60) {        alis_main_V6();    } else {        alis_main_V3();    }    return 0;}/** PORT: C prints the message and exit(-1)s: the port throws. */function alis_error(int $errnum, ...$args): void{    $err = [0, '', ''];    foreach (AlisVars::errors as $e) {        if ($e[0] == $errnum) {            $err = $e;            break;        }    }    try {        $msg = $err[2] !== '' ? vsprintf($err[2], array_map(fn ($a) => is_scalar($a) ? $a : '', $args)) : "error $errnum";    } catch (\Throwable) {        $msg = $err[2];    }    throw new \RuntimeException('ALIS: ' . rtrim((string)$msg));}// =============================================================================// MARK: - Finding resources in the script// =============================================================================function adresdes(int $idx): int{    $addr = get_0x14_script_org_offset(Alis::$flagmain ? Alis::$main->vram_org : Alis::$script->vram_org);    if (Alis::$platform->version >= 60) {        $len = xread16($addr + 0x3e);        if ($len > $idx) {            return s32($addr + 0x40 + $idx * 4);        }        return 0xf;    }    if (Alis::$platform->version == 10) {        if (Alis::$platform->kind == C::EPlatformPC) {            $addr = s32($addr + (xread16($addr + 0xe) & 0xffff));            $addr = s32($addr + (xread16($addr) & 0xffff));        } else {            $addr = s32($addr + xread32($addr + 0xe));            $addr = s32($addr + xread32($addr));        }        return s32($addr + xread16($addr + $idx * 2));    }    $addr = s32($addr + xread32($addr + 0xe));    $len = xread16($addr + 4);    if ($len > $idx) {        return s32($addr + xread32($addr) + $idx * 4);    }    return 0xf;}function adresform(int $idx): int{    $addr = get_0x14_script_org_offset(Alis::$script->vram_org);    if (Alis::$platform->version == 10) {        if (Alis::$platform->kind == C::EPlatformPC) {            $addr = s32($addr + (xread16($addr + 0xe) & 0xffff));            $addr = s32($addr + (xread16($addr + 6) & 0xffff));        } else {            $addr = s32($addr + xread32($addr + 0xe));            $addr = s32($addr + xread32($addr + 6));        }        return s32($addr + xread16($addr + $idx * 2));    }    $addr = s32($addr + xread32($addr + 0xe));    $len = xread16($addr + 0xa);    if ($len > $idx) {        $addr = s32($addr + xread32($addr + 0x6));        return s32($addr + xread16($addr + ($idx * 2)));    }    return 0;}// Absolute address of sound resource idx in the main script (flagmain) or the current one.function adresmus(int $idx): int{    $mem = get_0x14_script_org_offset(Alis::$flagmain ? Alis::$main->vram_org : Alis::$script->vram_org);    // v1.0: table of unsigned 16-bit offsets from its base    if (Alis::$platform->version == 10) {        $addr = $mem;        if (Alis::$platform->kind == C::EPlatformPC) {            $addr = s32($addr + (xread16($addr + 0xe) & 0xffff));            $addr = s32($addr + (xread16($addr + 0xc) & 0xffff));        } else {            $addr = s32($addr + xread32($addr + 0xe));            $addr = s32($addr + xread32($addr + 0xc));        }        return s32($addr + (xread16($addr + $idx * 2) & 0xffff));    }    $off = xread32($mem + 0xe);    $addr = s32($mem + $off);    $len = xread16($addr + 0x10);    if ($len > $idx) {        $at = s32(xread32($addr + 0xc) + $off + $idx * 4);        return s32($mem + xread32($mem + $at) + $at);    }    return s32($mem + 0x11);}// =============================================================================// MARK: - tab functions// =============================================================================function tabint(int $addr): int{    // v6: word-cell arrays use the v6 metadata layout    if (Alis::$platform->version >= 60) {        return v6_tabcell($addr, 1);    }    $result = s32($addr + Alis::$varD7 * 2);    $length = s8(xread8(--$addr));    --$addr;    if ($length < 0) {        if (Alis::$platform->version >= 30) {            $newaddr = xread32($addr + 2);            $newaddr = xread32($newaddr);            $result = s32($newaddr + Alis::$varD7 * 2);            $length &= 0xf;            for ($i = 0; $i < $length; $i++) {                $result = s32($result + mul32(xread32(($addr -= 4)), hread32(Alis::$acc)));                Alis::$acc += 4;            }        }    } else {        if (Alis::$platform->version >= 30) {            $length &= 0xf;        }        for ($i = 0; $i < $length; $i++) {            $result = s32($result + mul32(xread16(($addr -= 2)) & 0xffff, hread32(Alis::$acc)));            Alis::$acc += 4;        }    }    return $result;}function tabchar(int $addr): int{    // v6: byte-cell arrays use the v6 metadata layout    if (Alis::$platform->version >= 60) {        return v6_tabcell($addr, 0);    }    $result = s32($addr + Alis::$varD7);    $length = s8(xread8(--$addr));    --$addr;    if ($length < 0) {        if (Alis::$platform->version >= 30) {            $newaddr = xread32($addr + 2);            $newaddr = xread32($newaddr);            $result = s32($newaddr + Alis::$varD7);            $length &= 0xf;            for ($i = 0; $i < $length; $i++) {                $result = s32($result + mul32(xread32(($addr -= 4)), hread32(Alis::$acc)));                Alis::$acc += 4;            }        }    } else {        if (Alis::$platform->version >= 30) {            $length &= 0xf;        }        for ($i = 0; $i < $length; $i++) {            $result = s32($result + mul32(xread16(($addr -= 2)) & 0xffff, hread32(Alis::$acc)));            Alis::$acc += 4;        }    }    return $result;}// v6_tabcell (v6 fixed-stride array-cell resolver): see alis_v6.phpfunction tabstring(int $addr): int{    if (Alis::$platform->version >= 60) {        return v6_tabstring($addr);    }    $result = $addr;    $length = s8(xread8(--$addr));    $result = s32($result + mul32(Alis::$varD7, xread8(--$addr)));    if ($length < 0) {        if (Alis::$platform->version >= 30) {            $newaddr = xread32($addr + 2);            $newaddr = xread32($newaddr);            // The element size: v3 (DOS RRQ, 0xa220) reads the byte at base-2, like the direct case; base-1 is            // the flags byte. The other versions keep the C reference's base-1.            $sizeAddr = Alis::$platform->version < 40 ? $addr : $addr + 1;            $result = s32($newaddr + mul32(Alis::$varD7, xread8($sizeAddr)));            $length &= 0xf;            for ($i = 0; $i < $length; $i++) {                $result = s32($result + mul32(xread32(($addr -= 4)), hread32(Alis::$acc)));                Alis::$acc += 4;            }        }    } else {        if (Alis::$platform->version >= 30) {            $length &= 0xf;        }        for ($i = 0; $i < $length; $i++) {            $result = s32($result + mul32(xread16(($addr -= 2)) & 0xffff, hread32(Alis::$acc)));            Alis::$acc += 4;        }    }    return $result;}/** Returns the PHP stream (also in Alis::$fp) or null. */function afopen(string $path, int $openmode){    $exists = sys_fexists($path);    Alis::$fp = sys_fopen_b($path, $openmode);    if (Alis::$fp === false) {        Alis::$fp = null;    }    Alis::$typepack = 0;    Alis::$openmode = $openmode & 0xffff;    if (($openmode & 0x100) == 0 || $exists) {        if (($openmode & 0x200) == 0) {            if (Alis::$fp !== null) {                if (($openmode & 0x800) != 0) {                    // fread(alis.buffer, 0xc, 1, fp): a short read leaves the rest of the buffer as it was                    $buf = fread_bytes(Alis::$fp, 0xc);                    $n = strlen($buf);                    for ($i = 0; $i < $n; $i++) {                        Alis::$buffer[$i] = ord($buf[$i]);                    }                    $type = s32((Alis::$buffer[0] << 24) | (Alis::$buffer[1] << 16) | (Alis::$buffer[2] << 8) | Alis::$buffer[3]);                    $longpack = s32((Alis::$buffer[4] << 24) | (Alis::$buffer[5] << 16) | (Alis::$buffer[6] << 8) | Alis::$buffer[7]);                    if ($type == 0x50423630) {                        Alis::$typepack = s8(0xa0);                        Alis::$wordpack = 0;                        Alis::$longpack = $longpack;                    } elseif ($type == 0x50573630) {                        Alis::$typepack = s8(0xa0);                        Alis::$wordpack = 1;                        Alis::$longpack = $longpack;                    } elseif (Alis::$platform->kind == C::EPlatformPC && Alis::$platform->version >= 30) {                        // DOS v3 VM (open routine 0x2f2d: int21 AX=4200h, CX:DX=0): a file without a                        // PB60/PW60 header is rewound, so the next read starts at offset 0 (e.g. canyon.dat)                        fseek(Alis::$fp, 0, SEEK_SET);                    }                }            }        }    }    return Alis::$fp;}