F2: rete ferroviaria, cantieri, treni con fisica e blocchi, merci in stazione
- RailNetwork: nodi, archi con profilo campionato, divisione degli archi agli agganci (anche in cantiere), indice spaziale, cavalcavia sui binari altrui - Comandi: binari, stazioni, depositi, segnali, demolizioni, rinnovi, ammodernamenti, veicoli, composizioni, linee, assegnazioni, rientro - ConstructionSystem: squadre per livello, avanzamento, usura dei binari e invecchiamento delle strutture; costi d'esercizio e valore contabile - TrainSystem: A* con vincolo di svolta, prenotazione a blocchi con catena fino a un punto sicuro sul binario semplice, fisica 8.4, stallo in salita - StationSystem e StationWork: bacini, merci con destinazione sul grafo delle linee, carico sui carri, consegne con tariffa, trasbordi - Salvataggi estesi a tutto lo stato ferroviario; 11 nuovi test Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_0191R7vXgtbAvSV4V8tj8uzL
This commit is contained in:
28 files changed
+4122
-6
No files matched your search
@@ -0,0 +1,81 @@
|
||||
using ViaFerrea.Core.Commands;
|
||||
using ViaFerrea.Core.Common;
|
||||
using ViaFerrea.Core.Rail;
|
||||
using ViaFerrea.Core.Simulation;
|
||||
using ViaFerrea.Core.Simulation.Scenarios;
|
||||
using ViaFerrea.Tests.Harness;
|
||||
using ViaFerrea.Tests.Scenarios;
|
||||
|
||||
namespace ViaFerrea.Tests.Rail;
|
||||
|
||||
/// <summary>Mondo con comandi di comodo per i test ferroviari.</summary>
|
||||
public sealed class RailFixture
|
||||
{
|
||||
public World W { get; }
|
||||
public LoadedScenario? Scenario { get; }
|
||||
public CompanyId Me => W.Player.Id;
|
||||
|
||||
public RailFixture(World w, LoadedScenario? scenario = null)
|
||||
{
|
||||
W = w;
|
||||
Scenario = scenario;
|
||||
}
|
||||
|
||||
public static RailFixture Valdoria() { var s = ScenarioHelper.Load("valdoria"); return new RailFixture(s.World, s); }
|
||||
|
||||
public static Vec2 K(double x, double y) => new(x * 1000, y * 1000);
|
||||
|
||||
/// <summary>Esegue il comando nel prossimo tick e ne restituisce l'esito.</summary>
|
||||
public CommandResult Do(GameCommand c, CompanyId? issuer = null)
|
||||
{
|
||||
W.Enqueue(c with { Issuer = issuer ?? Me });
|
||||
W.RunTicks(1);
|
||||
return W.DrainResults().Last();
|
||||
}
|
||||
|
||||
public int Ok(GameCommand c, CompanyId? issuer = null)
|
||||
{
|
||||
var r = Do(c, issuer);
|
||||
Assert.True(r.Ok, $"{c.Type}: {r.Error} {r.Message}");
|
||||
return r.Created.Length > 0 ? r.Created[0] : -1;
|
||||
}
|
||||
|
||||
/// <summary>Esegue giorni finché la condizione è vera (o scade il limite).</summary>
|
||||
public bool RunUntil(Func<bool> condition, int maxDays)
|
||||
{
|
||||
for (int d = 0; d < maxDays * 8; d++)
|
||||
{
|
||||
if (condition()) return true;
|
||||
W.RunTicks(W.Calendar.TicksPerDay / 8);
|
||||
}
|
||||
return condition();
|
||||
}
|
||||
|
||||
/// <summary>Compra veicoli e compone un treno nel deposito.</summary>
|
||||
public int Train(int depot, string loco, int locos, string car, int cars, string name)
|
||||
{
|
||||
var ids = new List<VehicleId>();
|
||||
ids.AddRange(W_Buy(loco, depot, locos));
|
||||
if (cars > 0) ids.AddRange(W_Buy(car, depot, cars));
|
||||
return Ok(new ComposeTrainCommand(new DepotId(depot), ids, name));
|
||||
}
|
||||
|
||||
private IEnumerable<VehicleId> W_Buy(string type, int depot, int count) =>
|
||||
Do(new BuyVehicleCommand(type, new DepotId(depot), count)).Created.Select(i => new VehicleId(i));
|
||||
|
||||
/// <summary>
|
||||
/// Rete merci di Valdoria: stazione delle miniere, stazione dell'acciaieria, deposito e
|
||||
/// tracciato per il valico; restituisce (miniera, acciaieria, deposito).
|
||||
/// </summary>
|
||||
public (int Mine, int Mill, int Depot) BuildFreightNetwork(bool waitForConstruction = true)
|
||||
{
|
||||
int mine = Ok(new BuildStationCommand(K(2.2, 2.6), 2, "Rocca Bruna"));
|
||||
int mill = Ok(new BuildStationCommand(K(10.6, 5.4), 4, "Acciaieria"));
|
||||
int depot = Ok(new BuildDepotCommand(K(2.6, 4.4), "small", "Deposito Rocca Bruna"));
|
||||
Ok(new BuildTrackCommand(Scenario!.Route("valico", Me).Polyline, AllowTunnels: false));
|
||||
Ok(new BuildTrackCommand(new[] { K(2.6, 4.4), K(2.92, 4.95) }));
|
||||
if (waitForConstruction)
|
||||
Assert.True(RunUntil(() => W.Network.Edges.All(e => e.State == EdgeState.Active), 400), "cantieri completati");
|
||||
return (mine, mill, depot);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,127 @@
|
||||
using ViaFerrea.Core.Commands;
|
||||
using ViaFerrea.Core.Common;
|
||||
using ViaFerrea.Core.Rail;
|
||||
using ViaFerrea.Core.Simulation.Systems;
|
||||
using ViaFerrea.Tests.Harness;
|
||||
using static ViaFerrea.Tests.Rail.RailFixture;
|
||||
|
||||
namespace ViaFerrea.Tests.Rail;
|
||||
|
||||
public static class RailNetworkTests
|
||||
{
|
||||
[Test(Description = "Il tracciato del valico si completa nei giorni previsti dal piano e il costo è addebitato")]
|
||||
public static void TrackIsBuiltInPlannedDays()
|
||||
{
|
||||
var f = Valdoria();
|
||||
var cash = f.W.Player.Cash;
|
||||
var r = f.Do(new BuildTrackCommand(f.Scenario!.Route("valico", f.Me).Polyline, AllowTunnels: false));
|
||||
Assert.True(r.Ok, r.Message);
|
||||
var edge = f.W.Network.Edges[r.Created[0]];
|
||||
var project = f.W.Network.Projects[r.Created[3]];
|
||||
Assert.Equal(EdgeState.UnderConstruction, edge.State);
|
||||
Assert.True(f.W.Player.Cash < cash, "costo addebitato");
|
||||
f.RunUntil(() => edge.State == EdgeState.Active, 400);
|
||||
Assert.Equal(EdgeState.Active, edge.State);
|
||||
Assert.Approx(project.TotalDays, project.ProgressDays, 1.0, "giorni di cantiere");
|
||||
Assert.Equal(0L, f.W.MoneyBalanceSum());
|
||||
}
|
||||
|
||||
[Test(Description = "Le squadre limitano i cantieri contemporanei: con due squadre il terzo progetto aspetta")]
|
||||
public static void CrewsLimitConcurrentProjects()
|
||||
{
|
||||
var f = Valdoria();
|
||||
f.Ok(new BuildTrackCommand(new[] { K(11.3, 7.3), K(14.3, 7.3) }));
|
||||
f.Ok(new BuildTrackCommand(new[] { K(11.3, 7.6), K(14.3, 7.6) }));
|
||||
f.Ok(new BuildTrackCommand(new[] { K(11.3, 7.9), K(14.3, 7.9) }));
|
||||
f.W.RunDays(2);
|
||||
var projects = f.W.Network.Projects;
|
||||
Assert.Equal(2, ConstructionSystem.Crews(f.W, f.W.Player));
|
||||
Assert.True(projects[0].Crew >= 0 && projects[1].Crew >= 0);
|
||||
Assert.Equal(-1, projects[2].Crew, "terzo progetto in attesa");
|
||||
Assert.True(f.RunUntil(() => projects.All(p => p.Done), 200));
|
||||
Assert.True(projects[2].StartedDay >= projects[0].StartedDay + projects[0].TotalDays - 1);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public static void AttachingToTrackSplitsTheEdge()
|
||||
{
|
||||
var f = Valdoria();
|
||||
int main = f.Ok(new BuildTrackCommand(new[] { K(11.0, 9.5), K(14.0, 9.5) }));
|
||||
f.Ok(new BuildTrackCommand(new[] { K(12.5, 9.53), K(12.5, 11.0) }));
|
||||
var net = f.W.Network;
|
||||
Assert.Equal(3, net.Edges.Count);
|
||||
var junction = net.Nodes[net.Edges[main].B.Value];
|
||||
Assert.Equal(3, junction.Edges.Count, "scambio con tre archi");
|
||||
Assert.Approx(12500, junction.Position.X, 13);
|
||||
Assert.Approx(3000, net.Edges[main].Length + net.Edges[1].Length, 1e-6, "le due metà sommano la lunghezza originale");
|
||||
Assert.True(f.RunUntil(() => net.Edges.All(e => e.State == EdgeState.Active), 100), "anche la metà nuova finisce col cantiere");
|
||||
}
|
||||
|
||||
[Test(Description = "Attraversare il binario di un'altra compagnia richiede un cavalcavia automatico")]
|
||||
public static void CrossingForeignTrackBuildsAnOverpass()
|
||||
{
|
||||
var f = Valdoria();
|
||||
var rival = f.W.Companies.First(c => !c.IsPlayer).Id;
|
||||
f.Ok(new BuildTrackCommand(new[] { K(11.0, 9.5), K(14.0, 9.5) }), rival);
|
||||
var r = f.Do(new BuildTrackCommand(new[] { K(12.5, 8.8), K(12.5, 10.2) }));
|
||||
Assert.True(r.Ok, r.Message);
|
||||
var edge = f.W.Network.Edges[r.Created[0]];
|
||||
Assert.True(edge.LengthOf(WorkKind.Bridge) > 0, "cavalcavia");
|
||||
int k = Enumerable.Range(0, edge.S.Length).MinBy(i => Math.Abs(edge.Y[i] - 9500));
|
||||
double otherH = f.W.Network.Edges[0].HeightAt(1500);
|
||||
Assert.True(edge.H[k] >= otherH + f.W.Data.Construction.Rules.OverpassClearanceM - 0.5, "franco sul binario altrui");
|
||||
// incrociare a raso il proprio binario è vietato
|
||||
var own = f.Do(new BuildTrackCommand(new[] { K(13.5, 9.0), K(13.5, 10.0) }), rival);
|
||||
Assert.Equal(CommandError.InvalidTrack, own.Error);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public static void InvalidRequestsAreRejectedWithoutSideEffects()
|
||||
{
|
||||
var f = Valdoria();
|
||||
var cash = f.W.Player.Cash;
|
||||
Assert.Equal(CommandError.InvalidTrack, f.Do(new BuildTrackCommand(f.Scenario!.Route("diretto", f.Me).Polyline, AllowTunnels: false)).Error);
|
||||
Assert.Equal(CommandError.NotAllowed, f.Do(new BuildStationCommand(K(13.6, 4.6), 2)).Error, "stazione dentro la città");
|
||||
Assert.Equal(CommandError.InvalidArgument, f.Do(new BuildDepotCommand(K(5, 5), "huge")).Error);
|
||||
Assert.Equal(CommandError.NotFound, f.Do(new BuyVehicleCommand("loco_steam_1850", new DepotId(3))).Error);
|
||||
Assert.Equal(cash, f.W.Player.Cash);
|
||||
Assert.Equal(0, f.W.Network.Edges.Count);
|
||||
f.W.Money.Transfer(ViaFerrea.Core.Economy.Account.Of(f.Me), ViaFerrea.Core.Economy.Account.External, f.W.Player.Cash, ViaFerrea.Core.Economy.LedgerEntry.Other);
|
||||
Assert.Equal(CommandError.InsufficientFunds, f.Do(new BuildTrackCommand(new[] { K(11.0, 9.5), K(14.0, 9.5) })).Error);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public static void StationsHaveCatchmentsAndDemolitionRefunds()
|
||||
{
|
||||
var f = Valdoria();
|
||||
int mill = f.Ok(new BuildStationCommand(K(10.6, 5.4), 3, "Acciaieria"));
|
||||
var st = f.W.Network.Stations[mill];
|
||||
Assert.True(st.Industries.Any(i => f.W.Industries[i.Value].Def.Id == "steel_mill"));
|
||||
Assert.True(st.Towns.Count == 0, "Valdoria è oltre il bacino di 2 km");
|
||||
int track = f.Ok(new BuildTrackCommand(new[] { K(11.0, 9.5), K(14.0, 9.5) }));
|
||||
var before = f.W.Player.Cash;
|
||||
Assert.True(f.Do(new DemolishCommand(DemolishTarget.Edge, track)).Ok);
|
||||
Assert.True(f.W.Player.Cash > before, "rimborso del 10 %");
|
||||
Assert.True(f.Do(new DemolishCommand(DemolishTarget.Station, mill)).Ok);
|
||||
Assert.Equal(0L, f.W.MoneyBalanceSum());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public static void SignalsSplitBlocksAndRenewalRestoresCondition()
|
||||
{
|
||||
var f = Valdoria();
|
||||
int track = f.Ok(new BuildTrackCommand(new[] { K(11.0, 9.5), K(14.0, 9.5) }));
|
||||
f.RunUntil(() => f.W.Network.Edges[track].State == EdgeState.Active, 50);
|
||||
Assert.True(f.Do(new PlaceSignalCommand(new EdgeId(track), 1500)).Ok);
|
||||
var e = f.W.Network.Edges[track];
|
||||
Assert.Equal(2, e.BlocksForward.Length);
|
||||
Assert.Approx(1500, TrainSystem.BlockEnd(e, true, 0), 1e-9);
|
||||
Assert.Approx(1500, TrainSystem.BlockEnd(e, false, 0), 1e-9);
|
||||
e.Condition = 40;
|
||||
Assert.Approx(0.6, ConstructionSystem.ConditionFactor(f.W, e), 1e-12);
|
||||
Assert.True(f.Do(new RenewTrackCommand(new EdgeId(track))).Ok);
|
||||
Assert.Equal(EdgeState.Closed, e.State);
|
||||
f.RunUntil(() => e.State == EdgeState.Active, 50);
|
||||
Assert.Equal(100.0, e.Condition);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,94 @@
|
||||
using ViaFerrea.Core.Commands;
|
||||
using ViaFerrea.Core.Common;
|
||||
using ViaFerrea.Core.Economy;
|
||||
using ViaFerrea.Core.Persistence;
|
||||
using ViaFerrea.Core.Rail;
|
||||
using ViaFerrea.Tests.Harness;
|
||||
using static ViaFerrea.Tests.Rail.RailFixture;
|
||||
|
||||
namespace ViaFerrea.Tests.Rail;
|
||||
|
||||
public static class TrainTests
|
||||
{
|
||||
private static (RailFixture F, Train Train, int Line) FreightLine(int wagons = 5)
|
||||
{
|
||||
var f = Valdoria();
|
||||
var (mine, mill, depot) = f.BuildFreightNetwork();
|
||||
int tr = f.Train(depot, "loco_steam_1850", 1, "wagon_hopper", wagons, "Treno 12");
|
||||
int line = f.Ok(new CreateLineCommand("Linea 3, carbone", "#e0a526",
|
||||
new[] { new LineStop(new StationId(mine), WaitFull: true, MaxWaitDays: 2), new LineStop(new StationId(mill)) }));
|
||||
f.Ok(new AssignTrainCommand(new TrainId(tr), new LineId(line)));
|
||||
return (f, f.W.Trains[tr], line);
|
||||
}
|
||||
|
||||
[Test(Description = "La linea merci porta minerale e carbone all'acciaieria e il vettore incassa le tariffe")]
|
||||
public static void FreightLineDeliversAndEarns()
|
||||
{
|
||||
var (f, t, _) = FreightLine();
|
||||
var steel = f.W.Industries.First(i => i.Def.Id == "steel_mill");
|
||||
long revenueBefore = f.W.Player.YearEntries[(int)LedgerEntry.FreightRevenue];
|
||||
f.W.RunDays(60);
|
||||
Assert.True(t.Odometer > 50_000, $"il treno ha viaggiato ({t.Odometer / 1000:F1} km)");
|
||||
Assert.True(steel.InputStock.All(s => s > 0), "l'acciaieria riceve minerale e carbone");
|
||||
Assert.True(f.W.Player.YearEntries[(int)LedgerEntry.FreightRevenue] > revenueBefore, "tariffe incassate");
|
||||
Assert.True(steel.Served, "industria servita");
|
||||
Assert.Equal(0L, f.W.MoneyBalanceSum());
|
||||
for (int g = 0; g < f.W.Data.GoodCount; g++)
|
||||
Assert.Equal(f.W.Goods.ExpectedStock(g), f.W.TotalStock(g), $"merce {f.W.Data.Goods[g].Id}");
|
||||
}
|
||||
|
||||
[Test(Description = "Due treni in versi opposti sullo stesso binario semplice si incrociano in stazione senza stallo")]
|
||||
public static void OpposingTrainsOnSingleTrackDoNotDeadlock()
|
||||
{
|
||||
var (f, t1, line) = FreightLine();
|
||||
int depot = f.W.Network.Depots[0].Id.Value;
|
||||
int tr2 = f.Train(depot, "loco_steam_1850", 1, "wagon_hopper", 5, "Treno 13");
|
||||
var t2 = f.W.Trains[tr2];
|
||||
// il secondo parte più tardi: i due si troveranno in versi opposti
|
||||
f.W.RunDays(3);
|
||||
f.Ok(new AssignTrainCommand(new TrainId(tr2), new LineId(line)));
|
||||
f.W.RunDays(120);
|
||||
Assert.True(t1.Odometer > 150_000 && t2.Odometer > 150_000, $"entrambi viaggiano: {t1.Odometer / 1000:F0} e {t2.Odometer / 1000:F0} km");
|
||||
foreach (var e in f.W.Network.Edges) Assert.True(e.LockCount <= 2);
|
||||
Assert.False(f.W.Events.Recent.Any(e => e.Text.Contains("possibile stallo", StringComparison.Ordinal)));
|
||||
}
|
||||
|
||||
[Test(Description = "Un treno troppo pesante per la salita resta fermo (Stalled) e genera un avviso")]
|
||||
public static void OverloadedTrainStallsOnTheGrade()
|
||||
{
|
||||
var f = Valdoria();
|
||||
var (mine, mill, depot) = f.BuildFreightNetwork();
|
||||
int tr = f.Train(depot, "loco_steam_1850", 1, "wagon_hopper", 20, "Treno pesante");
|
||||
// carica forzata: 20 tramogge piene di minerale (contabilizzate come prodotte)
|
||||
var t = f.W.Trains[tr];
|
||||
int ore = f.W.Data.GoodIndex("iron_ore");
|
||||
var st = f.W.Network.Stations[mine];
|
||||
st.Waiting.Add(new Packet { Id = f.W.NextIds.Packet++, Kind = PacketKind.Freight, Good = ore, Units = 400, Origin = st.Id, Destination = new StationId(mill), HopLine = LineId.None, Contract = -1, ExpiresTick = long.MaxValue });
|
||||
f.W.Goods.Produced[ore] += 400;
|
||||
int line = f.Ok(new CreateLineCommand("Pesante", "#b3573e", new[] { new LineStop(new StationId(mine)), new LineStop(new StationId(mill)) }));
|
||||
for (int i = 0; i < st.Waiting.Count; i++) { var p = st.Waiting[i]; p.HopLine = new LineId(line); p.HopEnd = new StationId(mill); st.Waiting[i] = p; }
|
||||
f.Ok(new AssignTrainCommand(new TrainId(tr), new LineId(line)));
|
||||
Assert.True(f.RunUntil(() => t.State == TrainState.Stalled, 60), $"stato {t.State}");
|
||||
Assert.True(f.W.Events.Recent.Any(e => e.Text.Contains("non supera la salita", StringComparison.Ordinal)));
|
||||
}
|
||||
|
||||
[Test(Description = "Determinismo e salvataggio con treni in movimento")]
|
||||
public static void TrainsAreDeterministicAndSurviveSaveLoad()
|
||||
{
|
||||
var (a, ta, _) = FreightLine();
|
||||
a.W.RunDays(17);
|
||||
a.W.RunTicks(77); // a metà strada, fuori dal confine del giorno
|
||||
var b = SaveFile.Load(TestData.Data, SaveFile.Save(a.W, "test"));
|
||||
Assert.Equal(StateHasher.Compute(a.W), StateHasher.Compute(b));
|
||||
a.W.RunDays(40);
|
||||
b.RunDays(40);
|
||||
Assert.Equal(a.W.LastStateHash, b.LastStateHash);
|
||||
Assert.Approx(ta.Odometer, b.Trains[ta.Id.Value].Odometer, 1e-9);
|
||||
|
||||
var (c, _, _) = FreightLine();
|
||||
c.W.RunDays(17);
|
||||
c.W.RunTicks(77);
|
||||
c.W.RunDays(40);
|
||||
Assert.Equal(a.W.LastStateHash, c.W.LastStateHash, "due esecuzioni identiche");
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user