using RailEnterprise.Core.Common; using RailEnterprise.Core.Data; using RailEnterprise.Core.Economy; using RailEnterprise.Core.Rail; namespace RailEnterprise.Core.Simulation.Systems; /// /// Stazioni (guida 7): bacini di utenza, industrie servite, merci che passano dalle industrie /// del bacino alla stazione con una destinazione scelta sul grafo delle linee, scadenza dei /// pacchetti in attesa, nuovi tentativi di consegna ai consumatori. /// public sealed class StationSystem : ISimSystem { public string Name => "Stations"; private readonly List<(int Station, double Score)> _candidates = []; public void Step(WorldContext ctx) { if (!ctx.IsNewDay) return; var w = ctx.World; var net = w.Network; if (ctx.IsNewMonth || ctx.Day == 0) { foreach (var s in net.Stations) { if (net.IsAlive(s)) RailCommandHandlers.UpdateCatchment(w, s); } } if (ctx.IsNewMonth) TradingCommandHandlers.ChargeStorage(w); foreach (var s in net.Stations) { if (net.Nodes[s.Node.Value].Station != s.Id) continue; RerouteOwned(w, s); Expire(ctx, s); RetryDeliveries(w, s); } foreach (var s in net.Stations) { if (net.Nodes[s.Node.Value].Station != s.Id || !LoadsHere(w, s)) continue; LocalService(w, s, w.Data.SparePartsGood); LocalService(w, s, w.Data.MachineryGood); CollectFreight(ctx, s); } } /// /// Trasbordo nel bacino (ADR 0011): una stazione servita passa ricambi e macchinari dai produttori /// e dagli hub del suo bacino alle officine e alle industrie dello stesso bacino, senza treno. /// private static void LocalService(World w, Station s, int good) { if (ServiceNeed(w, s, good) <= 0) return; foreach (var id in s.Industries) { var producer = w.Industries[id.Value]; int o = producer.OutputIndexOf(good); if (producer.Closed || o < 0 || producer.OutputStock[o] <= 0) continue; int offered = producer.OutputStock[o]; int sold = offered - StationWork.DeliverService(w, s, good, offered, w.Market.GlobalPrice[good]); if (sold <= 0) continue; producer.OutputStock[o] -= sold; var sale = Money.FromCentsRounded(sold * w.Market.GlobalPrice[good]); w.Money.Transfer(Account.External, Account.Of(producer.Id), sale, LedgerEntry.Other); producer.SalesToday += sale.Cents; producer.LastServedDay = w.Clock.Day; if (o == 0) producer.ShippedToday += sold; } foreach (var id in s.Hubs) { var hub = w.Hubs[id.Value]; int units = Math.Min(ServiceNeed(w, s, good), hub.RemainingCapacity); if (units <= 0) continue; int delivered = units - StationWork.DeliverService(w, s, good, units, hub.SellPrice(w.Market.GlobalPrice[good])); if (delivered <= 0) continue; hub.UsedThisMonth += delivered; hub.ImportedThisMonth[good] += delivered; w.Goods.Imported[good] += delivered; } } private static bool LoadsHere(World w, Station s) { foreach (var line in w.Lines) { if (line.Removed || line.Owner != s.Owner) continue; foreach (var st in line.Stops) { if (st.Station == s.Id && st.Load) return true; } } return false; } /// /// Merce della compagnia in attesa (ADR 0016): ogni giorno ricalcola il tratto sulle linee di oggi, /// così una linea modificata non la lascia ad aspettare un treno che non passa più; senza /// percorso entra nel magazzino della stazione. /// private static void RerouteOwned(World w, Station s) { for (int i = s.Waiting.Count - 1; i >= 0; i--) { var p = s.Waiting[i]; if (!p.Owned) continue; if (StationWork.Route(w, s, ref p)) { s.Waiting[i] = p; continue; } s.Waiting.RemoveAt(i); TradingCommandHandlers.Store(w, s, p); } } private static void Expire(WorldContext ctx, Station s) { var w = ctx.World; for (int i = s.Waiting.Count - 1; i >= 0; i--) { var p = s.Waiting[i]; if (p.ExpiresTick > ctx.Tick) continue; s.Waiting.RemoveAt(i); if (p.Kind != PacketKind.Freight) continue; w.Goods.Decayed[p.Good] += p.Units; if (!p.AwaitingConsumer && !p.Owned) { var dest = w.Network.Stations[p.Destination.Value]; dest.Incoming[p.Good] = Math.Max(0, dest.Incoming[p.Good] - p.Units); } } } private static void RetryDeliveries(World w, Station s) { for (int i = s.Waiting.Count - 1; i >= 0; i--) { var p = s.Waiting[i]; if (!p.AwaitingConsumer) continue; p.Units = StationWork.DeliverToConsumers(w, s, p.Good, p.Units); if (p.Units <= 0) s.Waiting.RemoveAt(i); else s.Waiting[i] = p; } } /// /// Le industrie del bacino affidano la produzione alla stazione se esiste una destinazione /// raggiungibile con un consumatore; si sceglie quella con più bisogno, a parità la più vicina. /// private void CollectFreight(WorldContext ctx, Station s) { var w = ctx.World; var graph = w.LineGraphs.For(w, s.Owner); foreach (var id in s.Industries) { var ind = w.Industries[id.Value]; if (ind.Closed) continue; var outputs = ind.Def.Recipe.Outputs; for (int o = 0; o < outputs.Count; o++) { int good = outputs[o].GoodIndex; int units = ind.OutputStock[o]; if (units <= 0) continue; var reach = graph.From(s.Id, LineGraph.GoodCargo(good)); if (reach.Count == 0) continue; var dest = BestDestination(w, s, reach, good); if (dest is null) continue; var p = new Packet { Id = w.NextIds.Packet++, Kind = PacketKind.Freight, Good = good, Units = units, Origin = s.Id, Destination = dest.Destination, HopLine = dest.First.Line, HopEnd = dest.First.To, CreatedTick = ctx.Tick, ExpiresTick = ctx.Tick + (long)w.Data.Goods[good].DecayDaysAtStation * w.Calendar.TicksPerDay, ExpectedDays = w.Calendar.TrainMinutesToDays(dest.Minutes), Contract = -1, }; ind.OutputStock[o] = 0; ind.LastServedDay = ctx.Day; s.Waiting.Add(p); w.Network.Stations[dest.Destination.Value].Incoming[good] += units; var sale = Money.FromCentsRounded(units * w.Market.GlobalPrice[good]); w.Money.Transfer(Account.External, Account.Of(ind.Id), sale, LedgerEntry.Other); ind.SalesToday += sale.Cents; if (o == 0) ind.ShippedToday += units; } } if (s.Hubs.Count > 0) { ImportServiceGood(ctx, s, graph, w.Data.SparePartsGood); ImportServiceGood(ctx, s, graph, w.Data.MachineryGood); } } /// /// Un hub nel bacino importa ricambi e macchinari richiesti dalle officine e dalle industrie /// raggiungibili sulle linee (10.2, 11): li spedisce verso la stazione con più bisogno, entro la /// capacità mensile dell'hub. /// private void ImportServiceGood(WorldContext ctx, Station s, LineGraph graph, int good) { var w = ctx.World; var reach = graph.From(s.Id, LineGraph.GoodCargo(good)); if (reach.Count == 0) return; _candidates.Clear(); foreach (var key in reach.Keys) _candidates.Add((key, 0)); _candidates.Sort((a, b) => a.Station.CompareTo(b.Station)); Connection? best = null; int bestNeed = 0; foreach (var (sid, _) in _candidates) { var dest = w.Network.Stations[sid]; int need = ServiceNeed(w, dest, good) - dest.Incoming[good]; if (need <= bestNeed) continue; bestNeed = need; best = reach[sid]; } if (best is null) return; foreach (var id in s.Hubs) { if (bestNeed <= 0) return; var hub = w.Hubs[id.Value]; int units = Math.Min(bestNeed, hub.RemainingCapacity); if (units <= 0) continue; hub.UsedThisMonth += units; hub.ImportedThisMonth[good] += units; w.Goods.Imported[good] += units; bestNeed -= units; s.Waiting.Add(new Packet { Id = w.NextIds.Packet++, Kind = PacketKind.Freight, Good = good, Units = units, Origin = s.Id, Destination = best.Destination, HopLine = best.First.Line, HopEnd = best.First.To, CreatedTick = ctx.Tick, ExpiresTick = ctx.Tick + (long)w.Data.Goods[good].DecayDaysAtStation * w.Calendar.TicksPerDay, ExpectedDays = w.Calendar.TrainMinutesToDays(best.Minutes), Contract = -1, }); w.Network.Stations[best.Destination.Value].Incoming[good] += units; } } /// Ricambi o macchinari mancanti a officine e industrie nel bacino della stazione. private static int ServiceNeed(World w, Station s, int good) { int need = good == w.Data.SparePartsGood ? DepotNeed(w, s) : 0; foreach (var id in s.Industries) need += IndustryMath.ServiceNeed(w, w.Industries[id.Value], good); return need; } /// Ricambi mancanti alle officine nel bacino della stazione (scorta desiderata − scorta). private static int DepotNeed(World w, Station s) { int need = 0; foreach (var id in s.Depots) { var d = w.Network.Depots[id.Value]; if (w.Network.IsAlive(d)) need += Math.Max(0, d.PartsTarget - d.SpareParts); } return need; } private Connection? BestDestination(World w, Station from, IReadOnlyDictionary reach, int good) { Connection? best = null; double bestScore = double.NegativeInfinity; int dpm = w.Calendar.DaysPerMonth; var tb = w.Data.Balance.Town; _candidates.Clear(); foreach (var key in reach.Keys) _candidates.Add((key, 0)); _candidates.Sort((a, b) => a.Station.CompareTo(b.Station)); foreach (var (sid, _) in _candidates) { var dest = w.Network.Stations[sid]; var conn = reach[sid]; double need = 0; bool consumer = false; foreach (var id in dest.Industries) { var ind = w.Industries[id.Value]; if (ind.Closed) continue; int service = IndustryMath.ServiceNeed(w, ind, good); if (service > 0) { consumer = true; need += service; } int i = ind.InputIndexOf(good); if (i < 0) continue; consumer = true; need += IndustryMath.InputCapacity(ind, i, dpm) - ind.InputStock[i]; } foreach (var id in dest.Towns) { var town = w.Towns[id.Value]; if (town.DemandToday[good] <= 0) continue; consumer = true; need += town.DemandToday[good] * tb.StockDays - town.Stock[good]; } foreach (var id in dest.Hubs) { consumer = true; need += w.Hubs[id.Value].RemainingCapacity; } if (good == w.Data.SparePartsGood && dest.Depots.Count > 0) { consumer = true; need += DepotNeed(w, dest); } if (!consumer) continue; need -= dest.Incoming[good]; double score = need / (1 + conn.Minutes / 60); if (score > bestScore) { bestScore = score; best = conn; } } return best; } }