Files
Neutron/tools/binary/rocketship_motion_camera.py
T

334 lines
18 KiB
Python

#!/usr/bin/env python3
"""Guarded Rocketship motion/camera math and separate copied-source probe.
The projection omits original x87 bit identity and registry/body/actor execution.
The generated probe uses copied EXE functions and the copied OMT2 trig/angles.
"""
from __future__ import annotations
import argparse
import hashlib
import json
import math
from pathlib import Path
import re
import struct
from checkpoint_script_state import EXE_SHA256, find_case, read_va
from pe_inspect import PE
from rocketship import PROBE as BASE_PROBE
from shrink_heading import DLL_SHA256, half_acos_table, heading_units
SPANS = (
('flight_apply',0x41a140,0x41a6b1,'20fc706986e58791dc19334a01a772dd517cbd260079382dac2f009fc8707bb7'),
('flight_input_camera',0x41a6c0,0x41ade6,'eae8075a264d9c51d12deba47c9f24eb1624c646f688c57949c8aad8268ac99d'),
('facing',0x41adf0,0x41afa2,'ae33bec7932c0ac9d5287dcfd790d1699ebdef5ab05f74c843a43ae9bc2af4e1'),
('add_euler',0x472480,0x472570,'406c3904538abe07d88ca440e39ca56c00765d0871943991ba7b792da4803c16'),
('point_transform',0x472980,0x472b10,'18752360ad70d2db3aa95fdcc643d4099bca2e59843b1e57aca9f17b5b1ccb6c'),
('vector_transform',0x472b10,0x472c10,'ee9516aef07738fcf7da370af74185f7522686759218ad1bf4d93be46f0c28b2'),
('camera_ray',0x419de0,0x419ecf,'5ad2724e6dee64929a14ab8d7ab7ebcff1b219df547580bd044127310c6b6131'),
('flying_ctor',0x419b70,0x419db0,'85c0e74764282ed55e2c7268a0dec5944097b16f1a9df71054e5458b446ee2c0'),
('destination',0x472660,0x472685,'e18df19aec39509f78fd20861938b67f2688a6aa142f064a7f5721f4676ee344'),
('registry_facing',0x473240,0x473298,'46dc448d383d31fcb9eb4ad2c033f5c08cc51b5d196f982a7c25dfa3242fb91d'),
)
TABLES = ((0x4b25ac,0x328,0x4723f0),(0x4b25ac,0x334,0x458f90),
(0x4b25ac,0x36c,0x472660),(0x4b25ac,0x384,0x472980),
(0x4b25ac,0x38c,0x472b10),(0x4b25ac,0x3d8,0x41adf0),
(0x4b2a4c,0x12c,0x419de0))
CONSTANTS = ((0x48e5a0,3.),(0x49d5e8,4.),(0x48e5b0,180.),
(0x48e5c0,-180.),(0x48e5c4,360.),(0x49d5c0,1.2000000476837158),
(0x49d5c4,.6000000238418579),(0x49d5ac,.75),(0x48d954,2.),
(0x48e5e8,45.511112213134766),(0x49d5b8,.0181818176060915))
def f32(x): return struct.unpack('<f',struct.pack('<f',x))[0]
def collect(original):
original=Path(original)
pe=PE(find_case(original,'Neutron.exe'))
dll=PE(find_case(original,'OMT2.dll'))
if hashlib.sha256(pe.data).hexdigest()!=EXE_SHA256 or hashlib.sha256(dll.data).hexdigest()!=DLL_SHA256:
raise ValueError('Unexpected source image identity')
bodies=[]
for name,start,end,expected in SPANS:
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),end=hex(end),file_offset=hex(pe.offset(start-pe.base)),sha256=actual))
for tab,slot,target in TABLES:
if struct.unpack('<I',read_va(pe,tab+slot,4))[0]!=target: raise ValueError('Changed virtual target')
for va,value in CONSTANTS:
if struct.unpack('<f',read_va(pe,va,4))[0]!=value: raise ValueError('Changed motion/camera constant')
imports={int(v['iat'],16):v['name'] for v in pe.imports()}
if imports[0x48d108]!='?angles@OMedia3DVector@@QAEXAAF0@Z' or imports[0x48d10c]!='?global@OMediaCosSinTable@@2V1@A':
raise ValueError('Changed OMT vector/table import')
globals_=[0x4f8198,0x4f8182,0x50988c,0x509845,0x509acc,0x50988a,0x509aca,
0x48d914,0x48e5b0,0x49d5bc,0x48d924,0x49d5b8,0x48e5e8,
0x48d10c,0x48d108,0x4f81ac,0x49d5c0,0x49d5c4,
0x509a50,0x50985d,0x50985f,0x509aa0,0x509aa4,0x48d948,0x48d94c,
0x49b1fc,0x49d5e4,0x509882,0x509881,0x509885,0x509891,0x509848,
0x50985e,0x509834,0x49d5e0,0x49d5dc,0x48e5bc,0x509860,0x50993a,
0x49d5d8,0x49d5d4,0x48e5ec,0x495324,0x49d5d0,0x49d5cc,0x49d5c8,
0x48e5c0,0x48e5c4,0x48e5a0,0x49d5e8,0x5cfc60,0x5cfc64,
0x5cfc68,0x5cfc6c,0x49d5ac,0x48d954]
reloc=[]
for _,start,end,_ in SPANS:
code=read_va(pe,start,end-start)
for target in globals_:
pattern=struct.pack('<I',target)
for i in range(len(code)-3):
if code[i:i+4]==pattern:reloc.append((start+i,target))
return dict(source_sha256=EXE_SHA256,dll_sha256=DLL_SHA256,bodies=bodies,
vtables=[dict(table=hex(a),slot=hex(b),target=hex(c)) for a,b,c in TABLES],
constants=[dict(va=hex(a),value=b) for a,b in CONSTANTS],relocations=sorted(set(reloc)))
def trig(angle):
index=math.trunc(angle*f32(45.511112213134766))&16383
return f32(math.sin(index*math.tau/16384)),f32(math.cos(index*math.tau/16384))
def rotate(vector,euler):
"""472B10: negative Z, then negative X, then negative Y; lookup-quantized."""
x,y,z=vector;sx,cx=trig(euler[0]);sy,cy=trig(euler[1]);sz,cz=trig(euler[2])
a=f32(cz*y-sz*x)
b=cz*x+sz*y
c=cx*z-a*sx
return (f32(b*cy-c*sy),f32(a*cx+sx*z),f32(c*cy+b*sy))
def add_axis(value,delta):
total=value+delta
if total<0:total=360-abs(math.trunc(total))
elif total>360:total-=360
return f32(total)
def facing(rotation,destination,dt,enabled=True,barrel_timer=0):
if not enabled or barrel_timer>0:return tuple(rotation),enabled
differences=[]
active=False
for axis,(target,current) in enumerate(zip(destination,rotation)):
d=target-current
if d!=0:
active=True
if d>180:d-=360
elif axis!=1 and d<-180:d+=360
differences.append(d)
increments=[f32(d*dt*k) for d,k in zip(differences,(2,4,3))]
return tuple(add_axis(v,d) for v,d in zip(rotation,increments)),active
def horizontal(velocity,rotation,speed,bank,previous_bank,dt,friction=.8,
turn_timer=0,roll_timer=0,turn_latch=False,roll_latch=False,
turn_pressed=False,roll_pressed=False,suppressed=False):
"""Ordinary no-boost/no-roll apply, after inherited facing, before vertical."""
moving=any(v!=0 for v in velocity)
if not suppressed:
if not turn_pressed:turn_latch=False
elif moving and not turn_latch:
turn_latch=True
if turn_timer<=0:turn_timer=1
if not roll_pressed:roll_latch=False
elif moving and not roll_latch:
roll_latch=True
if roll_timer<=0:roll_timer=1
if turn_timer>0:
rotation=(rotation[0],add_axis(rotation[1],f32(180*dt)),rotation[2])
turn_timer=f32(max(0,turn_timer-dt))
elif moving:
previous_bank=bank
rotation=(rotation[0],add_axis(rotation[1],f32(bank*dt)),rotation[2])
if roll_timer>0:
roll_timer=f32(max(0,roll_timer-dt))
rotation=(rotation[0],rotation[1],add_axis(rotation[2],f32(270*dt)))
if moving:
side=f32(previous_bank*f32(.0181818176060915)*(1-f32(friction))*speed)
sy,cy=trig(rotation[1])
side_x=f32(cy*side);side_z=f32(sy*side)
else:side_x=side_z=0
forward=rotate((0,0,speed),rotation)
outgoing=velocity if turn_timer>0 else (f32(forward[0]+side_x),velocity[1],f32(forward[2]+side_z))
return dict(rotation=tuple(rotation),velocity=tuple(outgoing),previous_bank=previous_bank,
turn_timer=turn_timer,roll_timer=roll_timer,turn_latch=turn_latch,roll_latch=roll_latch)
def camera(root,rotation,old_eye,dt,detail=0,hit=None):
eye_local=rotate((0,200,-500),rotation);look_local=rotate((0,50,200),rotation)
eye=tuple(f32(a+b) for a,b in zip(root,eye_local))
look=tuple(f32(a+b) for a,b in zip(root,look_local))
gain=1
if hit is not None:
eye=tuple(f32(a-(a-b)*.75) for a,b in zip(look,hit));gain=2
multiplier=f32(.6 if detail<=1 else 1.2)
updated=tuple(f32(old+(want-old)*gain*dt*multiplier) for old,want in zip(old_eye,eye))
direction=tuple(f32(a-b) for a,b in zip(look,old_eye))
pitch,yaw=angles(direction)
return dict(eye=updated,desired_eye=eye,look=look,direction=direction,gain=gain,pitch=pitch,yaw=yaw)
def angles(vector):
x,y,z=vector;heading=heading_units(x,z)
a=(-heading)&16383
sine=f32(math.sin(a*math.tau/16384));cosine=f32(math.cos(a*math.tau/16384))
h=x*sine+z*cosine
if h==0 and y==0:value=0
else:
value=half_acos_table()[math.trunc(16384*y*y/(h*h+y*y))]
if y<0:value=8192+value if h<0 else 8192-value
elif h<0:value=16384-value
pitch=(4096-value)&16383
if pitch>8192:pitch-=16384
return pitch,heading-16384 if heading>8192 else heading
def ingest(report,log,executable,source):
content=Path(log).read_text()
if 'ROCKET_MOTION_CAMERA_COMPLETE:' not in content:raise ValueError('Incomplete original probe')
cases=[];seen=set()
for line in content.splitlines():
fields=line.split()
if not fields or fields[0] not in ('TRANSFORM','MOTION','AUX','FACING','CAMERA'):continue
kind,name,*pairs=fields
if (kind,name) in seen:raise ValueError('Repeated original case')
seen.add((kind,name));sample={}
for pair in pairs:
key,value=pair.split('=',1)
numbers=[float(v) for v in value.split(',')]
if not all(math.isfinite(v) for v in numbers):raise ValueError('Nonfinite original result')
sample[key]=numbers if ',' in value else numbers[0]
cases.append(dict(kind=kind,name=name,values=sample))
if len(cases)!=31:raise ValueError('Unexpected original case count')
return dict(scope='Copied EXE motion/facing/camera and copied OMT trig/angles; synthetic actor/body/ray/input dependencies; no game entrypoint',
source_sha256=report['source_sha256'],dll_sha256=report['dll_sha256'],
generator_sha256=hashlib.sha256(Path(source).read_bytes()).hexdigest(),
executable_sha256=hashlib.sha256(Path(executable).read_bytes()).hexdigest(),
log_sha256=hashlib.sha256(Path(log).read_bytes()).hexdigest(),cases=cases)
def probe_source(report):
prefix=BASE_PROBE[:BASE_PROBE.index('static void run(')]
prefix=prefix.replace('#include <string.h>','#include <string.h>\n#include <math.h>')
prefix=prefix.replace('memcpy(AT(0x41ac0e),finish,sizeof(finish));','(void)finish;')
reloc=',\n'.join(f'{{0x{a:x},0x{b:x}}}' for a,b in report['relocations'])
return prefix.replace('/* RELOCATIONS */',reloc)+PROBE_TAIL
PROBE_TAIL=r'''
typedef struct{float x,y,z,w;}Vec;
typedef void(TC*Angles)(const float*,short*,short*);
static Vec root,velocity;
static Vec trace_start,trace_end,hit_point;
static int ray_hit;
static HMODULE omt;
static Vec*TC get_root(void*self,Vec*out){(void)self;*out=root;return out;}
static Vec*TC get_velocity(void*self,Vec*out){(void)self;*out=velocity;return out;}
static void TC set_velocity(void*self,float x,float y,float z){(void)self;velocity.x=x;velocity.y=y;velocity.z=z;}
static int __cdecl trace(Vec start,Vec end,int sides){(void)sides;trace_start=start;trace_end=end;memcpy(AT(0x5cfc60),&hit_point,sizeof(hit_point));return ray_hit;}
static void __cdecl base_skip(float dt){(void)dt;}
static void patch_jump(unsigned va,void*fn){unsigned char*p=AT(va);p[0]=0xb8;*(uintptr_t*)(p+1)=(uintptr_t)fn;p[5]=0xff;p[6]=0xe0;}
static void setup(void){
map_copy();omt=LoadLibraryA("Z:\\work\\game\\OMT2.dll");require(omt!=NULL,"copied OMT2");
*(void**)AT(0x48d108)=GetProcAddress(omt,"?angles@OMedia3DVector@@QAEXAAF0@Z");
*(void**)AT(0x48d10c)=GetProcAddress(omt,"?global@OMediaCosSinTable@@2V1@A");
require(*(void**)AT(0x48d108)&&*(void**)AT(0x48d10c),"original angles/trig exports");
patch_jump(0x47c210,trace);
const unsigned char ready[]={0xb0,1,0xc3};memcpy(AT(0x475ca0),ready,sizeof(ready));
const unsigned char base[]={0xc2,4,0};memcpy(AT(0x40e050),base,sizeof(base));
const unsigned char finish[]={0x5f,0x5e,0x5b,0x83,0xc4,0x38,0xc2,4,0};memcpy(AT(0x41a470),finish,sizeof(finish));
table[0x310/4]=(uintptr_t)get_root;table[0x2bc/4]=(uintptr_t)get_velocity;table[0x2c4/4]=(uintptr_t)set_velocity;
table[0x328/4]=(uintptr_t)AT(0x4723f0);table[0x334/4]=(uintptr_t)AT(0x472480);table[0x36c/4]=(uintptr_t)AT(0x472660);
table[0x248/4]=(uintptr_t)AT(0x471ad0);table[0x384/4]=(uintptr_t)AT(0x472980);table[0x38c/4]=(uintptr_t)AT(0x472b10);
outer[0x12c/4]=(uintptr_t)AT(0x419de0);
}
static unsigned char*reset(float pitch,float yaw,float roll){
memset(object,0,sizeof(object));unsigned char*g=object+0xc0;*(uintptr_t**)object=outer;*(uintptr_t**)g=table;
memset(AT(0x509830),0,0x1d0);*(void**)AT(0x509a50)=camera;
memset(camera,0,sizeof(camera));F(g,0x224)=pitch;F(g,0x228)=yaw;F(g,0x22c)=roll;
F(g,0x150)=.8f;root=(Vec){100,200,300,1};ray_hit=0;mouse_x=mouse_y=grounded=0;
*(int*)AT(0x4f81ac)=0;return g;
}
static void transform_case(const char*name,float p,float y,float r,float x,float v,float z){
unsigned char*g=reset(p,y,r);Vec out;((Vec*(TC*)(void*,Vec*,float,float,float))AT(0x472b10))(g,&out,x,v,z);
printf("TRANSFORM %s euler=%.9g,%.9g,%.9g vector=%.9g,%.9g,%.9g observed=%.9g,%.9g,%.9g\n",name,p,y,r,x,v,z,out.x,out.y,out.z);
}
static void motion_case(const char*name,float vx,float vy,float vz,float p,float y,float r,float speed,float bank,float previous,float dt){
unsigned char*g=reset(p,y,r);velocity=(Vec){vx,vy,vz,0};F(g,0x608)=speed;F(g,0x614)=bank;F(g,0x618)=previous;
((void(TC*)(void*,float))AT(0x41a140))(g,dt);
printf("MOTION %s incoming=%.9g,%.9g,%.9g euler=%.9g,%.9g,%.9g speed=%.9g bank=%.9g previous=%.9g dt=%.9g observed_rotation=%.9g,%.9g,%.9g observed_velocity=%.9g,%.9g,%.9g observed_previous=%.9g\n",name,vx,vy,vz,p,y,r,speed,bank,previous,dt,F(g,0x224),F(g,0x228),F(g,0x22c),velocity.x,velocity.y,velocity.z,F(g,0x618));
}
static void aux_case(const char*name,float turn,float roll,int turn_press,int roll_press,int tlatch,int rlatch,float vy,float dt,int suppressed){
unsigned char*g=reset(0,0,0);velocity=(Vec){10,vy,100,0};F(g,0x608)=400;F(g,0x614)=16;F(g,0x618)=7;
F(g,0x674)=turn;F(g,0x670)=roll;g[0x679]=tlatch;g[0x678]=rlatch;
*(char*)AT(0x509845)=turn_press;*(char*)AT(0x50988a)=roll_press;*(char*)AT(0x4f8198)=suppressed;
((void(TC*)(void*,float))AT(0x41a140))(g,dt);*(char*)AT(0x4f8198)=0;
printf("AUX %s timer=%.9g,%.9g pressed=%d,%d latch=%d,%d vy=%.9g dt=%.9g suppressed=%d observed_rotation=%.9g,%.9g,%.9g observed_velocity=%.9g,%.9g,%.9g observed_timer=%.9g,%.9g observed_latch=%d,%d observed_previous=%.9g\n",name,turn,roll,turn_press,roll_press,tlatch,rlatch,vy,dt,suppressed,F(g,0x224),F(g,0x228),F(g,0x22c),velocity.x,velocity.y,velocity.z,F(g,0x674),F(g,0x670),g[0x679],g[0x678],F(g,0x618));
}
static void facing_case(const char*name,float p,float y,float r,float dp,float dy,float dr,float dt){
unsigned char*g=reset(p,y,r);F(g,0x274)=dp;F(g,0x278)=dy;F(g,0x27c)=dr;g[0xa]=1;
((void(TC*)(void*,float))AT(0x41adf0))(g,dt);
printf("FACING %s euler=%.9g,%.9g,%.9g dest=%.9g,%.9g,%.9g dt=%.9g observed_rotation=%.9g,%.9g,%.9g active=%d\n",name,p,y,r,dp,dy,dr,dt,F(g,0x224),F(g,0x228),F(g,0x22c),g[0xa]);
}
static void camera_case(const char*name,float p,float y,float r,float ex,float ey,float ez,float dt,int detail,int hit){
unsigned char*g=reset(p,y,r);F(g,0x5fc)=400;F(g,0x600)=1;F(g,0x604)=1400;F(g,0x660)=20;F(g,0x664)=-20;
F(g,0x63c)=0;F(g,0x640)=200;F(g,0x644)=-500;F(g,0x64c)=0;F(g,0x650)=50;F(g,0x654)=200;
F(camera,0x44)=ex;F(camera,0x48)=ey;F(camera,0x4c)=ez;*(int*)AT(0x4f81ac)=detail;ray_hit=hit;hit_point=(Vec){80,250,100,1};
((void(TC*)(void*,float))AT(0x41a6c0))(g,dt);
printf("CAMERA %s euler=%.9g,%.9g,%.9g old=%.9g,%.9g,%.9g dt=%.9g detail=%d hit=%d observed_eye=%.9g,%.9g,%.9g pitch=%d yaw=%d trace_start=%.9g,%.9g,%.9g trace_end=%.9g,%.9g,%.9g\n",name,p,y,r,ex,ey,ez,dt,detail,hit,F(camera,0x44),F(camera,0x48),F(camera,0x4c),*(short*)(camera+0x50),*(short*)(camera+0x52),trace_start.x,trace_start.y,trace_start.z,trace_end.x,trace_end.y,trace_end.z);
}
int main(void){setbuf(stdout,NULL);setup();
transform_case("forward",0,0,0,0,0,100);
transform_case("yaw90",0,90,0,0,0,100);
transform_case("pitch20",20,0,0,0,0,100);
transform_case("roll45",0,0,45,10,20,30);
transform_case("combined",20,70,35,10,20,30);
transform_case("negative",-20,-70,-35,10,20,30);
motion_case("stationary",0,0,0,0,0,0,400,16,7,.1f);
motion_case("vertical_only",0,10,0,0,0,0,400,16,7,.1f);
motion_case("left",0,0,100,0,0,0,400,16,7,.1f);
motion_case("right_seam",0,0,100,0,0,0,400,-16,7,.1f);
motion_case("pitch",0,0,100,20,70,0,1000,0,7,.1f);
motion_case("all_euler",0,10,100,20,70,35,1000,25,7,1.f/60);
motion_case("retained_bank_no_motion",0,0,0,20,70,35,1000,25,7,.1f);
aux_case("turn_start",0,0,1,0,0,0,10,.1f,0);
aux_case("roll_start",0,0,0,1,0,0,10,.1f,0);
aux_case("turn_finish",.05f,0,1,0,1,0,10,.1f,0);
aux_case("roll_finish",0,.05f,0,1,0,1,10,.1f,0);
aux_case("held_no_restart",0,0,1,0,1,0,10,.1f,0);
aux_case("released",0,0,0,0,1,1,10,.1f,0);
aux_case("suppressed",0,0,1,1,0,0,10,.1f,1);
facing_case("normal",0,20,0,20,20,-16,.1f);
facing_case("wrap",350,359,350,10,1,10,.1f);
facing_case("negative_yaw_delta",0,359,0,0,1,0,.1f);
facing_case("same",0,0,0,0,0,0,.1f);
facing_case("negative_fraction",0,0,0,-.5f,0,-.5f,.1f);
camera_case("straight",0,0,0,-40,50,-100,.1f,0,0);
camera_case("detail1",0,0,0,-40,50,-100,.1f,1,0);
camera_case("detail2",0,0,0,-40,50,-100,.1f,2,0);
camera_case("blocked",0,0,0,-40,50,-100,.1f,0,1);
camera_case("combined",20,70,35,-40,50,-100,1.f/60,0,0);
camera_case("combined_blocked",20,70,35,-40,50,-100,1.f/60,2,1);
puts("ROCKET_MOTION_CAMERA_COMPLETE: isolated copied EXE and OMT math, synthetic dependencies, no game entrypoint");FreeLibrary(omt);return 0;}
'''
def main():
cli=argparse.ArgumentParser(description=__doc__)
cli.add_argument('original',type=Path);cli.add_argument('--output',type=Path)
cli.add_argument('--probe-source',type=Path)
cli.add_argument('--probe-log',type=Path);cli.add_argument('--probe-executable',type=Path)
cli.add_argument('--compiled-source',type=Path)
args=cli.parse_args();report=collect(args.original)
for output in (args.output,args.probe_source):
if output is not None and output.resolve().is_relative_to(args.original.resolve()):cli.error('Use generated outputs outside originals')
if args.probe_source:
args.probe_source.parent.mkdir(parents=True,exist_ok=True);args.probe_source.write_text(probe_source(report))
if any((args.probe_log,args.probe_executable,args.compiled_source)):
if not all((args.probe_log,args.probe_executable,args.compiled_source)):cli.error('Supply log, executable and compiled source together')
report['original_probe']=ingest(report,args.probe_log,args.probe_executable,args.compiled_source)
if args.output:args.output.write_text(json.dumps(report,indent=2)+'\n')
else:print(json.dumps(report,indent=2))
if __name__=='__main__':main()