返回提交历史
Added
AutoMiningScript.Tests/BreadcrumbCompressionTests.cs
+106
-0
Modified
AutoMiningScript.Tests/CargoInventoryTests.cs
+152
-9
Modified
AutoMiningScript.Tests/DockingNavigationTests.cs
+74
-2
Modified
AutoMiningScript.Tests/NavigationDetourTests.cs
+25
-18
Modified
AutoMiningScript.Tests/ReturnStateTests.cs
+3
-2
Modified
AutoMiningScript.Tests/SavedMinerNavigationTests.cs
+2
-2
Added
AutoMiningScript.Tests/SorterSamplingTests.cs
+101
-0
Modified
AutoMiningScript/Core.cs
+1
-1
Modified
AutoMiningScript/FleetController.cs
+4
-1
Modified
AutoMiningScript/Flight.cs
+8
-3
Modified
AutoMiningScript/MinerController.cs
+23
-14
Modified
docs/VALIDATION.md
+21
-2
Added
docs/agent-debug/DEBUGGING.md
+115
-0
Added
docs/agent-debug/FULL_CYCLE_20260915.md
+51
-0
Added
docs/agent-debug/ORIGINAL_DEPLOYMENT_20260916.md
+25
-0
Added
tools/agent-debug/deploy_world.py
+121
-0
Added
tools/agent-debug/prepare_debug_world.py
+103
-0
Added
tools/agent-debug/tests/test_world_copy.py
+213
-0
Added
tools/agent-debug/trace_ams.py
+117
-0
SpaceEngineersModDev/AutoMiningScript
Fix return flight and sorter cargo accounting; add script-owned deployment tooling
908673d
代码差异
19 个文件
+1265
-54
@@ -0,0 +1,106 @@
1
using System;
2
using System.Collections.Generic;
3
using System.Reflection;
4
using Sandbox.ModAPI.Ingame;
5
using VRage.Game.ModAPI.Ingame.Utilities;
6
using VRageMath;
7
using Xunit;
8
using P=AutoMiningScript.Program;
9
10
namespace AutoMiningScript.Tests
11
{
12
public class BreadcrumbCompressionTests
13
{
14
static readonly BindingFlags Private=BindingFlags.Instance|BindingFlags.NonPublic;
15
static T Read<T>(object target,string name)=> (T)target.GetType().GetField(name,Private).GetValue(target);
16
static void Write(object target,string name,object value)=>target.GetType().GetField(name,Private).SetValue(target,value);
17
static void Call(object target,string name,params object[] arguments)=>target.GetType().GetMethod(name,Private).Invoke(target,arguments);
18
static List<Vector3D> Path(MinerStateTests.MinerRig r)=>Read<List<Vector3D>>(r.Miner,"breadcrumbs");
19
static MinerStateTests.MinerRig Rig()
20
{var r=new MinerStateTests.MinerRig();r.Task();r.State(P.FlightState.Transit);return r;}
21
static void Record(MinerStateTests.MinerRig r,Vector3D point)
22
{r.Position=point;Call(r.Miner,"RecordBreadcrumb");}
23
24
[Theory]
25
[InlineData(false)]
26
[InlineData(true)]
27
public void FiveKilometreStraightTravelRetainsBothEndpointsWithoutExhaustingTheBudget(bool smallNoise)
28
{
29
var r=Rig();var origin=new Vector3D(-67700,-123600,-162000);
30
for(int n=0;n<=500;n++)Record(r,origin+Vector3D.Right*(n*10.1)+Vector3D.Up*(smallNoise && n>1?Math.Sin(n)*.05:0));
31
Assert.Equal(P.FlightState.Transit,r.StateNow);Assert.Equal(2,Path(r).Count);
32
Assert.Equal(origin,Path(r)[0]);Assert.Equal(r.Position,Path(r)[1]);
33
}
34
35
[Theory]
36
[InlineData(90)]
37
[InlineData(180)]
38
[InlineData(1)]
39
public void ARealCornerOrReversalKeepsItsTurningPoint(double degrees)
40
{
41
var r=Rig();Record(r,Vector3D.Zero);Record(r,Vector3D.Right*11);Record(r,Vector3D.Right*22);
42
var corner=r.Position;var direction=new Vector3D(Math.Cos(degrees*Math.PI/180),Math.Sin(degrees*Math.PI/180),0);
43
Record(r,corner+direction*11);Record(r,corner+direction*22);
44
Assert.Equal(3,Path(r).Count);Assert.Equal(corner,Path(r)[1]);Assert.Equal(r.Position,Path(r)[2]);
45
}
46
47
[Fact]
48
public void AGradualCurveCannotAccumulateUnboundedDeviationFromRetainedChords()
49
{
50
var r=Rig();var samples=new List<Vector3D>();
51
// Adjacent headings differ by only 0.063 degrees; repeatedly refitting the
52
// last chord would otherwise hide an increasingly large circular arc.
53
for(int n=0;n<=300;n++)
54
{double angle=n*.0011;var point=new Vector3D(10000*Math.Sin(angle),10000*(1-Math.Cos(angle)),0);samples.Add(point);Record(r,point);}
55
Assert.Equal(P.FlightState.Transit,r.StateNow);Assert.InRange(Path(r).Count,20,127);
56
int index=0;
57
for(int n=1;n<Path(r).Count;n++)
58
{
59
var start=Path(r)[n-1];var end=Path(r)[n];var delta=end-start;
60
while(index<samples.Count)
61
{
62
var point=samples[index++];double t=Math.Max(0,Math.Min(1,Vector3D.Dot(point-start,delta)/delta.LengthSquared()));
63
Assert.InRange(Vector3D.Distance(point,start+delta*t),0,.200001);
64
if(point==end)break;
65
}
66
}
67
Assert.Equal(samples.Count,index);
68
}
69
70
[Fact]
71
public void RepeatedRealTurnsStillUseTheExisting128PointReturnBudget()
72
{
73
var r=Rig();var point=Vector3D.Zero;Record(r,point);
74
for(int n=1;n<=128;n++){point+=(n%2==0?Vector3D.Right:Vector3D.Up)*11;Record(r,point);}
75
Assert.Equal(128,Path(r).Count);Assert.Equal(P.FlightState.Returning,r.StateNow);
76
Assert.Equal(P.L.MinerRouteBudgetFull,Read<string>(r.Miner,"reason"));Assert.Equal(127,Read<int>(r.Miner,"returnIndex"));
77
}
78
79
[Fact]
80
public void RestoringACompressedPathKeepsItsPriorSegmentAndStartsANewBearing()
81
{
82
var r=Rig();Record(r,Vector3D.Zero);Record(r,Vector3D.Right*11);Record(r,Vector3D.Right*1000);
83
var saved=new MyIni();r.Miner.Save(saved);Assert.Equal(2,saved.Get("miner","BreadcrumbCount").ToInt32());
84
var restored=Rig();restored.Miner.Load(saved);Assert.Equal(Path(r),Path(restored));
85
restored.State(P.FlightState.Transit);Record(restored,Vector3D.Right*1011);Record(restored,Vector3D.Right*1022);
86
Assert.Equal(3,Path(restored).Count);Assert.Equal(Vector3D.Right*1000,Path(restored)[1]);
87
}
88
89
[Fact]
90
public void ReturningAlongACompressedSegmentStillRequiresFreshEnvelopeRays()
91
{
92
var r=Rig();for(int n=0;n<=200;n++)Record(r,Vector3D.Forward*(n*11));
93
r.State(P.FlightState.Returning);Write(r.Miner,"returnIndex",Path(r).Count-1);
94
r.Controller.Method("get_WorldMatrix",a=>MatrixD.CreateWorld(r.Position,Vector3D.Backward,Vector3D.Up));
95
bool ready=false;int rays=0;
96
r.Camera.Set("RaycastConeLimit",45f).Set("RaycastDistanceLimit",-1d)
97
.Method("get_WorldMatrix",a=>r.Controller.Value.WorldMatrix).Method("CanScan",a=>ready)
98
.Method("Raycast",a=>{rays++;return default(MyDetectedEntityInfo);});
99
var flight=Read<P.FlightController>(r.Miner,"flight");
100
for(int n=0;n<30;n++){r.Program.Now+=.05;Call(r.Miner,"ReturnHome",.05);}
101
Assert.Equal(0,rays);Assert.Equal(0,flight.CommandSpeed);Assert.All(r.Hardware.Thrusters,t=>Assert.Equal(0,t.ThrustOverridePercentage));
102
ready=true;for(int n=0;n<15;n++){r.Program.Now+=.05;Call(r.Miner,"ReturnHome",.05);}
103
Assert.True(rays>=18);Assert.True(flight.ScanClearance>0);Assert.True(flight.CommandSpeed>0);
104
}
105
}
106
}
@@ -27,6 +27,12 @@ namespace AutoMiningScript.Tests
27
27
return new Stub<IMyInventory>().Set("CurrentMass", (MyFixedPoint)mass)
28
28
.Set("CurrentVolume", (MyFixedPoint)volume).Set("MaxVolume", (MyFixedPoint)capacity)
29
29
.Method("get_ItemCount", a => items.Count)
30
.Method("GetItemAmount", a =>
31
{
32
MyFixedPoint amount=0;
33
foreach(var item in items)if(item.Type.Equals((MyItemType)a[0]))amount+=item.Amount;
34
return amount;
35
})
30
36
.Method("GetItems", a => { ((List<MyInventoryItem>)a[0]).AddRange(items); return null; });
31
37
}
32
38
static IMyTerminalBlock Block<T>(IMyCubeGrid grid, Stub<IMyInventory> inventory) where T : class, IMyTerminalBlock
@@ -87,20 +93,41 @@ namespace AutoMiningScript.Tests
87
93
}
88
94
89
95
[Fact]
90
public void TransportedIceStoneAndUraniumRemainUnloadableInAllThreeCargoBlockTypes()
96
public void TransportedOresIncludeSorterBuffersAndStillExcludeGeneratorSupplies()
91
97
{
92
98
var r = new Rig(); r.CargoItems.Add(Item("Ore", "Ice", 30));
93
99
var drill = new List<MyInventoryItem> { Item("Ore", "Stone", 20) };
94
100
var port = new List<MyInventoryItem> { Item("Ore", "Uranium", 10) };
101
var sorter = new List<MyInventoryItem> { Item("Ore", "Cobalt", 40) };
95
102
r.Hardware.InventoryBlocks.Add(Block<IMyShipDrill>(r.Program.Me.CubeGrid, Inventory(1, 100, 20, drill)));
96
103
r.Hardware.InventoryBlocks.Add(Block<IMyShipConnector>(r.Program.Me.CubeGrid, Inventory(1, 100, 10, port)));
104
r.Hardware.InventoryBlocks.Add(Block<IMyConveyorSorter>(r.Program.Me.CubeGrid, Inventory(1, 100, 40, sorter)));
97
105
r.Add<IMyGasGenerator>(100, 100, 500, Item("Ore", "Ice", 500));
98
r.Scan(); Assert.Equal(60, r.Resources.OreAmount); Assert.Equal(30, r.Resources.Ores["Ice"]);
106
r.Scan(); Assert.Equal(100, r.Resources.OreAmount); Assert.Equal(30, r.Resources.Ores["Ice"]);
107
Assert.Equal(40,r.Resources.Ores["Cobalt"]);
99
108
Assert.Equal(1, r.Resources.ServiceFlags); Assert.False(r.Resources.Empty);
100
r.CargoItems.Clear(); drill.Clear(); port.Clear(); r.Scan(); r.Scan();
109
r.CargoItems.Clear(); drill.Clear(); port.Clear(); sorter.Clear(); r.Scan(); r.Scan();
101
110
Assert.Equal(0, r.Resources.OreAmount); Assert.Equal(0, r.Resources.ServiceFlags); Assert.True(r.Resources.Empty);
102
111
}
103
112
113
[Theory]
114
[InlineData(0,false)]
115
[InlineData(.05,true)]
116
public void SorterOnlyOreIsNotEmptyAndFollowsTheConfiguredDepartureThreshold(double departureFill,bool departureReady)
117
{
118
var r=new Rig("[Cargo]\nDepartureFill="+departureFill.ToString(System.Globalization.CultureInfo.InvariantCulture));
119
var contents=new List<MyInventoryItem> {Item("Ore","Stone",1729.732172)};
120
var inventory=Inventory(.639999,1,1729.732172,contents);
121
r.Hardware.InventoryBlocks.Add(Block<IMyConveyorSorter>(r.Program.Me.CubeGrid,inventory));
122
r.Scan();r.Scan();
123
Assert.Equal(1729.732172,r.Resources.OreAmount,6);Assert.False(r.Resources.Empty);
124
Assert.Equal(1,r.Resources.ServiceFlags);Assert.Equal(.639999/101,r.Resources.Cargo,8);
125
Assert.Equal(departureReady,r.Resources.DepartureReady);
126
contents.Clear();inventory.Set("CurrentVolume",(MyFixedPoint)0).Set("CurrentMass",(MyFixedPoint)0);
127
r.Scan();Assert.False(r.Resources.Empty);r.Scan();
128
Assert.True(r.Resources.Empty);Assert.True(r.Resources.DepartureReady);Assert.Equal(0,r.Resources.ServiceFlags);
129
}
130
104
131
[Theory]
105
132
[InlineData(1)]
106
133
[InlineData(10)]
@@ -152,16 +179,21 @@ namespace AutoMiningScript.Tests
152
179
var r = new FleetStateTests.Rig(1, true); r.RegisterAll();
153
180
var minerGrid = new Stub<IMyCubeGrid>().Set("EntityId", 1000L).Value;
154
181
var blocks = new List<IMyTerminalBlock>(); int cargoTransfers = 0, supplyReads = 0, supplyTransfers = 0;
155
var destination = Inventory(0, 1000, 0, new List<MyInventoryItem>());
182
var received = new List<MyInventoryItem>();
183
var destination = Inventory(0, 1000, 0, received);
156
184
((List<IMyTerminalBlock>)typeof(P.FleetController).GetField("cargo", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(r.Fleet))
157
185
.Add(Block<IMyCargoContainer>(r.Program.Me.CubeGrid, destination));
158
foreach (var type in new[] { typeof(IMyCargoContainer), typeof(IMyShipDrill), typeof(IMyShipConnector), typeof(IMyReactor), typeof(IMyGasGenerator), typeof(IMyRefinery) })
186
foreach (var type in new[] { typeof(IMyCargoContainer), typeof(IMyShipDrill), typeof(IMyShipConnector), typeof(IMyConveyorSorter), typeof(IMyReactor), typeof(IMyGasGenerator), typeof(IMyRefinery) })
159
187
{
160
bool transport = type == typeof(IMyCargoContainer) || type == typeof(IMyShipDrill) || type == typeof(IMyShipConnector);
161
var contents = new List<MyInventoryItem> { Item("Ore", "Ice", 10) };
188
bool transport = type == typeof(IMyCargoContainer) || type == typeof(IMyShipDrill) || type == typeof(IMyShipConnector) || type == typeof(IMyConveyorSorter);
189
var contents = new List<MyInventoryItem> { Item("Ore", "Ice", 10), Item("Ingot", "Uranium", 20), Item("Component", "SteelPlate", 30) };
162
190
var inventory = Inventory(1, 100, 10, contents).Method("CanTransferItemTo", a => true)
163
191
.Method("GetItems", a => { if (!transport) supplyReads++; ((List<MyInventoryItem>)a[0]).AddRange(contents); return null; })
164
.Method("TransferItemTo", a => { if (transport) cargoTransfers++; else supplyTransfers++; return true; });
192
.Method("TransferItemTo", a =>
193
{
194
if (transport) cargoTransfers++; else supplyTransfers++;
195
var index=(int)a[1];received.Add(contents[index]);contents.RemoveAt(index);return true;
196
});
165
197
blocks.Add((IMyTerminalBlock)typeof(CargoInventoryTests).GetMethod("Block", BindingFlags.NonPublic | BindingFlags.Static)
166
198
.MakeGenericMethod(type).Invoke(null, new object[] { minerGrid, inventory }));
167
199
}
@@ -175,7 +207,118 @@ namespace AutoMiningScript.Tests
175
207
return null;
176
208
}).Value);
177
209
typeof(P.FleetController).GetMethod("UnloadOne", BindingFlags.NonPublic | BindingFlags.Instance).Invoke(r.Fleet, new object[0]);
178
Assert.Equal(3, cargoTransfers); Assert.Equal(0, supplyReads); Assert.Equal(0, supplyTransfers);
210
Assert.Equal(4, cargoTransfers); Assert.Equal(0, supplyReads); Assert.Equal(0, supplyTransfers);
211
Assert.Equal(40, (double)destination.Value.GetItemAmount(MyItemType.MakeOre("Ice")));
212
Assert.Equal(0, (double)destination.Value.GetItemAmount(MyItemType.MakeIngot("Uranium")));
213
Assert.Equal(0, (double)destination.Value.GetItemAmount(MyItemType.MakeComponent("SteelPlate")));
214
}
215
216
sealed class UnloadRig
217
{
218
public sealed class Sink
219
{
220
public Stub<IMyInventory> Inventory;
221
public readonly List<MyInventoryItem> Items=new List<MyInventoryItem>();
222
public double Room;
223
public int Calls;
224
}
225
public readonly FleetStateTests.Rig Fleet=new FleetStateTests.Rig(1,true);
226
public readonly List<MyInventoryItem> Items=new List<MyInventoryItem> {Item("Ore","Stone",10)};
227
public readonly List<Sink> Sinks=new List<Sink>();
228
public readonly Stub<IMyInventory> Source;
229
public bool ApiResult=true;
230
public UnloadRig(bool sorter=false)
231
{
232
Fleet.RegisterAll();
233
Source=Inventory(10,100,10,Items).Method("CanTransferItemTo",a=>true).Method("TransferItemTo",a=>
234
{
235
foreach(var sink in Sinks)if(ReferenceEquals(sink.Inventory.Value,a[0]))
236
{
237
sink.Calls++;
238
// SE reports an accepted transfer request even when its actual amount is zero.
239
int index=(int)a[1];var item=Items[index];double moved=Math.Min((double)item.Amount,sink.Room);
240
if(moved>0)
241
{
242
sink.Room-=moved;sink.Items.Add(Item("Ore",item.Type.SubtypeId,moved));
243
if(moved==(double)item.Amount)Items.RemoveAt(index);
244
else Items[index]=Item("Ore",item.Type.SubtypeId,(double)item.Amount-moved);
245
}
246
return ApiResult;
247
}
248
throw new InvalidOperationException("Unknown transfer destination");
249
});
250
var grid=new Stub<IMyCubeGrid>().Set("EntityId",1000L).Value;
251
Field<Dictionary<long,List<IMyTerminalBlock>>>("connectedBlocks")[1000]=new List<IMyTerminalBlock> {sorter?Block<IMyConveyorSorter>(grid,Source):Block<IMyShipDrill>(grid,Source)};
252
}
253
T Field<T>(string name) => (T)typeof(P.FleetController).GetField(name,BindingFlags.NonPublic|BindingFlags.Instance).GetValue(Fleet.Fleet);
254
public Sink Add(double room)
255
{
256
var sink=new Sink {Room=room};sink.Inventory=Inventory(room==0?100:0,room==0?100:room,0,sink.Items);
257
Sinks.Add(sink);Field<List<IMyTerminalBlock>>("cargo").Add(Block<IMyCargoContainer>(Fleet.Program.Me.CubeGrid,sink.Inventory));return sink;
258
}
259
public double LastProgress => Field<Dictionary<string,double>>("unloadProgress")[Fleet.Miners[0].Id];
260
public void Run(double now)
261
{
262
Fleet.Program.Now=now;
263
typeof(P.FleetController).GetMethod("UnloadOne",BindingFlags.NonPublic|BindingFlags.Instance).Invoke(Fleet.Fleet,new object[0]);
264
}
265
public double Remaining => (double)Source.Value.GetItemAmount(MyItemType.MakeOre("Stone"));
266
public static double Received(Sink sink) => (double)sink.Inventory.Value.GetItemAmount(MyItemType.MakeOre("Stone"));
267
}
268
269
[Fact]
270
public void SuccessfulNoOpAtFullInventoryContinuesToTheNextEmptyInventory()
271
{
272
var r=new UnloadRig();var full=r.Add(0);var empty=r.Add(100);
273
r.Run(50);
274
Assert.Equal(1,full.Calls);Assert.Equal(1,empty.Calls);
275
Assert.Equal(0,UnloadRig.Received(full));Assert.Equal(10,UnloadRig.Received(empty));
276
Assert.Equal(0,r.Remaining);Assert.Equal(50,r.LastProgress);
277
}
278
279
[Theory]
280
[InlineData(true)]
281
[InlineData(false)]
282
public void NoTransferredOreNeverRefreshesProgressRegardlessOfApiReturn(bool apiResult)
283
{
284
var r=new UnloadRig {ApiResult=apiResult};var full=r.Add(0);
285
r.Run(50);
286
Assert.Equal(1,full.Calls);Assert.Equal(10,r.Remaining);Assert.Equal(0,r.LastProgress);
287
Assert.Contains(P.L.F(P.L.FleetUnloadBlocked,r.Fleet.Miners[0].Id),r.Fleet.Fleet.Diagnostics);
288
}
289
290
[Fact]
291
public void PartialTransfersCountAsProgressWithoutRequiringTheWholeStackToFit()
292
{
293
var r=new UnloadRig();var small=r.Add(3);var second=r.Add(100);
294
r.Run(50);
295
Assert.Equal(3,UnloadRig.Received(small));Assert.Equal(7,r.Remaining);
296
Assert.Equal(0,second.Calls);Assert.Equal(50,r.LastProgress);
297
r.Run(60);
298
Assert.Equal(2,small.Calls);Assert.Equal(7,UnloadRig.Received(second));
299
Assert.Equal(0,r.Remaining);Assert.Equal(60,r.LastProgress);
300
}
301
302
[Fact]
303
public void OreQuantityCheckHandlesSeveralStacksOfTheSameType()
304
{
305
var r=new UnloadRig();r.Items.Clear();r.Items.Add(Item("Ore","Stone",6));r.Items.Add(Item("Ore","Stone",4));
306
var empty=r.Add(100);r.Run(50);
307
Assert.Equal(2,empty.Calls);Assert.Equal(10,UnloadRig.Received(empty));
308
Assert.Equal(0,r.Remaining);Assert.Equal(50,r.LastProgress);
309
}
310
311
[Fact]
312
public void FleetEmptiesResidualSorterOreIntoTheNextAvailableMotherInventoryWithoutTakingUraniumIngots()
313
{
314
var r=new UnloadRig(true);r.Items.Clear();
315
r.Items.Add(Item("Ore","Stone",1729.732172));r.Items.Add(Item("Ingot","Uranium",20));
316
var full=r.Add(0);var receiver=r.Add(2000);r.Run(50);
317
Assert.Equal(1,full.Calls);Assert.Equal(1,receiver.Calls);
318
Assert.Equal(1729.732172,UnloadRig.Received(receiver),6);Assert.Equal(0,r.Remaining);
319
Assert.Equal(20,(double)r.Source.Value.GetItemAmount(MyItemType.MakeIngot("Uranium")));
320
Assert.Equal(0,(double)receiver.Inventory.Value.GetItemAmount(MyItemType.MakeIngot("Uranium")));
321
Assert.Equal(50,r.LastProgress);
179
322
}
180
323
}
181
324
}
@@ -92,7 +92,7 @@ namespace AutoMiningScript.Tests
92
92
public void Tick(double dt=.05,bool integrate=false)
93
93
{
94
94
R.Program.Now+=dt;Dock.Position+=Dock.Velocity*dt;Dock.Center+=Dock.Velocity*dt;Dock.ReceivedAt=R.Program.Now;
95
string method=R.StateNow==P.FlightState.Holding?"Waiting":R.StateNow==P.FlightState.Returning?"ReturnHome":R.StateNow==P.FlightState.DockAlign?"DockAlign":R.StateNow==P.FlightState.DockApproach?"DockApproach":R.StateNow==P.FlightState.DockRetreat?"DockRetreat":null;
95
string method=R.StateNow==P.FlightState.Departing?"Departure":R.StateNow==P.FlightState.Holding?"Waiting":R.StateNow==P.FlightState.Returning?"ReturnHome":R.StateNow==P.FlightState.DockAlign?"DockAlign":R.StateNow==P.FlightState.DockApproach?"DockApproach":R.StateNow==P.FlightState.DockRetreat?"DockRetreat":null;
96
96
if(method==null)return;
97
97
Call(R.Miner,method,dt);States.Add(R.StateNow);
98
98
if(!integrate || Connected)return;
@@ -861,7 +861,7 @@ namespace AutoMiningScript.Tests
861
861
Write(r.R.Miner,"returnIndex",4);r.R.Position=r.Contact+Vector3D.Forward*100;
862
862
r.Orientation=MatrixD.CreateWorld(Vector3D.Zero,Vector3D.Backward,Vector3D.Up);r.Velocity=Vector3D.Backward*4;
863
863
bool passed=false;
864
for(int n=0;n<1200 && Read<int>(r.R.Miner,"returnIndex")>0;n++)
864
for(int n=0;n<1200 && r.R.Position.Z<r.Contact.Z-70;n++)
865
865
{
866
866
r.Tick(.05,true);
867
867
if(r.R.Position.Z>r.Contact.Z-75) {passed=true;Assert.True(r.Velocity.Length()>1,r.Reason);}
@@ -880,6 +880,78 @@ namespace AutoMiningScript.Tests
880
880
Assert.Equal(corner,Read<Vector3D>(r.Flight,"routeTarget"));
881
881
}
882
882
883
static DockRig LongDeparture(double cruise=15)
884
{
885
var r=new DockRig();r.Mass=10999.4;r.R.Hardware.Radius=4.63146;
886
r.R.Hardware.BodyMin=new Vector3D(-2.25,-1.75,-2.25);r.R.Hardware.BodyMax=new Vector3D(2.25,1.25,2.25);
887
r.R.Hardware.BodyHalfSize=new Vector3D(2.25,1.75,2.25);
888
r.R.Program.Config=new P.Settings("[Flight]\nCruiseSpeed="+cruise.ToString(System.Globalization.CultureInfo.InvariantCulture),"miner",r.R.Program.Config.Id);
889
r.Dock.ApproachDistance=100;r.Dock.LaneClearance=130;r.R.Position=r.Contact;
890
Write(r.R.Miner,"laneKind","depart");r.R.State(P.FlightState.Departing);
891
return r;
892
}
893
894
[Theory]
895
[InlineData(12)]
896
[InlineData(15)]
897
public void ALongDepartureUsesCruiseSpeedAfterItsScannedAccelerationRun(double cruise)
898
{
899
var r=LongDeparture(cruise);double began=r.R.Program.Now,peak=0;
900
for(int n=0;n<800 && r.R.StateNow==P.FlightState.Departing;n++)
901
{r.Tick(.05,true);peak=Math.Max(peak,r.Velocity.Length());}
902
Assert.Equal(P.FlightState.Transit,r.R.StateNow);Assert.True(r.Rays>=18);
903
Assert.InRange(peak,cruise*.9,cruise+.1);
904
Assert.True(r.R.Program.Now-began<35,"The 136m departure retained its old 2m/s cap.");
905
}
906
907
[Fact]
908
public void FasterDepartureStillNeedsFreshCameraClearance()
909
{
910
var r=LongDeparture();r.CamerasReady=false;var start=r.R.Position;
911
for(int n=0;n<150;n++)r.Tick(.05,true);
912
Assert.Equal(P.FlightState.Departing,r.R.StateNow);Assert.Equal(0,r.Rays);
913
Assert.InRange(Vector3D.Distance(start,r.R.Position),0,.001);Assert.Equal(0,r.Flight.CommandSpeed);
914
}
915
916
[Fact]
917
public void FasterDepartureBrakesBeforeAnActualObstacleOnItsExitAxis()
918
{
919
var r=LongDeparture();var start=r.R.Position;var obstacle=start+r.Dock.Forward*30;
920
r.Hit=end=>SphereHit(r,obstacle,2,end);
921
for(int n=0;n<500;n++)
922
{
923
r.Tick(.05,true);
924
Assert.True(Vector3D.Dot(r.R.Position-start,r.Dock.Forward)<25.75,"The hull passed the obstacle clearance boundary.");
925
}
926
Assert.True(r.Rays>0);Assert.True(r.Flight.CommandSpeed<.1);Assert.True(r.Velocity.Length()<.1);
927
Assert.Equal(P.FlightState.Departing,r.R.StateNow);
928
}
929
930
[Theory]
931
[InlineData(1d/60)]
932
[InlineData(.05)]
933
public void TenMetreReturnSamplesAdvanceAcrossAWeakThrusterBrakingHorizon(double dt)
934
{
935
var r=LongDeparture();r.R.State(P.FlightState.Returning);Write(r.R.Miner,"lane","");
936
foreach(var thrust in r.R.Hardware.Thrusters)((Stub<IMyThrust>)RemotingServices.GetRealProxy(thrust)).Set("MaxEffectiveThrust",28800f);
937
var path=Read<List<Vector3D>>(r.R.Miner,"breadcrumbs");path.Clear();
938
for(int n=0;n<=60;n++)path.Add(r.Contact+Vector3D.Forward*(300+n*10));
939
Write(r.R.Miner,"returnIndex",60);r.R.Position=r.Contact+Vector3D.Forward*950;
940
r.Orientation=MatrixD.CreateWorld(Vector3D.Zero,Vector3D.Backward,Vector3D.Up);
941
r.Flight.BrakeAcceleration=2.618;double lowest=double.MaxValue,peak=0;var trace=new List<string>();
942
for(int n=0;n<60/dt && r.R.Position.Z<r.Contact.Z-650;n++)
943
{
944
r.Tick(dt,true);peak=Math.Max(peak,r.Velocity.Length());
945
if(n%(int)Math.Round(1/dt)==0)trace.Add("t="+n*dt+" v="+r.Velocity.Length()+" cmd="+r.Flight.CommandSpeed+" dist="+Vector3D.Distance(r.Flight.RouteTarget,r.R.Position)+" clear="+r.Flight.ScanClearance+" brake="+r.Flight.BrakeAcceleration+" index="+Read<int>(r.R.Miner,"returnIndex"));
946
if(r.R.Position.Z>r.Contact.Z-800)lowest=Math.Min(lowest,r.Velocity.Length());
947
}
948
Assert.True(r.R.Position.Z>=r.Contact.Z-650);Assert.True(r.Rays>=18);
949
// A coarse update cadence can correctly brake for an unfinished envelope scan.
950
// Neither cadence should retain the old 10m/s return cap or stop at every sample.
951
Assert.True(peak>10.5 && lowest>1,"peak="+peak+" lowest="+lowest+"\n"+string.Join("\n",trace));
952
Assert.InRange(peak,0,15.1);Assert.InRange(lowest,0,15.1);
953
}
954
883
955
[Fact]
884
956
public void DepartureKeepsItsConnectedRollUntilClearOfTheMother()
885
957
{
@@ -22,7 +22,7 @@ namespace AutoMiningScript.Tests
22
22
public Vector3D Position,Velocity,Gravity;
23
23
public double Travel;
24
24
public bool Collided,Turned;
25
public bool TurnedWithoutCoverageGap;
25
public bool TurnedOffRouteWithoutCoverageGap;
26
26
public readonly List<string> Turns=new List<string>();
27
27
public Func<Vector3D,bool> SelfShadow;
28
28
public int SelfHits,PartialSelfHits;
@@ -76,14 +76,14 @@ namespace AutoMiningScript.Tests
76
76
R.Ship.Cameras.Add(camera.Value);
77
77
}
78
78
}
79
public bool Step(Vector3D target,double speed=6,bool allowDetour=true)
79
public bool Step(Vector3D target,double speed=6,bool allowDetour=true,bool faceTravel=true)
80
80
{
81
81
const double dt=.05;R.Program.Now+=dt;
82
82
var before=ScanState;
83
83
var requestedBefore=Read<bool>("hasDetour")?Read<Vector3D>("detour"):target;
84
84
var aim=requestedBefore-Position;
85
85
requestedBefore=Position+P.Data.Unit(aim,R.Orientation.Forward)*Math.Max(aim.Length(),R.Ship.Radius*3+5);
86
bool arrived=R.Flight.Move(target,Vector3D.Zero,Vector3D.Forward,Vector3D.Up,speed,.4,true,dt,true,allowDetour);
86
bool arrived=R.Flight.Move(target,Vector3D.Zero,Vector3D.Forward,Vector3D.Up,speed,.4,true,dt,faceTravel,allowDetour);
87
87
var after=ScanState;
88
88
if(before!=after)Record(after+" "+R.Flight.CameraDiagnostics);
89
89
if(Read<bool>("choosingRoute"))candidates[Read<int>("detourAttempts")%26]=after+" "+R.Flight.CameraDiagnostics;
@@ -92,11 +92,11 @@ namespace AutoMiningScript.Tests
92
92
if(turn>.001)
93
93
{
94
94
Turned=true;var required=Read<bool>("scanFailed")?Read<Vector3D>("cameraTarget"):requestedBefore;
95
// Evaluate the old hull pose and geometric field of view only.
96
// Depleted charge or a previously self-occluded camera cannot
97
// justify rotating a direction that already has coverage.
95
// Travel may turn the hull onto its active leg. Extra camera-specific
96
// turns still need a geometric gap rather than depleted charge.
98
97
var coverage=R.Ship.Cameras.Select(c=>c.EntityId+":"+Covers(c.WorldMatrix,required)).ToArray();
99
int available=R.Ship.Cameras.Count(c=>Covers(c.WorldMatrix,required));TurnedWithoutCoverageGap|=available>0;
98
int available=R.Ship.Cameras.Count(c=>Covers(c.WorldMatrix,required));
99
TurnedOffRouteWithoutCoverageGap|=available>0 && (!faceTravel || Vector3D.Dot(desired.Forward,P.Data.Unit(aim,desired.Forward))<.99999);
100
100
Turns.Add("t="+R.Program.Now+" angle="+turn+" requested="+required+" geometric coverage="+string.Join(",",coverage)+" "+after);
101
101
}
102
102
Vector3D force=Vector3D.Zero;foreach(var t in R.Ship.Thrusters)force+=t.WorldMatrix.Backward*t.MaxEffectiveThrust*t.ThrustOverridePercentage;
@@ -116,19 +116,20 @@ namespace AutoMiningScript.Tests
116
116
117
117
[Theory]
118
118
[InlineData(0)] [InlineData(1)] [InlineData(2)] [InlineData(3)] [InlineData(4)] [InlineData(5)]
119
public void NavigationUsesEachInstalledDirectionWithoutTurningTheHull(int axis)
119
public void TravelFacesItsActualLegEvenWhenAnInstalledSideOrRearCameraAlreadyCoversIt(int axis)
120
120
{
121
121
var directions=new[]{Vector3D.Right,Vector3D.Left,Vector3D.Up,Vector3D.Down,Vector3D.Forward,Vector3D.Backward};
122
122
var w=new World();for(int n=0;n<30;n++)w.Step(directions[axis]*100);
123
Assert.False(w.Turned,w.Diagnostics);Assert.True(w.Rays[axis]>0,w.Diagnostics);Assert.True(w.Travel>1,w.Diagnostics);
123
Assert.True(Vector3D.Dot(w.R.Orientation.Forward,directions[axis])>.99999,w.Diagnostics);
124
Assert.True(w.Rays[axis]>0,w.Diagnostics);Assert.True(w.Travel>1,w.Diagnostics);
124
125
}
125
126
126
127
[Fact]
127
public void AnInstalledUnchargedSideCameraWaitsInsteadOfTurningToTheFrontCamera()
128
public void ScanCoverageWaitsForAnInstalledSideCameraWithoutRotatingForCharge()
128
129
{
129
var w=new World();w.Charged[0]=false;for(int n=0;n<20;n++)w.Step(Vector3D.Right*100);
130
var w=new World();w.Charged[0]=false;for(int n=0;n<20;n++)w.Step(Vector3D.Right*100,faceTravel:false);
130
131
Assert.False(w.Turned,w.Diagnostics);Assert.InRange(w.Travel,0,.001);Assert.Equal(0,w.Rays.Sum());
131
w.Charged[0]=true;for(int n=0;n<30;n++)w.Step(Vector3D.Right*100);
132
w.Charged[0]=true;for(int n=0;n<30;n++)w.Step(Vector3D.Right*100,faceTravel:false);
132
133
Assert.False(w.Turned,w.Diagnostics);Assert.True(w.Travel>1,w.Diagnostics);
133
134
}
134
135
@@ -140,7 +141,7 @@ namespace AutoMiningScript.Tests
140
141
var target=new Vector3D(15,0,-65);bool arrived=false;
141
142
for(int n=0;n<6000 && !arrived;n++){arrived=w.Step(target);Assert.False(w.Collided,w.Diagnostics);}
142
143
Assert.True(arrived,w.Diagnostics);Assert.NotEmpty(w.Waypoints);Assert.InRange(w.Travel,60,150);
143
Assert.False(w.TurnedWithoutCoverageGap,w.Diagnostics);
144
Assert.False(w.TurnedOffRouteWithoutCoverageGap,w.Diagnostics);
144
145
if(!sixCameras)Assert.True(w.Turned,w.Diagnostics);
145
146
if(sixCameras)Assert.True(w.Rays.Count(n=>n>0)>=3,w.Diagnostics);
146
147
Assert.True(w.Waypoints.Any(p=>Math.Abs(p.Y)>4),w.Diagnostics);
@@ -167,13 +168,14 @@ namespace AutoMiningScript.Tests
167
168
{
168
169
var w=new World();
169
170
w.Obstacles.Add(new BoundingBoxD(new Vector3D(-30,-3,-12),new Vector3D(30,3,-3.4)));
170
// A lens housing shadows the upper-right edge of the view, while
171
// central and other directional rays still return actual world hits.
172
w.SelfShadow=v=>v.Y>2 && v.X>v.Y*1.05;
171
// Hold the configured hull attitude while testing a narrow housing shadow
172
// beside the local +Y axis. Central and other directional rays are clear.
173
// Once an alternate leg is approved, travel acquires its usual heading.
174
w.SelfShadow=v=>v.Y>2 && v.X>v.Y*.05 && v.X<v.Y*.15;
173
175
var target=new Vector3D(15,0,-65);bool arrived=false;
174
176
for(int n=0;n<6000 && !arrived;n++)
175
177
{
176
arrived=w.Step(target);
178
arrived=w.Step(target,faceTravel:w.Waypoints.Count>0);
177
179
Assert.False(w.Collided,w.Diagnostics);
178
180
if(w.PartialSelfHits>0 && w.Waypoints.Count==0)Assert.Equal(0,w.R.Flight.CommandSpeed);
179
181
}
@@ -253,7 +255,7 @@ namespace AutoMiningScript.Tests
253
255
for(int n=0;n<500 && !approved;n++)
254
256
{
255
257
int before=(int)typeof(P.FlightController).GetField("detourAttempts",flags).GetValue(r.Flight);
256
var centre=r.Ship.CameraAttitude(r.Flight.RouteTarget,Vector3D.Up);
258
var centre=P.Data.Frame(Vector3D.Zero,r.Flight.RouteTarget,Vector3D.Up);
257
259
bool centreSupported=r.Flight.CanSupport(centre.Forward,centre.Up,.1);
258
260
r.Program.Now+=.05;
259
261
r.Flight.Move(target,Vector3D.Zero,Vector3D.Forward,Vector3D.Up,6,.4,true,.05,true);
@@ -262,6 +264,11 @@ namespace AutoMiningScript.Tests
262
264
Assert.True(Math.Abs(localGravity.Z)<=1.40001,"An envelope-camera turn must retain the 30% hover reserve: "+localGravity+" / "+r.Flight.Problem);
263
265
int after=(int)typeof(P.FlightController).GetField("detourAttempts",flags).GetValue(r.Flight);
264
266
if(centreSupported && after>before && r.Flight.Problem==P.L.F(P.L.MinerHoverReserve,30d))rejectedEnvelopeTurn=true;
267
// Forward travel cannot use the old side-facing cruise workaround.
268
// Restore a usable forward view only after verifying that the unsafe
269
// envelope turn was rejected and the current hover stayed supported.
270
if(rejectedEnvelopeTurn && r.Ship.Cameras.Count==2)
271
r.Ship.Cameras.Add(r.MakeCamera(99,()=>100000,()=>default(MyDetectedEntityInfo)).Value);
265
272
r.Orientation=desired.GetOrientation();
266
273
approved=!(bool)typeof(P.FlightController).GetField("choosingRoute",flags).GetValue(r.Flight);
267
274
}
@@ -78,14 +78,15 @@ namespace AutoMiningScript.Tests
78
78
}
79
79
80
80
[Fact]
81
public void NearPortWaitingUsesItsCoveredEscapeRouteWithoutUnnecessaryRotation()
81
public void NearPortWaitingFacesItsEscapeRouteAndWaitsForCompleteCameraClearance()
82
82
{
83
83
var r = new MinerStateTests.MinerRig(); var dock = Waiting(r);
84
84
r.Position = Vector3D.Right * 10;int rays=0;
85
85
r.Camera.Method("Raycast",a=>{rays++;return default(MyDetectedEntityInfo);});Step(r, dock);
86
86
Assert.False(Read<bool>(r.Miner, "waitingAligning"));
87
87
Assert.True(r.Camera.Value.CanScan(dock.WaitingLocal));
88
Assert.True(Vector3D.Dot(Desired(r).Forward,Vector3D.Forward) > .999);
88
Assert.True(Vector3D.Dot(Desired(r).Forward,Vector3D.Normalize(dock.WaitingLocal-r.Position)) > .99999);
89
Assert.True(Vector3D.Dot(Desired(r).Up,Vector3D.Up) > .99999);
89
90
var flight=Read<P.FlightController>(r.Miner,"flight");
90
91
Assert.True(rays>0);Assert.Equal(dock.WaitingLocal,flight.RouteTarget);
91
92
Assert.True(Vector3D.Dot(Read<Vector3D>(flight,"scanDirection"),Vector3D.Normalize(dock.WaitingLocal-r.Position))>.999);
@@ -103,7 +103,7 @@ namespace AutoMiningScript.Tests
103
103
for(int n=-5;n<=5;n++)w.Obstacles.Add(new BoundingBoxD(new Vector3D(n*4-.2,-3,front-.3),new Vector3D(n*4+.2,3,front)));
104
104
}
105
105
var target=new Vector3D(15,0,-75);bool arrived=false;double gap=HullGap(w);int highestCandidate=0;
106
w.Step(target);Assert.False(w.Turned,w.Diagnostics);
106
w.Step(target);Assert.True(Vector3D.Dot(w.R.Orientation.Forward,Vector3D.Normalize(target))>.99999,w.Diagnostics);
107
107
for(int n=0;n<7000 && !arrived;n++)
108
108
{
109
109
arrived=w.Step(target);gap=Math.Min(gap,HullGap(w));highestCandidate=Math.Max(highestCandidate,Read<int>(w,"detourAttempts"));
@@ -111,7 +111,7 @@ namespace AutoMiningScript.Tests
111
111
" waypoint="+w.R.Flight.RouteTarget+" / "+w.R.Flight.Problem+" / "+w.R.Flight.CameraDiagnostics);
112
112
}
113
113
Assert.True(arrived,w.Diagnostics);Assert.NotEmpty(w.Waypoints);Assert.True(used.Count>=3,w.Diagnostics);
114
Assert.False(w.TurnedWithoutCoverageGap,w.Diagnostics);Assert.False(w.Collided,w.Diagnostics);
114
Assert.False(w.TurnedOffRouteWithoutCoverageGap,w.Diagnostics);Assert.False(w.Collided,w.Diagnostics);
115
115
Assert.InRange(w.Travel,70,210);
116
116
Assert.True(w.Waypoints.Any(p=>Math.Abs(p.Y)>4),"Failed to choose a full-body opening; max candidate="+highestCandidate+"\n"+w.Diagnostics);
117
117
}
@@ -0,0 +1,101 @@
1
using System;
2
using System.Collections.Generic;
3
using System.Reflection;
4
using Sandbox.ModAPI.Ingame;
5
using VRage;
6
using VRage.Game.ModAPI.Ingame;
7
using Xunit;
8
using P=AutoMiningScript.Program;
9
10
namespace AutoMiningScript.Tests
11
{
12
public class SorterSamplingTests
13
{
14
static readonly BindingFlags Private=BindingFlags.Instance|BindingFlags.NonPublic;
15
static void Call(object target,string name)=>target.GetType().GetMethod(name,Private).Invoke(target,null);
16
static void Put(List<MyInventoryItem> items,double amount)
17
{
18
items.Clear();if(amount<=0)return;object value=default(MyInventoryItem);
19
typeof(MyInventoryItem).GetField("Type").SetValue(value,MyItemType.MakeOre("Stone"));
20
typeof(MyInventoryItem).GetField("Amount").SetValue(value,(MyFixedPoint)amount);
21
items.Add((MyInventoryItem)value);
22
}
23
sealed class Rig
24
{
25
public readonly MinerStateTests.MinerRig R=new MinerStateTests.MinerRig();
26
public readonly List<MyInventoryItem> First=new List<MyInventoryItem>(),Second=new List<MyInventoryItem>(),Port=new List<MyInventoryItem>(),Buffer=new List<MyInventoryItem>();
27
public readonly Stub<IMyConveyorSorter> Sorter;
28
public Rig()
29
{
30
R.Task();R.Hardware.InventoryBlocks.Clear();
31
Add<IMyShipDrill>(First);Add<IMyShipDrill>(Second);Add<IMyShipConnector>(Port);
32
Sorter=Add<IMyConveyorSorter>(Buffer).Set("Enabled",true).Set("DrainAll",true);
33
R.Hardware.SetSampling(true);
34
}
35
Stub<T> Add<T>(List<MyInventoryItem> items) where T:class,IMyTerminalBlock
36
{
37
var inventory=new Stub<IMyInventory>().Set("CurrentMass",(MyFixedPoint)0).Set("CurrentVolume",(MyFixedPoint)0).Set("MaxVolume",(MyFixedPoint)100)
38
.Method("get_ItemCount",a=>items.Count).Method("GetItems",a=>{((List<MyInventoryItem>)a[0]).AddRange(items);return null;});
39
var block=new Stub<T>().Set("CubeGrid",R.Program.Me.CubeGrid).Set("HasInventory",true).Set("InventoryCount",1).Method("GetInventory",a=>inventory.Value);
40
R.Hardware.InventoryBlocks.Add(block.Value);return block;
41
}
42
public void Amounts(double first,double second,double buffer)
43
{Put(First,first);Put(Second,second);Put(Buffer,buffer);}
44
public void Scan(P.FlightState state=P.FlightState.Drilling)
45
{R.Program.Now+=.5;R.Resources.Update(.5,state,0,0);}
46
public void Sample()=>Call(R.Miner,"SampleOre");
47
public void Baseline()=>Call(R.Miner,"ResetSample");
48
}
49
50
[Fact]
51
public void ActualDrillToSorterTransfersPreserveOreAndAllowAConfirmedDiscovery()
52
{
53
var r=new Rig();
54
// Real miner 7, 2026-09-15: inventory-03 JSONL lines 348/349 and 351/352.
55
// Two drill buffers transfer to central sorter 95026802382736041.
56
r.Amounts(93.481720,424.960224,45.786960);r.Scan(P.FlightState.Align);r.Baseline();
57
Assert.Equal(564.228904,r.R.Resources.Ores["Stone"],5);
58
r.Amounts(93.481720,0,470.747184);r.Scan();
59
Assert.Equal(564.228904,r.R.Resources.OreAmount,5);Assert.True(r.R.Resources.SamplingValid);
60
r.Sample();r.Sample();Assert.DoesNotContain(r.R.Sent,p=>p.Kind=="RESULT");
61
62
r.Amounts(704.451512,1232.909312,470.747184);r.Scan();
63
Assert.Equal(2408.108008,r.R.Resources.Ores["Stone"],5);Assert.True(r.R.Resources.SamplingValid);
64
r.Sample();Assert.DoesNotContain(r.R.Sent,p=>p.Kind=="RESULT");
65
r.Amounts(678.375836,0,1729.732172);r.Scan();
66
Assert.Equal(2408.108008,r.R.Resources.Ores["Stone"],5);Assert.True(r.R.Resources.SamplingValid);
67
r.Sample();var report=P.JobReport.FromIni(Assert.Single(r.R.Sent,p=>p.Kind=="RESULT").Body);
68
Assert.Equal("Discovery",report.Outcome);Assert.Equal("Stone",report.Ore);
69
Assert.True(r.Sorter.Value.Enabled);Assert.True(r.Sorter.Value.DrainAll);
70
}
71
72
[Fact]
73
public void ActualLossFromASorterStillInvalidatesAndLatchesTheSample()
74
{
75
var r=new Rig();r.Amounts(10,0,100);r.Scan();r.Baseline();
76
r.Amounts(10,0,80);r.Scan();Assert.False(r.R.Resources.SamplingValid);
77
r.Amounts(10,0,100);r.Scan();Assert.False(r.R.Resources.SamplingValid);
78
r.Sample();Assert.DoesNotContain(r.R.Sent,p=>p.Kind=="RESULT");
79
Assert.True((bool)typeof(P.MinerController).GetField("invalidSample",Private).GetValue(r.R.Miner));
80
r.R.Resources.ResetSampleValidation();r.Scan();Assert.True(r.R.Resources.SamplingValid);
81
}
82
83
[Fact]
84
public void PreexistingSorterOreIsInTheAlignmentBaselineAndCannotBecomeANewDiscovery()
85
{
86
var r=new Rig();r.Amounts(0,0,100);r.Scan(P.FlightState.Align);r.Baseline();
87
r.Amounts(100,0,0);r.Scan();Assert.True(r.R.Resources.SamplingValid);
88
r.Sample();r.Sample();Assert.DoesNotContain(r.R.Sent,p=>p.Kind=="RESULT");
89
Assert.Equal(100,r.R.Resources.Ores["Stone"]);
90
}
91
92
[Fact]
93
public void AForeignSorterCannotBeCountedAsLocalMinedOre()
94
{
95
var r=new Rig();r.Amounts(0,0,100);
96
r.Sorter.Set("CubeGrid",new Stub<IMyCubeGrid>().Set("EntityId",999L).Value);
97
r.Scan();Assert.Empty(r.R.Resources.Ores);Assert.False(r.R.Resources.SamplingValid);
98
r.Sample();Assert.DoesNotContain(r.R.Sent,p=>p.Kind=="RESULT");
99
}
100
}
101
}
@@ -36,7 +36,7 @@ namespace AutoMiningScript
36
36
{
37
37
public static List<T> CreateList<T>() => new List<T>();
38
38
public static Dictionary<TKey,TValue> CreateDictionary<TKey,TValue>() => new Dictionary<TKey,TValue>();
39
public static bool CargoInventory(IMyTerminalBlock block) => block is IMyCargoContainer || block is IMyShipDrill || block is IMyShipConnector;
39
public static bool CargoInventory(IMyTerminalBlock block) => block is IMyCargoContainer || block is IMyShipDrill || block is IMyShipConnector || block is IMyConveyorSorter;
40
40
// Shared engine API names keep the eight pasteable exports below 100k.
41
41
public static readonly Vector3D Zero = Vector3D.Zero, Forward = Vector3D.Forward, Up = Vector3D.Up;
42
42
public static readonly StringComparison Ordinal = StringComparison.Ordinal, IgnoreCase = StringComparison.OrdinalIgnoreCase;
@@ -792,7 +792,10 @@ namespace AutoMiningScript
792
792
if (target.Closed || target.CubeGrid != P.Me.CubeGrid || dock.Status != MyShipConnectorStatus.Connected || dock.OtherConnector == null || dock.OtherConnector.CubeGrid.EntityId != grid) break;
793
793
var destination = target.GetInventory(0);
794
794
if (!source.CanTransferItemTo(destination, items[k].Type)) continue;
795
if (source.TransferItemTo(destination, k, null, true)) { unloadProgress[t.Id] = P.Now; transfers++; break; }
795
// The engine can return true even when a full/restricted target takes nothing.
796
var before=source.GetItemAmount(items[k].Type);
797
source.TransferItemTo(destination, k, null, true);
798
if (source.GetItemAmount(items[k].Type)<before) { unloadProgress[t.Id] = P.Now; transfers++; break; }
796
799
}
797
800
}
798
801
}
@@ -160,10 +160,15 @@ namespace AutoMiningScript
160
160
var displacement = activeTarget - position;
161
161
var distance = Data.Length(displacement);
162
162
var direction = distance > 0.001 ? displacement / distance : desired.Forward;
163
// Keep existing camera coverage and hull attitude. Turn only when the
164
// required direction has no working camera, independently of its charge.
163
// Travel attitude follows the active leg, independently of which camera
164
// can observe it. Stationary scans still turn only for missing coverage.
165
165
if (faceTravel && distance > tolerance)
166
desired=h.CameraAttitude(position+direction*Data.Max(distance,h.Radius*3+5),up);
166
{
167
desired=Data.Frame(Data.Zero,direction,up);
168
// Retain an already aligned hull within the same angular tolerance
169
// as valid scans, including a small lens-specific coverage correction.
170
if(Data.Length(RotationError(basis,desired))<.035)desired=basis.GetOrientation();
171
}
167
172
else if (faceTravel) desired = basis.GetOrientation();
168
173
Acceleration = AvailableAcceleration(direction);
169
174
Vector3D brakeDirection = Data.LengthSquared(relativeVelocity) > 0.01 ? -Vector3D.Normalize(relativeVelocity) : -direction;
@@ -40,6 +40,7 @@ namespace AutoMiningScript
40
40
bool canceling;
41
41
bool dockInitialized,waitingAligning;
42
42
double nextInitialization;
43
Vector3D breadcrumbDirection;
43
44
44
45
public MinerController(Program p):base(p)
45
46
{
@@ -52,6 +53,7 @@ namespace AutoMiningScript
52
53
bool WatchdogEnabled => P.Config.Flag("Watchdog","Enabled",false);
53
54
string WatchdogId => P.Config.Text("Watchdog","Id",P.Config.Id+"-watchdog");
54
55
double MaxDockAge => P.Config.Number("Dock","MaxTelemetryAge",0.5,0.1,2);
56
double CruiseSpeed => P.Config.Number("Flight","CruiseSpeed",15,1,80);
55
57
Vector3D Position => ship.Controller==null?P.Me.GetPosition():ship.Controller.GetPosition();
56
58
double HomeDistance => home==null?0:Data.Distance(Position,home.Center);
57
59
double BudgetDistance
@@ -59,7 +61,7 @@ namespace AutoMiningScript
59
61
get
60
62
{
61
63
if(home==null)return HomeDistance;
62
var speed=P.Config.Number("Flight","CruiseSpeed",15,1,80);
64
var speed=CruiseSpeed;
63
65
var time=Data.InterceptTime(home.Center-Position,home.Velocity,speed);
64
66
return time<0?10000000:Data.Max(HomeDistance,time*speed);
65
67
}
@@ -209,7 +211,7 @@ namespace AutoMiningScript
209
211
if(!DockValid()) {AbortDock(L.MinerDepartureWindowInvalid);return;}
210
212
Vector3D f,u;var target=DockTarget(Data.Max(DockDistance,dock.LaneClearance+ship.Radius+2),out f,out u,false);
211
213
flight.SetDockContact(dock.GridId,dock.Position,Data.Max(1.5,P.Me.CubeGrid.GridSize));
212
if(flight.Move(target,dock.PointVelocity(target),f,u,2,0.7,true,dt))
214
if(flight.Move(target,dock.PointVelocity(target),f,u,CruiseSpeed,0.7,true,dt))
213
215
{
214
216
ReleaseLane();flight.ClearDockContact();breadcrumbs.Add(Position);Set(FlightState.Transit,L.MinerTravelTaskEntry);
215
217
return;
@@ -243,7 +245,7 @@ namespace AutoMiningScript
243
245
if(!surveying && !flight.CanSupport(face,Data.Perpendicular(face,cruiseUp),0.3)) {BeginReturn(L.MinerTargetAttitudeThrustLow);return;}
244
246
// Observation rays may point sideways from the arrival path. Keep the
245
247
// travel camera facing the actual leg (including detours) until stopped.
246
var arrived=flight.Move(target,Data.Zero,face,Data.Perpendicular(face,cruiseUp),P.Config.Number("Flight","CruiseSpeed",15,1,80),surveying?1:.4,true,dt,true);
248
var arrived=flight.Move(target,Data.Zero,face,Data.Perpendicular(face,cruiseUp),CruiseSpeed,surveying?1:.4,true,dt,true);
247
249
if(SurveyTransitResult(dt,arrived))return;
248
250
reason=L.F(L.MinerDockNavigationProgress,L.MinerTravelTaskEntry,distance,Data.Length(ship.Controller.GetShipVelocities().LinearVelocity),flight.AttitudeError*180/Math.PI);
249
251
if(flight.Problem.Length>0)reason=flight.Problem+" / "+reason;
@@ -436,11 +438,17 @@ namespace AutoMiningScript
436
438
}
437
439
void RecordBreadcrumb()
438
440
{
439
if(breadcrumbs.Count==0 || Data.Distance(Position,breadcrumbs[breadcrumbs.Count-1])>10)
440
{
441
if(breadcrumbs.Count>=128) {BeginReturn(L.MinerRouteBudgetFull);return;}
442
breadcrumbs.Add(Position);
443
}
441
int count=breadcrumbs.Count;var point=Position;var last=count==0?point:breadcrumbs[count-1];
442
if(count>0 && Data.Distance(point,last)<=10)return;
443
// Keep the segment's original bearing: repeatedly fitting its latest two
444
// points could erase a gradual curve. Every omitted point stays within
445
// 10 cm of this fixed line (20 cm of the final endpoint chord).
446
if(count>1 && Data.Dot(point-last,breadcrumbDirection)>0 &&
447
Data.LengthSquared(Data.Cross(point-breadcrumbs[count-2],breadcrumbDirection))<=.01)
448
{breadcrumbs[count-1]=point;return;}
449
if(count>=128) {BeginReturn(L.MinerRouteBudgetFull);return;}
450
// A restored path starts a new segment; its previous bearing is not saved.
451
breadcrumbDirection=Data.Unit(point-last,Data.Zero);breadcrumbs.Add(point);
444
452
}
445
453
void ReturnHome(double dt)
446
454
{
@@ -451,16 +459,17 @@ namespace AutoMiningScript
451
459
{returnIndex=-1;Set(FlightState.DockAlign,L.MinerDockOuterEntry,true);DockAlign(dt);return;}
452
460
if(returnIndex>=0)
453
461
{
454
// Blend nearly straight verified segments; sharp corners still require
455
// braking. Each resulting motion continues to require fresh scans.
456
if(returnIndex>0)
462
// Look beyond the cruise braking distance, not just the next 10 m
463
// sample. Preserve sharp corners; each blended leg still needs scans.
464
double speed=CruiseSpeed,look=speed*1.5+speed*speed/(2*Data.Max(.1,flight.BrakeAcceleration*.65));
465
while(returnIndex>0)
457
466
{
458
467
Vector3D leg=breadcrumbs[returnIndex]-Position,next=breadcrumbs[returnIndex-1]-breadcrumbs[returnIndex];
459
double look=Data.Max(2,Data.Length(ship.Controller.GetShipVelocities().LinearVelocity)*1.5);
460
if(Data.Length(leg)<look && (Data.Length(leg)<0.1 || Data.Dot(Data.Unit(leg,Data.Forward),Data.Unit(next,Vector3D.Backward))>0.98))returnIndex--;
468
if(Data.Length(leg)>=look || (Data.Length(leg)>=.1 && Data.Dot(Data.Unit(leg,Data.Forward),Data.Unit(next,Vector3D.Backward))<=.98))break;
469
returnIndex--;
461
470
}
462
471
var target=breadcrumbs[returnIndex];var f=Data.Unit(target-Position,ship.Controller.WorldMatrix.Forward);var up=TravelUp(f);
463
if(flight.Move(target,Data.Zero,f,up,10,2,true,dt,true))returnIndex--;
472
if(flight.Move(target,Data.Zero,f,up,speed,2,true,dt,true))returnIndex--;
464
473
if(flight.Problem.Length>0)reason=flight.Problem;return;
465
474
}
466
475
if(home==null || P.Now-home.ReceivedAt>5) {reason=L.MinerBaseLostHold;flight.Hold(dt);return;}
@@ -4,6 +4,25 @@
4
4
5
5
## 开发机检查
6
6
7
### 2026-09-16 原存档部署
8
9
按用户要求,通过 AgentBridge 新增的通用离线管理 CLI 将中文最终导出写入原存档“飚船啦兄弟萌”:1 个主控、12 台矿机;156 个编程块中其余 143 个源码未变。写入前完整备份活动存档文件,逐个核对新源码摘要,保留 Storage、CustomData、启用状态、世界配置和其他设备,失效旧二进制 sector 缓存。此次没有加载原存档,因此不将离线写入当作该存档的游戏内编译或完整循环验收。具体证据、备份及后续限制见 [部署记录](agent-debug/ORIGINAL_DEPLOYMENT_20260916.md)。
10
11
### 2026-09-15 卸货与完整循环复测
12
13
本轮 AMS 专用调试文档、脚本和本地原始记录已归入本仓库的 `docs/agent-debug/`、`tools/agent-debug/` 和 `artifacts/agent-debug/`。下文未另注明目录的采样与复核文件均位于 `artifacts/agent-debug/`;游戏插件仓库只保留通用调试能力。
14
15
继续通过自研加载器和 AgentBridge 操作授权离线副本。已确认真实探索命中、自动试钻、实际矿物增量、石头矿种确认及矿区生成、返航连接和矿物转入母舰。另发现采样误判和分拣器缓存未纳入货物分类;最终版修复后的严格全库存卸净尚缺完整连续证据。不能把原有矿石卸空或收到 `Probe` 任务本身当作新一轮采矿成功。
16
17
- 卸货先排查真实传送路径:5、11、7 号钻头到母舰均有拓扑连接、目标货仓有空间,但石头被中央分拣器的 `Ingot` 白名单阻断;连接器到母舰的石头路径原本可用。在副本中只给 5 号中央分拣器增加 `Ore` 后,钻头到母舰的实际物品通路转为可用。186 个快照中 5 号保持连接,原有 179880.279714 kg 石头降至零;其中一个相邻采样区间,源减少与母舰接收增加同为 166420.820202 kg。作为对照,尚未修改的 11 号仍保持 169682.666046 kg。母舰货物可能随后被生产设备消耗,不能用最后的母舰矿石余额反推全部卸载量。此段使用更新前脚本,证明分拣器配置确实阻断卸货,不作为新代码修复的独立实机证据。记录为本仓库的 `artifacts/agent-debug/full-cycle-unload-review.json` 与 `full-cycle-sorter-unload-proof.jsonl`。
18
- 源码另有独立缺陷:游戏的 `TransferItemTo` 可以在实际转移零数量时返回 `true`。主控现在比较源库存中同矿种转移前后的总量,仅实际减少才更新卸货进度;没有减少就继续其他接收货仓,部分转移也计入进度,不要求整堆一次放下。反应堆、制气机等功能库存供料保留,后续分拣器缓存归类修复见下项。新增五项回归覆盖返回值真假但零转移、满柜后空柜、部分转移及同矿种多堆;卸货及资源定向 103/103 通过。
19
- 普通航行机头跟随实际航段和绕行方向,离港、返航使用巡航速度上限;直线路径前视考虑当前速度、真实制动力及扫描限制,避免每个短记录点逐一刹停。弱推力 2.618 m/s²、60 Hz/20 Hz 及摄像机遮挡回归通过;正式对接的轴向捕获限位和正常贴合 0.5 m/s 下限保留。首次全量发现旧测试仍固定要求机头保持原方向,已改为核对实际等待航段方向和上方向,保留全船体扫描、未完成扫描时零推力等安全断言;233 项相关定向检查通过。
20
- 中文候选 `e16d74c9` 的实机记录已出现真实 `SurveyHit`:任务 733 命中小行星,下一采样取得试钻任务 893;试钻因五点地表起伏过大报告 `Blocked` 后继续探索,尚无真实钻采库存增量。7 号在脚本时间 311.0 秒报告“航路记录预算已满”并返航、连接后再次离港。源码每 10 米追加一个返航点、上限 128,直线冗余记录也会耗尽预算。修复以本段最初方向为固定基准,仅连续前进且距该直线不超过 0.1 米时延伸末点;保留转弯、折返、渐变曲线及原有 128 点保护,不反复重拟合方向。九项新增回归覆盖 5 公里直线、轻微测量扰动、转角与折返、缓弯、重载及返航新鲜扫描;历史轨迹不作为免扫描通行证。相关定向 347/347 通过,修复后的游戏复测仍进行中。缺陷实证为 `full-cycle-seven-inspect-current.json`、`full-cycle-flight-01.jsonl` 与 `full-cycle-live-review.json`。
21
- 中文候选 `0deb6470` 继续正常分配的试钻任务 894,实际进入钻采并产生石头,钻头库存堵塞后沿原孔退钻返航。连接后,母舰接收增加与矿机货仓、钻头及连接器减少同为 **174210.962332 kg**,随后矿机再次离港;但中央分拣器另有 **1729.732172 kg** 石头未计入旧货物分类,不能报告本次离港前全船卸净。采样曾把钻头向分拣器的内部转移误判为矿物丢失:两个区间分别呈现原货物库存减少、分拣器增加 **424.960224 kg** 和 **1258.984988 kg**,对应总量不变,却锁存采样无效。后续重新核对矿机 `Discovered` 与主控持久记录,确认 **02:55:23 UTC 已识别 Stone,并生成 deposit-895**;`Discovery` 即时发送,不写入 `lastReport`,不能据该字段或旧原因文字判定从未确认。较晚记录中分拣器残留也已归零,不将第一次离港时的残载说成永久无法卸出。证据见 `full-cycle-first-mining-loop-review.json`、`full-cycle-sampling-transfer-review.json` 和 `full-cycle-inventory-03.jsonl`。
22
- 分拣器修复统一扩展 `CargoInventory`:矿机货仓、钻头、连接器和分拣器的矿石同时参与采样、货量、卸货与 `Empty` 判断;不改变分拣器过滤或开关,仍不卸载铀锭,反应堆、制气机与生产设备库存继续排除。四项新增采样回归涵盖实测逐步流转、真实丢矿仍报错、既有缓存不冒充新发现及外网格排除;三项新增货物回归涵盖残矿非空、严格卸净和主控实际卸载分拣器并保留铀锭。联合卸货/资源/采样定向 110/110、另一组采样/矿机/质量定向 119/119 通过。`DepartureFill=0.05` 仍允许低于阈值的残载离港,与 `Empty` 分开;需要严格卸净的复测使用 `DepartureFill=0`,不把默认阈值的放行当作卸净证明。
23
24
航路压缩前的 `e16d74c9` 基线中英文各 867/867 项测试通过,压缩修复后的 `0deb6470` 阶段各 876/876 通过;历史记录分别为 `artifacts/agent-debug/ams-build-e16d74c9-15e4c169.json` 与 `ams-build-0deb6470-15e4c169.json`。包含分拣器共同分类的最终构建中英文各 **883/883** 项测试通过,八份导出逐份通过编译、角色、字符数和 SHA-256 核验。中文矿机 **97141** 字符,SHA-256 `39ca17bb98ca99d96df420b2586ff0bd7900684b95dfeea3073fd9a584a74a16`;中文主控 **98049** 字符,SHA-256 `32445f94aaa6cdbcb0b3cbbb540efc76ee458bdc42fb298620cca4e40699664e`。英文矿机 **99542**、主控 **99207** 字符。首次运行在英文测试完成前中断,未更新清单;已重新执行完整构建并确认两种语言全部通过。最终日志为 `obj/agent-debug-sorter-final-build.log`,清单为 `dist/manifest.json`,复核记录为 `artifacts/agent-debug/ams-build-39ca17bb-32445f94.json`。构建通过不代表最后的矿种确认与全库存卸净已在游戏中通过。
25
7
26
### 2026-09-14 后续实机复测
8
27
9
28
通过自研 XFE 加载器与 AgentBridge,实际运行 Space Engineers 1.210.014 的离线副本 `XFE Agent Debug AMS 20260914-182847`。原存档和原工作树已有修改不参与部署。下面的运行数据来自游戏遥测;早期段落中的“待验证”保留为当时的历史记录。
@@ -15,11 +34,11 @@
15
34
16
35
最终完整构建中英文各 856/856 项测试通过,八份导出均通过编译、角色、字符限制和 SHA-256 核验。中文矿机 97002 字符,SHA-256 `9553e0ec92de8fc93c814852f37ff088f579c038ca8bdcf6c06b57e0f44d28ab`;中文主控 97973 字符,SHA-256 `8a42840b6e3d73f578814d27e3fc3ccb8bfabc59231bc126b9008781f1122030`。英文矿机 99403、主控 99131 字符。日志为 `obj/agent-debug-capture-final-build.log`,导出清单为 `dist/manifest.json`。副本中实际运行的全部 13 个 PB 与最终清单相符,均有编译实例且无编译错误;保存副本并正常退出后,原存档按复制前相同范围复核的 25 个文件未变(不包含原有备份目录)。
17
36
18
本轮具体版本、原始记录文件及验证边界见 AgentBridge 仓库的 `docs/DEBUGGING.md`。这些记录不代表全舰队长时间无人采矿循环、所有镜头布局和全部 UI 验收项目已经完成。
37
本轮具体版本、原始记录文件及验证边界见本仓库的 `docs/agent-debug/DEBUGGING.md`。这些记录不代表全舰队长时间无人采矿循环、所有镜头布局和全部 UI 验收项目已经完成。
19
38
20
39
### 较早的开发与实机记录
21
40
22
2026-09-14 不可达探索入口退出:在原仓库 `f6b7d8f` 的独立工作树中修复,不改动原工作树已有的主控修改。AgentBridge 对授权单机副本的实机采样显示,7号在同一探索任务346上多次停车、换绕行点再回头;从脚本时间204秒持续到503秒仍未进入扫描。导航能进行局部绕行,不能用单帧 `Blocked` 代表任务入口可达。现有命中点距目标约1.54米,矿机半径约4.63米,因此这条采样路径不足以安全抵达原入口。原始证据为 AgentBridge 项目的 `artifacts/seven-survey-navigation.jsonl` 和 `artifacts/seven-current.json`。
41
2026-09-14 不可达探索入口退出:在原仓库 `f6b7d8f` 的独立工作树中修复,不改动原工作树已有的主控修改。AgentBridge 对授权单机副本的实机采样显示,7号在同一探索任务346上多次停车、换绕行点再回头;从脚本时间204秒持续到503秒仍未进入扫描。导航能进行局部绕行,不能用单帧 `Blocked` 代表任务入口可达。现有命中点距目标约1.54米,矿机半径约4.63米,因此这条采样路径不足以安全抵达原入口。原始证据为本仓库的 `artifacts/agent-debug/seven-survey-navigation.jsonl` 和 `artifacts/agent-debug/seven-current.json`。
23
42
24
43
探索入口按累计接近至少2米刷新进展窗口;45秒没有有效接近时当次制动,沿现有可靠结果协议报告 `Blocked` 并在空中等待续派。当帧真实小行星命中仍优先报告 `SurveyHit`,合法绕行和缓慢累计接近保留。没有把任意绕行点冒充原扫描入口,以免错误完成覆盖任务;非探索任务保留原受阻处理。
25
44