TR
games/alis / src / Alis / fn / rrq3d.php · commit 9c722cf
<?phpnamespace App\Alis;// Port of alis/src/render/rrq3d.c (MIT, Olivier Huguenot, Vadim Kindl).// Robinson's Requiem 3D terrain renderer, platform-independent part (the DOS-specific half is// fn/rrq3d_dos.php). See docs/porting.md.//// Port choices:// - Struct-returning functions return PHP arrays keyed by the C field names://     lenstoland()  → ['grid_x', 'grid_y', 'scaled_x', 'scaled_y']                     (sLSTLResult)//     clandtopix()  → ['cam_x', 'cam_y', 'alt_proj', 'screen_x', 'screen_y', 'depth', 'zoom'] (sCLTPResult)//   Values are normalised to the C field types (alt_proj is u32 kept as s32 bits).// - The C function pointers calclan0/doland/landtofi/clrvga/vgatofen are Closures in Rrq3dVars,//   called through the same-named wrapper functions below (set by render3d_init(), lazily if needed).// - Dropped: the enhanced 32-bit renderer (quant3/quant4, fog_blend, vgatobuf, rebuild_dark_rgba,//   terrgba/depthbuf allocation, depth stamping, emode branches: only the emode == 0 path is kept).//   The 68k back end (rrq3d_68k.c) is not ported: its entry points are stubs.// - tabsin/tabcos (s16 * into opcodes.c tables[]) are indexes into OpcodesVars::tables.// - Hot loops write Alis::$mem through a PHP reference ($m = &Alis::$mem) so that each byte write is//   in place (mem_set/mem_write rebuild the whole memory string).// ---------------------------------------------------------------------------------------------// rrq3d.h shared inline helpers// ---------------------------------------------------------------------------------------------function concat11(int $a, int $b): int{    return (($a & 0xff) << 8) | ($b & 0xff);}/** u32 result as s32 bits. */function concat13(int $a, int $b): int{    return (((($a & 0xff) ^ 0x80) - 0x80) << 24) | ($b & 0x00ffffff);}/** u32 result as s32 bits. */function concat22(int $a, int $b): int{    return (((($a & 0xffff) ^ 0x8000) - 0x8000) << 16) | ($b & 0xffff);}/** Carry out of the u32 addition p1 + p2 (exact on 32-bit PHP: 16-bit halves). */function carry4(int $p1, int $p2): int{    $lo = ($p1 & 0xffff) + ($p2 & 0xffff);    $hi = (($p1 >> 16) & 0xffff) + (($p2 >> 16) & 0xffff) + ($lo >> 16);    return $hi >> 16;}function scarry2(int $p1, int $p2): int{    $s = $p1 + $p2;    return ($s > 32767 || $s < -32768) ? 1 : 0;}function concat31(int $a, int $b): int{    return (($a & 0xff) << 8) | ($b & 0xff);}function sborrow2(int $x, int $y): int{    $x = s16($x);    $y = s16($y);    $r = s16($x - $y);    return ((($x ^ $y) & ($x ^ $r)) & 0x8000) !== 0 ? 1 : 0;}/** High 16 bits (integer part) of a 32-bit value stored with xwrite32. */function xread32hi16(int $offset): int{    return xread16(Alis::$xle ? $offset + 2 : $offset);}/** Low 16 bits of a 32-bit value stored with xwrite32. */function xread32lo16(int $offset): int{    return xread16(Alis::$xle ? $offset : $offset + 2);}// ---------------------------------------------------------------------------------------------// Port helpers (not in the C)// ---------------------------------------------------------------------------------------------/** (v << 16) | (v >> 16) on a u32 (s32 bits). */function rrq_swap32(int $v): int{    return (((($v & 0xffff) ^ 0x8000) - 0x8000) << 16) | (($v >> 16) & 0xffff);}/** concat22((s16)((a + b) >> 16), (s16)(a + b) + carry4(a, b)): the 68k ADDX carry-chain emulation. */function rrq_addx(int $a, int $b): int{    $lo = ($a & 0xffff) + ($b & 0xffff);    $hi = (($a >> 16) & 0xffff) + (($b >> 16) & 0xffff) + ($lo >> 16);    return (((($hi & 0xffff) ^ 0x8000) - 0x8000) << 16) | (($lo + ($hi >> 16)) & 0xffff);}/** memset(alis.mem + p, c, n), in place. */function rrq_fill(int $p, int $c, int $n): void{    if ($n <= 0) {        return;    }    $m = &Alis::$mem;    $ch = \chr($c & 0xff);    for ($e = $p + $n; $p < $e; $p++) {        $m[$p] = $ch;    }}/** memcpy(alis.mem + dst, alis.mem + src, n) for non-overlapping ranges, in place. */function rrq_copy(int $dst, int $src, int $n): void{    if ($n <= 0) {        return;    }    $m = &Alis::$mem;    $chunk = \substr($m, $src, $n);    for ($i = 0; $i < $n; $i++) {        $m[$dst + $i] = $chunk[$i];    }}// ---------------------------------------------------------------------------------------------// rrq3d.c// ---------------------------------------------------------------------------------------------/** sLSTLResult as ['grid_x', 'grid_y', 'scaled_x', 'scaled_y']. */function lenstoland(int $scene_addr, int $render_context, int $screen_x, int $screen_y, int $alt_offset): array{    // Rotate screen-space offset by yaw angle into world-space grid position    $yaw_idx = xread16($scene_addr + 0x38);    $cosval = OpcodesVars::tables[OpcodesVars::tabcos + $yaw_idx];    $sinval = OpcodesVars::tables[OpcodesVars::tabsin + $yaw_idx];    $grid_x = s16(xread16($scene_addr + 0x16) + s16(($screen_x * $cosval - $screen_y * $sinval) >> 9));    $grid_y = s16(xread16($scene_addr + 0x18) + s16(($screen_x * $sinval + $screen_y * $cosval) >> 9));    // Scale grid coordinates by world-to-grid shift factor    $sh = xread16($render_context - 0x3c0) & 0x3f;    // The original also computed scene[0x1a] + alt_offset here (unused).    return [        'grid_x' => $grid_x,        'grid_y' => $grid_y,        'scaled_x' => s16($grid_x >> $sh),        'scaled_y' => s16($grid_y >> $sh),    ];}/** s32 → s16 saturation of the DOS CDQ+IDIV quotients. */function rrq_sat16(int $q): int{    if ($q < -32768 || $q > 32767) {        return $q < 0 ? -32768 : 32767;    }    return $q;}function clandtopix_o0(int $scene_addr, int $rel_x, int $rel_y, int $rel_z): array{    // Rotate world-space deltas into camera-space    $angle = xread16($scene_addr + 0x38);    $cosval = OpcodesVars::tables[OpcodesVars::tabcos + $angle];    $sinval = OpcodesVars::tables[OpcodesVars::tabsin + $angle];    $cam_x = (($rel_x * $cosval) + ($rel_y * $sinval)) >> 9;    $cam_y = (($rel_y * $cosval) - ($rel_x * $sinval)) >> 9;    // Beyond far clip distance    if (xread16($scene_addr + 0x94) < $cam_y) {        return ['cam_x' => 0, 'cam_y' => -1, 'alt_proj' => 0, 'screen_x' => 0, 'screen_y' => 0, 'depth' => -1, 'zoom' => 0x100];    }    // Pitch-corrected altitude projection    $pitch = xread16($scene_addr + 0x34);    $pitch_corr = (s16($cam_y) * OpcodesVars::tables[OpcodesVars::tabsin - 2 * $pitch]) >> 9;    $alt_proj = s32(-($rel_z + $pitch_corr));    // Scale by FOV factors    $cam_x = mul32($cam_x, xread16($scene_addr + 0x76));    $alt_proj = mul32($alt_proj, xread16($scene_addr + 0x7a));    // Perspective divide for screen X (uses 16-bit truncated cam_y)    $x_divisor = s16($cam_y) + xread16($scene_addr + 0x70);    if ($x_divisor == 0 || $x_divisor > 32767 || ($x_divisor < 0 && $x_divisor >= -32768)) {        $x_divisor = 1;    }    // DOS: CDQ+IDIV — 64-bit dividend / 32-bit divisor    if (Alis::$platform->is_little_endian) {        $screen_x = rrq_sat16(cdiv($cam_x, $x_divisor));    } else {        $screen_x = cdiv($cam_x, $x_divisor);        if ($screen_x < -32768 || $screen_x > 32767) {            $screen_x = ($screen_x < 0 ? -32768 : 32767) * ($x_divisor < 0 ? -1 : 1);        }    }    // Perspective divide for screen Y and zoom (uses full 32-bit cam_y)    $y_divisor = $cam_y + xread16($scene_addr + 0x74);    if ($y_divisor == 0 || $y_divisor > 32767 || ($y_divisor < 0 && $y_divisor >= -32768)) {        $y_divisor = 1;    }    if (Alis::$platform->is_little_endian) {        $screen_y = rrq_sat16(cdiv($alt_proj, $y_divisor));        $zoom = rrq_sat16(cdiv(xread16($scene_addr + 0x7a) << 8, $y_divisor));    } else {        $screen_y = cdiv($alt_proj, $y_divisor);        if ($screen_y < -32768 || $screen_y > 32767) {            $screen_y = ($screen_y < 0 ? -32768 : 32767) * ($y_divisor < 0 ? -1 : 1);        }        $zoom = cdiv(xread16($scene_addr + 0x7a) << 8, $y_divisor);        if ($zoom < -32768 || $zoom > 32767) {            $zoom = ($zoom < 0 ? -32768 : 32767) * ($y_divisor < 0 ? -1 : 1);        }    }    return [        'cam_x' => $cam_x,        'cam_y' => $cam_y,        'alt_proj' => $alt_proj,        'screen_x' => s16($screen_x),        'screen_y' => s16($screen_y),        'depth' => s16($cam_y),        'zoom' => s16($zoom),    ];}// A perspective divisor of 0, above 32767 or in -32768..-1 becomes 1.function persp_divisor(int $d): int{    return ($d == 0 || $d > 32767 || ($d < 0 && $d >= -32768)) ? 1 : $d;}// 32-bit quotient saturated to s16, the sign flipped for a negative divisor (big-endian games).function persp_div(int $n, int $d): int{    $q = cdiv($n, $d);    if ($q < -32768 || $q > 32767) {        $q = ($q < 0 ? -32768 : 32767) * ($d < 0 ? -1 : 1);    }    return $q;}// clandtopix for big-endian games: 32-bit divides only.function clandtopix_be(int $scene_addr, int $rel_x, int $rel_y, int $rel_z): array{    $angle = xread16($scene_addr + 0x38);    $cosval = OpcodesVars::tables[OpcodesVars::tabcos + $angle];    $sinval = OpcodesVars::tables[OpcodesVars::tabsin + $angle];    $cam_x = (($rel_x * $cosval) + ($rel_y * $sinval)) >> 9;    $cam_y = (($rel_y * $cosval) - ($rel_x * $sinval)) >> 9;    if (xread16($scene_addr + 0x94) < $cam_y) {        return ['cam_x' => 0, 'cam_y' => -1, 'alt_proj' => 0, 'screen_x' => 0, 'screen_y' => 0, 'depth' => -1, 'zoom' => 0x100];    }    $pitch_corr = (s16($cam_y) * OpcodesVars::tables[OpcodesVars::tabsin - 2 * xread16($scene_addr + 0x34)]) >> 9;    $alt_proj = mul32(-($rel_z + $pitch_corr), xread16($scene_addr + 0x7a));    $cam_x = mul32($cam_x, xread16($scene_addr + 0x76));    $x_div = persp_divisor(s16($cam_y) + xread16($scene_addr + 0x70));    $y_div = persp_divisor($cam_y + xread16($scene_addr + 0x74));    return [        'cam_x' => $cam_x,        'cam_y' => $cam_y,        'alt_proj' => $alt_proj,        'screen_x' => s16(persp_div($cam_x, $x_div)),        'screen_y' => s16(persp_div($alt_proj, $y_div)),        'depth' => s16($cam_y),        'zoom' => s16(persp_div(xread16($scene_addr + 0x7a) << 8, $y_div)),    ];}/** sCLTPResult as ['cam_x', 'cam_y', 'alt_proj', 'screen_x', 'screen_y', 'depth', 'zoom']. */function clandtopix(int $scene_addr, int $rel_x, int $rel_y, int $rel_z): array{    if (Alis::$platform->is_little_endian) {        return clandtopix_o0($scene_addr, $rel_x, $rel_y, $rel_z);    }    return clandtopix_be($scene_addr, $rel_x, $rel_y, $rel_z);}function calctoy(int $scene_addr, int $render_context): void{    // Compute combined far clip distance    xwrite16($scene_addr + 0x94, xread16($render_context - 0x3f2) * 2 + xread16($scene_addr + 0x6c));    // Copy camera position to render context    xwrite16($render_context - 0x26c, xread16($scene_addr + 0xa));    xwrite16($render_context - 0x26a, xread16($scene_addr + 0xc));    xwrite16($render_context - 0x268, xread16($scene_addr + 0x16));    xwrite16($render_context - 0x266, xread16($scene_addr + 0x18));    xwrite16($render_context - 0x264, xread16($scene_addr + 0x1a));    // Precompute trig values for rotation angles    $pitch_idx = xread16($scene_addr + 0x34);    $yaw_idx = xread16($scene_addr + 0x38);    $cos_pitch = OpcodesVars::tables[OpcodesVars::tabcos + $pitch_idx];    $sin_pitch = OpcodesVars::tables[OpcodesVars::tabsin + $pitch_idx];    $cos_yaw = OpcodesVars::tables[OpcodesVars::tabcos + $yaw_idx];    $sin_yaw = OpcodesVars::tables[OpcodesVars::tabsin + $yaw_idx];    xwrite16($render_context - 0x28e, $cos_pitch);    xwrite16($render_context - 0x28a, $cos_yaw);    xwrite16($render_context - 0x290, $sin_pitch);    xwrite16($render_context - 0x28c, $sin_yaw);    // DOS also writes trig values to scene_addr for use by other systems    xwrite16($scene_addr + 0xaa, $cos_pitch);    xwrite16($scene_addr + 0xac, $sin_pitch);    xwrite16($scene_addr + 0xb2, $cos_yaw);    xwrite16($scene_addr + 0xb4, $sin_yaw);    // Copy camera position to secondary render context slots    xwrite16($render_context - 0x360, xread16($scene_addr + 0x16));    xwrite16($render_context - 0x35e, xread16($scene_addr + 0x18));    xwrite16($render_context - 0x35c, xread16($scene_addr + 0x1a));    $half = xread16($render_context - 0x3f4);    // Project frustum corners to terrain grid (far plane)    $res = lenstoland($scene_addr, $render_context, s16((-$half - (xread16($scene_addr + 0x6a) >> 1)) - $half), xread16($scene_addr + 0x6c), 0);    xwrite16($render_context - 0x37e, $res['grid_x']);    xwrite16($render_context - 0x37c, $res['grid_y']);    xwrite16($render_context - 0x3a2, $res['scaled_x']);    xwrite16($render_context - 0x3a0, $res['scaled_y']);    $res = lenstoland($scene_addr, $render_context, s16(((xread16($scene_addr + 0x6a) >> 1) - $half) - $half), xread16($scene_addr + 0x6c), 0);    xwrite16($render_context - 0x378, $res['grid_x']);    xwrite16($render_context - 0x376, $res['grid_y']);    xwrite16($render_context - 0x39c, $res['scaled_x']);    xwrite16($render_context - 0x39a, $res['scaled_y']);    // Project frustum corners to terrain grid (near plane)    $res = lenstoland($scene_addr, $render_context, s16((-$half - (xread16($scene_addr + 0x64) >> 1)) - $half), xread16($scene_addr + 0x66), 0);    xwrite16($render_context - 0x372, $res['grid_x']);    xwrite16($render_context - 0x370, $res['grid_y']);    xwrite16($render_context - 0x396, $res['scaled_x']);    xwrite16($render_context - 0x394, $res['scaled_y']);    $res = lenstoland($scene_addr, $render_context, s16(((xread16($scene_addr + 0x64) >> 1) - $half) - $half), xread16($scene_addr + 0x66), 0);    xwrite16($render_context - 0x36c, $res['grid_x']);    xwrite16($render_context - 0x36a, $res['grid_y']);    xwrite16($render_context - 0x390, $res['scaled_x']);    xwrite16($render_context - 0x38e, $res['scaled_y']);    // Project frustum center edges to terrain grid    $res = lenstoland($scene_addr, $render_context, s16(-$half), xread16($scene_addr + 0x6c), 0);    xwrite16($render_context - 0x366, $res['grid_x']);    xwrite16($render_context - 0x364, $res['grid_y']);    xwrite16($render_context - 0x38a, $res['scaled_x']);    xwrite16($render_context - 0x388, $res['scaled_y']);    $res = lenstoland($scene_addr, $render_context, s16(-$half), xread16($scene_addr + 0x66), 0);    xwrite16($render_context - 0x35a, $res['grid_x']);    xwrite16($render_context - 0x358, $res['grid_y']);    xwrite16($render_context - 0x384, $res['scaled_x']);    xwrite16($render_context - 0x382, $res['scaled_y']);    // Grid-to-world shift factor    $gs = xread16($render_context - 0x3c0) & 0x3f;    $cx = xread16($scene_addr + 0x16);    $cy = xread16($scene_addr + 0x18);    $cz = s16(-xread16($scene_addr + 0x1a));    // Project grid positions back to screen space (far corners)    $res2 = clandtopix($scene_addr, s16((xread16($render_context - 0x3a2) << $gs) - $cx), s16((xread16($render_context - 0x3a0) << $gs) - $cy), $cz);    xwrite32($render_context - 0x330, $res2['cam_x']);    xwrite32($render_context - 0x32c, $res2['cam_y']);    xwrite32($render_context - 0x328, $res2['alt_proj']);    xwrite16($render_context - 0x354, $res2['screen_x']);    xwrite16($render_context - 0x352, $res2['screen_y']);    xwrite16($render_context - 0x350, $res2['depth']);    $res2 = clandtopix($scene_addr, s16((xread16($render_context - 0x39c) << $gs) - $cx), s16((xread16($render_context - 0x39a) << $gs) - $cy), $cz);    xwrite32($render_context - 0x324, $res2['cam_x']);    xwrite32($render_context - 0x320, $res2['cam_y']);    xwrite32($render_context - 0x31c, $res2['alt_proj']);    xwrite16($render_context - 0x34e, $res2['screen_x']);    xwrite16($render_context - 0x34c, $res2['screen_y']);    xwrite16($render_context - 0x34a, $res2['depth']);    // Project grid positions back to screen space (near corners)    $res2 = clandtopix($scene_addr, s16((xread16($render_context - 0x396) << $gs) - $cx), s16((xread16($render_context - 0x394) << $gs) - $cy), $cz);    xwrite32($render_context - 0x318, $res2['cam_x']);    xwrite32($render_context - 0x314, $res2['cam_y']);    xwrite32($render_context - 0x310, $res2['alt_proj']);    xwrite16($render_context - 0x348, $res2['screen_x']);    xwrite16($render_context - 0x346, $res2['screen_y']);    xwrite16($render_context - 0x344, $res2['depth']);    $res2 = clandtopix($scene_addr, s16((xread16($render_context - 0x390) << $gs) - $cx), s16((xread16($render_context - 0x38e) << $gs) - $cy), $cz);    xwrite32($render_context - 0x30c, $res2['cam_x']);    xwrite32($render_context - 0x308, $res2['cam_y']);    xwrite32($render_context - 0x304, $res2['alt_proj']);    xwrite16($render_context - 0x342, $res2['screen_x']);    xwrite16($render_context - 0x340, $res2['screen_y']);    xwrite16($render_context - 0x33e, $res2['depth']);    // Project center grid positions to screen space (fixed altitude)    $res2 = clandtopix($scene_addr, s16(xread16($render_context - 0x366) - $cx), s16(xread16($render_context - 0x364) - $cy), -0x100);    xwrite32($render_context - 0x300, $res2['cam_x']);    xwrite32($render_context - 0x2fc, $res2['cam_y']);    xwrite32($render_context - 0x2f8, $res2['alt_proj']);    xwrite16($render_context - 0x33c, $res2['screen_x']);    xwrite16($render_context - 0x33a, $res2['screen_y']);    xwrite16($render_context - 0x338, $res2['depth']);    $res2 = clandtopix($scene_addr, s16(xread16($render_context - 0x35a) - $cx), s16(xread16($render_context - 0x358) - $cy), -0x100);    xwrite32($render_context - 0x2f4, $res2['cam_x']);    xwrite32($render_context - 0x2f0, $res2['cam_y']);    xwrite32($render_context - 0x2ec, $res2['alt_proj']);    xwrite16($render_context - 0x336, $res2['screen_x']);    xwrite16($render_context - 0x334, $res2['screen_y']);    xwrite16($render_context - 0x332, $res2['depth']);    // Restore far clip distance    xwrite16($scene_addr + 0x94, xread16($scene_addr + 0x6c) - xread16($render_context - 0x3f2));}function altiland(int $scene_addr, int $render_context): void{    // Temporarily adjust clip planes for calctoy    $clip_adjust = xread16($render_context - 0x3f4);    xwrite16($scene_addr + 0x6c, $clip_adjust + xread16($scene_addr + 0x6c));    xwrite16($scene_addr + 0x66, xread16($scene_addr + 0x66) - $clip_adjust);    calctoy($scene_addr, $render_context);    $clip_adjust = xread16($render_context - 0x3f4);    xwrite16($scene_addr + 0x6c, xread16($scene_addr + 0x6c) - $clip_adjust);    xwrite16($scene_addr + 0x66, $clip_adjust + xread16($scene_addr + 0x66));    xwrite32($render_context - 0x2c8, shl32(xread32($render_context - 0x32c), 0x10));    // DOS uses 179 rows (0xB3) for finer depth resolution; m68k uses 49 (0x31)    $le = Alis::$platform->is_little_endian;    $num_rows = $le ? Rrq3dConst::DOS_ALT_ROWS : Rrq3dConst::M68K_ALT_ROWS;    $sentinel_count = $le ? Rrq3dConst::DOS_ALT_SENTINEL : Rrq3dConst::M68K_ALT_SENTINEL;    // Set up row interpolation parameters    $scale_end = xread32($render_context - 0x2ec);    $scale_start = xread32($render_context - 0x2f8);    $row_scale = xread32($render_context - 0x2f8);    $screen_y_fp = shl32(xread32($render_context - 0x32c), 0x10);    $screen_y_step = s16(cdiv(mul32(s32(xread32($render_context - 0x314) - xread32($render_context - 0x32c)), 0x100), $num_rows)) - 1;    xwrite16($render_context - 0x262, $screen_y_step);    $alti_ptr = Img::$atalti;    $x3a8 = xread16($render_context - 0x3a8);    $row_delta = s16(cdiv(s32($scale_end - $scale_start), $num_rows));    // Fill altitude lookup table (num_rows rows x 0xFF columns)    for ($s = 0; $s < $num_rows; $s++) {        $divisor_val = s16($x3a8 + s16(shr32($screen_y_fp, 0x10)));        $quotient_val = s16(cdiv($row_scale, $divisor_val));        $row_factor = $quotient_val * 0x100;        xwrite16($alti_ptr, 20000);        $alti_ptr += 2;        // Accumulate fixed-point altitude offsets.        // The C does SWAP.L / NEG.W / restore / SWAP.L / ADD.L: the restore makes accum unchanged, so each        // entry is -(s16)(accum >> 16) with accum = row_factor * (i + 1), which always fits an s32        // (|row_factor| <= 0x800000, i + 1 <= 255).        $accum = $row_factor;        for ($i = 0; $i < 0xff; $i++, $alti_ptr += 2) {            xwrite16($alti_ptr, -s16($accum >> 16));            $accum += $row_factor;        }        $screen_y_fp = s32($screen_y_fp + $screen_y_step * 0x100);        $row_scale = s32($row_scale + $row_delta);    }    // Sentinel row (beyond last visible row)    for ($i = 0; $i < $sentinel_count; $i++, $alti_ptr += 2) {        xwrite16($alti_ptr, 20000);    }    // Compute horizon line position (aspect-corrected from far clip distance)    $a = s16(xread16($scene_addr + 0x6c) * 4);    $b = s16(cdiv($a * 0x168, 0x140));    $c = s16(($b + 0x80) & 0xff00);    Img::$fhorizon = s16(cdiv($c * 0x140, 0x168));}function iniland(int $sceneadr, int $render_context): void{    // Compute depth range between far and near planes    Img::$purey2 = s16(xread16($sceneadr + 0x6c) - xread16($sceneadr + 0x66));    Img::$purey = Img::$purey2 >> 2;    Img::$purey2 >>= 4;    // Initialize grid wrap/bounds    xwrite16($render_context - 0x298, 0);    xwrite16($render_context - 0x296, 0);    xwrite16($render_context - 0x294, xread16($render_context - 0x3e8));    xwrite16($render_context - 0x292, xread16($render_context - 0x3e6));    // Build terrain strip pointer table    $strip_stride = ((xread16($render_context - 0x3ca) & 0xffff) << 1) & 0xffff;    $strip_count = s16(xread16($render_context - 0x3cc) - 1);    if (s8(xread8($render_context - 1)) < 0) {        // Get address of block allocated in calloctab        $render_context = xread32(xread32($render_context));    }    $strip_count = s16($strip_count << 2);    for ($i = 0; $i <= $strip_count; $i += 4, $render_context += $strip_stride) {        xwrite32(Img::$atlland + $i, $render_context);    }    // Build pixel row pointer table (one entry per scanline)    $row_stride = Alis::$platform->is_little_endian ? Hd3d::stride() : ((xread16($sceneadr + 0x12) + 1) & 0xffff);    $render_context = xread32(xread32($sceneadr + 0x30));    // 200 entries exactly: the region is 0x320 bytes, atalti follows (the HD pass: its own, bigger table, fn/hd3d.php)    for ($i = 0, $n = Hd3d::rows() * 4; $i < $n; $i += 4, $render_context += $row_stride) {        xwrite32(Img::$atlpix + $i, $render_context);    }    // Build anti-aliasing lookup table: alias[d][i] = (i * 256) / d    $alias_ptr = Img::$atalias;    $aw = Hd3d::aliasWidth();    for ($d = 1; $d <= $aw; $d++) {        for ($i = 0; $i < $aw; $i++, $alias_ptr += 2) {            xwrite16($alias_ptr, \intdiv($i * 0x100, $d));        }    }}function inilens(int $sceneadr, int $render_context): void{    // Scene frustum offsets:    //   0x64 = near_width_x, 0x66 = near_dist, 0x68 = near_height_y    //   0x6a = far_width_x,  0x6c = far_dist,  0x6e = far_height_y    // Combined far clip distance    xwrite16($sceneadr + 0x94, (xread16($sceneadr + 0x6c) - xread16($render_context - 0x3f2)) - xread16($render_context - 0x3f2));    // Half near distance: DOS divides by 4, m68k divides by 2    xwrite16($sceneadr + 0x92, xread16($sceneadr + 0x66) >> (Alis::$platform->is_little_endian ? 2 : 1));    $u6c = xread16($sceneadr + 0x6c) & 0xffff;    $u66 = xread16($sceneadr + 0x66) & 0xffff;    // Focal distance X: (far_dist * near_width - near_dist * far_width) / (far_width - near_width)    xwrite16($sceneadr + 0x70, s16(cdiv(s32(mul32($u6c, xread16($sceneadr + 0x64) & 0xffff) - mul32($u66, xread16($sceneadr + 0x6a) & 0xffff)), xread16($sceneadr + 0x6a) - xread16($sceneadr + 0x64))));    // FOV scale X: (focal_x + far_dist) * viewport_width / far_width    xwrite16($sceneadr + 0x76, s16(cdiv(mul32(xread16($sceneadr + 0x70) + xread16($sceneadr + 0x6c), xread16($sceneadr + 0x12) + 1), xread16($sceneadr + 0x6a))));    // Focal distance Y: (far_dist * near_height - near_dist * far_height) / (far_height - near_height)    xwrite16($sceneadr + 0x74, s16(cdiv(s32(mul32($u6c, xread16($sceneadr + 0x68) & 0xffff) - mul32($u66, xread16($sceneadr + 0x6e) & 0xffff)), xread16($sceneadr + 0x6e) - xread16($sceneadr + 0x68))));    // FOV scale Y: (focal_y + far_dist) * viewport_height / far_height    xwrite16($sceneadr + 0x7a, s16(cdiv(mul32(xread16($sceneadr + 0x74) + xread16($sceneadr + 0x6c), xread16($sceneadr + 0x14) + 1), xread16($sceneadr + 0x6e))));    // Copy focal/scale values to render context    xwrite16($render_context - 0x3ac, xread16($sceneadr + 0x70));    xwrite16($render_context - 0x3aa, xread16($sceneadr + 0x76));    xwrite16($render_context - 0x3a8, xread16($sceneadr + 0x74));    xwrite16($render_context - 0x3a6, xread16($sceneadr + 0x7a));    // Column step factor: far_width / half_shift    xwrite16($render_context - 0x3a4, cdiv(xread16($sceneadr + 0x6a), xread16($render_context - 0x3f4)));}function initltra(): void{    // Line jump tables are only used by the original asm (see initltra_asm).}function openland(int $scene_id): void{    $scene_id = s16($scene_id);    $scene_addr = s32(Alis::$basemain + $scene_id);    $render_context = s32(xread16($scene_addr + 0x42) + xread32(Alis::$atent + xread16($scene_addr + 0x40)));    $le = Alis::$platform->is_little_endian;    // Allocate VRAM buffer for scene    if (xread32($scene_addr + 0x30) == 0) {        if ($le) {            // DOS: 320 bytes/row with 4-row top padding            $buffer = io_malloc(((xread16($scene_addr + 0x14) + 9) & 0xffff) * 0x140);            xwrite32($scene_addr + 0x30, $buffer);            xwrite32($buffer, s32(xread32($buffer) + 0x500)); // offset by 4 scanlines        } else {            $buffer = io_malloc(s32(((xread16($scene_addr + 0x12) + 1) & 0xffff) * ((xread16($scene_addr + 0x14) + 1) & 0xffff) + 0x140));            xwrite32($scene_addr + 0x30, $buffer);        }    }    // double normal draw distance    if (Img::$ddrawdist) {        xwrite16($scene_addr + 0x6a, 960 * 2);        xwrite16($scene_addr + 0x6c, 1680 * 2);        xwrite16($scene_addr + 0x6e, 1200 * 2);    }    // Allocate shared pixel, altitude, and alias tables    if (Img::$tlpix == 0) {        if ($le) {            // DOS layout: single allocation containing altitude data, scanline ptrs,            // alias table, and terrain strips all in one block.            // Layout: [altitude 0x16800] [atlpix 0x320] [atalias 0x2000] [atlland strip_count*4]            $strip_count = xread16($render_context - 0x3cc) & 0xffff;            Img::$tlpix = io_malloc($strip_count * 4 + Rrq3dConst::DOS_TABLES_SZ);            $raw_base = xread32(Img::$tlpix);            Img::$atalti = $raw_base;            Img::$atlpix = $raw_base + Rrq3dConst::DOS_ATLPIX_OFS;            Img::$atalias = Img::$atlpix + Rrq3dConst::DOS_ATALIAS_OFS;            Img::$atlland = Img::$atalias + Rrq3dConst::DOS_ATLLAND_OFS;            Img::$tlland = Img::$tlpix; // same allocation, mark as allocated        } else {            // m68k layout: separate allocations            Img::$tlpix = io_malloc(0x8720);            Img::$atlpix = xread32(Img::$tlpix);            Img::$atalti = Img::$atlpix + 0x320;            Img::$atalias = Img::$atalti + 0x6400;        }    }    // Allocate terrain strip table (m68k only, DOS includes it in the single alloc above)    if (Img::$tlland == 0) {        Img::$tlland = io_malloc(xread16($render_context - 0x3cc) * 4);        Img::$atlland = xread32(Img::$tlland);    }    // Initialize scene parameters: default altitude and zero rotation angles    xwrite16($scene_addr + 0x1a, 0x14);    xwrite16($scene_addr + 0x34, 0);    xwrite16($scene_addr + 0x36, 0);    xwrite16($scene_addr + 0x38, 0);    // (enhanced 32-bit RGBA terrain buffer allocation dropped: emode only)    // Initialize renderer subsystems    initltra();    inilens($scene_addr, $render_context);    iniland($scene_addr, $render_context);    altiland($scene_addr, $render_context);    Img::$landone = 0;}function landtopix(int $scene_addr, int $sprite_id): void{    $le = Alis::$platform->is_little_endian;    $sprite = sprite_var($sprite_id & 0xffff);    Img::$newad = $sprite->data;    // Select rotation frame based on camera-relative angle    $creducing = s8($sprite->creducing);    if (1 < $creducing) {        // DOS: sprite rotation angle is at sprite offset 0x26 (high word of u32 at 0x24 on LE)        $sprite_angle = $le ? s16($sprite->sprite_0x28 >> 16) : s16($sprite->sprite_0x28);        // loop while bit 15 of norm_angle is clear        for ($norm_angle = ($sprite_angle - xread16($scene_addr + 0x38) + 900) & 0xffff; ($norm_angle & 0x8000) == 0; $norm_angle = ($norm_angle - 0x168) & 0xffff) {        }        $frame_idx = \intdiv(($creducing & 0xffff) * (($norm_angle + 0x168) & 0xffff) + 0xb4, 0x168);        $frame_offset = s16($frame_idx);        if ($creducing <= s8($frame_idx)) {            $frame_offset = 0;        }        Img::$newad = s32(Img::$newad + $frame_offset * 4);    }    // Resolve bitmap data and metadata pointers    $sprite_hdr = s32(xread32(Img::$newad) + Img::$newad);    $bitmap = $sprite_hdr;    $meta = Img::$zoombid;    if (xread8($sprite_hdr) == 3) {        Img::$newad = s32(Img::$newad + xread16($sprite_hdr + 2) * 4);        $bitmap = s32(xread32(Img::$newad) + Img::$newad);        $meta = $sprite_hdr;    }    // Project sprite position to screen space    Img::$newf = s16(xread8($meta + 1) ^ $sprite->flaginvx);    if (s8($sprite->credon_off) == -0x80) {        Img::$newzoomy = s16($sprite->newzoomy);        Img::$newx = s16(xread16($scene_addr + 0xa) + $sprite->depx);        Img::$newy = s16(xread16($scene_addr + 0xc) - $sprite->depz);        Img::$newd = s16($sprite->depy);        $zoom_shift = 0;    } else {        $res = clandtopix($scene_addr, s16($sprite->depx - xread16($scene_addr + 0x16)), s16($sprite->depy - xread16($scene_addr + 0x18)), s16($sprite->depz - xread16($scene_addr + 0x1a)));        Img::$newzoomy = $res['zoom'];        Img::$newd = $res['depth'];        Img::$newx = s16(xread16($scene_addr + 0xa) + $res['screen_x']);        Img::$newy = s16(xread16($scene_addr + 0xc) + $res['screen_y']);        $zoom_shift = s8($sprite->credon_off) & 0xffff;    }    // Apply zoom adjustments    // DOS: no bitmap double-size flag check    if (!$le && (xread8($bitmap + 1) & 0x20) != 0) {        Img::$newzoomy = s16(Img::$newzoomy * 2);    }    if (8 <= s8($zoom_shift)) {        // Multiply first, then shift — preserves precision for small (zoom_shift - 8) values        Img::$newzoomy = s16(shr32(mul32(Img::$newzoomy, ($zoom_shift - 8) & 0xffff), 3));        $zoom_shift = 3;    }    if ($le && s8($sprite->credon_off) == -0x80) {        // DOS 0x80 path: load newzoomx from separate sprite field        Img::$newzoomx = s16($sprite->newzoomx);    } else {        Img::$newzoomx = Img::$newzoomy;    }    // Fallback for out-of-range bitmap address    if (ult(0xdfffff, $bitmap)) {        Img::$newad = Img::$landnewad;        $bitmap = Img::$landdata;        Img::$newd = -1000;        $sprite->state = 1;    }    $zoom_shift = ($zoom_shift + 1) & 0x3f;    // Compute scaled sprite dimensions    // DOS: axes are swapped — height uses newzoomx, width uses newzoomy    $h_zoom = ($le ? Img::$newzoomx : Img::$newzoomy) & 0xffff;    $w_zoom = ($le ? Img::$newzoomy : Img::$newzoomx) & 0xffff;    $scaled_h = (((mul32(xread16($bitmap + 4) + 1, $h_zoom * 2) >> $zoom_shift) + 0xff) >> 8) - 1;    if ($scaled_h < 0) {        $scaled_h = 0;    }    $scaled_w = (((mul32(xread16($bitmap + 2) + 1, $w_zoom * 2) >> $zoom_shift) + 0xff) >> 8) - 1;    if ($scaled_w < 0) {        $scaled_w = 0;    }    Img::$newh = s16($scaled_h);    Img::$newl = s16($scaled_w);    // Adjust position by hotspot offset    // DOS: axes are swapped — Y hotspot uses newzoomx, X hotspot uses newzoomy    if ($le) {        // DOS: single shift by (zoom_shift + 8), no intermediate truncation        Img::$newy = s16(Img::$newy + s16(mul32(s16(((xread16($bitmap + 4) & 0xffff) >> 1) - xread16($meta + 6)) * s16($h_zoom), -2) >> ($zoom_shift + 8)));        Img::$newx = s16(Img::$newx + s16(mul32(s16(((xread16($bitmap + 2) & 0xffff) >> 1) - xread16($meta + 4)) * s16($w_zoom), -2) >> ($zoom_shift + 8)));    } else {        Img::$newy = s16(Img::$newy + s16(((s16(((xread16($bitmap + 4) & 0xffff) >> 1) - xread16($meta + 6)) * $h_zoom) >> 8) * -2 >> $zoom_shift));        Img::$newx = s16(Img::$newx + s16(((s16(((xread16($bitmap + 2) & 0xffff) >> 1) - xread16($meta + 4)) * $w_zoom) >> 8) * -2 >> $zoom_shift));    }}// Walk the terrain sprite list: remove dead sprites, project live ones to screen spacefunction spritland(int $scene_addr, int $list_head): void{    $list_head &= 0xffff;    $current = $list_head;    while (true) {        $prev = $current;        $prev_sprite = sprite_var($prev);        $current = $prev_sprite->link;        if ($current == 0) {            break;        }        $sprite = sprite_var($current);        // the HD pass projects again the sprites the game projected earlier (state 0 since: they still have the        // game's screen position and zoom, and the HD land drew them at half their size, elsewhere); their depth        // does not change with the scale, so they stay where they are in the list (fn/hd3d.php)        if ($sprite->state == 0 && Hd3d::$inPass) {            landtopix($scene_addr, $current);            $sprite->newad = Img::$newad & 0xffffff;            $sprite->newx = Img::$newx;            $sprite->newy = Img::$newy;            $sprite->newf = s8(Img::$newf);            $sprite->width = Img::$newl;            $sprite->height = Img::$newh;            $sprite->newzoomx = Img::$newzoomx & 0xffff;            $sprite->newzoomy = Img::$newzoomy & 0xffff;        } elseif ($sprite->state != 0) {            if ($sprite->state == 1) {                // Dead sprite: unlink and return to free list                $prev_sprite->link = $sprite->link;                $sprite->to_next = Img::$libsprit;                Img::$libsprit = $current;                $current = $prev;            } else {                // Active sprite: project to screen and depth-sort into list                landtopix($scene_addr, $current);                $sprite->newad = Img::$newad & 0xffffff;                $sprite->newx = Img::$newx;                $sprite->newy = Img::$newy;                $sprite->newd = Img::$newd;                $sprite->newf = s8(Img::$newf);                $sprite->width = Img::$newl;                $sprite->height = Img::$newh;                $sprite->newzoomx = Img::$newzoomx & 0xffff;                $sprite->newzoomy = Img::$newzoomy & 0xffff;                $prev_sprite->link = $sprite->link;                $prev = rangesprite($current, $prev, $list_head);                $current = $prev;            }        }    }}function skyfast(int $tgt, int $fill, int $stride, int $height): int{    $clipl = Img::$clipl;    $step = $clipl + $stride;    for ($l = 0; $l < $height; $l++, $tgt += $step) {        rrq_fill($tgt, $fill, $clipl);    }    return $tgt;}function skytofen(int $scene_addr, int $render_context): void{    if (Img::$ftstpix != 0) {        return;    }    // Resolve sky bitmap data (follow pointer chain, handle type 3 redirect)    $sky_res = xread32($scene_addr + 0xa4);    $sky_data = s32(xread32($sky_res) + $sky_res);    $hotspot_y = 0;    $bitmap = $sky_data;    if (xread8($sky_data) == 3) {        $sky_res = s32(s16(xread16($sky_data + 2) * 4) + $sky_res);        $bitmap = s32(xread32($sky_res) + $sky_res);        $hotspot_y = xread16($sky_data + 6);    }    // (fog colour derivation dropped: emode only)    $clipx1 = Img::$clipx1;    $clipy1 = Img::$clipy1;    $clipy2 = Img::$clipy2;    $clipl = Img::$clipl;    $cliph = Img::$cliph;    if (xread8($bitmap) == 1) {        // Solid color sky fill        $c = xread8($bitmap + 1) & 0xf;        skyfast(s32($clipx1 + xread32(Img::$atlpix + s16(($clipy1 - Img::$wlogy1) * 4))), $c | ($c << 4), s16(Img::$wloglarg - $clipl), s16($cliph - 1));        return;    }    // Compute sky scroll position    $bh = xread16($bitmap + 4);    Img::$skyposy = s16(($hotspot_y + xread16($scene_addr + 0xc) + xread16($render_context - 0x352)) - ((($bh + 1) & 0xffff) >> 1));    $tex_width = s16(xread16($bitmap + 2) + 1);    $scroll_mod = s16(cmod(s16(s16(shr32(xread16($scene_addr + 0x38) * xread16($scene_addr + 0xa8), 8)) - $clipx1), $tex_width));    $scroll_pos = (-$scroll_mod) & 0xffff;    if (0 < $scroll_mod) {        $scroll_pos = ($tex_width + $scroll_pos) & 0xffff;    }    Img::$skyposx = s16($scroll_pos & 0xfffe);    Img::$skyleft = s16($tex_width - Img::$skyposx);    if ($clipl < s16($tex_width - Img::$skyposx)) {        Img::$skyleft = $clipl;    }    $skyposy = Img::$skyposy;    $dst = s32($clipx1 + xread32(Img::$atlpix + s16(($clipy1 - Img::$wlogy1) * 4)));    $stride_gap = s16(Img::$wloglarg - $clipl);    $data_offset = Alis::$platform->bpp == 4 ? 6 : 8;    // Fill top gap above sky texture    $top_gap = s16($skyposy - $clipy1);    if ($top_gap != 0 && $clipy1 <= $skyposy) {        if ($cliph < $top_gap) {            $top_gap = $cliph;        }        $dst = skyfast($dst, xread8($bitmap + $data_offset), $stride_gap, s16($top_gap - 1));    }    // Compute visible sky row range (clamped to clip rect)    $sky_top = $skyposy;    if ($skyposy < $clipy1) {        $sky_top = $clipy1;    }    $sky_bottom = s16($bh + $skyposy);    if ($clipy2 < s16($bh + $skyposy)) {        $sky_bottom = $clipy2;    }    $row_count = s16($sky_bottom - $sky_top);    // Blit sky texture rows with horizontal wrapping    if ($row_count != 0 && $sky_top <= $sky_bottom) {        $tex_stride = (xread16($bitmap + 2) + 1) & 0xffff;        $src_offset = 0;        if ((($clipy1 - $skyposy) & 0xffff) != 0 && $skyposy <= $clipy1) {            $src_offset = (($clipy1 - $skyposy) & 0xffff) * $tex_stride;        }        $row_src = s32($bitmap + Img::$skyposx + $src_offset + $data_offset);        $half_left = s16((Img::$skyleft >> 1) - 1);        // left portion: (half_left + 1) words from skyposx to the texture edge (if half_left >= 0)        $left_bytes = $half_left > -1 ? 2 * ($half_left + 1) : 0;        // wrapped portion: (wrap_total - 1) words from the texture start (if wrap_total > 1)        $wrap_total = s16(($clipl >> 1) - $half_left);        $wrap_bytes = 1 < $wrap_total ? 2 * ($wrap_total - 1) : 0;        $tex_stride_s = s16($tex_stride);        $odd = $clipl & 1;        $m = &Alis::$mem;        do {            // Copy left portion (from skyposx to texture edge)            if ($left_bytes) {                $chunk = \substr($m, $row_src, $left_bytes);                for ($i = 0; $i < $left_bytes; $i++) {                    $m[$dst + $i] = $chunk[$i];                }                $dst += $left_bytes;            }            // Copy wrapped portion (src rewinds to texture start)            if ($wrap_bytes) {                $chunk = \substr($m, $row_src + $left_bytes - $tex_stride_s, $wrap_bytes);                for ($i = 0; $i < $wrap_bytes; $i++) {                    $m[$dst + $i] = $chunk[$i];                }                $dst += $wrap_bytes;            }            // Odd clipl: 16-bit loops wrote (clipl & ~1) bytes; advance dst past the            // missing last pixel so the stride_gap brings us to the correct next row.            $dst += $odd + $stride_gap;            $row_src += $tex_stride_s;            $row_count = s16($row_count - 1);        } while ($row_count != -1);        unset($m);    }    // Fill bottom gap below sky texture    $bottom_gap = s16(($clipy2 - $skyposy) - $bh);    if ($bottom_gap != 0 && $bh <= s16($clipy2 - $skyposy)) {        if ($cliph < $bottom_gap) {            $bottom_gap = $cliph;        }        skyfast($dst, xread8(s32($bitmap + mul32((xread16($bitmap + 2) + 1) & 0xffff, $bh) + $data_offset)), $stride_gap, s16($bottom_gap - 1));    }}function glandtopix(int $render_context, int &$out_x, int &$out_y, int $offset_x, int $offset_y, int $depth): void{    // Rotate + FOV-scale two points through the same projection    $s28c = xread16($render_context - 0x28c);    $s28a = xread16($render_context - 0x28a);    $s3aa = xread16($render_context - 0x3aa);    $proj_num_x = s16(($out_y * $s28c + $out_x * $s28a) >> 9) * $s3aa;    $proj_num_y = s16(($offset_y * $s28c + $offset_x * $s28a) >> 9) * $s3aa;    // Perspective divide    $divisor = s16(xread16($render_context - 0x3ac) + $depth);    if ($divisor <= 0) {        $divisor = 1;    }    $out_x = s16(\intdiv($proj_num_x, $divisor));    $out_y = s16(\intdiv($proj_num_y, $divisor));}function barlands(int $drawy, int $barheight, int $barwidth): void{    if (!Alis::$platform->is_little_endian) {        return;    }    // asm: TEST DX,DX; JZ return    $barheight = s16($barheight);    if ($barheight == 0) {        return;    }    // PORT: a negative barheight makes the C s16 counter wrap (65536 - n rows written past the buffer);    // not reproduced.    if ($barheight < 0) {        return;    }    // asm fill: (DAT_0001aac6 & 0x0F) + 0x80    $fill = \chr(((Rrq3dVars::$terrain_fill_color & 0x0f) + 0x80) & 0xff);    // asm: AX -= wlogx2; EDI = atlpix[(u16)AX] + (s16)precx    $y_idx = s16(s16($drawy) - Img::$wlogy1);    $dst = xread32(Img::$atlpix + ($y_idx & 0xffff) * 4);    // IMPORTANT: signed add like MOVSX    $dst += Img::$precx;    // asm: REP STOSB, width in EBX    $w = $barwidth & 0xffff;    $stride = Img::$wloglarg & 0xffff;    $m = &Alis::$mem;    for ($h = $barheight; $h != 0; --$h) {        for ($p = $dst, $e = $dst + $w; $p < $e; $p++) {            $m[$p] = $fill;        }        $dst += $stride;    }}/* Original zoomtofen render body (0x2373e-0x237f6 normal + 0x238a4-0x23920   flipped). Renders directly into image.wlogic; reads/writes image.ztflow*.   The u32 accumulators (68k ADDX/SUBX emulation) are kept as 16-bit halves here: same results,   no float overflow on 32-bit PHP. */function zoomtofen_render_c(Sprite $sprite, int $bitmap, int $data_offset, int $clipped_width, int $clipped_height, int $zoom_y_step, int $zoom_y_int, int $zoom_y_frac, int $zoom_x_step, int $screen_x, int $screen_y, int $x_orig, int $bitmap_width): void{    $wloglarg = Img::$wloglarg;    // Calculate target framebuffer address    $framebuffer = s32($screen_x + (($screen_y - Img::$wlogy1) & 0xffff) * $wloglarg + Img::$wlogic);    Img::$ztflowy &= 0xffff;    // Calculate initial Y texture offset for clipped sprite    $y_offset = ($screen_y - $sprite->newy) & 0xffff;    $texture_y = $y_offset;    $zmul = (($zoom_y_frac & 0xff) << 8) | ($zoom_y_int & 0xff);    if ($y_offset != 0) {        // Accumulate Y texture coordinate with zoom factor        $texture_y = mul32($y_offset, $zmul);        // Orig 0x2376c `move.b D1,(ztflowy)`: in-place byte0 write, bytes 1-3 kept.        Img::$ztflowy = concat13($texture_y, Img::$ztflowy);        $texture_y = mul32(shr32($texture_y, 8) & 0xffff, (read16($bitmap + 2) + 1) & 0xffff);    }    $Sh = ($zoom_y_step >> 16) & 0xffff;    $Sl = $zoom_y_step & 0xffff;    $Xh = ($zoom_x_step >> 16) & 0xffff;    $Xl = $zoom_x_step & 0xffff;    $line_skip = s16($wloglarg - $clipped_width);    $m = &Alis::$mem;    // Rendering path for horizontally flipped sprites    if (($sprite->newf & 1) != 0) {        // Start from right edge of bitmap for flipped rendering        $bitmap_row_offset = s32((read16($bitmap + 2) & 0xffff) + $texture_y);        // Orig 0x238ac `move.w #-1,(ztflowx)`: high word only.        Img::$ztflowx = -0x10000 | (Img::$ztflowx & 0xffff);        // Calculate X texture offset accounting for clipping on left edge        if ((($screen_x - $x_orig) & 0xffff) != 0) {            $zoom_y_frac = mul32(($screen_x - $x_orig) & 0xffff, $zmul);            // Orig 0x238c0 `sub.b D2,(ztflowx)`: in-place byte0 write.            Img::$ztflowx = concat13(-1 - s8($zoom_y_frac), Img::$ztflowx);            $bitmap_row_offset = s32($bitmap_row_offset - shr32($zoom_y_frac, 8));        }        $zoom_y_frac = Img::$ztflowy;        $Fh = ($zoom_y_frac >> 16) & 0xffff;        $Fl = $zoom_y_frac & 0xffff;        $Zh0 = (Img::$ztflowx >> 16) & 0xffff;        $rowbase = $bitmap_row_offset + $data_offset;        // Render pixels row by row        for ($y = 0; $y < $clipped_height; $y++, $framebuffer += $line_skip) {            $Zh = $Zh0;            $Zl = $Fl;            // Render individual pixels in row, stepping backward through texture (flipped)            for ($x = 0; $x < $clipped_width; $x++, $framebuffer++) {                $bmp_idx = (($Zl ^ 0x8000) - 0x8000) + $rowbase;                if ($bmp_idx < 0) {                    $bmp_idx += 0x10000;                }                $pixel = $m[$bitmap + $bmp_idx];                if ($pixel !== "\0") {                    $m[$framebuffer] = $pixel;                }                // zoom_y_int -= zoom_y_step with SUBX borrow into the low word                $dl = $Zl - $Sl;                $dh = $Zh - $Sh - ($dl < 0 ? 1 : 0);                $Zh = $dh & 0xffff;                $Zl = ($dl - ($dh < 0 ? 1 : 0)) & 0xffff;            }            // Step to next texture row with fixed-point arithmetic            $sl = $Fl + $Xl;            $sh = $Fh + $Xh + ($sl >> 16);            $Fh = $sh & 0xffff;            $Fl = $sl & 0xffff;            if ($sh >> 16) {                // Handle fractional overflow to next line                $Fl = ($bitmap_width + $Fl) & 0xffff;            }        }    }    // Rendering path for normal (non-flipped) sprites    else {        Img::$ztflowx &= 0xffff;        // Calculate X texture offset accounting for clipping on left edge        if ((($screen_x - $x_orig) & 0xffff) != 0) {            $zoom_y_frac = mul32(($screen_x - $x_orig) & 0xffff, $zmul);            // Orig 0x23796 `move.b D2,(ztflowx)`: in-place byte0 write.            Img::$ztflowx = concat13($zoom_y_frac, Img::$ztflowx);            $texture_y = s32($texture_y + shr32($zoom_y_frac, 8));        }        $zoom_y_frac = Img::$ztflowy;        $Fh = ($zoom_y_frac >> 16) & 0xffff;        $Fl = $zoom_y_frac & 0xffff;        $Zh0 = (Img::$ztflowx >> 16) & 0xffff;        $base = $bitmap + $texture_y + $data_offset;        // Render pixels row by row        for ($y = 0; $y < $clipped_height; $y++, $framebuffer += $line_skip) {            $Zh = $Zh0;            $Zl = $Fl;            // Render individual pixels in row, stepping forward through texture (normal)            for ($x = 0; $x < $clipped_width; $x++, $framebuffer++) {                $pixel = $m[$base + $Zl];                if ($pixel !== "\0") {                    $m[$framebuffer] = $pixel;                }                // zoom_y_int += zoom_y_step with ADDX carry into the low word                $sl = $Zl + $Sl;                $sh = $Zh + $Sh + ($sl >> 16);                $Zh = $sh & 0xffff;                $Zl = ($sl + ($sh >> 16)) & 0xffff;            }            // Step to next texture row with fixed-point arithmetic            $sl = $Fl + $Xl;            $sh = $Fh + $Xh + ($sl >> 16);            $Fh = $sh & 0xffff;            $Fl = $sl & 0xffff;            if ($sh >> 16) {                // Handle fractional overflow to next line                $Fl = ($bitmap_width + $Fl) & 0xffff;            }        }    }}function zoomtofen(Sprite $sprite): void{    // Get sprite bitmap data with offset stored in header    $bitmap = s32($sprite->newad + xread32($sprite->newad));    $b0 = xread8($bitmap);    $data_offset = ($b0 == 0x18 || $b0 == 0x1a) ? 6 : 8;    // Only process valid sprite formats (0x14, 0x18, 0x1a, 0x1c, 0x1e)    if ($b0 == 0x14 || $b0 == 0x18 || $b0 == 0x1a || $b0 == 0x1c || $b0 == 0x1e) {        // Initialize clipped dimensions (add 1 because dimensions are 0-based)        $clipped_width = s16($sprite->width + 1);        $clipped_height = ($sprite->height + 1) & 0xffff;        // Calculate zoom scale factor (fixed-point: 8.8 format)        // Formula: (bitmap_height << 8) / clipped_height        $zoom_y_scale = cdiv(((read16($bitmap + 4) + 1) & 0xffff) << 8, $clipped_height);        $zoom_y_int = s16($zoom_y_scale);        $zoom_y_frac = shr32(shl32($zoom_y_int, 8), 0x10);        $zoom_y_step = shl32($zoom_y_int, 0x18) | $zoom_y_frac; // Combined step value for tight inner loop        $clipx1 = Img::$clipx1;        $clipy1 = Img::$clipy1;        $clipx2 = Img::$clipx2;        $clipy2 = Img::$clipy2;        $newy = $sprite->newy;        // Clip sprite against vertical boundaries        $y_extent = s16(($newy - $clipy1) - Img::$cliph);        $screen_y = $newy;        if ((Img::$cliph <= (($newy - $clipy1) & 0xffff) && $y_extent != 0) || (s16(-$clipped_height - $y_extent) < 0)) {            if ($clipy2 < $newy) {                return; // Sprite entirely below clipping area            }            $y_extent = s16($newy + $clipped_height - 1);            if ($y_extent < $clipy1) {                return; // Sprite entirely above clipping area            }            // Clip top edge if above clipping boundary            if ($newy < $clipy1) {                $clipped_height = ($newy + ($clipped_height - $clipy1)) & 0xffff;                $screen_y = $clipy1;            }            // Clip bottom edge if below clipping boundary            if ($clipy2 < $y_extent) {                $clipped_height = ($clipy2 + ($clipped_height - $y_extent)) & 0xffff;            }        }        // Clip sprite against horizontal boundaries        $x_orig = $sprite->newx;        $x_extent = s16(($x_orig - $clipx1) - Img::$clipl);        $screen_x = $x_orig;        if ((Img::$clipl <= (($x_orig - $clipx1) & 0xffff) && $x_extent != 0) || (s16(-$clipped_width - $x_extent) < 0)) {            if ($clipx2 < $x_orig) {                return; // Sprite entirely right of clipping area            }            $x_extent = s16($x_orig + $clipped_width - 1);            if ($x_extent < $clipx1) {                return; // Sprite entirely left of clipping area            }            // Clip left edge if left of clipping boundary            if ($x_orig < $clipx1) {                $clipped_width = s16($x_orig + ($clipped_width - $clipx1));                $screen_x = $clipx1;            }            // Clip right edge if right of clipping boundary            if ($clipx2 < $x_extent) {                $clipped_width = s16($clipx2 + ($clipped_width - $x_extent));            }        }        // Calculate zoom X scale (bitmap width in pixels)        $bitmap_width = s16(read16($bitmap + 2) + 1);        $zoom_x_step = concat22(($zoom_y_int & 0xff) << 8, $bitmap_width * s8(shr32($zoom_y_scale, 8)));        // Standard rendering path (not collision test mode)        if (Img::$ftstpix == 0) {            if (Hd3d::$inPass) {                if (!isset(Hd3d::$drawn[spl_object_id($sprite)])) {                    Hd3d::$skipped++;                    if (!Hd3d::$allSprites) {                        return;        // not on the game's own picture (fn/hd3d.php)                    }                }            } elseif (Hd3d::$recording) {                Hd3d::$drawn[spl_object_id($sprite)] = true;            }            // Pure-C billboard scaler            zoomtofen_render_c($sprite, $bitmap, $data_offset, $clipped_width, $clipped_height, $zoom_y_step, $zoom_y_int, $zoom_y_frac, $zoom_x_step, $screen_x, $screen_y, $x_orig, $bitmap_width);        }        // Collision detection path (pixel-perfect hit testing)        elseif ($screen_y <= Img::$ytstpix && Img::$ytstpix < s16($clipped_height + $screen_y) && $screen_x <= Img::$xtstpix && Img::$xtstpix < s16($clipped_width + $screen_x)) {            // Calculate sprite-space coordinates of the test point            $zm = (shl32($zoom_y_frac, 8) & 0xffff) | ($zoom_y_int & 0xff);            $test_x = shr32(mul32((Img::$xtstpix - $x_orig) & 0xffff, $zm), 8);            $test_y = mul32(shr32(mul32((Img::$ytstpix - $newy) & 0xffff, $zm), 8) & 0xffff, (read16($bitmap + 2) + 1) & 0xffff);            // Mirror coordinates if sprite is flipped            if ($sprite->newf != 0) {                $test_y = s32(s16(read16($bitmap + 2) + 1) + $test_y - 1);                $test_x = s32(-$test_x);            }            // Check if hit point is non-transparent in the sprite bitmap            // (u32 index: a wrapped negative one would read far outside the bitmap in C)            $idx = s32($test_x + $test_y + 8);            if ($idx >= 0 && xread8($bitmap + $idx) != 0 && xread32($sprite->script_ent + Alis::$atent) != 0) {                // Record hit info for entity script callback                Img::$cxtstpix = $sprite->depx;                Img::$cytstpix = $sprite->depy;                Img::$cztstpix = $sprite->depz;                Img::$etstpix = s16($sprite->script_ent);                Img::$antstpix = $sprite->newad;                Img::$dtstpix = $sprite->newd;            }        }    }}// Renders a zoomed 2D sprite to the framebuffer using floating-point arithmetic// Same functionality as zoomtofen but with improved precision using floats// PORT: unused by the C (no caller); PHP floats are doubles, the C uses 32-bit float.function zoomtofenf(Sprite $sprite): void{    // Get sprite bitmap data with offset stored in header    $bitmap = s32($sprite->newad + xread32($sprite->newad));    $b0 = xread8($bitmap);    // Only process valid sprite formats (0x18, 0x1a, 0x1c, 0x1e)    if ($b0 == 0x18 || $b0 == 0x1a || $b0 == 0x1c || $b0 == 0x1e) {        // Initialize clipped dimensions (add 1 because dimensions are 0-based)        $clipped_width = s16($sprite->width + 1);        $clipped_height = ($sprite->height + 1) & 0xffff;        // Calculate zoom scale factors using floating-point arithmetic        $bitmap_height = (float) (read16($bitmap + 4) + 1);        $bitmap_width = (float) (read16($bitmap + 2) + 1);        $zoom_y_scale = $clipped_height ? $bitmap_height / (float) $clipped_height : INF;        $zoom_x_scale = $clipped_width ? $bitmap_width / (float) $clipped_width : INF;        $clipx1 = Img::$clipx1;        $clipy1 = Img::$clipy1;        $clipx2 = Img::$clipx2;        $clipy2 = Img::$clipy2;        $newy = $sprite->newy;        // Clip sprite against vertical boundaries        $y_extent = s16(($newy - $clipy1) - Img::$cliph);        $screen_y = $newy;        if ((Img::$cliph <= (($newy - $clipy1) & 0xffff) && $y_extent != 0) || (s16(-$clipped_height - $y_extent) < 0)) {            if ($clipy2 < $newy) {                return; // Sprite entirely below clipping area            }            $y_extent = s16($newy + $clipped_height - 1);            if ($y_extent < $clipy1) {                return; // Sprite entirely above clipping area            }            // Clip top edge if above clipping boundary            if ($newy < $clipy1) {                $clipped_height = ($newy + ($clipped_height - $clipy1)) & 0xffff;                $screen_y = $clipy1;            }            // Clip bottom edge if below clipping boundary            if ($clipy2 < $y_extent) {                $clipped_height = ($clipy2 + ($clipped_height - $y_extent)) & 0xffff;            }        }        // Clip sprite against horizontal boundaries        $x_orig = $sprite->newx;        $x_extent = s16(($x_orig - $clipx1) - Img::$clipl);        $screen_x = $x_orig;        if ((Img::$clipl <= (($x_orig - $clipx1) & 0xffff) && $x_extent != 0) || (s16(-$clipped_width - $x_extent) < 0)) {            if ($clipx2 < $x_orig) {                return; // Sprite entirely right of clipping area            }            $x_extent = s16($x_orig + $clipped_width - 1);            if ($x_extent < $clipx1) {                return; // Sprite entirely left of clipping area            }            // Clip left edge if left of clipping boundary            if ($x_orig < $clipx1) {                $clipped_width = s16($x_orig + ($clipped_width - $clipx1));                $screen_x = $clipx1;            }            // Clip right edge if right of clipping boundary            if ($clipx2 < $x_extent) {                $clipped_width = s16($clipx2 + ($clipped_width - $x_extent));            }        }        $bw = (int) $bitmap_width;        $bh = (int) $bitmap_height;        // Standard rendering path (not collision test mode)        if (Img::$ftstpix == 0) {            // Calculate target framebuffer address            $framebuffer = s32($screen_x + (($screen_y - Img::$wlogy1) & 0xffff) * Img::$wloglarg + Img::$wlogic);            // Calculate initial texture Y coordinate accounting for clipping            $texture_y = (float) ($screen_y - $newy) * $zoom_y_scale;            $line_skip = s16(Img::$wloglarg - $clipped_width);            $flip = ($sprite->newf & 1) != 0;            $m = &Alis::$mem;            // Render pixels row by row            for ($y = 0; $y < $clipped_height; $y++, $framebuffer += $line_skip) {                // Calculate X texture coordinate at left edge (accounting for clipping)                $texture_x = ((float) ($screen_x - $x_orig) * $zoom_x_scale);                if ($flip) {                    // For flipped sprites, mirror the X coordinate                    $texture_x = $bitmap_width - 1.0 - $texture_x;                }                $step = $flip ? -$zoom_x_scale : $zoom_x_scale;                // Render individual pixels in row                for ($x = 0; $x < $clipped_width; $x++, $framebuffer++) {                    $px = (int) $texture_x;                    $py = (int) $texture_y;                    // Clamp to bitmap boundaries                    if ($px >= 0 && $px < $bw && $py >= 0 && $py < $bh) {                        $pixel = $m[$bitmap + $py * $bw + $px + 8];                        if ($pixel !== "\0") { // Skip transparent pixels                            $m[$framebuffer] = $pixel;                        }                    }                    $texture_x += $step;                }                $texture_y += $zoom_y_scale; // Step to next texture row            }        }        // Collision detection path (pixel-perfect hit testing)        elseif ($screen_y <= Img::$ytstpix && Img::$ytstpix < s16($clipped_height + $screen_y) && $screen_x <= Img::$xtstpix && Img::$xtstpix < s16($clipped_width + $screen_x)) {            // Calculate sprite-space coordinates of the test point            $test_x = (int) ((float) (Img::$xtstpix - $x_orig) * $zoom_x_scale);            $test_y = (int) ((float) (Img::$ytstpix - $newy) * $zoom_y_scale);            // Mirror coordinates if sprite is flipped            if ($sprite->newf != 0) {                $test_x = $bw - 1 - $test_x;            }            // Check if hit point is within bitmap and non-transparent            if ($test_x >= 0 && $test_x < $bw && $test_y >= 0 && $test_y < $bh) {                if (xread8($bitmap + $test_y * $bw + $test_x + 8) != 0 && xread32($sprite->script_ent + Alis::$atent) != 0) {                    // Record hit info for entity script callback                    Img::$cxtstpix = $sprite->depx;                    Img::$cytstpix = $sprite->depy;                    Img::$cztstpix = $sprite->depz;                    Img::$etstpix = s16($sprite->script_ent);                    Img::$antstpix = $sprite->newad;                    Img::$dtstpix = $sprite->newd;                }            }        }    }}// Render a billboard sprite at a terrain cell positionfunction barsprite(int $render_context, int $type_idx, int $world_x, int $world_y, int $unused): void{    $sprite = sprite_var(Img::$atexsprite);    $tex_entry = xread32($render_context + 0x10 + $type_idx);    if (xread32($tex_entry) != 0) {        // Project terrain position to screen space        $sh = xread16($render_context - 0x3c0) & 0x3f;        $result = clandtopix(Img::$mapscreen, s16(($world_x << $sh) - xread16($render_context - 0x268)), s16(($world_y << $sh) - xread16($render_context - 0x266)), s16(Img::$solh - xread16($render_context - 0x264)));        $sprite_depth = $result['depth'];        if ($sprite_depth < xread16(Img::$mapscreen + 0x92)) {            $sprite_depth = -1;        }        $sprite->newx = s16(xread16($render_context - 0x26c) + $result['screen_x']);        $sprite->newy = s16(xread16($render_context - 0x26a) + $result['screen_y']);        $sprite->newd = $sprite_depth;        $sprite->newzoomx = $result['zoom'] & 0xffff;        $sprite->newzoomy = $result['zoom'] & 0xffff;        if (-1 < $sprite_depth) {            $sprite->script_ent = xread16($render_context + 0x1c + $type_idx) & 0xffff;            $sprite->credon_off = s8(xread8($render_context + 0x15 + $type_idx));            // Resolve bitmap and metadata pointers            $bitmap_base = s32(xread32($tex_entry) + $tex_entry);            $meta = Img::$zoombid;            $bitmap = $bitmap_base;            if (s8(xread8($bitmap)) == 3) {                $tex_entry = s32($tex_entry + xread16($bitmap + 2) * 4);                $bitmap = s32(xread32($tex_entry) + $tex_entry);                $meta = $bitmap_base;            }            $sprite->newad = $tex_entry & 0xffffff;            $sprite->newf = s8(xread8($meta + 1));            // Compute zoom shift from detail level            $detail_level = $sprite->credon_off & 0xff;            if ((xread8($bitmap + 1) & 0x20) == 0) {                $detail_level = ($detail_level + 1) & 0xff;            }            $detail_shift = $detail_level & 0x3f;            // Compute scaled sprite dimensions            $sprite_height = (s32(shr32(mul32(s16(xread16($bitmap + 4) + 1), $sprite->newzoomy), 8) * 2) >> $detail_shift) - 1;            if ($sprite_height < 0) {                $sprite_height = 0;            }            $sprite_width_calc = (s32(shr32(mul32(s16(xread16($bitmap + 2) + 1), $sprite->newzoomx), 8) * 2) >> $detail_shift) - 1;            $sprite_width = s16($sprite_width_calc);            if ($sprite_width_calc < 0) {                $sprite_width = 0;            }            $sprite->width = $sprite_width;            $sprite->height = s16($sprite_height);            // Adjust position by hotspot offset            $sprite->newy = s16(s16(((s16((xread16($bitmap + 4) >> 1) - xread16($meta + 6)) * $sprite->newzoomy) >> 8) * -2 >> $detail_shift) + $sprite->newy);            $sprite->newx = s16(s16(((s16((xread16($bitmap + 2) >> 1) - xread16($meta + 4)) * $sprite->newzoomx) >> 8) * -2 >> $detail_shift) + $sprite->newx);            zoomtofen($sprite);        }    }}// Render all sprites in the depth-sorted list that are behind the current depth layerfunction spritaff(int $depth_layer): void{    $idx = Img::$spritnext & 0xffff;    while (true) {        if ($idx == 0) {            // End of sprite list: reset depth sentinel            Img::$spritnext = $idx;            Img::$spritprof = 0x8000;            return;        }        $sprite = sprite_var($idx);        if ($sprite->newd <= $depth_layer) {            break;        }        // Render valid sprite        if (-1 < $sprite->state && -1 < $sprite->newf && -1 < $sprite->newd) {            if (Hd3d::$on) { $GLOBALS['spr'][Hd3d::$inPass ? 'hd' : 'low'][$idx] = [$sprite->newx, $sprite->newy, $sprite->width, $sprite->height, $sprite->newd]; }            zoomtofen($sprite);        }        $idx = $sprite->link;    }    // Update next-to-render pointer and depth threshold    Img::$spritprof = sprite_var($idx)->newd;    Img::$spritnext = $idx;}function affiland(int $scene): void{    $scene_addr = s32(Alis::$basemain + $scene);    // (enhanced RGBA / depth buffer allocation and dark RGBA rebuild dropped: emode only)    // Set up logic buffer and viewport from scene data    Img::$mapscreen = $scene_addr;    Img::$wloglarg = Alis::$platform->is_little_endian ? Hd3d::stride() : s16(xread16($scene_addr + 0x12) + 1);    Img::$wlogic = xread32(xread32($scene_addr + 0x30));    Img::$wlogx1 = xread16($scene_addr + 0xe);    Img::$wlogy1 = xread16($scene_addr + 0x10);    // Resolve render context from entity table    $render_context = s32(xread16($scene_addr + 0x42) + xread32(Alis::$atent + xread16($scene_addr + 0x40)));    // Initialize clipping rectangle from scene viewport    Img::$fenx1 = xread16($scene_addr + 0xe);    Img::$landclipy1 = xread16($scene_addr + 0x10);    Img::$landclipx2 = s16(xread16($scene_addr + 0x12) + Img::$fenx1);    Img::$feny2 = s16(xread16($scene_addr + 0x14) + Img::$landclipy1);    Img::$clipl = s16((Img::$landclipx2 - Img::$fenx1) + 1);    Img::$landcliph = s16((Img::$feny2 - Img::$landclipy1) + 1);    Img::$vbarclipx2 = s16(Img::$landclipx2 + 1);    Img::$feny1 = Img::$landclipy1;    Img::$fenx2 = Img::$landclipx2;    Img::$clipx1 = Img::$fenx1;    Img::$clipy1 = Img::$landclipy1;    Img::$clipx2 = Img::$landclipx2;    Img::$clipy2 = Img::$feny2;    Img::$cliph = Img::$landcliph;    if (Img::$ftstpix == 0) {        if ((xread8($scene_addr) & 0x80) == 0) {            // No 3D flag: copy VGA buffer to display if switching            if ((Alis::$fswitch != 0) && (Img::$switchland != 0)) {                // Sync the OTHER double-buffer page with the just-rendered static scene.                Img::$fenlargw = Img::$wloglarg >> 2;                Img::$wloglarg = Img::$wloglarg >> 1;                tvtofen();                Img::$switchland = 0;            }        } else {            // Full 3D terrain render pipeline            $hd = Hd3d::wanted($scene_addr) ? hd3d_begin($scene_addr, $render_context) : null;            calctoy($scene_addr, $render_context);            spritland($scene_addr, xread16($scene_addr + 2));            calclan0($scene_addr, $render_context);            if (((xread8($scene_addr + 1) & 0x40) == 0) && (xread16($scene_addr + 0xa2) == 0)) {                clrvga();            }            doland($scene_addr, $render_context);            if ($hd !== null) {                hd3d_low($hd);       // the land as drawn (before vgatofen): which pixels of the screen are the 3D            }            vgatofen();            Img::$landone = 1;            Img::$switchland = 1;            if ($hd !== null) {                hd3d_pass($hd);      // the same picture again at twice the resolution (fn/hd3d.php)            }        }    } else {        // Hit-test mode: skip rendering, only compute terrain data        calclan0($scene_addr, $render_context);        doland($scene_addr, $render_context);    }    // Restore logic buffer state    Img::$wlogic = Img::$logic;    Img::$wlogx1 = Img::$logx1;    Img::$wlogy1 = Img::$logy1;    Img::$wlogx2 = Img::$logx2;    Img::$wlogy2 = Img::$logy2;    Img::$wloglarg = Img::$loglarg;    Img::$fenlargw = Img::$loglarg >> 2;}function pixtoland(int $render_context): void{    // Inverse perspective projection: screen (x, y) + depth → world (x, y, z)    // Read camera world position    $cam_wx = xread16($render_context - 0x268);    $cam_wy = xread16($render_context - 0x266);    $cam_wz = xread16($render_context - 0x264);    // Read camera screen center    $cam_sx = xread16($render_context - 0x26c);    $cam_sy = xread16($render_context - 0x26a);    // Read precomputed trig values    $cos_yaw = xread16($render_context - 0x28a);    $sin_yaw = xread16($render_context - 0x28c);    $sin_pitch = xread16($render_context - 0x290);    // Read FOV projection factors    $fov_num_x = xread16($render_context - 0x3ac);    $fov_den_x = xread16($render_context - 0x3aa);    $fov_num_y = xread16($render_context - 0x3a8);    $fov_den_y = xread16($render_context - 0x3a6);    $depth = Img::$dtstpix;    // Screen deltas from camera center    $dx = s16(Img::$xtstpix - $cam_sx);    $dy = s16($cam_sy - Img::$ytstpix);    $depth_adj_x = s16($fov_num_x + $depth);    // Unproject X: rotate dx by cos(yaw), scale by perspective, subtract depth*sin(yaw)    $rot_cos = s16(($dx * $cos_yaw) >> 9);    $unproj_x = s16(cdiv($rot_cos * $depth_adj_x, $fov_den_x));    $depth_sin = s16(($depth * $sin_yaw) >> 9);    Img::$cxtstpix = s16($cam_wx + ($unproj_x - $depth_sin));    // Unproject Y: rotate dx by sin(yaw), scale by perspective, add depth*cos(yaw)    $rot_sin = s16(($dx * $sin_yaw) >> 9);    $unproj_y = s16(cdiv($rot_sin * $depth_adj_x, $fov_den_x));    $depth_cos = s16(($depth * $cos_yaw) >> 9);    Img::$cytstpix = s16($cam_wy + $depth_cos + $unproj_y);    // Unproject Z: scale dy by perspective, add depth*sin(pitch)    $depth_adj_y = s16($fov_num_y + $depth);    $unproj_z = s16(cdiv($dy * $depth_adj_y, $fov_den_y));    $depth_pitch = s16(($depth * $sin_pitch) >> 9);    Img::$cztstpix = s16($cam_wz + $depth_pitch + $unproj_z);}function pointpix(int $x, int $y): void{    // Resolve scene address from current script    $scene_id = xread16(Alis::$script->vram_org - 0x16);    $scene_addr = s32(Alis::$basemain + $scene_id);    // Initialize hit-test state    Img::$dtstpix = xread16($scene_addr + 0x94);    Img::$etstpix = -1;    Img::$ntstpix = -1;    Img::$ftstpix = 1;    Img::$xtstpix = s16($x);    Img::$ytstpix = s16($y);    // Run terrain hit-test if scene is not disabled    if ((xread8($scene_addr) & 0x40) == 0) {        affiland($scene_id);        // Resolve hit entity sprite index from entity table        if (-1 < Img::$etstpix) {            $ent = xread32(xread32(Alis::$atent + Img::$etstpix) - 0x14);            $entity_data = s32(xread32($ent + 0xe) + $ent);            Img::$ntstpix = s16(s32((Img::$antstpix & 0xffffff) - (xread32($entity_data) + $entity_data)) >> 2);            if (xread16($entity_data + 4) <= Img::$ntstpix) {                // Sprite index out of range: fall back to base entity table                $base = s32(Alis::$basemain + xread32(Alis::$basemain + 0xe));                Img::$ntstpix = s16(s32((Img::$antstpix & 0xffffff) - (xread32($base) + $base)) >> 2);            }        }    }    // Convert hit screen position back to world coordinates    $render_context = s32(xread16($scene_addr + 0x42) + xread32(Alis::$atent + xread16($scene_addr + 0x40)));    pixtoland($render_context);    Img::$ftstpix = 0;}// ---------------------------------------------------------------------------------------------// Function pointers for platform-specific dispatch (Rrq3dVars closures; C: calclan0, doland, ...)// ---------------------------------------------------------------------------------------------function calclan0(int $scene_addr, int $render_context): void{    if (Rrq3dVars::$calclan0 === null) {        render3d_init();    }    (Rrq3dVars::$calclan0)($scene_addr, $render_context);}function doland(int $scene_addr, int $render_context): void{    if (Rrq3dVars::$doland === null) {        render3d_init();    }    (Rrq3dVars::$doland)($scene_addr, $render_context);}function landtofi(int $unused, int $scene_id): void{    if (Rrq3dVars::$landtofi === null) {        render3d_init();    }    (Rrq3dVars::$landtofi)($unused, $scene_id);}function clrvga(): void{    if (Rrq3dVars::$clrvga === null) {        render3d_init();    }    (Rrq3dVars::$clrvga)();}function vgatofen(): void{    if (Rrq3dVars::$vgatofen === null) {        render3d_init();    }    (Rrq3dVars::$vgatofen)();}// rrq3d_68k.c back end: fn/rrq3d_68k.php.function render3d_init(): void{    if (Alis::$platform->is_little_endian) {        Rrq3dVars::$calclan0 = calclan0_dos(...);        Rrq3dVars::$doland = doland_dos(...);        Rrq3dVars::$landtofi = landtofi_dos(...);        Rrq3dVars::$clrvga = clrvga_dos(...);        Rrq3dVars::$vgatofen = vgatofen_dos(...);    } else {        Rrq3dVars::$calclan0 = calclan0_68k(...);        Rrq3dVars::$doland = doland_68k(...);        Rrq3dVars::$landtofi = landtofi_68k(...);        Rrq3dVars::$clrvga = clrvga_68k(...);        Rrq3dVars::$vgatofen = vgatofen_68k(...);    }}