Files
Rail_Enterprise/src/RailEnterprise.Core/Persistence/RailSerializer.cs
T
Alby96andClaude Opus 5.5 e157dd77bc F6: compravendita in proprio e spedizione della merce tra stazioni
Dal livello che sblocca il commercio la compagnia può comprare e vendere
merci in proprio. Così può fare arbitraggio tra un produttore con il
magazzino pieno e un consumatore a secco anche dove il vettore non ha
contratti. Le regole sono nell'ADR 0016.

- Ogni stazione della compagnia ha un magazzino: 500 unità e una
  giacenza di 25 centesimi per unità al mese, in balance.json, blocco
  «trading». La merce in magazzino rientra nell'invariante delle merci.
- BuyGoods compra al prezzo locale marginale dell'ADR 0004, unità per
  unità, partendo dal più economico, dai produttori del bacino e dagli
  hub. La merce presa dagli hub conta come importata.
- SellGoods vende ai consumatori del bacino partendo dal prezzo più
  alto, entro lo spazio libero e la cassa di ciascuno. Vende anche agli
  hub, e quella merce conta come esportata.
- Il denaro di entrambi i comandi passa dal registro, sulla voce
  «Commercio».
- ShipGoods (comando 40) spedisce la merce propria come pacchetto senza
  tariffa né consumatore. Il pacchetto entra nel magazzino di
  destinazione, che riserva lo spazio alla partenza. Il percorso dei
  pacchetti già esistenti non cambia: l'accettazione F4 dà ancora
  35/20 guasti senza la linea e 75/2 con la linea.
- Il salvataggio passa al corpo versione 4 (TradingSerializer). I
  salvataggi più vecchi si caricano con i magazzini vuoti, e i magazzini
  entrano nell'hash di stato.
- MarketReport porta i magazzini nel blocco 1. Il Mercato globale ha il
  riquadro «Compravendita in proprio».
- Le IA non commerciano ancora.

Refs #31.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-07 15:26:20 +01:00

545 lines
19 KiB
C#

