<?phpnamespace App\Alis\Lang;/** * An unpacked ALIS script (VM v2x / v3x, little endian: the PC games) and its parts: * * 0x00 id (u16) 0x02 code location (u16: the main entry is at +2) 0x04 two bytes * 0x06 "after" vector (u32, relative to 0x06) 0x0a "before" vector (u32, relative to 0x0a) * 0x0e resources (u32: the resource directory) 0x12 three words (variables, vram size, ...) * 0x18 the program, then the resources up to the end. * * Plus what the .io file around it says: its packing byte, its check word, the main script's 16 VM spec bytes. */final class Script{ public string $name = ''; public int $id = 0; public int $class1 = 0; public int $class2 = 0; public int $words1 = 0; public int $vram = 0; public int $words3 = 0; /** high byte of the .io magic (0xa0: packed) and its check word (0 = the main script) */ public int $pack = 0; public int $check = 1; public ?string $specs = null; public string $resources = ''; /** offsets in the unpacked script: the program is $code (from 0x18) */ public int $main = 0x18; public int $before = 0; public int $after = 0; public string $code = ''; /** Is this the unpacked image of a script (else a data file of the game: kept as it is)? */ public static function isScript(string $bytes): bool { if (strlen($bytes) < 0x18) { return false; } $h = unpack('vid/vcode/Cu1/Cu2/Vafter/Vbefore/Vres', $bytes); return $h['res'] >= 0x18 && $h['res'] <= strlen($bytes) && $h['code'] + 2 >= 0x18 && $h['code'] + 2 < $h['res'] && ($h['before'] === 0 || 10 + $h['before'] < $h['res']) && ($h['after'] === 0 || 6 + $h['after'] < $h['res']); } /** From the unpacked bytes (the VM's image). */ public static function fromBytes(string $name, string $bytes, int $pack = 0, int $check = 1, ?string $specs = null): self { $h = unpack('vid/vcode/Cu1/Cu2/Vafter/Vbefore/Vres/vw1/vvram/vw3', $bytes); $s = new self(); $s->name = $name; $s->id = $h['id']; $s->class1 = $h['u1']; $s->class2 = $h['u2']; $s->words1 = $h['w1']; $s->vram = $h['vram']; $s->words3 = $h['w3']; $s->pack = $pack; $s->check = $check; $s->specs = $specs; $s->main = $h['code'] + 2; $s->before = $h['before'] ? 10 + $h['before'] : 0; $s->after = $h['after'] ? 6 + $h['after'] : 0; $s->code = substr($bytes, 0x18, $h['res'] - 0x18); $s->resources = substr($bytes, $h['res']); return $s; } /** The unpacked bytes (what the VM loads). */ public function bytes(): string { $res = 0x18 + strlen($this->code); return pack('vvCCVVVvvv', $this->id, $this->main - 2, $this->class1, $this->class2, $this->after ? $this->after - 6 : 0, $this->before ? $this->before - 10 : 0, $res, $this->words1, $this->vram, $this->words3) . $this->code . $this->resources; } /** The .io file of the script, not packed (magic: the file size, packing byte 0). */ public function ioFile(): string { $body = $this->bytes(); $head = $this->check === 0 ? 6 + 16 : 6; return pack('Vv', $head + strlen($body), $this->check) . ($this->check === 0 ? str_pad((string) $this->specs, 16, "\0") : '') . $body; }}