Implement source-backed Scooter vehicle in tutorial and outside
This commit is contained in:
1 parent
8df5e81070
commit
62c07a3d59
44 files changed
+3135
-174
No files matched your search
@@ -85,7 +85,8 @@ Require(allGadgetsView.Lines.Length<=32 && allGadgetsView.Lines[allGadgetsView.S
|
||||
"Last player action remains visible within the widescreen overlay capacity");
|
||||
menu.Key(81);Require(menu.Key(40)==DebugAction.GiveRocketship,"Player tools expose Rocketship after Give All Gadgets");
|
||||
menu.Key(81); Require(menu.Key(40)==DebugAction.GiveGrappler,"Player tools expose Grappler after Rocketship");
|
||||
menu.Key(81); Require(menu.Selected==0,"Player navigation wraps after Grappler");
|
||||
menu.Key(81); Require(menu.Key(40)==DebugAction.GiveScooter,"Player tools grant Scooter for tutorial/outside");
|
||||
menu.Key(81); Require(menu.Selected==0,"Player navigation wraps after Scooter");
|
||||
Console.WriteLine("PASS Give All Gadgets navigation, repeat handling and overlay bounds");
|
||||
|
||||
var original = Path.GetFullPath(args.Length == 1 ? args[0] : "../Original");
|
||||
|
||||
@@ -38,5 +38,9 @@
|
||||
<Compile Include="../../src/GamePort/Game/GrapplerRay.cs" />
|
||||
<Compile Include="../../src/GamePort/Game/RocketOrientation.cs" />
|
||||
<Compile Include="../../src/GamePort/Game/OriginalHeading.cs" />
|
||||
<Compile Include="../../src/GamePort/Game/Scooter.cs"/>
|
||||
<Compile Include="../../src/GamePort/Game/ScooterCamera.cs"/>
|
||||
<Compile Include="../../src/GamePort/Game/ScooterMotion.cs"/>
|
||||
<Compile Include="../../src/GamePort/Game/ScooterWheels.cs"/>
|
||||
</ItemGroup>
|
||||
</Project>
|
||||
@@ -0,0 +1,10 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
<PropertyGroup><OutputType>Exe</OutputType><TargetFramework>net10.0</TargetFramework>
|
||||
<ImplicitUsings>enable</ImplicitUsings><Nullable>enable</Nullable><EnableDefaultCompileItems>false</EnableDefaultCompileItems></PropertyGroup>
|
||||
<ItemGroup><Compile Include="Program.cs"/><Compile Include="../../src/GamePort/Assets/*.cs"/>
|
||||
<Compile Include="../../src/GamePort/Game/*.cs"/>
|
||||
<Compile Include="../../src/GamePort/Application/PlayerGadgetMaterial.cs"/>
|
||||
<Compile Include="../../src/GamePort/Application/ScooterVisuals.cs"/>
|
||||
<None Include="original-motion-reference.json" CopyToOutputDirectory="PreserveNewest"/>
|
||||
</ItemGroup>
|
||||
</Project>
|
||||
@@ -0,0 +1,155 @@
|
||||
using System.Numerics;
|
||||
using System.Text.Json;
|
||||
using GamePort.Assets;
|
||||
using GamePort.Game;
|
||||
using GamePort.Application;
|
||||
|
||||
var tests=new(string,Action)[]{("copied-original drive/input/facing/terrain observations",Original),
|
||||
("selection summons at Goddard, strict contact mounts",Mount),
|
||||
("outside normal tile drives, steers, brakes and jumps",Outside),
|
||||
("actual wheel supports and source offsets",Wheels),
|
||||
("front-door impact owns throttle for four seconds then recovers",Wall),
|
||||
("unmount raises40, restores Goddard and stops engine",Release),
|
||||
("camera uses new-eye aim, distance gains and sphere delegate",Camera),
|
||||
("cutscene/noclip/reset release control and sound",Lifecycle),
|
||||
("actual tutorial RETURN accepts the passenger and cleans vehicle",Return),
|
||||
("original vehicle/wheel/rider geometry stays unit scale",Visuals),
|
||||
("outside companion follows, freezes while summoned, and returns near Jimmy",Companion),
|
||||
};
|
||||
foreach(var(name,test)in tests){test();Console.WriteLine("PASS "+name);}Console.WriteLine($"Scooter integration: {tests.Length} groups passed.");
|
||||
static void Original()
|
||||
{
|
||||
using var doc=JsonDocument.Parse(File.ReadAllText(Path.Combine(AppContext.BaseDirectory,"original-motion-reference.json")));
|
||||
int count=0;
|
||||
foreach(var c in doc.RootElement.GetProperty("cases").EnumerateArray())
|
||||
{
|
||||
var p=c.GetProperty("input").EnumerateArray().Select(v=>v.GetSingle()).ToArray();
|
||||
var o=c.GetProperty("observed").EnumerateArray().Select(v=>v.GetSingle()).ToArray();var name=c.GetProperty("name").GetString()!;
|
||||
switch(c.GetProperty("kind").GetString())
|
||||
{
|
||||
case "DRIVE":
|
||||
var d=ScooterMotion.Apply(new(p[0],p[6],Reverse:p[12]!=0,Braking:p[11]!=0,Throttle:p[10]!=0,BrakeTime:p[13]),new(p[1],p[2],p[3]),new(p[4],p[5],0),p[9]!=0,(int)p[7],(int)p[8],p[14],.8f);
|
||||
Near(d.Steering.Speed,o[0],name+" scalar");NearV(d.Velocity,new(o[1],o[2],o[3]),name+" velocity");
|
||||
Near(d.Rotation.Y,o[4],name+" yaw");Near(d.Steering.YawRate,o[5],name+" rate");Near(d.Steering.Blend,o[6],name+" blend");Near(d.Steering.BrakeTime,o[7],name+" timer");break;
|
||||
case "INPUT":
|
||||
var s=ScooterMotion.Input(new(p[0],p[1],p[2]!=0,p[3]!=0,p[4]!=0),new(p[5]!=0,p[6]!=0,p[7]!=0,p[8]!=0,false),(int)p[9],p[10]);
|
||||
Near(s.Speed,o[0],name);Near(s.Angle,o[1],name);Check(s.KeyboardTurn==(o[2]!=0)&&s.Reverse==(o[3]!=0)&&s.Braking==(o[4]!=0)&&s.Throttle==(o[5]!=0),name+" flags");break;
|
||||
case "NORMAL":
|
||||
var normal=ScooterWheels.TerrainTarget(new(p[0],p[1],p[2]),p[3]);Near(normal.X,o[0],name+" pitch");Near(normal.Z,o[2],name+" roll");break;
|
||||
case "FACE":NearV(ScooterWheels.Face(new(p[0],p[1],p[2]),new(p[3],p[4],p[5]),p[6],p[7]),new(o[0],o[1],o[2]),name);break;
|
||||
case "WALL":
|
||||
var contact=ScooterMotion.Contact(p[0],new(p[1],p[2],p[3]),Vector3.Zero,new(p[4],p[5],p[6]),new(3,4,5),p[7]!=0,p[8]!=0,p[9]);
|
||||
Near(contact.Speed,o[0],name+" speed");NearV(new(p[1],p[2],p[3]),new(o[1],o[2],o[3]),name+" no bounce");
|
||||
NearV(contact.Acceleration,new(o[4],o[5],o[6]),name+" acceleration");Check(contact.Impact==(o[7]!=0),name+" impact");break;
|
||||
case "CRASH":
|
||||
var impact=ScooterMotion.Impact(new(120,100,-60),new(10,20,30),p[0],p[1]);
|
||||
NearV(impact.Velocity,new(o[0],o[1],o[2]),name+" velocity");NearV(impact.AngularVelocity,new(o[3],o[4],o[5]),name+" angular");
|
||||
Near(impact.Time,o[6],name+" timer");Check(impact.Active==(o[7]!=0),name+" expiry");break;
|
||||
}count++;
|
||||
}
|
||||
Check(count==53,"native numeric coverage");Console.WriteLine($"Compared {count} original numeric observations.");
|
||||
}
|
||||
static void Mount(){using var f=new Fixture("VR05");f.Summon();Check(f.S.Spawned&&!f.S.Mounted&&f.P.GadgetMode==4,"summon does not mount");f.Mount();Check(f.S.Mounted&&f.D.AuthoredControlledTag==f.S.Actor.Tag&&f.Binding.InventoryControlled,"contact owns control/menu");}
|
||||
static void Outside()
|
||||
{
|
||||
using var f=new Fixture("LEV1");f.I.Inventory.SetState(0,4,1);
|
||||
var menu=new GadgetScreen(f.I.Inventory,()=>f.P.GadgetMode);
|
||||
Check(menu.Toggle(f.Binding.InventoryControlled),"outside gadget panel opens");
|
||||
menu.Point(GadgetScreen.Positions[4]+new Vector2(50),"LEV1",0);
|
||||
Check(menu.Hovered==4&&menu.Activate("LEV1",0)&&f.S.Spawned&&!menu.Open,"ordinary owned tile summons outside");
|
||||
f.Mount();var root=f.S.Root;
|
||||
for(int i=0;i<100;i++)f.Frame(new(true,false,false,false,false));
|
||||
Check(f.S.Steering.Speed>200&&Vector3.Distance(root,f.S.Root)>100,"outside ordinary driving");
|
||||
float yaw=f.S.Rotation.Y;for(int i=0;i<20;i++)f.Frame(new(true,false,true,false,false));
|
||||
Check(f.S.Rotation.Y!=yaw&&f.S.Steering.Angle>0,"outside steering");
|
||||
float speed=f.S.Steering.Speed;for(int i=0;i<10;i++)f.Frame(new(false,true,false,false,false));
|
||||
Check(f.S.Steering.Speed<speed,"brake");
|
||||
for(int i=0;i<120&&!f.S.Supported;i++)f.Frame(default);
|
||||
if(f.S.Supported){int jumps=f.S.Jumps;f.Frame(new(false,false,false,false,true));Check(f.S.Jumps==jumps+1&&f.S.PendingImpulse.Y==700,"supported jump queues impulse");}
|
||||
Check(f.P.Energy==20,"no invented gadget energy debit");
|
||||
}
|
||||
static void Wheels(){using var f=new Fixture("VR05");f.Summon();for(int i=0;i<100;i++)f.Frame(default);Check(f.S.FrontSupports+f.S.RearSupports>=2,"real support query accepts wheels");Check(ScooterWheels.Offsets.SequenceEqual(new Vector3[]{new(-3,1,73),new(3,1,73),new(-3,1,-30),new(3,1,-30)}),"four exact narrow offsets");}
|
||||
static void Wall()
|
||||
{
|
||||
using var f=new Fixture("LEV1","frontdoor");f.Summon();f.Mount();
|
||||
for(int i=0;i<180&&!f.S.ImpactActive;i++)f.Frame(new(true,false,false,false,false));
|
||||
Check(f.S.Contacts>0&&f.S.ImpactActive&&f.S.Steering.Speed==0,"actual porch wall enters impact");
|
||||
for(int i=0;i<240&&f.S.ImpactActive;i++)f.Frame(default);
|
||||
Check(!f.S.ImpactActive&&f.S.Velocity==Vector3.Zero,"four-second impact recovers");
|
||||
for(int i=0;i<20;i++)f.Frame(new(true,false,false,false,false));
|
||||
Check(f.S.Steering.Speed>0||f.S.ImpactActive,"throttle resumes after expiry");
|
||||
}
|
||||
static void Release()
|
||||
{
|
||||
using var f=new Fixture("VR05");int starts=0,stops=0,pitches=0;f.S.EngineStarted+=()=>starts++;f.S.EngineStopped+=()=>stops++;
|
||||
f.S.EngineSpeedChanged+=_=>pitches++;f.Summon();f.Frame(default);
|
||||
Check(starts==1&&pitches==0,"first engine frame captures base frequency without tuning");
|
||||
f.Mount();var root=f.S.Root;var dog=f.D.FindActor("C3DGODDARD")!;
|
||||
f.I.Inventory.SelectGadget(-1);NearV(f.P.ActorRoot,root+Vector3.UnitY*40,"dismount elevation");
|
||||
Check(!f.S.Spawned&&!f.S.Mounted&&f.D.Controlled&&f.P.Velocity==Vector3.Zero&&dog.Visible&&dog.BodyEnabled,"owners restored");
|
||||
NearV(dog.Position,root,"Goddard returns at scooter root");Check(starts==1&&stops==1&&!f.S.EnginePlaying,"engine cleanup once");
|
||||
}
|
||||
static void Camera()
|
||||
{
|
||||
var c=ScooterCamera.Follow(Vector3.Zero,Vector3.Zero,new(0,50,-300),.1f);
|
||||
NearV(c.DesiredEye,new(-30,50,-200),"defaultlocal");NearV(c.Eye,new(-3,50,-290),"near smoothing");
|
||||
int calls=0;var clipped=ScooterCamera.Follow(Vector3.Zero,Vector3.Zero,new(0,50,-1000),.1f,(a,b)=>{calls++;Check(a==Vector3.Zero,"sphere starts at root");return b*.8f;});
|
||||
Check(calls==1&&clipped.Gain==2.8f,"far gain/clip");var(p,y)=OriginalHeading.Angles(clipped.Look-clipped.Eye);
|
||||
NearV(Vector3.Normalize(clipped.Target-clipped.Eye),RocketOrientation.Rotate(Vector3.UnitZ,new(p*.02197265625f,y*.02197265625f,0)),"new eye heading");
|
||||
var impact=ScooterCamera.Follow(new(100,100,100),Vector3.Zero,new(0,50,-300),.1f,impact:true);
|
||||
NearV(impact.Eye,new(3,50,-288),"impact XZ-only smoothing");Check(impact.Look==new Vector3(100),"impact aims at root");
|
||||
}
|
||||
static void Lifecycle()
|
||||
{
|
||||
using var f=new Fixture("VR05");f.Summon();f.Mount();f.D.ReleasePlayerGadget();Check(!f.S.Spawned&&!f.S.EnginePlaying&&f.P.GadgetMode==-1,"namedJimmy cleanup");
|
||||
f.Summon();f.Mount();f.P.SetNoclip(true);f.Binding.Step(default);Check(!f.S.Spawned&&f.D.Controlled,"noclip releases");
|
||||
f.Binding.ResetVehicle();Check(f.S.BodySteps==0&&!f.S.Spawned,"reset");
|
||||
}
|
||||
static void Return()
|
||||
{
|
||||
using var f=new Fixture("VR05");f.I.SetReturnContext("level1b.gam","STARTEXP");f.Summon();f.Mount();
|
||||
var portal=f.Level.Entities.First(e=>e.Kind=="LOAD"&&e.Text("LevelName")=="RETURN");LevelTransition? request=null;f.I.Transition+=t=>request=t;
|
||||
f.P.ApplyAuthoredTransform(portal.Position,f.P.Yaw);f.I.Update(f.P.ActorRoot,60,f.S.Actor);
|
||||
Check(request is{Returning:true}&&!f.S.Spawned&&f.D.Controlled,"passenger RETURN releases vehicle");
|
||||
}
|
||||
static void Visuals()
|
||||
{
|
||||
using var f=new Fixture("VR05");var visuals=new ScooterVisuals(f.World,"artifacts/extracted");f.Summon();f.Mount();
|
||||
visuals.Update(visuals.Mesh,f.S,.1,f.P.Appearance);var vertices=visuals.Mesh.Vertices.Skip(f.World.Vertices.Length).ToArray();
|
||||
visuals.Update(visuals.Mesh,f.S,.1,f.P.Appearance);Check(vertices.SequenceEqual(visuals.Mesh.Vertices.Skip(f.World.Vertices.Length)),"repeated render does not accumulate transforms");
|
||||
Check(visuals.Mesh.Draws.Count(d=>d.Visible)>f.World.Draws.Count(d=>d.Visible),"body/wheel/rider visible");
|
||||
f.I.Inventory.SelectGadget(-1);visuals.Update(visuals.Mesh,f.S,.1,f.P.Appearance);Check(visuals.Mesh.Draws.Skip(f.World.Draws.Length).All(d=>!d.Visible),"helpers hide");
|
||||
}
|
||||
static void Companion()
|
||||
{
|
||||
using var f=new Fixture("LEV1");var jimmy=f.D.FindActor("JIM1")!;var dog=f.D.FindActor("C3DGODDARD")!;
|
||||
var patrol=new ActorPatrol(dog,f.D.FindActor,(b,dt)=>b with{Position=b.Position+b.Velocity*dt}){FollowPlayer=true};
|
||||
patrol.Step(FixedStepClock.Step);Check(patrol.Velocity.Length()>400,"state4 chooses follow velocity");
|
||||
var before=dog.Position;patrol.Step(FixedStepClock.Step);Check(dog.Position!=before,"prior velocity moves next body phase");
|
||||
f.Summon();before=dog.Position;patrol.Step(FixedStepClock.Step);Check(dog.Position==before,"disabled companion does not drift");
|
||||
f.I.Inventory.SelectGadget(-1);Check(dog.MovementEnabled,"unequip resumes companion");
|
||||
dog.Position=jimmy.Position+new Vector3(3000,0,0);patrol.Step(FixedStepClock.Step);
|
||||
NearV(dog.Position,jimmy.Position+RocketOrientation.Rotate(new(0,0,-800),jimmy.Rotation),"far follow warp");
|
||||
f.D.EnsureCompanion(jimmy.Position,Vector3.Zero);NearV(dog.Position,jimmy.Position,"explicit reset placement updates existing actor");
|
||||
}
|
||||
static void Check(bool ok,string name){if(!ok)throw new Exception(name);}
|
||||
static void Near(float a,float b,string name)=>Check(float.IsFinite(a)&&Math.Abs(a-b)<.02f,$"{name}: {a} != {b}");
|
||||
static void NearV(Vector3 a,Vector3 b,string name)=>Check(Vector3.Distance(a,b)<.04f,$"{name}: {a} != {b}");
|
||||
sealed class Fixture:IDisposable
|
||||
{
|
||||
public GamLevel Level{get;}public Mesh World{get;}public LabSimulation P{get;}public SceneDirector D{get;}public SceneInteractions I{get;}public Scooter S{get;}public PlayerSceneBinding Binding{get;}
|
||||
public Fixture(string code,string? startTag=null)
|
||||
{
|
||||
string name=code=="LEV1"?"level1":"VR05";World=Mesh.LoadSceneJson(AssetPath.Resolve("artifacts/extracted",name+"/scene.json"));Level=GamLevel.Load(AssetPath.Resolve("../Original","gam/"+name+".gam"));
|
||||
var save=OriginalSave.Load("../Original/NewGame.tsk");var tasks=new TaskStates(save.Tasks);var start=Level.FindStart(startTag)!;D=new(Level,tasks,(_,_)=>0);I=new(D,tasks,save);D.Begin(start,false);
|
||||
var ray=OriginalCameraRay.FromRouteScene(World,code);
|
||||
P=new(new(World),new MorphAnimation("artifacts/extracted/animations/jimstop/animation.json").Base,start.Position,start.Rotation.Y,
|
||||
(a,b)=>ray.Trace(a,b),(a,b)=>ray.TraceGeometry(a,b),code=="VR05"?OriginalStaticCollision.FromRouteScene(World,code):null){LevelCode=code};
|
||||
D.SyncActor("JIM1",P.ActorRoot,new(0,P.Yaw,0));D.EnsureCompanion(P.ActorRoot+RocketOrientation.Rotate(new(0,0,-250),new(0,P.Yaw,0)),startTag=="frontdoor"?Vector3.Zero:new(0,P.Yaw,0));
|
||||
S=new(D.AddOwnedActor("C3DJEEP","3JEE",Vector3.Zero),World,code);Binding=new(D,P,I.Inventory,"JIM1",scooter:S);
|
||||
}
|
||||
public void Summon(){I.Inventory.SetState(0,4,1);I.Inventory.SelectGadget(4);}
|
||||
public void Frame(PlayerInput input){Binding.Step(input);D.Step(FixedStepClock.Step);}
|
||||
public void Mount(){for(int i=0;i<120&&!S.Mounted;i++)Frame(new(false,true,false,false,false));if(!S.Mounted)throw new Exception($"Contact mount failed: Jimmy{P.ActorRoot}, Scooter{S.Root}");for(int i=0;i<60;i++)Frame(default);}
|
||||
public void Dispose(){S.Release();Binding.Dispose();}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,45 @@
|
||||
"""Identity and provenance for copied-original Scooter numeric observations."""
|
||||
from pathlib import Path
|
||||
import collections
|
||||
import hashlib
|
||||
import json
|
||||
import math
|
||||
import sys
|
||||
import unittest
|
||||
ROOT=Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0,str(ROOT/'tools/binary'))
|
||||
from scooter_motion import collect
|
||||
from checkpoint_script_state import read_va
|
||||
from pe_inspect import PE
|
||||
|
||||
class ScooterMotionEvidence(unittest.TestCase):
|
||||
def test_source_identity_ranges_and_offsets(self):
|
||||
source=collect(ROOT.parent/'Original')
|
||||
fixture=json.loads((ROOT/'tests/GamePort.ScooterTests/original-motion-reference.json').read_text())
|
||||
self.assertEqual(source['sha256'],fixture['source_sha256'])
|
||||
self.assertEqual(source['motion_ranges'],fixture['ranges'])
|
||||
self.assertEqual(len(source['motion_ranges']),20)
|
||||
for span in fixture['ranges']:
|
||||
self.assertEqual(int(span['file_offset'],16),int(span['va'],16)-0x400000)
|
||||
|
||||
def test_generator_provenance_and_complete_native_cases(self):
|
||||
fixture=json.loads((ROOT/'tests/GamePort.ScooterTests/original-motion-reference.json').read_text())
|
||||
for name,digest in fixture['files'].items():
|
||||
# Generated binaries/logs are identified, but not required in a fresh checkout.
|
||||
if name.startswith('tools/'):
|
||||
self.assertEqual(hashlib.sha256((ROOT/name).read_bytes()).hexdigest(),digest)
|
||||
self.assertEqual(len(digest),64)
|
||||
self.assertEqual(collections.Counter(c['kind'] for c in fixture['cases']),
|
||||
dict(DRIVE=22,INPUT=9,NORMAL=8,FACE=3,WALL=7,CRASH=4))
|
||||
self.assertEqual(len({(c['kind'],c['name']) for c in fixture['cases']}),53)
|
||||
self.assertTrue(all(math.isfinite(v) for c in fixture['cases'] for k in ('input','observed') for v in c[k]))
|
||||
self.assertEqual(fixture['table_quarter'],dict(sin=1,cos=0))
|
||||
|
||||
def test_camera_face_only_flag_and_vehicle_body_overrides(self):
|
||||
pe=PE(ROOT.parent/'Original/Neutron.exe')
|
||||
self.assertEqual(read_va(pe,0x413870,2),bytes.fromhex('6a00'))
|
||||
# Explicit prevent-lowering true, bounce false; neither comes from Jimmy.
|
||||
self.assertEqual(read_va(pe,0x464c75,5),bytes.fromhex('e8f6c20000'))
|
||||
self.assertEqual(read_va(pe,0x464c7d,5),bytes.fromhex('e80ec40000'))
|
||||
|
||||
if __name__=='__main__':unittest.main()
|
||||
+103
-70
@@ -1,3 +1,4 @@
|
||||
"""Exact original Scooter resources, material links and source-pivot expansion."""
|
||||
from pathlib import Path
|
||||
import hashlib
|
||||
import json
|
||||
@@ -9,90 +10,122 @@ from unittest.mock import patch
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
ORIGINAL = ROOT.parent/'Original'
|
||||
sys.path.insert(0, str(ROOT/'tools/extractors'))
|
||||
sys.path.insert(0, str(ROOT/'tools/binary'))
|
||||
from scooter_resources import (CANVASES, CLIPS, JIMMY_RGBA_SHA256, SOURCES, export_scooter)
|
||||
from ase import expand_mesh, read_ase
|
||||
from entities import resolve_asset
|
||||
from omt import FormatError
|
||||
from png import read_png
|
||||
from scooter_resources import SOURCES, export_scooter
|
||||
from omt import Database, FormatError, read_canvas, read_shape
|
||||
from pe_inspect import PE
|
||||
from checkpoint_script_state import read_va
|
||||
|
||||
|
||||
@unittest.skipUnless(ORIGINAL.exists(), 'Original assets are local integration fixtures')
|
||||
@unittest.skipUnless(ORIGINAL.exists(), 'Original resources are local fixtures')
|
||||
class ScooterResourceTests(unittest.TestCase):
|
||||
def test_original_shape_material_links_and_pixels(self):
|
||||
def test_exact_omt_shapes_canvas_pixels_and_material_links(self):
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
output = Path(directory)/'scooter'
|
||||
manifest = export_scooter(ORIGINAL, output)
|
||||
self.assertEqual(manifest, json.loads((output/'scooter.json').read_text()))
|
||||
out = Path(directory)/'scooter'; manifest = export_scooter(ORIGINAL, out)
|
||||
self.assertEqual(manifest, json.loads((out/'scooter.json').read_text()))
|
||||
self.assertEqual(manifest['sources'], SOURCES)
|
||||
self.assertEqual([s['triangles'] for s in manifest['shapes']], [176, 56])
|
||||
for identity, expected_canvas in ((0, 1), (1, 0)):
|
||||
scene = json.loads((output/f'shape_{identity}/scene.json').read_text())
|
||||
self.assertEqual(len(scene['materials']), 1)
|
||||
self.assertEqual(scene['materials'][0]['texture'], dict(type='Canv', id=expected_canvas))
|
||||
texture = scene['textures'][0]
|
||||
self.assertEqual(texture['id'], expected_canvas)
|
||||
image = read_png(output/f'shape_{identity}'/texture['png'])
|
||||
self.assertEqual(image['rgba'], (output/f'shape_{identity}'/texture['path']).read_bytes())
|
||||
wheel = json.loads((output/'shape_1/scene.json').read_text())
|
||||
self.assertIn(-1, [m['material'] for m in wheel['meshes']])
|
||||
self.assertEqual((output/'jimycarl.rgba').read_bytes(),
|
||||
read_png(resolve_asset(ORIGINAL, 'png/jimycarl.png'))['rgba'])
|
||||
for id_, name, offset, size, width, height, digest in CANVASES:
|
||||
self.assertEqual(hashlib.sha256((out/f'canvas_{id_}.rgba').read_bytes()).hexdigest(), digest)
|
||||
self.assertEqual((out/f'canvas_{id_}.rgba').stat().st_size, width*height*4)
|
||||
body = json.loads((out/manifest['bodyMesh']).read_text())
|
||||
wheel = json.loads((out/manifest['wheelMesh']).read_text())
|
||||
self.assertEqual((len(body['vertices']), len(body['indices'])), (176*3, 176*3))
|
||||
self.assertEqual((len(wheel['vertices']), len(wheel['indices'])), (56*3, 56*3))
|
||||
for mesh in (body, wheel):
|
||||
self.assertEqual({m['id']:m['texture']['id'] for m in mesh['materials']}, {0:1,1:0})
|
||||
self.assertTrue(all((out/Path(manifest['bodyMesh']).parent/t['path']).is_file() for t in mesh['textures']))
|
||||
self.assertEqual([s['materialPolygons'] for s in manifest['shapes']], [{'0':176},{'1':28,'null':28}])
|
||||
self.assertEqual(sum(p['materialId'] is None for p in wheel['collisionPolygons']),28)
|
||||
|
||||
def test_jimmy_exact_base_topology_and_morph_positions(self):
|
||||
def test_original_mesh_pivots_vertices_uvs_normals_and_null_draws_preserved(self):
|
||||
database = Database(resolve_asset(ORIGINAL, 'omt/scooter.omt'))
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
output = Path(directory)/'scooter'
|
||||
export_scooter(ORIGINAL, output)
|
||||
base = read_ase(resolve_asset(ORIGINAL, 'ASE/jimstop.ASE'))['objects'][0]['samples'][0]
|
||||
for stem in ('jimscooter', 'jimscooterstop'):
|
||||
source = read_ase(resolve_asset(ORIGINAL, f'ASE/{stem}.ASE'))
|
||||
animation = json.loads((output/stem/'animation.json').read_text())
|
||||
self.assertEqual((animation['framesPerSecond'], animation['ticksPerFrame']), (10, 480))
|
||||
self.assertEqual([f['time'] for f in animation['frames']], [0, 480])
|
||||
self.assertEqual(animation['sha256'], source['sha256'])
|
||||
for index, sample in enumerate(source['objects'][0]['samples']):
|
||||
expected = expand_mesh(dict(sample, faces=base['faces'], uvs=base['uvs'],
|
||||
textureFaces=base['textureFaces']))
|
||||
actual = json.loads((output/stem/animation['frames'][index]['path']).read_text())
|
||||
self.assertEqual(actual['vertices'], [list(v) for v in expected['vertices']])
|
||||
self.assertEqual(actual['uvs'], [list(v) for v in expected['uvs']])
|
||||
out=Path(directory)/'scooter';m=export_scooter(ORIGINAL,out)
|
||||
for metadata in m['shapes']:
|
||||
entry=next(e for e in database.entries if e.type=='3DSh' and e.id==metadata['shapeId'])
|
||||
source=read_shape(database.payload(entry));actual=json.loads((out/metadata['path']).read_text())
|
||||
expected_vertices=[];expected_uvs=[];expected_normals=[]
|
||||
for poly in source['polygons']:
|
||||
for corner in poly['corners']:
|
||||
expected_vertices.append(list(source['vertices'][corner['vertex']]))
|
||||
expected_uvs.append(list(corner['uv']))
|
||||
ni=corner['normal'];expected_normals.append(list(source['normals'][ni] if ni<len(source['normals']) else poly['normal']))
|
||||
self.assertEqual(actual['vertices'],expected_vertices)
|
||||
self.assertEqual(actual['uvs'],expected_uvs)
|
||||
self.assertEqual(actual['normals'],expected_normals)
|
||||
self.assertEqual(actual['indices'],list(range(len(expected_vertices))))
|
||||
wheel=json.loads((out/m['wheelMesh']).read_text())
|
||||
self.assertEqual(sum(d['indexCount'] for d in wheel['meshes'] if d['material']==-1),28*3)
|
||||
|
||||
def test_unbound_morphs_retain_source_161_ticks_and_no_guessed_uvs(self):
|
||||
def test_stored_source_spheres_are_not_actor_radius_or_visual_scale(self):
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
output = Path(directory)/'scooter'
|
||||
manifest = export_scooter(ORIGINAL, output)
|
||||
for entry in manifest['unboundMorphs']:
|
||||
morph = json.loads((output/entry['path']).read_text())
|
||||
self.assertEqual((morph['framesPerSecond'], morph['ticksPerFrame']), (30, 160))
|
||||
samples = morph['objects'][0]['samples']
|
||||
self.assertEqual([s['time'] for s in samples], [0, 161])
|
||||
self.assertEqual([len(s['vertices']) for s in samples], [195, 195])
|
||||
self.assertTrue(all(not s['uvs'] and not s['textureFaces'] for s in samples))
|
||||
self.assertEqual(morph['sha256'], hashlib.sha256(
|
||||
resolve_asset(ORIGINAL, 'ASE/'+entry['source']).read_bytes()).hexdigest())
|
||||
m=export_scooter(ORIGINAL,Path(directory)/'scooter')
|
||||
body,wheel=m['shapes']
|
||||
self.assertEqual(body['storedSphere']['radius'],91.31170654296875)
|
||||
self.assertEqual(wheel['storedSphere']['radius'],23.769514083862305)
|
||||
self.assertEqual(body['storedSphere']['sourceRadiusOffset'],124)
|
||||
self.assertEqual(wheel['storedSphere']['sourceRadiusOffset'],92324)
|
||||
self.assertNotIn('actorScale',m['bindings'])
|
||||
self.assertEqual(m['bindings']['bodyDatabaseShape'],0)
|
||||
self.assertEqual(m['bindings']['wheelDatabaseShape'],1)
|
||||
|
||||
def test_original_subtrees_ancestors_and_symlinks_rejected(self):
|
||||
for output in (ORIGINAL, ORIGINAL/'png/generated-scooter', ORIGINAL.parent):
|
||||
with self.subTest(output=output), self.assertRaises(ValueError):
|
||||
export_scooter(ORIGINAL, output)
|
||||
def test_two_rider_morphs_keep_exact_samples_topology_and_opaque_atlas(self):
|
||||
base=read_ase(resolve_asset(ORIGINAL,'ASE/jimstop.ASE'))['objects'][0]['samples'][0]
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
output = Path(directory)/'scooter'
|
||||
output.mkdir()
|
||||
outside = Path(directory)/'unchanged'
|
||||
outside.write_text('unchanged')
|
||||
for relative in ('scooter.json', 'shape_0', 'jimscooter', 'jimycarl.rgba'):
|
||||
(output/relative).symlink_to(outside)
|
||||
with self.subTest(relative=relative), self.assertRaises(ValueError):
|
||||
export_scooter(ORIGINAL, output)
|
||||
self.assertEqual(outside.read_text(), 'unchanged')
|
||||
(output/relative).unlink()
|
||||
out=Path(directory)/'scooter';m=export_scooter(ORIGINAL,out)
|
||||
self.assertEqual(hashlib.sha256((out/'jimycarl.rgba').read_bytes()).hexdigest(),JIMMY_RGBA_SHA256)
|
||||
for stem in CLIPS:
|
||||
animation=json.loads((out/stem/'animation.json').read_text())
|
||||
self.assertEqual([f['time'] for f in animation['frames']],[0,480])
|
||||
self.assertEqual(animation['texture']['path'],'../jimycarl.rgba')
|
||||
source=read_ase(resolve_asset(ORIGINAL,f'ASE/{stem}.ASE'))['objects'][0]['samples']
|
||||
for sample,frame in zip(source,animation['frames'],strict=True):
|
||||
expected=expand_mesh({**sample,'faces':base['faces'],'textureFaces':base['textureFaces'],'uvs':base['uvs']})
|
||||
actual=json.loads((out/stem/frame['path']).read_text())
|
||||
self.assertEqual(actual['vertices'],[list(p) for p in expected['vertices']])
|
||||
self.assertEqual(actual['uvs'],[list(p) for p in expected['uvs']])
|
||||
self.assertEqual(actual['indices'],expected['indices'])
|
||||
self.assertEqual((len(m['levels'][0]['entities']),len(m['levels'][1]['entities'])),(18,322))
|
||||
self.assertEqual(m['goddardTransformation']['indexedVertices'],195)
|
||||
self.assertEqual(m['goddardTransformation']['sourceTimes'],[0,161])
|
||||
|
||||
def test_changed_source_identity_rejected_before_writes(self):
|
||||
def test_original_binding_spans_and_alias_string_operands(self):
|
||||
pe=PE(resolve_asset(ORIGINAL,'Neutron.exe'))
|
||||
expected=[(0x4214f0,37,'3aa8cb83c0e81fa70622d540015517ecd60549945ace69b6cfe9357641dbd19b'),
|
||||
(0x422c58,40,'92f233fbba67cc7eb63d29614f6d8a04da703169b91b86e53b36ee5d722b2929'),
|
||||
(0x41cdf0,20,'1a0e33a555990de9d997d9fe5dc33af242c3994681e511b3b6f5134857659b82'),
|
||||
(0x468270,42,'cacdf3e512e808601f753b22504a553da79de578b0a792a322ee43966119a838')]
|
||||
for va,length,digest in expected:
|
||||
self.assertEqual(hashlib.sha256(read_va(pe,va,length)).hexdigest(),digest)
|
||||
self.assertEqual(pe.offset(va-pe.base),va-0x400000)
|
||||
for va,string in [(0x4ef104,b'jimscooter.ase\0'),(0x4ef0f0,b'Jimscooterstop.ase\0'),
|
||||
(0x4ee9ec,b'HISCOOT\0'),(0x4ef0e4,b'HISCOOTSTOP\0'),(0x4ee9f4,b'godscooter.ASE\0')]:
|
||||
self.assertEqual(read_va(pe,va,len(string)),string)
|
||||
|
||||
def test_changed_original_or_contract_rejects_before_output(self):
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
output = Path(directory)/'scooter'
|
||||
with patch.dict(SOURCES, {'omt/scooter.omt': '0'*64}), self.assertRaises(FormatError):
|
||||
export_scooter(ORIGINAL, output)
|
||||
self.assertFalse(output.exists())
|
||||
out=Path(directory)/'scooter'
|
||||
with patch.dict(SOURCES,{'omt/scooter.omt':'0'*64}):
|
||||
with self.assertRaises(FormatError):export_scooter(ORIGINAL,out)
|
||||
self.assertFalse(out.exists())
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
out=Path(directory)/'scooter'
|
||||
with patch('scooter_resources.CANVASES',((0,'changed',22568,3966,32,32,'0'*64),)):
|
||||
with self.assertRaises(FormatError):export_scooter(ORIGINAL,out)
|
||||
self.assertFalse(out.exists())
|
||||
|
||||
def test_original_and_generated_symlink_paths_rejected(self):
|
||||
for destination in (ORIGINAL, ORIGINAL/'ASE/generated', ORIGINAL.parent):
|
||||
with self.assertRaises(ValueError):export_scooter(ORIGINAL,destination)
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
out=Path(directory)/'scooter';out.mkdir();(out/'linked').symlink_to(ORIGINAL,target_is_directory=True)
|
||||
with self.assertRaises(ValueError):export_scooter(ORIGINAL,out)
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
def test_export_is_deterministic(self):
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
root=Path(directory);export_scooter(ORIGINAL,root/'a');export_scooter(ORIGINAL,root/'b')
|
||||
a={str(p.relative_to(root/'a')):p.read_bytes() for p in (root/'a').rglob('*') if p.is_file()}
|
||||
b={str(p.relative_to(root/'b')):p.read_bytes() for p in (root/'b').rglob('*') if p.is_file()}
|
||||
self.assertEqual(a,b)
|
||||
Reference in new issue
Block a user