Files
Neutron/tools/binary/bubble_motion.py
T

230 lines
11 KiB
Python

#!/usr/bin/env python3
"""Read-only Bubble movement source guards and bounded arithmetic projections.
Static source projections do not execute original gameplay or emulate x87/trig
table precision. REA Evidence/provider limitations are in bubble-motion.md.
"""
from __future__ import annotations
import argparse
from dataclasses import dataclass
import hashlib
import json
import math
from pathlib import Path
import struct
from checkpoint_script_state import EXE_SHA256, find_case, read_va
from pe_inspect import PE
BODIES = (
('frame', 0x437940, 0x437c3a, '9579bfb1c4d9ae6abf2a1c78d6f99544871a63216fb80b9a906e3a76ebe27983'),
('apply', 0x4387e0, 0x438a58, 'c4de9afecf895c0ae30d5e939716e66abe33e7306506ddf0da981ede5061371c'),
('input', 0x439900, 0x43a111, '895f27be2ad03f49230fe34e98753095285a61f52b4adbbb15f1dd7c868b2901'),
('dispatch', 0x438a60, 0x438bb4, '99717e7fbac658abcb4b825047d2c35714b8b9e1361534374a109e8556641fc9'),
('jump_predicate', 0x4378d0, 0x43793a, 'f723e460743e29309cdb0efdb8b25df2513490bd84e9d175e6493f963614ab01'),
('landing_hook', 0x42a720, 0x42a72b, '157917f7713b11d5959c99602ce485abe99a268e396dc380d329bc52acd7e93a'),
('empty_hook', 0x472970, 0x472971, 'ae3f4619b0413d70d3004b9131c3752153074e45725be13b9a148978895e359e'),
('fire_predicate', 0x42a7a0, 0x42a7d6, 'c8fa10f42eefe68a195d9980f1a57558a240cd7877bfeab567e7868c0ddf419f'),
('support_pose', 0x42469b, 0x4246e9, '40e025e4bdc8bcdbcb24651e3d81908a5b7a9e2cc8de81d733da7490ea76c1d4'),
('wrapper_input', 0x426030, 0x4263f0, '365773538a65d99bd9e5d04c790eee7758ee528bdc385dba309f49d49ea9e5bb'),
('vector_transform', 0x472b10, 0x472c10, 'ee9516aef07738fcf7da370af74185f7522686759218ad1bf4d93be46f0c28b2'),
)
VTABLES = (
(0x4a3bdc, 0x128, 0x439900), (0x4a3bdc, 0x13c, 0x4387e0),
(0x4a3bdc, 0x154, 0x42a720), (0x4a3bdc, 0x158, 0x4378d0),
(0x4a3bdc, 0x15c, 0x42a7a0), (0x4a373c, 0x2bc, 0x471f10),
(0x4a373c, 0x2c4, 0x471f40), (0x4a373c, 0x38c, 0x472b10),
)
CONSTANTS = ((0x48d948, 'f', .5), (0x48d96c, 'f', 100.),
(0x4a3e78, 'f', -50.), (0x48d400, 'f', 50.),
(0x49d5b8, 'f', 0.0181818176060915),
(0x4afd2c, 'f', -.25), (0x49d5dc, 'f', 0.9090909361839294),
(0x494cb8, 'd', 1.8), (0x4a6850, 'd', .8),
(0x4a2ad0, 'd', .2), (0x48e598, 'd', 1.5))
SITES = (
('mode2_apply_dispatch', 0x437a5d, 33), ('publish_speed', 0x437c22, 17),
('nonzero_velocity_gate', 0x43884e, 17), ('yaw_add', 0x43885f, 34),
('velocity_store', 0x438950, 44), ('support_gate', 0x43899a, 18),
('held_jump_bounce900', 0x4389d8, 45), ('released_bounce300', 0x438a0c, 68),
('fire_forward_mode2', 0x439abb, 43), ('support_input_decay', 0x439ba2, 75),
('turn50', 0x439cb2, 73), ('mode2_lean', 0x439cfb, 55),
('mode2_camera', 0x439f4d, 239), ('base_input_first', 0x426081, 8),
('gadget_input_consumes', 0x426095, 17), ('drain_after_input', 0x426264, 65),
('supported_stop', 0x4246a9, 51),
)
HANDOFF_BODIES = (
('cleanupA20', 0x428037, 0x4280cc, 'b8891ee4fb67c566785ed329194717c3e30a895bd15bda91eedd81d76d026a55'),
('normal_destinations', 0x43951e, 0x4395cf, 'b3c30081c2f5dad2b51b240d1b91eb345700bcf9f3ff356793724890340a40ce'),
('normal_direction_flags', 0x438f66, 0x4393fb, '5e8af054cbf28fb5f676f6f05a0efea4c8e2ebc1ae69cce09abbca57f60a68e2'),
('rotation', 0x43a420, 0x43a5cf, 'e052ee855e625d03a3317dcc7d507081c7519576381afa5741572157e5ffb988'),
('constructorA20', 0x4226c9, 0x4226d5, '41cfd341bf4e4602eb69c04e4837e05de62746a3117335b651e4ab29ddac9c8d'),
('normal_air_pose', 0x439d81, 0x439e33, '38d71efb31ca7ee03e248658bf469e0141a1cbf47f177b63d10cea9c7b5469da'),
)
def collect_handoff(pe: PE):
"""Bounded direct-displacement search; does not rule out derived aliases."""
bodies = []
for name, start, end, expected in HANDOFF_BODIES:
actual = hashlib.sha256(read_va(pe, start, end-start)).hexdigest()
if actual != expected:
raise ValueError(f'Changed handoff span {name}')
bodies.append(dict(name=name, va=hex(start), file_offset=hex(pe.offset(start-pe.base)),
length=end-start, sha256=actual))
text = next(s for s in pe.sections if s['name'] == '.text')
start, size = text['file_offset'], text['raw_size']
raw = pe.data[start:start+size]
matches = []
offset = 0
while (offset := raw.find(struct.pack('<I', 0xa20), offset)) >= 0:
matches.append(pe.va(start+offset))
offset += 1
expected = [0x4226d1,0x428047,0x42821c,0x45cfe3,0x45d024,0x45d035]
if matches != expected:
raise ValueError('Changed A20 literal/displacement search boundary')
# First3 are MOV disp32 writes; remaining3 are unrelated PUSH immediates.
for va, prefix in [(0x4226cf,b'\x89\x9d'), (0x428045,b'\xc7\x86'), (0x42821a,b'\xc7\x86')]:
if read_va(pe, va, 2) != prefix:
raise ValueError('Changed direct A20 write')
return dict(bodies=bodies, text_va=hex(pe.base+text['rva']), text_size=size,
a20_raw_dword_occurrences=[hex(a) for a in matches],
a20_direct_writes=['0x4226cf','0x428045','0x42821a'],
a20_consumer=None, derived_aliases_excluded=False,
cleanup_resets_euler=False, ground_no_input_resets_euler=False,
accepted_ground_destination_pitch=0, accepted_ground_destination_roll=0,
ordinary_air_destination_pitch=0, ordinary_air_roll_multiplier=-1)
def collect(original: Path | str):
pe = PE(find_case(Path(original), 'Neutron.exe'))
digest = hashlib.sha256(pe.data).hexdigest()
if digest != EXE_SHA256:
raise ValueError('Unexpected original EXE identity')
bodies = []
for name, start, end, expected in BODIES:
actual = hashlib.sha256(read_va(pe, start, end-start)).hexdigest()
if actual != expected:
raise ValueError(f'Changed source span {name}')
bodies.append(dict(name=name, va=hex(start), file_offset=hex(pe.offset(start-pe.base)),
length=end-start, sha256=actual))
for base, slot, expected in VTABLES:
if struct.unpack('<I', read_va(pe, base+slot, 4))[0] != expected:
raise ValueError(f'Changed virtual {base:x}+{slot:x}')
for va, kind, expected in CONSTANTS:
if struct.unpack('<'+kind, read_va(pe, va, struct.calcsize(kind)))[0] != expected:
raise ValueError(f'Changed constant {va:x}')
return dict(sha256=digest, bodies=bodies,
sites=[dict(name=n, va=hex(v), file_offset=hex(pe.offset(v-pe.base)),
bytes=read_va(pe, v, z).hex()) for n,v,z in SITES],
vtables=[dict(table=hex(b), slot=hex(s), target=hex(t)) for b,s,t in VTABLES],
constants=[dict(va=hex(a), value=v) for a,k,v in CONSTANTS],
movement_mode=2, max_speed=1350, bounce_released=300, bounce_held=900,
bounce_sound=106, landing_mode_reset=False, handoff=collect_handoff(pe))
def finite(*values):
if not all(math.isfinite(v) for v in values):
raise ValueError('Finite bounded inputs required')
@dataclass(frozen=True)
class InputResult:
speed: float
turn: float
target_pitch: float
target_roll: float
def keyboard_step(speed: float, turn: float, seconds: float, *, forward=False,
backward=False, left=False, right=False, fire=False, supported=False,
maximum=1350.) -> InputResult:
"""439900 keyboard subset; effective fire predicate supplied by caller.
Includes supported slowdown before Down and separate later apply slowdown.
Mouse/analog and camera are documented but deliberately not approximated here.
"""
finite(speed, turn, seconds, maximum)
if not 0 <= seconds < 1 or maximum <= 0:
raise ValueError('Bounded timestep and positive maximum required')
amount = 100*seconds
if left:
turn += amount
elif right:
turn -= amount
elif turn < 0:
turn = min(0, turn+amount)
elif turn > 0:
turn = max(0, turn-amount)
throttle = forward or fire
if throttle and speed < maximum:
speed = min(maximum, speed+30)
if not throttle and speed > maximum*0.9090909361839294:
speed -= 17.5
if supported:
speed = speed-17.5 if speed > 0 else 0.
if backward:
if speed > 0:
speed = max(0., speed-(35. if supported else 17.5))
elif speed < 0:
speed = min(0., speed+35.)
turn = max(-50., min(50., turn))
return InputResult(speed, turn, -10. if throttle else 10. if backward else 0., -.25*turn)
@dataclass(frozen=True)
class ApplyResult:
velocity: tuple[float, float, float]
yaw: float
published_speed: float
sound: int | None
movement_mode: int = 2
def apply_step(speed: float, turn: float, yaw: float, pitch: float,
velocity: tuple[float, float, float], seconds: float, *,
supported=False, jump=False, friction=.8) -> ApplyResult:
"""4387E0 algebra with host trig; original table quantization is not emulated.
XZ is composed using pre-bounce speed, while the published scalar can halve.
Original acceleration and impulse are untouched by this routine.
"""
finite(speed, turn, yaw, pitch, seconds, friction, *velocity)
if not 0 <= seconds < 1:
raise ValueError('Bounded timestep required')
side = 0.
if any(v != 0 for v in velocity):
yaw += turn*seconds
side = turn*(1-friction)*speed*0.0181818176060915
sine, cosine = math.sin(math.radians(yaw)), math.cos(math.radians(yaw))
forward = speed*math.cos(math.radians(pitch))
vx, vy, vz = -sine*forward+cosine*side, velocity[1], cosine*forward+sine*side
sound = None
if supported:
if jump:
vy, sound = 900., 106
else:
speed *= .5
vy = 300.
return ApplyResult((vx,vy,vz), yaw, speed, sound)
def ordinary_destination(previous: tuple[float,float,float], yaw: float, turn: float,
*, airborne=False, accepted_ground_direction=False):
"""Bounded destination handoff, not rotation/interpolation scheduling.
Ordinary ground no-input preserves the prior Bubble target. Accepted ground
steering replaces pitch/roll with0; normal airborne input supplies roll-turn.
"""
finite(*previous, yaw, turn)
if airborne:
return (0., yaw, -turn)
if accepted_ground_direction:
return (0., yaw, 0.)
return previous
if __name__ == '__main__':
cli = argparse.ArgumentParser(description=__doc__)
cli.add_argument('original', type=Path)
print(json.dumps(collect(cli.parse_args().original), indent=2))