using RailEnterprise.Core.Common;
using RailEnterprise.Core.Rail;
using RailEnterprise.Core.Simulation;
namespace RailEnterprise.Core.Persistence;
/// <summary>Serializzazione dello stato ferroviario: rete, cantieri, veicoli, treni, linee, pacchetti.</summary>
public static class RailSerializer
{
public static void Write(World w, SaveWriter s)
{
var net = w.Network;
s.Write(net.NextProject);
s.Write(net.Nodes.Count);
foreach (var n in net.Nodes)
{
s.Write(n.Position.X);
s.Write(n.Position.Y);
s.Write(n.HeightM);
s.Write(n.Owner.Value);
s.Write(n.Station.Value);
s.Write(n.Depot.Value);
s.Write(n.Removed);
s.Write(n.Edges.Count);
foreach (var e in n.Edges) s.Write(e.Value);
}
s.Write(net.Edges.Count);
foreach (var e in net.Edges)
{
s.Write(e.A.Value);
s.Write(e.B.Value);
s.Write(e.Owner.Value);
s.Write(e.TrackClass);
s.Write(e.DoubleTrack);
s.Write(e.Electrified);
s.Write((byte)e.State);
s.Write(e.S);
s.Write(e.X);
s.Write(e.Y);
s.Write(e.H);
s.Write(e.Ground);
s.Write(e.Kinds.Length);
foreach (var k in e.Kinds) s.Write((byte)k);
s.Write(e.SpeedLimitKmh);
s.Write(e.Condition);
s.Write(e.StructureCondition);
s.Write(e.BuiltDay);
s.Write(e.LastRenewalDay);
s.Write(e.LastInspectionDay);
s.Write(e.BuildCostCents);
s.Write(e.Project);
s.Write(e.Signals.Count);
foreach (double sig in e.Signals) s.Write(sig);
s.Write(e.LockDir);
s.Write(e.LockCount);
s.Write(e.BlocksForward);
s.Write(e.BlocksBackward);
s.Write(e.WearToday);
s.Write(e.TonnesThisYear);
}
s.Write(net.Stations.Count);
foreach (var st in net.Stations)
{
s.Write(st.Owner.Value);
s.Write(st.Name);
s.Write(st.Node.Value);
s.Write(st.Position.X);
s.Write(st.Position.Y);
s.Write(st.Platforms);
s.Write(st.BuiltDay);
s.Write(st.BuildCostCents);
s.Write(st.PlatformTrain);
s.Write(st.Incoming);
WriteIds(s, st.Industries.Select(i => i.Value));
WriteIds(s, st.Towns.Select(i => i.Value));
WriteIds(s, st.Hubs.Select(i => i.Value));
WritePackets(s, st.Waiting);
}
s.Write(net.Depots.Count);
foreach (var d in net.Depots)
{
s.Write(d.Owner.Value);
s.Write(d.Name);
s.Write(d.Node.Value);
s.Write(d.Position.X);
s.Write(d.Position.Y);
s.Write(d.Size);
s.Write(d.BuiltDay);
s.Write(d.BuildCostCents);
s.Write(d.SpareParts);
}
s.Write(net.Projects.Count);
foreach (var p in net.Projects)
{
s.Write(p.Id);
s.Write(p.Owner.Value);
s.Write((byte)p.Kind);
WriteIds(s, p.Edges.Select(e => e.Value));
s.Write(p.TotalDays);
s.Write(p.ProgressDays);
s.Write(p.Crew);
s.Write(p.QueuedDay);
s.Write(p.StartedDay);
s.Write(p.Done);
s.Write(p.UpgradeClass);
s.Write(p.UpgradeDouble);
s.Write(p.UpgradeElectrified);
s.Write(p.Works.Count);
foreach (var work in p.Works)
{
s.Write((byte)work.Kind);
s.Write(work.StartM);
s.Write(work.EndM);
s.Write(work.MaxHeightM);
s.Write(work.CostCents);
s.Write(work.Days);
s.Write(work.BridgeType);
}
}
s.Write(w.Vehicles.Count);
foreach (var v in w.Vehicles)
{
s.Write(v.Def.Id);
s.Write(v.Owner.Value);
s.Write(v.BoughtDay);
s.Write(v.Train.Value);
s.Write(v.Depot.Value);
s.Write(v.Sold);
s.Write(v.Components);
s.Write(v.OdometerKm);
s.Write(v.Good);
s.Write(v.Load);
s.Write(v.Pax);
}
s.Write(w.Lines.Count);
foreach (var l in w.Lines)
{
s.Write(l.Owner.Value);
s.Write(l.Name);
s.Write(l.Color);
s.Write(l.Removed);
s.Write(l.Stops.Count);
foreach (var st in l.Stops)
{
s.Write(st.Station.Value);
s.Write(st.Load);
s.Write(st.Unload);
s.Write(st.WaitFull);
s.Write(st.MaxWaitDays);
}
}
s.Write(w.Trains.Count);
foreach (var t in w.Trains)
{
s.Write(t.Owner.Value);
s.Write(t.Name);
WriteIds(s, t.Vehicles.Select(v => v.Value));
s.Write(t.HomeDepot.Value);
s.Write(t.Line.Value);
s.Write(t.StopIndex);
s.Write((byte)t.State);
s.Write(t.Removed);
s.Write(t.Reserve);
s.Write(t.GoingToDepot.Value);
s.Write(t.EmptyMassT);
s.Write(t.LocoMassT);
s.Write(t.PowerKw);
s.Write(t.TractiveKn);
s.Write(t.MaxSpeedKmh);
s.Write(t.LengthM);
s.Write(t.Cx);
s.Write(t.NeedsElectrification);
s.Write(t.Locomotives);
s.Write(t.AtNode.Value);
s.Write(t.ArrivedVia.Value);
s.Write(t.Route.Count);
foreach (var step in t.Route)
{
s.Write(step.Edge.Value);
s.Write(step.Forward);
}
s.Write(t.RouteIndex);
s.Write(t.StepPos);
s.Write(t.Speed);
s.Write(t.Odometer);
s.Write(t.ReservedStep);
s.Write(t.ReservedBlock);
s.Write(t.ArrivalPlatform);
s.Write(t.Held.Count);
foreach (var h in t.Held)
{
s.Write(h.Kind);
s.Write(h.Id);
s.Write(h.Index);
s.Write(h.Forward);
s.Write(h.LeftAt);
}
s.Write(t.DwellTicks);
s.Write(t.ArrivedTick);
s.Write(t.Platform);
s.Write(t.StallSeconds);
s.Write(t.WaitingSinceTick);
s.Write(t.WaitWarned);
WritePackets(s, t.Cargo);
s.Write(t.RevenueThisYear);
s.Write(t.RevenueLastYear);
s.Write(t.KmThisYear);
}
}
private static void WriteIds(SaveWriter s, IEnumerable<int> ids)
{
var list = ids.ToList();
s.Write(list.Count);
foreach (int i in list) s.Write(i);
}
private static void WritePackets(SaveWriter s, List<Packet> packets)
{
s.Write(packets.Count);
foreach (var p in packets)
{
s.Write(p.Id);
s.Write((byte)p.Kind);
s.Write(p.Good);
s.Write(p.Units);
s.Write(p.Origin.Value);
s.Write(p.Destination.Value);
s.Write(p.HopLine.Value);
s.Write(p.HopEnd.Value);
s.Write(p.CreatedTick);
s.Write(p.ExpiresTick);
s.Write(p.ExpectedDays);
s.Write(p.Contract);
s.Write(p.ReturnTrip);
s.Write(p.AwaitingConsumer);
}
}
// ------------------------------------------------------------------ lettura
public static void Read(World w, SaveReader r, int[] goodMap)
{
var net = w.Network;
int goods = w.Data.GoodCount;
int MapGood(int g) => g < 0 ? g : g < goodMap.Length ? goodMap[g] : -1;
net.NextProject = r.ReadInt32();
int nodes = r.ReadInt32();
for (int i = 0; i < nodes; i++)
{
var n = new TrackNode
{
Id = new NodeId(i),
Position = new Vec2(r.ReadDouble(), r.ReadDouble()),
HeightM = r.ReadDouble(),
Owner = new CompanyId(r.ReadInt32()),
Station = new StationId(r.ReadInt32()),
Depot = new DepotId(r.ReadInt32()),
Removed = r.ReadBool(),
};
int count = r.ReadInt32();
for (int k = 0; k < count; k++) n.Edges.Add(new EdgeId(r.ReadInt32()));
net.Nodes.Add(n);
}
int edges = r.ReadInt32();
for (int i = 0; i < edges; i++)
{
var a = new NodeId(r.ReadInt32());
var b = new NodeId(r.ReadInt32());
var owner = new CompanyId(r.ReadInt32());
int cls = r.ReadInt32();
bool dbl = r.ReadBool();
bool ele = r.ReadBool();
var state = (EdgeState)r.ReadByte();
var S = r.ReadDoubleArray();
var X = r.ReadDoubleArray();
var Y = r.ReadDoubleArray();
var H = r.ReadDoubleArray();
var ground = r.ReadDoubleArray();
var kinds = new WorkKind[r.ReadCount(1)];
for (int k = 0; k < kinds.Length; k++) kinds[k] = (WorkKind)r.ReadByte();
var limits = r.ReadDoubleArray();
var e = new TrackEdge
{
Id = new EdgeId(i),
A = a,
B = b,
Owner = owner,
TrackClass = cls,
DoubleTrack = dbl,
Electrified = ele,
State = state,
S = S,
X = X,
Y = Y,
H = H,
Ground = ground,
Kinds = kinds,
SpeedLimitKmh = limits,
Condition = r.ReadDouble(),
StructureCondition = r.ReadDouble(),
BuiltDay = r.ReadInt64(),
LastRenewalDay = r.ReadInt64(),
LastInspectionDay = r.ReadInt64(),
BuildCostCents = r.ReadInt64(),
Project = r.ReadInt32(),
};
int signals = r.ReadInt32();
for (int k = 0; k < signals; k++) e.Signals.Add(r.ReadDouble());
e.LockDir = r.ReadInt32();
e.LockCount = r.ReadInt32();
e.BlocksForward = r.ReadInt32Array();
e.BlocksBackward = r.ReadInt32Array();
e.WearToday = r.ReadDouble();
e.TonnesThisYear = r.ReadDouble();
net.Edges.Add(e);
}
int stations = r.ReadInt32();
for (int i = 0; i < stations; i++)
{
var st = new Station
{
Id = new StationId(i),
Owner = new CompanyId(r.ReadInt32()),
Name = r.ReadRequiredString(),
Node = new NodeId(r.ReadInt32()),
Position = new Vec2(r.ReadDouble(), r.ReadDouble()),
Platforms = r.ReadInt32(),
BuiltDay = r.ReadInt64(),
BuildCostCents = r.ReadInt64(),
PlatformTrain = r.ReadInt32Array(),
};
var incoming = r.ReadInt32Array();
st.Incoming = new int[goods];
st.Stock = new int[goods];
for (int g = 0; g < incoming.Length; g++)
{
int m = MapGood(g);
if (m >= 0) st.Incoming[m] = incoming[g];
}
foreach (int id in ReadIds(r)) st.Industries.Add(new IndustryId(id));
foreach (int id in ReadIds(r)) st.Towns.Add(new TownId(id));
foreach (int id in ReadIds(r)) st.Hubs.Add(new HubId(id));
ReadPackets(r, st.Waiting, MapGood);
net.Stations.Add(st);
}
int depots = r.ReadInt32();
for (int i = 0; i < depots; i++)
{
net.Depots.Add(new Depot
{
Id = new DepotId(i),
Owner = new CompanyId(r.ReadInt32()),
Name = r.ReadRequiredString(),
Node = new NodeId(r.ReadInt32()),
Position = new Vec2(r.ReadDouble(), r.ReadDouble()),
Size = r.ReadRequiredString(),
BuiltDay = r.ReadInt64(),
BuildCostCents = r.ReadInt64(),
SpareParts = r.ReadInt32(),
});
}
int projects = r.ReadInt32();
for (int i = 0; i < projects; i++)
{
int id = r.ReadInt32();
var owner = new CompanyId(r.ReadInt32());
var kind = (ProjectKind)r.ReadByte();
var edgeIds = ReadIds(r).Select(x => new EdgeId(x)).ToList();
double total = r.ReadDouble();
double progress = r.ReadDouble();
int crew = r.ReadInt32();
long queued = r.ReadInt64();
long started = r.ReadInt64();
bool done = r.ReadBool();
int upClass = r.ReadInt32();
bool upDouble = r.ReadBool();
bool upElectric = r.ReadBool();
int works = r.ReadInt32();
var list = new List<Work>(works);
for (int k = 0; k < works; k++)
{
list.Add(new Work((WorkKind)r.ReadByte(), r.ReadDouble(), r.ReadDouble(), r.ReadDouble(), r.ReadInt64(), r.ReadInt32(), r.ReadString()));
}
net.Projects.Add(new ConstructionProject
{
Id = id,
Owner = owner,
Kind = kind,
Edges = edgeIds,
TotalDays = total,
ProgressDays = progress,
Crew = crew,
QueuedDay = queued,
StartedDay = started,
Done = done,
UpgradeClass = upClass,
UpgradeDouble = upDouble,
UpgradeElectrified = upElectric,
Works = list,
});
}
net.Touch();
int vehicles = r.ReadInt32();
for (int i = 0; i < vehicles; i++)
{
string defId = r.ReadRequiredString();
if (!w.Data.TryVehicle(defId, out var def) || def is null) throw new InvalidDataException($"Veicolo «{defId}» assente dai dati correnti");
var v = new Vehicle
{
Id = new VehicleId(i),
Def = def,
Owner = new CompanyId(r.ReadInt32()),
BoughtDay = r.ReadInt64(),
Train = new TrainId(r.ReadInt32()),
Depot = new DepotId(r.ReadInt32()),
Sold = r.ReadBool(),
Components = r.ReadDoubleArray(),
OdometerKm = r.ReadDouble(),
};
v.Good = MapGood(r.ReadInt32());
v.Load = r.ReadInt32();
v.Pax = r.ReadInt32();
w.Vehicles.Add(v);
}
int lines = r.ReadInt32();
for (int i = 0; i < lines; i++)
{
var l = new Line
{
Id = new LineId(i),
Owner = new CompanyId(r.ReadInt32()),
Name = r.ReadRequiredString(),
Color = r.ReadRequiredString(),
Removed = r.ReadBool(),
};
int stops = r.ReadInt32();
for (int k = 0; k < stops; k++)
l.Stops.Add(new LineStop(new StationId(r.ReadInt32()), r.ReadBool(), r.ReadBool(), r.ReadBool(), r.ReadInt32()));
w.Lines.Add(l);
}
int trains = r.ReadInt32();
for (int i = 0; i < trains; i++)
{
var t = new Train
{
Id = new TrainId(i),
Owner = new CompanyId(r.ReadInt32()),
Name = r.ReadRequiredString(),
};
foreach (int v in ReadIds(r)) t.Vehicles.Add(new VehicleId(v));
t.HomeDepot = new DepotId(r.ReadInt32());
t.Line = new LineId(r.ReadInt32());
t.StopIndex = r.ReadInt32();
t.State = (TrainState)r.ReadByte();
t.Removed = r.ReadBool();
t.Reserve = r.ReadBool();
t.GoingToDepot = new DepotId(r.ReadInt32());
t.EmptyMassT = r.ReadDouble();
t.LocoMassT = r.ReadDouble();
t.PowerKw = r.ReadDouble();
t.TractiveKn = r.ReadDouble();
t.MaxSpeedKmh = r.ReadDouble();
t.LengthM = r.ReadDouble();
t.Cx = r.ReadDouble();
t.NeedsElectrification = r.ReadBool();
t.Locomotives = r.ReadInt32();
t.AtNode = new NodeId(r.ReadInt32());
t.ArrivedVia = new EdgeId(r.ReadInt32());
int route = r.ReadInt32();
for (int k = 0; k < route; k++) t.Route.Add(new RouteStep(new EdgeId(r.ReadInt32()), r.ReadBool()));
t.RouteIndex = r.ReadInt32();
t.StepPos = r.ReadDouble();
t.Speed = r.ReadDouble();
t.Odometer = r.ReadDouble();
t.ReservedStep = r.ReadInt32();
t.ReservedBlock = r.ReadInt32();
t.ArrivalPlatform = r.ReadInt32();
int held = r.ReadInt32();
for (int k = 0; k < held; k++)
t.Held.Add(new HeldResource { Kind = r.ReadByte(), Id = r.ReadInt32(), Index = r.ReadInt32(), Forward = r.ReadBool(), LeftAt = r.ReadDouble() });
t.DwellTicks = r.ReadDouble();
t.ArrivedTick = r.ReadInt64();
t.Platform = r.ReadInt32();
t.StallSeconds = r.ReadDouble();
t.WaitingSinceTick = r.ReadInt64();
t.WaitWarned = r.ReadBool();
ReadPackets(r, t.Cargo, MapGood);
t.RevenueThisYear = r.ReadInt64();
t.RevenueLastYear = r.ReadInt64();
t.KmThisYear = r.ReadDouble();
w.Trains.Add(t);
}
}
private static List<int> ReadIds(SaveReader r)
{
int n = r.ReadCount(4);
var list = new List<int>(n);
for (int i = 0; i < n; i++) list.Add(r.ReadInt32());
return list;
}
private static void ReadPackets(SaveReader r, List<Packet> target, Func<int, int> mapGood)
{
int n = r.ReadCount(8);
for (int i = 0; i < n; i++)
{
var p = new Packet
{
Id = r.ReadInt32(),
Kind = (PacketKind)r.ReadByte(),
Good = mapGood(r.ReadInt32()),
Units = r.ReadInt32(),
Origin = new StationId(r.ReadInt32()),
Destination = new StationId(r.ReadInt32()),
HopLine = new LineId(r.ReadInt32()),
HopEnd = new StationId(r.ReadInt32()),
CreatedTick = r.ReadInt64(),
ExpiresTick = r.ReadInt64(),
ExpectedDays = r.ReadDouble(),
Contract = r.ReadInt32(),
ReturnTrip = r.ReadBool(),
AwaitingConsumer = r.ReadBool(),
};
if (p.Kind != PacketKind.Freight || p.Good >= 0) target.Add(p);
}
}
}