Files
EscapistsReintroduced/tests/test_powered_flight_policy.py
T

155 lines
11 KiB
Python

"""Run actual extracted fixture rules; no native flight or Enforce claims."""
from pathlib import Path
import unittest
from policy_harness import body, run
SOURCE=Path(__file__).resolve().parents[1]/'addons/core/Scripts/Game/ERR/ERR_NativePoweredFlightProbe.c'
class PoweredFlightPolicy(unittest.TestCase):
def test_actual_authority_all_inputs(self):
method=body(SOURCE,'static bool Authority(')
run('#include <cassert>\n'+method+'''
int main(){for(int mask=0;mask<256;mask++) {
bool server=mask&1, enabled=mask&2, stopped=mask&4, pilot=mask&8, seat=mask&16, player=mask&32, alive=mask&64, fuel=mask&128;
assert(Authority(server,enabled,stopped,pilot,seat,player,alive,fuel)==(server&&enabled&&!stopped&&pilot&&seat&&!player&&alive&&fuel));
}}
''')
def test_actual_hover_landing_and_bounded_input_rules(self):
methods='\n'.join(body(SOURCE,key).replace('Math.','Math::') for key in ['static float ClampInput(', 'static float DesiredVertical(', 'static bool Hover(', 'static bool Landed('])
run('''
#include <cassert>
#include <cmath>
#include <algorithm>
struct Math { static float Clamp(float x,float low,float high){return std::clamp(x,low,high);} static float AbsFloat(float x){return std::abs(x);} };
'''+methods+'''
int main(){
assert(ClampInput(3)==1 && ClampInput(-3)==-1);
assert(ClampInput(0.8f,0.15f)==0.15f);
assert(DesiredVertical(0,false)==1.5f && DesiredVertical(8,false)==0);
assert(DesiredVertical(8,true)==-0.8f && DesiredVertical(0,true)==0);
assert(Hover(8,0.2f,0.1f,1,1));
assert(!Hover(0,0,0,1,0) && !Hover(11,0,0,1,0));
assert(!Hover(8,2,0,1,0) && !Hover(8,0,0.6f,1,0));
assert(!Hover(8,0,0,0.9f,0) && !Hover(8,0,0,1,9));
assert(Landed(true,0.1f,0.1f,0.01f,1));
assert(!Landed(false,0,0,0,1)); // low stationary hover is never landing
assert(!Landed(true,2,0,0,1) && !Landed(true,0,1,0,1));
assert(!Landed(true,0,0,0.2f,1) && !Landed(true,0,0,0,0.8f));
}
''')
def test_native_input_only_and_local_hooks(self):
source=SOURCE.read_text()
for forbidden in ('SetVelocity(', 'SetAngularVelocity(', 'SetWorldTransform(', 'SetOrigin(', 'SetAngles(', '.Teleport(', 'ForceStartEngine(', '.EngineStart(', 'RotorSetForce', 'RotorSetTorque', 'SetHealth(', 'SetFuel(', 'SetGlobalFuelConsumptionScale', 'GetInputManager('):
self.assertNotIn(forbidden,source)
self.assertTrue(source.startswith('#ifdef WORKBENCH'))
self.assertIn('outcome == "powered-flight"',source)
self.assertIn('controller != m_Character || owner != m_Pilot',source)
self.assertIn('controller != m_Controller',source)
self.assertIn('super.OnPrepareControls(owner, am, dt, player)',source)
self.assertEqual(source.count('.StartEngine()'),1)
self.assertEqual(source.count('physics.SetActive('),1)
self.assertIn('m_Wakes == 0',source)
for control in ('Collective','CyclicForward','CyclicAside','AntiTorque'):
self.assertIn('m_Input.SetVehicle'+control+'(',source)
self.assertIn('m_Input.GetVehicle'+control+'()',source)
def test_native_initialization_precedes_single_pilot_allocation(self):
source=SOURCE.read_text()
tick=body(SOURCE,'int Tick(')
spawn=tick.split('if (m_Stage == 0)',1)[1].split('if (m_Stage == 8)',1)[0]
initialize=tick.split('if (m_Stage == 8)',1)[1].split('if (m_Stage == 1)',1)[0]
seating=tick.split('if (m_Stage == 1)',1)[1].split('\n Diagnostic(now)',1)[0]
self.assertNotIn('SpawnCharacterInCompartment',spawn)
self.assertIn('m_Stage = 8; m_StageDeadline = now + 30000',spawn)
self.assertEqual(source.count('.SpawnCharacterInCompartment('),1)
call=initialize.index('.SpawnCharacterInCompartment(')
for guard in ('now >= m_StageDeadline', 'if (!componentsReady) return 0;', 'm_PilotSpawnRequested = true;', 'm_Group.GetAgentsCount() == 0'):
self.assertLess(initialize.index(guard),call)
self.assertNotIn('m_StageDeadline =',initialize)
self.assertIn('nativeGroup == m_Group',initialize)
self.assertIn('m_Controller.GetPilotCompartmentSlot() != m_Seat',seating)
self.assertIn('m_Controller.GetPilotCompartmentSlot() == m_Seat',body(SOURCE,'protected bool PoweredAuthority('))
def test_empty_primary_native_seat_and_readiness_are_observed(self):
method=body(SOURCE,'protected bool PollNativeFlightComponents(')
for guard in ('manager.GetCompartments(slots)', 'slots.Count() <= 64', 'PilotCompartmentSlot.Cast(slot)', 'pilotSlot.GetOwner() != m_Aircraft', 'pilotSlot.GetVehicle() != m_Aircraft', 'GetCompartmentName() != "PilotCompartment"', 'ECompartmentType.PILOT', '!pilotSlot.IsCompartmentAccessible()', 'pilotSlot.GetOccupant() || pilotSlot.IsReserved() || pilotSlot.IsGetInLocked()', 'm_Simulation.IsValid()', 'm_Fuel.HasFuel()'):
self.assertIn(guard,method)
self.assertIn('now >= m_NextInitializationLog || now >= m_StageDeadline',method)
self.assertIn('m_NextInitializationLog = now + 2000',method)
self.assertIn('return m_Controller && validSimulation && m_Seat && fueled;',method)
self.assertNotIn('.Spawn(',method)
self.assertNotIn('.SpawnCharacterInCompartment(',method)
def test_seating_diagnostics_observe_all_guards_without_mutation(self):
method=body(SOURCE,'protected void SeatingDiagnostic(')
for predicate in ('OwnPilot()', 'm_Seat.GetOccupant() == m_Pilot', 'm_Controller.GetPilotCompartmentSlot() == m_Seat', 'ERR_CasualtyLoadingRules.AircraftReady(m_Aircraft)', 'ERR_Actors.Group(m_Pilot)', 'ERR_Actors.CanFight(m_Pilot)', 'physics.IsActive()', 'physics.IsDynamic()', 'physics.GetVelocity()', 'physics.GetAngularVelocity()', 'm_Simulation.HasAnyGroundContact()', 'm_Simulation.IsValid()', 'access.IsGettingIn()', 'access.IsGettingOut()', 'm_Simulation.GetWorldTransform(nativeTransform)', 'm_Aircraft.GetWorldTransform(entityTransform)'):
self.assertIn(predicate,method)
self.assertIn('now < m_NextSeatingLog && now < m_StageDeadline',method)
self.assertIn('m_NextSeatingLog = now + 2000',method)
self.assertIn('ERR_CasualtyGroundSupport.Parked(m_Aircraft, now >= m_StageDeadline)',method)
for mutation in ('.Set', '.Spawn', '.Delete', '.GetInVehicle(', 'm_StageDeadline =', 'm_Stable =', 'Check('):
self.assertNotIn(mutation,method)
seating=body(SOURCE,'int Tick(').split('if (m_Stage == 1)',1)[1].split('\n Diagnostic(now);',1)[0]
self.assertIn('SeatingDiagnostic(now);',seating)
self.assertLess(seating.index('SeatingDiagnostic(now);'),seating.index('now >= m_StageDeadline'))
def test_memberless_group_and_exact_pilot_lod_are_explicit(self):
source=SOURCE.read_text()
self.assertIn('static const ResourceName GROUP = "{000CD338713F2B5A}Prefabs/AI/Groups/Group_Base.et";',source)
self.assertNotIn('Prefabs/Groups/OPFOR/Group_USSR_Base.et',source)
self.assertIn('m_Group.InitFactionKey("USSR") && m_Group.GetFactionName() == "USSR"',source)
initialize=body(SOURCE,'int Tick(').split('if (m_Stage == 8)',1)[1].split('if (m_Stage == 1)',1)[0]
self.assertIn('pilotControl.GetControlAIAgent()',initialize)
self.assertIn('m_PilotAgent && OwnPilot()',initialize)
self.assertIn('m_OriginalPilotLOD = m_PilotAgent.GetPermanentLOD()',initialize)
self.assertIn('m_PilotAgent.SetPermanentLOD(0); m_PilotAgent.ActivateAI();',initialize)
self.assertEqual(source.count('m_PilotAgent.SetPermanentLOD(0)'),1)
self.assertIn('m_PilotLODSaved && m_PilotAgent && OwnPilot() && !PlayerPresent()',body(SOURCE,'void Stop()'))
self.assertIn('m_PilotAgent.SetPermanentLOD(m_OriginalPilotLOD)',body(SOURCE,'void Stop()'))
def test_native_collective_encoding_preserves_signed_controller(self):
methods='\n'.join(body(SOURCE,key).replace('Math.','Math::') for key in ['static float ClampInput(', 'static float NativeCollective('])
run('#include <cassert>\n#include <algorithm>\nstruct Math { static float Clamp(float x,float low,float high){return std::clamp(x,low,high);} };\n'+methods+'''
int main(){
assert(NativeCollective(-1)==0); assert(NativeCollective(0)==0.5f); assert(NativeCollective(1)==1);
assert(NativeCollective(-5)==0 && NativeCollective(5)==1);
float previous=-1;
for(int i=-100;i<=100;i++) {float command=NativeCollective(i/100.f); assert(command>=0 && command<=1 && command>=previous); previous=command;}
}
''')
pilot=body(SOURCE,'void ApplyPilot(')
self.assertLess(pilot.index('ERR_PoweredFlightRules.NativeCollective(collective)'),pilot.index('m_Input.SetVehicleCollective(collective)'))
self.assertIn('m_Input.GetVehicleCollective() == 0',SOURCE.read_text())
def test_control_and_flight_geometry_use_actual_world_pose(self):
for signature in ('void ApplyPilot(', 'protected void Diagnostic(', 'int Tick('):
method=body(SOURCE,signature)
self.assertIn('m_Aircraft.GetWorldTransform(transform)',method)
self.assertNotIn('m_Simulation.GetWorldTransform(transform)',method)
# Internal simulation pose remains diagnostic only, never geometry feedback.
self.assertEqual(SOURCE.read_text().count('m_Simulation.GetWorldTransform('),1)
def test_final_apply_is_the_only_integrator_and_positive_signal_is_required(self):
source=SOURCE.read_text()
prepare=body(SOURCE,'override void OnPrepareControls(')
native_apply=body(SOURCE,'protected override void OnApplyControls(')
observe=body(SOURCE,'void ObservePilotPreparation(')
self.assertNotIn('ApplyPilot',prepare)
self.assertNotIn('.SetVehicle',observe)
self.assertNotIn('m_Collective =',observe)
self.assertLess(native_apply.index('super.OnApplyControls(owner, timeSlice)'),native_apply.index('probe.ApplyPilot(this, owner, timeSlice)'))
self.assertEqual(source.count('m_Collective + error * dt'),1)
self.assertEqual(source.count('probe.ApplyPilot('),1)
gate=body(SOURCE,'int Tick(').split('if (m_Stage == 9)',1)[1].split('if (m_Stage == 4 ||',1)[0]
self.assertIn('now >= m_StageDeadline',gate)
self.assertIn('signals.FindSignal("MainRotorCollective")',gate)
self.assertLess(gate.index('signalIndex >= 0'),gate.index('signals.GetSignalValue(signalIndex)'))
self.assertIn('now - m_PositiveSignalSince < 500',gate)
self.assertIn('m_ControlUpdates >= m_PositiveGateUpdates + 3',gate)
method=body(SOURCE,'static bool CollectiveObserved(').replace('Math.','Math::')
run('#include <cassert>\n#include <cmath>\nstruct Math { static float AbsFloat(float x){return std::abs(x);} };\n'+method+'''
int main(){assert(CollectiveObserved(.05f,.05f));assert(!CollectiveObserved(.05f,0));assert(!CollectiveObserved(0,0));assert(!CollectiveObserved(.05f,1));assert(!CollectiveObserved(.5f,.5f));assert(!CollectiveObserved(.05f,NAN));}
''')
def test_stop_and_engine_shutdown_are_bounded(self):
source=SOURCE.read_text();stop=body(SOURCE,'void Stop()')
self.assertIn('OwnPilot() && !PlayerPresent()',stop)
self.assertIn('s_Current = null',stop)
self.assertNotIn('StopEngine',stop) # no engine kill on midair fail/capture
self.assertNotIn('DeleteSpawned',stop)
self.assertIn('((m_Stage >= 4 && m_Stage <= 6) || m_Stage == 9) && !m_Controller.IsEngineOn()',source)
self.assertIn('m_Fuel.GetTotalFuel() < m_InitialFuel - 0.05',source)
self.assertIn('m_Controller.StopEngine(false)',source)
self.assertIn('ERR_PoweredFlightRules.Landed(m_Simulation.HasAnyGroundContact()',source)
if __name__=='__main__': unittest.main()