Implement Bubble controller, sprite and VR01 body behavior

This commit is contained in:
UnixNight committed 2026-11-02 16:57:54 -05:00
1 parent 9ea578492d
commit 1ae5f4251c
51 files changed
+2811 -54

No files matched your search

@@ -0,0 +1,14 @@
<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" Link="Assets/%(Filename)%(Extension)" />
<Compile Include="../../src/GamePort/Game/*.cs" Link="Game/%(Filename)%(Extension)" />
</ItemGroup>
</Project>
+152
View File
@@ -0,0 +1,152 @@
using System.Numerics;
using GamePort.Game;
var tests = new (string Name, Action Check)[]
{
("mode2 fire throttles without forward arrows and caps at current maximum", FireThrottle),
("turn limit 50, left precedence, release and pose priorities", TurnAndPose),
("supported input reduction precedes brake and permits negative crossing", SupportInput),
("coast threshold and air brake retain source ordering", CoastAndBrake),
("supported XZ 112.5 halves only later published scalar to 56.25", PublishedScalarOrder),
("held bounce 900 and repeat sound versus released 300 without sound", BounceBranches),
("unsupported apply retains vertical velocity and scalar", Unsupported),
("zero incoming velocity suppresses yaw and side, including nonzero scalar", Stationary),
("quantized pitch cosine scales only horizontal forward velocity", QuantizedPitch),
("nonzero incoming velocity turns and adds source lateral term", Lateral),
("finite input and bounded timestep validation", InvalidInputs),
};
foreach (var (name, check) in tests)
{
check();
Console.WriteLine($"PASS {name}");
}
Console.WriteLine($"Bubble motion checks: {tests.Length} passed. Source arithmetic/port regressions; no original gameplay execution.");
static PlayerInput Input(bool forward = false, bool backward = false, bool left = false,
bool right = false, bool fire = false) => new(forward, backward, left, right, false, Fire: fire);
static void FireThrottle()
{
var fire = BubbleMotion.StepInput(0, 0, Input(fire: true), false, .1f);
Check(fire == BubbleMotion.StepInput(0, 0, Input(forward: true), false, .1f), "fire matches forward");
Near(fire.Speed, 30, 0, "source per-call increment");
Near(fire.TargetPitch, -10, 0, "forward target pitch");
Near(BubbleMotion.StepInput(1340, 0, Input(fire: true), false, .1f).Speed, 1350, 0, "Bubble cap");
Near(BubbleMotion.StepInput(640, 0, Input(forward: true), false, .1f, 650).Speed, 650, 0, "caller maximum");
}
static void TurnAndPose()
{
var both = BubbleMotion.StepInput(100, 49, Input(left: true, right: true), false, .5f);
Near(both.TurnRate, 50, 0, "left precedence and positive cap");
Near(both.TargetRoll, -12.5f, 0, "source lean sign");
Near(BubbleMotion.StepInput(100, -49, Input(right: true), false, .5f).TurnRate, -50, 0, "negative cap");
Near(BubbleMotion.StepInput(100, -20, Input(), false, .5f).TurnRate, 0, 0, "release crosses zero");
var throttleBrake = BubbleMotion.StepInput(100, 10, Input(forward: true, backward: true, left: true), false, .1f);
Near(throttleBrake.Speed, 112.5f, 0, "forward before backward");
Near(throttleBrake.TargetPitch, -10, 0, "throttle pitch wins");
Near(throttleBrake.TargetRoll, -5, 0, "updated turn drives lean");
Near(BubbleMotion.StepInput(100, 0, Input(backward: true), false, .1f).TargetPitch, 10, 0, "brake pitch");
Near(BubbleMotion.StepInput(100, 0, Input(), false, .1f).TargetPitch, 0, 0, "coast pitch");
}
static void SupportInput()
{
Near(BubbleMotion.StepInput(100, 0, Input(), true, .1f).Speed, 82.5f, 0, "supported coast");
Near(BubbleMotion.StepInput(100, 0, Input(backward: true), true, .1f).Speed, 47.5f, 0, "support decay then full brake");
var crossed = BubbleMotion.StepInput(5, 0, Input(), true, .1f).Speed;
Near(crossed, -12.5f, 0, "unclamped source crossing");
Near(BubbleMotion.StepInput(crossed, 0, Input(), true, .1f).Speed, 0, 0, "following supported input clears negative");
}
static void CoastAndBrake()
{
Near(BubbleMotion.StepInput(1350, 0, Input(), false, .1f).Speed, 1332.5f, 0, "high coast decay");
Near(BubbleMotion.StepInput(1200, 0, Input(), false, .1f).Speed, 1200, 0, "below coast threshold");
Near(BubbleMotion.StepInput(5, 0, Input(backward: true), false, .1f).Speed, 0, 0, "positive brake clamps");
Near(BubbleMotion.StepInput(-5, 0, Input(backward: true), false, .1f).Speed, 0, 0, "negative brake clamps");
}
static void PublishedScalarOrder()
{
var steering = BubbleMotion.StepInput(100, 0, Input(forward: true), true, .1f);
Near(steering.Speed, 112.5f, 0, "supported input scalar");
var applied = BubbleMotion.StepApply(steering.Speed, steering.TurnRate, 0, 0, Vector3.UnitZ, true, false, .1f);
Near(applied.Velocity.Z, 112.5f, 0, "XZ composed before bounce decay");
Near(applied.Speed, 56.25f, 0, "only later published scalar halves");
Near(applied.Velocity.Y, 300, 0, "automatic released bounce");
}
static void BounceBranches()
{
var held = BubbleMotion.StepApply(100, 0, 0, 0, new(0, -800, 10), true, true, .1f);
Check(held.Velocity == new Vector3(0, 900, 100) && held.Boing, "direct held velocity and sound");
Near(held.Speed, 100, 0, "held bounce retains scalar");
Check(BubbleMotion.StepApply(100, 0, 0, 0, held.Velocity, true, true, .1f).Boing, "no invented edge latch");
var released = BubbleMotion.StepApply(100, 0, 0, 0, new(0, -800, 10), true, false, .1f);
Check(released.Velocity == new Vector3(0, 300, 100) && !released.Boing, "released velocity without boing");
Near(released.Speed, 50, 0, "released scalar");
}
static void Unsupported()
{
var applied = BubbleMotion.StepApply(100, 0, 0, 0, new(0, -99, 10), false, true, .1f);
Near(applied.Velocity.Y, -99, 0, "unsupported liveY retained");
Near(applied.Speed, 100, 0, "unsupported scalar retained");
Check(!applied.Boing, "unsupported jump produces no sound");
}
static void Stationary()
{
var applied = BubbleMotion.StepApply(100, 50, 0, 0, Vector3.Zero, false, false, .1f);
Near(applied.Yaw, 0, 0, "zero incoming velocity skips direct yaw");
Check(applied.Velocity == new Vector3(0, 0, 100), "forward still starts, side remains zero");
}
static void QuantizedPitch()
{
const float pitch = 17.123f;
var expected = LabSimulation.Trig(pitch).Cos * 100;
var applied = BubbleMotion.StepApply(100, 0, 0, pitch, new(0, -12, 1), false, false, .1f);
Near(applied.Velocity.Z, expected, 0, "same quantized cosine helper");
Near(applied.Velocity.Y, -12, 0, "transformed forwardY deliberately unused");
Check(applied.Velocity.Z != MathF.Cos(pitch * MathF.PI / 180) * 100, "continuous cosine would differ");
}
static void Lateral()
{
var applied = BubbleMotion.StepApply(100, 50, 0, 0, Vector3.UnitY, false, false, .1f);
Near(applied.Yaw, 5, 0, "direct yaw from nonzero incomingY");
var (sin, cos) = LabSimulation.Trig(5);
var side = 50 * .0181818176060915f * (1 - .8f) * 100;
Near(applied.Velocity.X, -sin * 100 + cos * side, 0, "yaw-only lateralX");
Near(applied.Velocity.Z, cos * 100 + sin * side, 0, "yaw-only lateralZ");
}
static void InvalidInputs()
{
foreach (var seconds in new[] { -1f, 1f, float.NaN, float.PositiveInfinity })
{
Throws(() => BubbleMotion.StepInput(0, 0, Input(), false, seconds));
Throws(() => BubbleMotion.StepApply(0, 0, 0, 0, Vector3.Zero, false, false, seconds));
}
Throws(() => BubbleMotion.StepInput(float.NaN, 0, Input(), false, .1f));
Throws(() => BubbleMotion.StepInput(0, 0, Input(), false, .1f, 0));
Throws(() => BubbleMotion.StepApply(0, 0, 0, 0, new(float.NaN, 0, 0), false, false, .1f));
}
static void Check(bool condition, string message)
{
if (!condition) throw new InvalidOperationException(message);
}
static void Near(float actual, float expected, float tolerance, string message) =>
Check(float.IsFinite(actual) && MathF.Abs(actual - expected) <= tolerance,
$"{message}: expected {expected}, got {actual}");
static void Throws(Action action)
{
try { action(); }
catch (ArgumentOutOfRangeException) { return; }
throw new InvalidOperationException("Expected bounded-input rejection");
}
@@ -0,0 +1,7 @@
<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" />
</ItemGroup>
</Project>
+149
View File
@@ -0,0 +1,149 @@
using System.Numerics;
using System.Buffers.Binary;
using System.Text;
using GamePort.Assets;
using GamePort.Game;
using GamePort.Application;
var count=0;
void Check(bool value,string message){if(!value)throw new Exception(message);}
void Near(float actual,float expected,string message)=>Check(MathF.Abs(actual-expected)<.002f,$"{message}: {actual} != {expected}");
void Test(string name,Action action){action();count++;Console.WriteLine($"PASS {name}");}
Mesh Floor(int material=0)=>new(
[new(new(-4000,0,-4000),Vector2.Zero,Vector3.One),new(new(4000,0,-4000),Vector2.Zero,Vector3.One),
new(new(4000,0,4000),Vector2.Zero,Vector3.One),new(new(-4000,0,4000),Vector2.Zero,Vector3.One)],
[0,1,2,0,2,3]){HasCollisionMaterialIds=true,CollisionPolygons=[new(0,0,Vector3.UnitY,"floor","floor",material),new(0,1,Vector3.UnitY,"floor","floor",material)]};
LabSimulation Player(string level="VR01",Mesh? world=null)
{
world??=Floor();
return new(new SceneCollision(world),AseMesh.Load("../Original/ASE/jimstop.ase"),new(0,80,0),0,
originalCollision:OriginalStaticCollision.FromRouteScene(world,"VR01")){LevelCode=level};
}
void Until(LabSimulation player,Func<bool> done,PlayerInput input=default)
{for(var i=0;i<700&&!done();i++)player.Step(input);Check(done(),"requested phase not reached");}
Test("six copied-original radius/factor body references",()=>{
var physics=new OriginalBodyPhysics(OriginalStaticCollision.FromRouteScene(Floor(),"VR01"));
foreach(var c in new[]{
(66.4f,0f,160f,.415f,66.4000015f,0f,true),(26f,0f,160f,.415f,66.4000015f,0f,true),
(75.9f,0f,160f,.415f,75.6777802f,-13.333334f,false),(66.4f,0f,60f,1.265f,75.9000015f,0f,true),
(66.4f,300f,160f,.415f,71.1777802f,286.666656f,false),(66.4f,900f,160f,.415f,81.1777802f,886.666687f,false)})
{
var r=physics.Step(new(new(0,c.Item1,0),new(0,c.Item2,0),Vector3.Zero,Vector3.Zero),1f/60,c.Item3,c.Item4);
Near(r.Body.Position.Y,c.Item5,"root");Near(r.Body.Velocity.Y,c.Item6,"velocity");Check(r.Body.Supported==c.Item7,"support");
}
});
Test("equip and cleanup retain logical root, queued impulse and source650 maximum",()=>{
var p=Player();p.Step(new(false,false,false,false,true));var root=p.ActorRoot;var impulse=p.PendingImpulse;
p.GadgetMode=0;
Check(p.ActorRoot==root&&p.PendingImpulse==impulse&&impulse.Y==550,"equip must not recenter/reset queued impulse");
Check(p.MovementMode==2&&p.InteractionRadius==160&&p.BodyFactor==.415f&&p.MaximumSpeed==1350,"source body/controller settings");
p.GadgetMode=-1;
Check(p.ActorRoot==root&&p.PendingImpulse==impulse&&p.MovementMode==0&&p.MaximumSpeed==650&&p.BodyFactor==1.265f&&p.InteractionRadius==60,
"cleanup changes its fields without a teleport or blanket physics clear");
});
Test("mode2 persists through repeated automatic300 bounces without550/jetpack",()=>{
var p=Player();p.JetpackInventoryState=()=>1;p.GadgetMode=0;var sounds=new List<int>();p.GadgetSound+=(id,_)=>sounds.Add(id);
Until(p,()=>p.BubbleBounces>=3);
Check(p.GadgetMode==0&&p.MovementMode==2&&p.Velocity.Y==300&&p.Jumps==0&&p.Bursts==0,"automatic bounce path");
Check(p.Pose==PlayerPose.Idle&&!sounds.Contains(106),"supported STOP, released bounce has no boing");
});
Test("held supported bounce is direct900 and requests106",()=>{
var p=Player();p.GadgetMode=0;var sounds=new List<int>();p.GadgetSound+=(id,_)=>sounds.Add(id);
Until(p,()=>p.BubbleBounces>0,new(false,false,false,false,true));
Check(p.Velocity.Y==900&&sounds.SequenceEqual(new[]{106})&&p.PendingImpulse==Vector3.Zero&&p.MovementMode==2,"direct liveY/source sound");
});
Test("controlled drain, independent sprite clock and tutorial bypass",()=>{
var p=Player("LV1B");p.GadgetMode=0;p.Step(default);Near(p.Energy,20-1f/120,"ordinary controlled cost");
var root=p.BubbleRoot;var energy=p.Energy;var time=p.Bubble.Timer;var controllers=p.ControllerSteps;
p.Step(default,false,false);
Check(p.Energy==energy&&p.Bubble.Timer>time&&p.BubbleRoot==root&&p.ControllerSteps==controllers,"raw control loss does not stop effect clock or move captured sprite");
var vr=Player();vr.GadgetMode=0;for(var i=0;i<90;i++)vr.Step(default);
Check(vr.Energy==20&&vr.Bubble.Active,"VR01 exemption and expansion");
});
Test("depletion cleans once and notifies selection owner without restarting loop",()=>{
var p=Player("LV1B");p.Energy=.001f;var director=new SceneDirector(new("LV1B",[Entity("3JIM","JIM1")]),new TaskStates([]),(_,_)=>1);
var bag=new SceneInventory(new int[19]);bag.SetState(0,0,1);using var binding=new PlayerSceneBinding(director,p,bag,"JIM1");
var starts=0;var stops=0;var warnings=new List<int>();p.GadgetSound+=(_,loop)=>{if(loop)starts++;};p.BubbleSoundStopped+=()=>stops++;p.EnergySound+=warnings.Add;
bag.SelectGadget(0);binding.Step(default);
Check(p.Energy==0&&p.GadgetMode==-1&&p.MovementMode==0&&p.MaximumSpeed==650&&p.Bubble.Collapsing&&!p.Bubble.Expanding,"source depletion cleanup");
Check(starts==1&&stops==1&&bag.SelectedGadget==-1&&warnings.SequenceEqual(new[]{80,182}),"one loop and shared warning/selection ownership");
});
Test("transition flags reject re-equip until original fade finishes",()=>{
var p=Player();p.GadgetMode=0;p.GadgetMode=0;
Check(p.GadgetMode==-1&&p.Bubble.Collapsing&&!p.Bubble.Expanding,"select-again caller cleanup precedes active flag gate");
p.GadgetMode=0;Check(p.GadgetMode==-1,"collapsing owned effect blocks re-equip");
Until(p,()=>!p.Bubble.Visible);p.GadgetMode=0;
Check(p.GadgetMode==0&&p.Bubble.Expanding&&p.MaximumSpeed==1350,"hidden after strict fade allows next activation");
});
Test("Bubble fire throttles without starting the ordinary ray",()=>{
var world=Floor();var p=Player("LV1B",world);var director=new SceneDirector(new("LV1B",[Entity("3JIM","JIM1")]),new TaskStates([]),(_,_)=>1);
var bag=new SceneInventory(new int[19]);bag.SetState(0,3,1);using var ray=new SceneGadgets(director,bag,p,world);
p.GadgetMode=0;for(var i=0;i<20;i++)p.Step(new(false,false,true,false,false,Fire:true));
Check(p.Speed>0&&p.TurnRate>0&&p.Pitch<0&&!ray.Ray.Visible&&!p.Shooting,"shared fire predicate is Bubble throttle, not shoot");
});
Test("lava bypass, retained entry and strict4-second debounce",()=>{
var state=new Vr01FloorState();var e=state.Visit(111,0);
Check(e.Entered&&!e.Damaged&&!state.Flashing&&state.SoundSelector==35,"Bubble entry bypass");
e=state.Visit(111,-1);Check(!e.Entered&&e.Damaged&&state.Flashing,"cleanup starts damage without replaying entry");
for(var i=0;i<16;i++)state.Step(.25f,_=>{});
Check(state.Flashing&&state.Timer==4,"exact4 still flashes");
Vector4 color=default;state.Step(MathF.Pow(2,-24),c=>color=c);
Check(!state.Flashing&&state.Timer==4&&color==Vector4.One,"unrounded comparison before float store");
state.Visit(0,-1);Check(!state.InLava&&state.SoundSelector==5,"ordinary floor resets entry and selector");
});
Test("actual VR01 floor111 retained through airborne cleanup and raw control loss",()=>{
var mesh=Mesh.LoadSceneJson("artifacts/extracted/VR01/scene.json");var collision=OriginalStaticCollision.FromRouteScene(mesh,"VR01");
Check(!collision.HasSpecialPlayerContacts&&collision.PolygonCount==80&&collision.WallPolygonCount==60,"actual static-only wall coverage");
var index=Array.FindIndex(mesh.CollisionPolygons,p=>p.MaterialId==111);var first=index*3;
var center=(mesh.Vertices[mesh.Indices[first]].Position+mesh.Vertices[mesh.Indices[first+1]].Position+mesh.Vertices[mesh.Indices[first+2]].Position)/3;
var p=Player("VR01",mesh);p.GadgetMode=0;p.RestoreReturnRoot(center+Vector3.UnitY*66.4f);
var score=0;var sounds=new List<int>();p.ScoreChanged+=delta=>score+=delta;p.GadgetSound+=(id,_)=>sounds.Add(id);
p.Step(new(false,false,false,false,true));
Check(p.Velocity.Y==900&&score==0&&sounds.Contains(39)&&!sounds.Contains(190)&&p.FloorState.InLava,"Bubble supports lava and skips damage");
p.GadgetMode=-1;p.Step(default,false,false);
Check(!p.Grounded&&score==-5&&p.FloorState.Flashing&&p.Energy==20,"retained material callback runs airborne/uncontrolled; VR energy alone exempt");
});
Test("stored material writes preserve Invisible/lava phase ownership",()=>{
var appearance=new PlayerAppearance();var inv=new InvisibleGadget();inv.AlphaRequested+=appearance.SetAlpha;inv.BlendRequested+=appearance.SetBlend;
inv.Equip(20,false);for(var i=0;i<14;i++)inv.Step(.5f,true,false,false,20,false,_=>{});inv.Step(0,true,true,false,20,false,_=>{});
Check(appearance.Color.W==.7f&&appearance.Blend==MeshBlend.Additive,"activation material request");
var lava=new Vr01FloorState();lava.Visit(111,2);lava.Step(.25f,appearance.SetColor);
Check(appearance.Color.W==1&&appearance.Blend==MeshBlend.Additive,"late direct RGBA changes alpha without changing blend bit");
for(var i=0;i<8;i++)inv.Step(.5f,true,false,false,18,false,_=>{});
Check(appearance.Color.W==1&&appearance.Blend==MeshBlend.Alpha,"indexed flash does not reapply alpha.7");
inv.Release();Check(appearance.Color==Vector4.One&&appearance.Blend==MeshBlend.Opaque,"alpha-reset clears blending");
});
Test("practice0 loads before live equip; rejected raw mode opens panel directly",()=>{
var p=Player("LV1B");var bag=new SceneInventory(new int[19]);bag.SetState(0,0,1);bag.SetState(0,2,1);bag.GadgetSelected+=i=>p.GadgetMode=GadgetScreen.EquippedMode(i);
var screen=new GadgetScreen(bag,()=>p.GadgetMode);var destination=-1;screen.PracticeRequested+=i=>destination=i;
screen.Toggle(true);screen.Point(new(520,120),"LV1B",60);screen.Activate("LV1B",60);
screen.Point(new(50,200),"LV1B",60);screen.Activate("LV1B",60);
Check(destination==0&&bag.SelectedGadget==0&&p.GadgetMode==-1&&!p.Bubble.Visible,"source practice branch precedes body/effect setup");
p.Energy=0;bag.SelectGadget(2);Check(p.GadgetMode==-1&&bag.SelectedGadget==2,"rejected Invisible display/raw split");
Check(screen.Toggle(true)&&screen.Open,"key dispatcher reads raw mode, not display index");
});
Test("camera cleanup and modern debug stop release Bubble and restore defaults",()=>{
var p=Player("LV1B");var command=Entity("3MCA","cleanup",("CameraTarget0","none"));
var director=new SceneDirector(new("LV1B",[Entity("3JIM","JIM1"),command]),new TaskStates([]),(_,_)=>1);
var bag=new SceneInventory(new int[19]);bag.SetState(0,0,1);using var binding=new PlayerSceneBinding(director,p,bag,"JIM1");
bag.SelectGadget(0);director.Trigger("cleanup");
Check(p.GadgetMode==-1&&p.MaximumSpeed==650&&p.Bubble.Collapsing&&binding.UnsupportedGadgetCleanups==0,"named-Jimmy source cleanup");
Until(p,()=>!p.Bubble.Visible);bag.SelectGadget(0);p.StopDebugMotion();
Check(p.GadgetMode==-1&&bag.SelectedGadget==-1&&p.MovementMode==0,"modern stop boundary prevents dangling movement2 gadget");
Until(p,()=>!p.Bubble.Visible);bag.SelectGadget(0);p.SetNoclip(true);
for(var i=0;i<70;i++)p.Step(default);
Check(!p.Bubble.Visible&&p.Noclip&&p.GadgetMode==-1,"owned fade advances during modern flight after cleanup");
});
Console.WriteLine($"Bubble integration:{count} groups passed; broader damage, dynamic collision and original whole-game comparison remain separate.");
GamEntity Entity(string kind,string tag,params(string Name,object Value)[] values)
{
var props=new Dictionary<string,GamProperty>(StringComparer.Ordinal);
foreach(var(name,value) in new[]{("ObjectTag",(object)tag)}.Concat(values))
{
if(value is string text)props[name]=new(name,1,Encoding.Latin1.GetBytes(text));
else{var raw=new byte[4];BinaryPrimitives.WriteInt32BigEndian(raw,(int)value);props[name]=new(name,6,raw);}
}
return new(kind,props.Count,props,[]);
}
@@ -0,0 +1,13 @@
<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/BubbleEffect.cs" />
<Compile Include="../../src/GamePort/Application/BubbleVisuals.cs" />
</ItemGroup>
</Project>
+161
View File
@@ -0,0 +1,161 @@
using System.Numerics;
using System.Text.Json;
using GamePort.Application;
using GamePort.Assets;
using GamePort.Game;
var count = 0;
void Check(bool condition, string message) { if (!condition) throw new Exception(message); }
void Near(float actual, float expected, string message) =>
Check(MathF.Abs(actual - expected) < .0002f, $"{message}: {actual} != {expected}");
void Test(string name, Action action) { action(); count++; Console.WriteLine($"PASS {name}"); }
void Invalid(Action action)
{
try { action(); }
catch (Exception exception) when (exception is ArgumentException or InvalidDataException) { return; }
throw new Exception("Invalid input accepted");
}
BubbleEffect Active(bool conventionalBlend = false)
{
var effect = new BubbleEffect(conventionalBlend);
effect.Start(); effect.Step(.5f); effect.Step(.5f); effect.Step(.01f);
Check(effect.Active && !effect.Expanding, "expansion completes strictly after1");
return effect;
}
Test("strict expansion boundary changes all RGBA without changing geometry", () =>
{
var effect = new BubbleEffect();
Check(!effect.Visible && effect.Width == 200 && effect.Height == 200, "constructor hidden200 square");
effect.Start(); effect.Step(.5f);
Check(effect.Visible && effect.Expanding && !effect.Active && effect.Color == new Vector4(.5f), "half expansion fullRGBA");
Check(effect.Width == 200 && effect.Height == 200, "fade retains source dimensions");
effect.Step(.5f);
Check(effect.Expanding && !effect.Active && effect.Color == Vector4.One, "exact1 still expanding");
effect.Step(.01f);
Check(effect.Active && !effect.Expanding && effect.Width == 200, "completion frame still fade branch");
effect.Step(0);
Check(effect.Width == 240, "next active invocation adopts pulse geometry");
Near(effect.Height, (float)(240 + Math.Sin((double)effect.Timer * 10) * 30), "height pulse");
});
Test("active graphics branches preserve additive RGBA or set half alpha", () =>
{
foreach (var conventional in new[] { false, true })
{
var initial = new BubbleEffect(conventional);
Check(initial.Color == (conventional ? new Vector4(.9f, .9f, .9f, 1) : Vector4.One), "source initialization graphics branch");
var effect = Active(conventional);
effect.Step(.25f);
Check(effect.Color == (conventional ? new Vector4(1, 1, 1, .5f) : Vector4.One), "source graphics branch");
Near(effect.Width, 240, "pulse fixed width");
Check(effect.Height >= 210 && effect.Height <= 270, "30 unit height excursion");
}
});
Test("Stop leaf retains expansion priority; cleanup explicitly clears it", () =>
{
var leaf = new BubbleEffect(); leaf.Start(); leaf.Step(.25f); leaf.Stop(); leaf.Step(.25f);
Check(leaf.Expanding && leaf.Collapsing && leaf.Color == new Vector4(.25f), "expansion still wins without cleanup write");
leaf.Stop(); leaf.ClearExpansion(); leaf.Step(.25f);
Check(!leaf.Expanding && leaf.Collapsing && leaf.Color == new Vector4(.75f), "cleanup reveals collapse");
leaf.Step(.75f);
Check(leaf.Timer == 1 && leaf.Color == Vector4.Zero && leaf.Visible && leaf.Collapsing, "exactzero remains visible/collapsing");
leaf.Step(.001f);
Check(!leaf.Visible && !leaf.Collapsing && leaf.Color == Vector4.Zero, "strictnegative hides");
});
Test("fade compares unrounded addition even when stored timer rounds to one", () =>
{
var effect = new BubbleEffect(); effect.Start(); effect.Step(.5f); effect.Step(.5f);
effect.Step(MathF.Pow(2, -25));
Check(effect.Timer == 1 && effect.Active && !effect.Expanding, "x87 sum before float store controls strict comparison");
effect.Stop(); effect.ClearExpansion(); effect.Step(.5f); effect.Step(.5f); effect.Step(MathF.Pow(2, -25));
Check(effect.Timer == 1 && !effect.Collapsing && !effect.Visible, "unrounded collapse comparison");
});
Test("independent timer, retained dimensions, Reset and bounded timestep", () =>
{
var effect = Active(); effect.Step(.2f);
var height = effect.Height;
effect.Stop(); effect.ClearExpansion(); effect.Step(.5f);
Check(effect.Width == 240 && effect.Height == height && effect.Color == new Vector4(.5f), "collapse fades last active geometry");
effect.Step(.6f);
var hiddenTimer = effect.Timer; effect.Step(.1f);
Check(effect.Timer > hiddenTimer, "hidden effect still advances independently");
effect.Reset();
Check(!effect.Visible && !effect.Active && !effect.Expanding && !effect.Collapsing
&& effect.Timer == 0 && effect.Color == Vector4.One && effect.Width == 200 && effect.Height == 200, "explicit reset");
foreach (var seconds in new[] { -.1f, 1f, float.NaN, float.PositiveInfinity }) Invalid(() => effect.Step(seconds));
});
var prepared = args.Length == 0 ? "artifacts/extracted" : args[0];
Test("original texture world quad preserves source colors and collision metadata", () =>
{
var source = new Mesh([new(Vector3.Zero, Vector2.Zero, Vector3.One)], [0, 0, 0])
{
CollisionPolygons = [new(2, 3, Vector3.UnitY, "material")], HasCollisionMaterialIds = true,
Textures = new() { [int.MinValue + 16000] = PngImage.White }
};
var visual = new BubbleVisuals(source, prepared);
Check(visual.Mesh.Vertices.Length == 5 && visual.Mesh.Indices.Length == 9 && visual.Mesh.Draws.Length == 2, "append quad and implicit source draw");
Check(ReferenceEquals(visual.Mesh.CollisionPolygons, source.CollisionPolygons) && visual.Mesh.HasCollisionMaterialIds, "collision metadata preserved");
var draw = visual.Mesh.Draws[^1];
Check(!draw.ScreenSpace && draw.Blend == MeshBlend.Additive && !draw.Visible, "world-space blended draw starts hidden");
Check(draw.TextureId != int.MinValue + 16000 && visual.Mesh.Textures[draw.TextureId].Width == 146, "texture collision avoided");
var effect = new BubbleEffect(); effect.Start(); effect.Step(.5f);
var root = new Vector3(10, 20, 30);
visual.Update(visual.Mesh, effect, root, new(0, 0, -1000), Vector3.Zero);
Check(draw.Visible && draw.Opacity == .5f && draw.Blend == MeshBlend.Additive, "RGBA alpha and additive blend");
var corners = visual.Mesh.Vertices.Skip(1).ToArray();
Check(corners.All(v => v.Color == new Vector3(.5f)), "RGB fade carried by all vertices");
Check(corners.Aggregate(Vector3.Zero, (sum, v) => sum + v.Position) / 4 == root, "caller root is quad center");
Near(Vector3.Distance(corners[0].Position, corners[1].Position), 200, "width remains200 while fading");
Near(Vector3.Distance(corners[1].Position, corners[2].Position), 200, "height remains200 while fading");
Check(corners.Select(v => v.Uv).SequenceEqual(new Vector2[] { new(0, 1), new(1, 1), new(1, 0), new(0, 0) }), "entire original image");
effect = Active(true); effect.Step(.1f);
visual.Update(visual.Mesh, effect, root, new(0, 0, -1000), Vector3.Zero);
Check(draw.Blend == MeshBlend.Alpha && draw.Opacity == .5f && visual.Mesh.Vertices[1].Color == Vector3.One, "conventional graphics branch");
effect.Reset(); visual.Update(visual.Mesh, effect, root, Vector3.Zero, Vector3.Zero);
Check(!draw.Visible, "reset hides owned quad");
});
Test("camera degeneracies produce finite orthonormal corners", () =>
{
var visual = new BubbleVisuals(new([], []), prepared);
var effect = Active();
foreach (var target in new[] { Vector3.Zero, Vector3.UnitY, -Vector3.UnitY, new Vector3(3, 4, 5) })
{
visual.Update(visual.Mesh, effect, Vector3.One, Vector3.Zero, target);
Check(visual.Mesh.Vertices.All(v => float.IsFinite(v.Position.X + v.Position.Y + v.Position.Z)), "finite camera-facing basis");
Near(Vector3.Distance(visual.Mesh.Vertices[0].Position, visual.Mesh.Vertices[1].Position), 200, "orthonormal horizontal edge");
Near(Vector3.Distance(visual.Mesh.Vertices[1].Position, visual.Mesh.Vertices[2].Position), 200, "orthonormal vertical edge");
}
Invalid(() => visual.Update(new([], []), effect, Vector3.Zero, Vector3.Zero, Vector3.UnitZ));
Invalid(() => visual.Update(visual.Mesh, effect, new(float.NaN), Vector3.Zero, Vector3.UnitZ));
});
Test("manifest traversal, dimensions and altered original pixels are rejected", () =>
{
var directory = Path.Combine(Path.GetTempPath(), "neutron-bubble-test-" + Guid.NewGuid());
Directory.CreateDirectory(Path.Combine(directory, "bubble"));
try
{
var source = Path.Combine(prepared, "bubble");
using var manifest = JsonDocument.Parse(File.ReadAllBytes(Path.Combine(source, "bubble.json")));
var root = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(manifest.RootElement.GetRawText())!;
var texture = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(root["textures"][0].GetRawText())!;
void Save() { root["textures"] = JsonSerializer.SerializeToElement(new[] { texture }); File.WriteAllText(Path.Combine(directory, "bubble/bubble.json"), JsonSerializer.Serialize(root)); }
texture["path"] = JsonSerializer.SerializeToElement("../outside.rgba"); Save();
File.Copy(Path.Combine(source, "canvas_1.rgba"), Path.Combine(directory, "outside.rgba"));
Invalid(() => new BubbleVisuals(new([], []), directory));
texture["path"] = JsonSerializer.SerializeToElement("canvas_1.rgba");
texture["width"] = JsonSerializer.SerializeToElement(145); Save();
Invalid(() => new BubbleVisuals(new([], []), directory));
texture["width"] = JsonSerializer.SerializeToElement(146); Save();
File.WriteAllBytes(Path.Combine(directory, "bubble/canvas_1.rgba"), new byte[146 * 146 * 4]);
Invalid(() => new BubbleVisuals(new([], []), directory));
}
finally { Directory.Delete(directory, true); }
});
Console.WriteLine($"Bubble effect/visual checks passed: {count}");
+1
View File
@@ -70,6 +70,7 @@ menu.Key(43);
for(var i=0;i<10;i++)menu.Key(81);
Require(menu.Key(40)==DebugAction.GiveInvisible,"Player tools can grant/select implemented Invisible device");
menu.Key(81);Require(menu.Key(40)==DebugAction.UnequipGadget,"Explicit gadget unequip");
menu.Key(81);Require(menu.Key(40)==DebugAction.GiveBubble,"Player tools grant/select the implemented Bubble");
var invisibleView=menu.View(new("LV1B","STARTEXP",Vector3.Zero,0,0,true,20,0,30,"NONE",true,0,10000,false,
Systems:new(){InvisibleRemaining=4.5f,InvisibleRecharge=0,Targetable=false}));
Require(invisibleView.Lines.Length<=32 && invisibleView.Lines.Any(s=>s.Contains("INVISIBLE 4.5")),"Bounded Invisible timer/target diagnostics");
@@ -18,6 +18,10 @@
<Compile Include="../../src/GamePort/Game/JetpackBurst.cs"/>
<Compile Include="../../src/GamePort/Game/PlayerEnergy.cs"/>
<Compile Include="../../src/GamePort/Game/InvisibleGadget.cs"/>
<Compile Include="../../src/GamePort/Game/BubbleEffect.cs"/>
<Compile Include="../../src/GamePort/Game/BubbleMotion.cs"/>
<Compile Include="../../src/GamePort/Game/PlayerAppearance.cs"/>
<Compile Include="../../src/GamePort/Game/Vr01FloorState.cs"/>
<Compile Include="../../src/GamePort/Game/SceneCollision.cs"/>
<Compile Include="../../src/GamePort/Game/RecoveredMotion.cs"/>
<Compile Include="../../src/GamePort/Game/FixedStepClock.cs"/>
@@ -22,6 +22,10 @@
<Compile Include="../../src/GamePort/Game/JetpackBurst.cs"/>
<Compile Include="../../src/GamePort/Game/PlayerEnergy.cs"/>
<Compile Include="../../src/GamePort/Game/InvisibleGadget.cs"/>
<Compile Include="../../src/GamePort/Game/BubbleEffect.cs"/>
<Compile Include="../../src/GamePort/Game/BubbleMotion.cs"/>
<Compile Include="../../src/GamePort/Game/PlayerAppearance.cs"/>
<Compile Include="../../src/GamePort/Game/Vr01FloorState.cs"/>
<Compile Include="../../src/GamePort/Game/SceneCollision.cs"/>
<Compile Include="../../src/GamePort/Game/RecoveredMotion.cs"/>
<Compile Include="../../src/GamePort/Game/FixedStepClock.cs"/>
+83
View File
@@ -0,0 +1,83 @@
"""Guard original Bubble body boundaries and actual VR01 policy coverage."""
from pathlib import Path
import sys
import unittest
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / 'tools/binary'))
from bubble_body import LavaState, collect, floor_phase, lava_flash
class BubbleBodyTests(unittest.TestCase):
def test_source_identity_guards_and_vr01_virtual_filter(self):
report = collect(ROOT.parent / 'Original')
self.assertEqual(len(report['bodies']), 8)
self.assertEqual(len(report['sites']), 27)
self.assertEqual(len(report['tables']), 10)
bindings = {(int(t['table'], 16), int(t['slot'], 16)): int(t['target'], 16)
for t in report['tables']}
self.assertEqual(bindings[0x4cd740, 0x134], 0x475cd0)
self.assertEqual(bindings[0x4cd740, 0x130], 0x44e030)
self.assertEqual(bindings[0x4a373c, 0x37c], 0x472970)
self.assertTrue(all(int(b['va'], 16) - int(b['file_offset'], 16) == 0x400000
for b in report['bodies']))
def test_actual_vr01_lava_is_support_only_not_wall374(self):
report = collect(ROOT.parent / 'Original')
room = report['archives'][0]
self.assertEqual((room['polygon_count'], room['registered'], room['walls']), (80, 80, 60))
self.assertEqual([(s['id'], s['name'], s['vertices']) for s in room['shapes']], [(0, 'VRRoom', 60)])
self.assertEqual({p['corners'] for p in room['polygons']}, {3})
self.assertEqual({p['material'] for p in room['polygons']}, {0, 1, 2, 3, 4, 111})
self.assertTrue(all(p['texture'] is not None for p in room['polygons']))
lava = [p for p in room['polygons'] if p['material'] == 111]
self.assertEqual([p['polygon'] for p in lava], list(range(48, 54)))
self.assertTrue(all(not p['wall'] and not p['callback374'] for p in lava))
self.assertEqual(report['vr01_entities'].get('3SOL', 0), 0)
self.assertEqual(report['vr01_entities']['3ROC'], 1) # Dynamic eligibility remains a gate.
def test_bubble_bypasses_lava_damage_but_keeps_entry_sound_and_selector(self):
state, actions = floor_phase(LavaState(), 111, 0)
self.assertEqual(actions, ('sound39', 'retarget_existing_floor_loop_35'))
self.assertTrue(state.entered)
self.assertFalse(state.flashing)
self.assertEqual(floor_phase(state, 111, 0), (state, ()))
state, actions = floor_phase(state, 4, 0)
self.assertFalse(state.entered)
self.assertEqual(actions, ('retarget_existing_floor_loop_5',))
def test_lava_cleanup_mode_changes_damage_before_next_flash_tick(self):
bubble, _ = floor_phase(LavaState(), 111, 0)
state, actions = floor_phase(bubble, 111, -1)
self.assertEqual(actions, ('energy_minus5_common_helper', 'score_minus5_common_helper', 'cancel_mode1'))
self.assertTrue(state.flashing)
self.assertEqual(floor_phase(state, 111, -1), (state, ()))
state, color = lava_flash(LavaState(entered=True, flashing=True, timer=3.5), .5)
self.assertTrue(state.flashing) # Strict >4, not >=4.
self.assertEqual(color[1::2], (1., 1.))
state, color = lava_flash(state, .125)
self.assertFalse(state.flashing)
self.assertEqual(color, (1.,) * 4)
state, actions = floor_phase(state, 111, -1)
self.assertEqual(actions[0], 'energy_minus5_common_helper')
# FCOM precedes thefloat store: a sum just above4 clears the latch
# even when the persisted timer rounds to exactly4.
state, color = lava_flash(LavaState(flashing=True, timer=4), 2 ** -24)
self.assertEqual(state.timer, 4)
self.assertFalse(state.flashing)
self.assertEqual(color, (1.,) * 4)
def test_base_eligibility_and_linked_texture_gates(self):
original = LavaState()
for kwargs in ({'eligible': False}, {'integration': False}, {'polygon_present': False},
{'material_present': False}, {'texture_present': False}):
self.assertEqual(floor_phase(original, 111, -1, **kwargs), (original, ()))
_, actions = floor_phase(original, 111, -1)
self.assertEqual(actions[:2], ('sound39', 'sound190'))
# Current support is deliberately not an input: source consumes retained338.
with self.assertRaises(ValueError):
floor_phase(original, 120, -1)
if __name__ == '__main__':
unittest.main()
+96
View File
@@ -0,0 +1,96 @@
"""Original-byte guards and mode2 arithmetic projections, not native gameplay."""
from pathlib import Path
import math
import sys
import unittest
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT/'tools/binary'))
from bubble_motion import apply_step, collect, keyboard_step, ordinary_destination
class BubbleMotionTests(unittest.TestCase):
def test_source_spans_virtuals_constants_and_offsets(self):
report = collect(ROOT.parent/'Original')
self.assertEqual((len(report['bodies']),len(report['vtables'])), (11,8))
self.assertEqual(len(report['sites']),17)
self.assertTrue(all(int(b['va'],16)-int(b['file_offset'],16)==0x400000
for b in report['bodies']))
self.assertFalse(report['landing_mode_reset'])
def test_fire_is_bubble_throttle_without_ordinary_beam(self):
a = keyboard_step(0,0,.25,fire=True)
b = keyboard_step(0,0,.25,forward=True)
self.assertEqual(a,b)
self.assertEqual((a.speed,a.target_pitch), (30,-10))
self.assertEqual(keyboard_step(1340,0,.25,fire=True).speed,1350)
def test_mode2_turn_cap_release_and_forward_backward_pose_priority(self):
self.assertEqual(keyboard_step(0,49,.5,left=True,right=True).turn,50)
self.assertEqual(keyboard_step(0,-49,.5,right=True).turn,-50)
a = keyboard_step(100,20,.5)
self.assertEqual((a.turn,a.target_pitch,a.target_roll),(0,0,0))
b = keyboard_step(100,10,.1,forward=True,backward=True,left=True)
self.assertEqual((b.speed,b.target_pitch,b.target_roll),(112.5,-10,-5))
def test_grounded_input_decay_precedes_brake_and_can_cross_below_zero(self):
self.assertEqual(keyboard_step(100,0,.1,supported=True).speed,82.5)
self.assertEqual(keyboard_step(100,0,.1,supported=True,backward=True).speed,47.5)
self.assertEqual(keyboard_step(100,0,.1,supported=True,forward=True).speed,112.5)
crossed = keyboard_step(5,0,.1,supported=True).speed
self.assertEqual(crossed,-12.5)
self.assertEqual(keyboard_step(crossed,0,.1,supported=True).speed,0)
def test_coast_threshold_and_air_brake_do_not_start_reverse(self):
self.assertEqual(keyboard_step(1350,0,.1).speed,1332.5)
self.assertEqual(keyboard_step(1200,0,.1).speed,1200)
self.assertEqual(keyboard_step(5,0,.1,backward=True).speed,0)
self.assertEqual(keyboard_step(-5,0,.1,backward=True).speed,0)
def test_apply_preserves_vertical_and_pitch_scales_horizontal_only(self):
a = apply_step(100,0,0,60,(0,-12,10),.1)
self.assertAlmostEqual(a.velocity[2],50)
self.assertEqual(a.velocity[1],-12)
self.assertEqual((a.published_speed,a.sound,a.movement_mode),(100,None,2))
def test_supported_jump_direct_velocity_and_released_scalar_order(self):
a = apply_step(100,0,0,0,(0,-800,10),.1,supported=True)
self.assertEqual(a.velocity,(0,300,100))
self.assertEqual((a.published_speed,a.sound,a.movement_mode),(50,None,2))
b = apply_step(100,0,0,0,(0,-800,10),.1,supported=True,jump=True)
self.assertEqual(b.velocity,(0,900,100))
self.assertEqual((b.published_speed,b.sound),(100,106))
# No edge latch: a second supported apply also produces the high bounce.
self.assertEqual(apply_step(100,0,0,0,b.velocity,.1,supported=True,jump=True).sound,106)
def test_zero_incoming_velocity_suppresses_direct_yaw_and_side_only(self):
stopped = apply_step(100,50,0,0,(0,0,0),.1)
self.assertEqual((stopped.yaw,stopped.velocity),(0,(0,0,100)))
moving = apply_step(100,50,0,0,(0,1,0),.1)
self.assertEqual(moving.yaw,5)
self.assertNotEqual(moving.velocity[0],stopped.velocity[0])
for seconds in (-1,1,math.inf,math.nan):
with self.assertRaises(ValueError): apply_step(0,0,0,0,(0,0,0),seconds)
with self.assertRaises(ValueError): keyboard_step(0,0,seconds)
def test_cleanup_and_ground_no_input_do_not_invent_upright_reset(self):
report = collect(ROOT.parent/'Original')['handoff']
self.assertEqual(len(report['bodies']),6)
self.assertEqual(len(report['a20_raw_dword_occurrences']),6)
self.assertEqual(report['a20_direct_writes'],['0x4226cf','0x428045','0x42821a'])
self.assertIsNone(report['a20_consumer'])
self.assertFalse(report['derived_aliases_excluded'])
self.assertFalse(report['cleanup_resets_euler'])
self.assertFalse(report['ground_no_input_resets_euler'])
target = (-10.,42.,-12.5)
self.assertEqual(ordinary_destination(target,43,20),target)
self.assertEqual(ordinary_destination(target,43,20,accepted_ground_direction=True),(0,43,0))
def test_ordinary_air_handoff_targets_zero_pitch_but_retains_turn_lean(self):
target = (-10.,42.,-12.5)
self.assertEqual(ordinary_destination(target,43,20,airborne=True),(0,43,-20))
self.assertEqual(ordinary_destination(target,43,0,airborne=True),(0,43,0))
if __name__ == '__main__':
unittest.main()
+76
View File
@@ -0,0 +1,76 @@
from pathlib import Path
import hashlib
import json
import sys
import tempfile
import unittest
from unittest.mock import patch
ROOT = Path(__file__).resolve().parents[1]
ORIGINAL = ROOT.parent/'Original'
sys.path.insert(0, str(ROOT/'tools/extractors'))
from bubble_resources import ARCHIVE_SHA256, PAYLOAD_SHA256, RGBA_SHA256, export_bubble
from omt import FormatError
from png import read_png
@unittest.skipUnless(ORIGINAL.exists(), 'Original assets are local integration fixtures')
class BubbleResourceTests(unittest.TestCase):
def test_exact_canvas_pixels_and_source_provenance(self):
with tempfile.TemporaryDirectory() as directory:
output = Path(directory)/'bubble'
manifest = export_bubble(ORIGINAL, output)
self.assertEqual(manifest, json.loads((output/'bubble.json').read_text()))
self.assertEqual((manifest['schema'], manifest['source'], manifest['sourceSha256']),
(1, 'RetainedSprites.omt', ARCHIVE_SHA256))
self.assertEqual(len(manifest['textures']), 1)
entry = manifest['textures'][0]
self.assertEqual((entry['id'], entry['name'], entry['width'], entry['height']),
(1, 'orangebubble', 146, 146))
self.assertEqual((entry['sourceOffset'], entry['sourceBytes'], entry['sourceSha256']),
(0x17FCE, 66322, PAYLOAD_SHA256))
rgba = (output/entry['path']).read_bytes()
self.assertEqual((len(rgba), hashlib.sha256(rgba).hexdigest()), (146*146*4, RGBA_SHA256))
self.assertEqual(read_png(output/entry['png'])['rgba'], rgba)
self.assertEqual((rgba[3::4].count(0), rgba[3::4].count(255)), (5492, 15824))
def test_original_subtrees_and_ancestors_rejected_before_writes(self):
for output in (ORIGINAL, ORIGINAL/'omt/generated-bubble', ORIGINAL.parent):
with self.subTest(output=output), self.assertRaises(ValueError):
export_bubble(ORIGINAL, output)
def test_output_child_symlinks_cannot_overwrite_another_file(self):
with tempfile.TemporaryDirectory() as directory:
root = Path(directory)
target = root/'unchanged'
target.write_bytes(b'unchanged')
output = root/'bubble'
output.mkdir()
for name in ('canvas_1.rgba', 'canvas_1.png', 'bubble.json'):
(output/name).symlink_to(target)
with self.subTest(name=name), self.assertRaises(ValueError):
export_bubble(ORIGINAL, output)
self.assertEqual(target.read_bytes(), b'unchanged')
(output/name).unlink()
def test_bad_decoded_dimensions_or_pixels_rejected_before_output(self):
for canvas in (dict(width=1, height=1, rgba=b'\0'*4),
dict(width=146, height=146, rgba=b'\0'*(146*146*4))):
with tempfile.TemporaryDirectory() as directory:
output = Path(directory)/'bubble'
with patch('bubble_resources.read_canvas', return_value=canvas), self.assertRaises(FormatError):
export_bubble(ORIGINAL, output)
self.assertFalse(output.exists())
def test_bad_archive_identity_rejected_before_decode(self):
with tempfile.TemporaryDirectory() as directory:
output = Path(directory)/'bubble'
with patch('bubble_resources.digest', return_value='0'*64), \
patch('bubble_resources.read_canvas') as decoder, self.assertRaises(FormatError):
export_bubble(ORIGINAL, output)
decoder.assert_not_called()
self.assertFalse(output.exists())
if __name__ == '__main__':
unittest.main()