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>
This commit is contained in:
1 parent
3f00acb994
commit
e157dd77bc
32 files changed
+1624
-25
No files matched your search
@@ -47,6 +47,7 @@ public enum CommandType : ushort
|
||||
FundResearch = 37,
|
||||
DelegateRegion = 38,
|
||||
MergeCompany = 39,
|
||||
ShipGoods = 40,
|
||||
}
|
||||
|
||||
/// <summary>Codici di errore stabili degli esiti dei comandi.</summary>
|
||||
|
||||
@@ -51,18 +51,34 @@ public sealed record RejectAgreementCommand(AgreementId Agreement) : GameCommand
|
||||
public override CommandType Type => CommandType.RejectAgreement;
|
||||
}
|
||||
|
||||
/// <summary>Compra merce al prezzo locale in una stazione (commercio, livello 2).</summary>
|
||||
/// <summary>
|
||||
/// Compra fino a <paramref name="Units"/> unità del bene dai produttori e dagli hub nel bacino di una
|
||||
/// stazione della compagnia, al prezzo locale, senza superare <paramref name="MaxUnitPrice"/> per
|
||||
/// unità; la merce entra nel magazzino della stazione (commercio, sbloccato da tiers.json, ADR 0016).
|
||||
/// </summary>
|
||||
public sealed record BuyGoodsCommand(StationId Station, string Good, int Units, Money MaxUnitPrice) : GameCommand
|
||||
{
|
||||
public override CommandType Type => CommandType.BuyGoods;
|
||||
}
|
||||
|
||||
/// <summary>Vende merce della compagnia al prezzo locale in una stazione.</summary>
|
||||
/// <summary>
|
||||
/// Vende fino a <paramref name="Units"/> unità dal magazzino della stazione ai consumatori e agli hub
|
||||
/// del bacino, al prezzo locale, non sotto <paramref name="MinUnitPrice"/> per unità.
|
||||
/// </summary>
|
||||
public sealed record SellGoodsCommand(StationId Station, string Good, int Units, Money MinUnitPrice) : GameCommand
|
||||
{
|
||||
public override CommandType Type => CommandType.SellGoods;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Spedisce fino a <paramref name="Units"/> unità dal magazzino di una stazione a quello di un'altra
|
||||
/// stazione della compagnia sulle sue linee, senza tariffa; id 40, aggiunto in F6 (ADR 0016).
|
||||
/// </summary>
|
||||
public sealed record ShipGoodsCommand(StationId From, StationId To, string Good, int Units) : GameCommand
|
||||
{
|
||||
public override CommandType Type => CommandType.ShipGoods;
|
||||
}
|
||||
|
||||
/// <summary>Offerta d'acquisto di un'industria.</summary>
|
||||
public sealed record BuyIndustryCommand(IndustryId Industry, Money Offer) : GameCommand
|
||||
{
|
||||
|
||||
@@ -13,6 +13,7 @@ public sealed class BalanceFile
|
||||
public required MapBalance Map { get; init; }
|
||||
public required MarketBalance Market { get; init; }
|
||||
public required LocalPriceBalance LocalPrice { get; init; }
|
||||
public required TradingBalance Trading { get; init; }
|
||||
public required IndustryBalance Industry { get; init; }
|
||||
public required GrowthBalance Growth { get; init; }
|
||||
public required TownBalance Town { get; init; }
|
||||
@@ -211,6 +212,15 @@ public sealed class WorldMarketParams
|
||||
public required double PriceFloor { get; init; }
|
||||
}
|
||||
|
||||
/// <summary>Compravendita in proprio (F6, ADR 0016): magazzino della compagnia in ogni sua stazione.</summary>
|
||||
public sealed class TradingBalance
|
||||
{
|
||||
/// <summary>Unità complessive (tutti i beni, comprese le spedizioni in arrivo) per stazione.</summary>
|
||||
public required int WarehouseCapacity { get; init; }
|
||||
/// <summary>Costo di giacenza mensile per unità in magazzino (centesimi).</summary>
|
||||
public required long StorageCostPerUnitPerMonth { get; init; }
|
||||
}
|
||||
|
||||
public sealed class LocalPriceBalance
|
||||
{
|
||||
public required double Lambda { get; init; }
|
||||
|
||||
@@ -199,7 +199,7 @@ public static class MarketOutlook
|
||||
return (s * perMonth, d * perMonth, worldSupply * perMonth, worldDemand * perMonth);
|
||||
}
|
||||
|
||||
/// <summary>Giacenze di un bene nei magazzini (input e output) delle industrie aperte e nelle stazioni.</summary>
|
||||
/// <summary>Giacenze di un bene nei magazzini (input e output) delle industrie aperte e nelle stazioni (merci in attesa e magazzini delle compagnie).</summary>
|
||||
public static double StockUnits(World w, int good)
|
||||
{
|
||||
long sum = 0;
|
||||
@@ -218,6 +218,7 @@ public static class MarketOutlook
|
||||
{
|
||||
if (p.Kind == PacketKind.Freight && p.Good == good) sum += p.Units;
|
||||
}
|
||||
sum += s.StockOf(good);
|
||||
}
|
||||
return sum;
|
||||
}
|
||||
|
||||
@@ -342,6 +342,7 @@ public static class RailSerializer
|
||||
};
|
||||
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);
|
||||
|
||||
@@ -0,0 +1,89 @@
|
||||
using RailEnterprise.Core.Rail;
|
||||
using RailEnterprise.Core.Simulation;
|
||||
|
||||
namespace RailEnterprise.Core.Persistence;
|
||||
|
||||
/// <summary>
|
||||
/// Compravendita in proprio (corpo del salvataggio dalla versione 4, ADR 0016): magazzini della
|
||||
/// compagnia nelle stazioni (beni salvati per id testuale) e pacchetti di merce propria in stazione
|
||||
/// e a bordo, indicati per id. I salvataggi precedenti si caricano con i magazzini vuoti.
|
||||
/// </summary>
|
||||
public static class TradingSerializer
|
||||
{
|
||||
public static void Write(World w, SaveWriter s)
|
||||
{
|
||||
var goods = w.Data.Goods;
|
||||
s.Write(w.Network.Stations.Count);
|
||||
foreach (var st in w.Network.Stations)
|
||||
{
|
||||
int n = 0;
|
||||
foreach (int u in st.Stock) if (u != 0) n++;
|
||||
s.Write(n);
|
||||
for (int g = 0; g < st.Stock.Length; g++)
|
||||
{
|
||||
if (st.Stock[g] == 0) continue;
|
||||
s.Write(goods[g].Id);
|
||||
s.Write(st.Stock[g]);
|
||||
}
|
||||
WriteOwned(s, st.Waiting);
|
||||
}
|
||||
s.Write(w.Trains.Count);
|
||||
foreach (var t in w.Trains) WriteOwned(s, t.Cargo);
|
||||
}
|
||||
|
||||
private static void WriteOwned(SaveWriter s, List<Packet> packets)
|
||||
{
|
||||
int n = 0;
|
||||
foreach (var p in packets) if (p.Owned) n++;
|
||||
s.Write(n);
|
||||
foreach (var p in packets)
|
||||
{
|
||||
if (p.Owned) s.Write(p.Id);
|
||||
}
|
||||
}
|
||||
|
||||
public static void Read(World w, SaveReader r)
|
||||
{
|
||||
int stations = r.ReadInt32();
|
||||
for (int i = 0; i < stations; i++)
|
||||
{
|
||||
var st = i < w.Network.Stations.Count ? w.Network.Stations[i] : null;
|
||||
int n = r.ReadInt32();
|
||||
for (int k = 0; k < n; k++)
|
||||
{
|
||||
string id = r.ReadRequiredString();
|
||||
int units = r.ReadInt32();
|
||||
// un bene tolto dai dati sparisce dal magazzino, come negli altri depositi rimappati
|
||||
if (st is not null && w.Data.TryGoodIndex(id, out int g)) Simulation.Systems.TradingMath.AddToWarehouse(st, g, units, w.Data.GoodCount);
|
||||
}
|
||||
ReadOwned(r, st?.Waiting);
|
||||
}
|
||||
int trains = r.ReadInt32();
|
||||
for (int i = 0; i < trains; i++) ReadOwned(r, i < w.Trains.Count ? w.Trains[i].Cargo : null);
|
||||
}
|
||||
|
||||
private static void ReadOwned(SaveReader r, List<Packet>? packets)
|
||||
{
|
||||
int n = r.ReadInt32();
|
||||
if (n == 0) return;
|
||||
var ids = new HashSet<int>();
|
||||
for (int k = 0; k < n; k++) ids.Add(r.ReadInt32());
|
||||
if (packets is null) return;
|
||||
for (int i = 0; i < packets.Count; i++)
|
||||
{
|
||||
var p = packets[i];
|
||||
if (!ids.Contains(p.Id)) continue;
|
||||
p.Owned = true;
|
||||
packets[i] = p;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Salvataggi delle versioni 1–3: nessuna merce della compagnia, magazzini vuoti.</summary>
|
||||
public static void Migrate(World w)
|
||||
{
|
||||
foreach (var st in w.Network.Stations)
|
||||
{
|
||||
if (st.Stock.Length < w.Data.GoodCount) st.Stock = new int[w.Data.GoodCount];
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -14,16 +14,23 @@ namespace RailEnterprise.Core.Persistence;
|
||||
public static class WorldSerializer
|
||||
{
|
||||
/// <summary>Versione del corpo del salvataggio (migrazioni in <see cref="Read"/>).</summary>
|
||||
public const int BodyVersion = 3;
|
||||
public const int BodyVersion = 4;
|
||||
|
||||
/// <summary>Scrive l'intero mondo (impostazioni, terreno, stato dinamico, eventi).</summary>
|
||||
public static void Write(World w, SaveWriter s)
|
||||
public static void Write(World w, SaveWriter s) => Write(w, s, BodyVersion);
|
||||
|
||||
/// <summary>
|
||||
/// Scrive il corpo nel formato di una versione precedente (le sezioni nate dopo si omettono):
|
||||
/// serve a provare le migrazioni dei salvataggi.
|
||||
/// </summary>
|
||||
public static void Write(World w, SaveWriter s, int bodyVersion)
|
||||
{
|
||||
s.Write(BodyVersion);
|
||||
if (bodyVersion < 1 || bodyVersion > BodyVersion) throw new ArgumentOutOfRangeException(nameof(bodyVersion));
|
||||
s.Write(bodyVersion);
|
||||
WriteDictionary(w.Data, s);
|
||||
WriteSettings(w.Settings, s);
|
||||
WriteTerrain(w.Terrain, w.SeaSide, s);
|
||||
WriteDynamic(w, s);
|
||||
WriteDynamic(w, s, bodyVersion);
|
||||
s.Write(w.LastStateHash);
|
||||
s.Write(w.LastHashDay);
|
||||
WriteEvents(w.Events, s);
|
||||
@@ -33,7 +40,9 @@ public static class WorldSerializer
|
||||
/// Stato dinamico (tutto tranne terreno, impostazioni ed eventi): è ciò che entra nell'hash
|
||||
/// giornaliero. Il terreno vi entra attraverso il suo hash.
|
||||
/// </summary>
|
||||
public static void WriteDynamic(World w, SaveWriter s)
|
||||
public static void WriteDynamic(World w, SaveWriter s) => WriteDynamic(w, s, BodyVersion);
|
||||
|
||||
private static void WriteDynamic(World w, SaveWriter s, int version)
|
||||
{
|
||||
if (w.TerrainHash == 0) w.TerrainHash = w.Terrain.ComputeHash();
|
||||
s.Write(w.TerrainHash);
|
||||
@@ -234,8 +243,9 @@ public static class WorldSerializer
|
||||
}
|
||||
|
||||
RailSerializer.Write(w, s);
|
||||
MaintenanceSerializer.Write(w, s);
|
||||
CorporateSerializer.Write(w, s);
|
||||
if (version >= 2) MaintenanceSerializer.Write(w, s);
|
||||
if (version >= 3) CorporateSerializer.Write(w, s);
|
||||
if (version >= 4) TradingSerializer.Write(w, s);
|
||||
}
|
||||
|
||||
private static void WriteRecipeStock(List<RecipeItemDef> items, int[] stock, SaveWriter s)
|
||||
@@ -680,6 +690,9 @@ public static class WorldSerializer
|
||||
// versione 3 (F5): industrie, borsa, offerte, aste, fine partita, agenti IA
|
||||
if (version >= 3) CorporateSerializer.Read(w, r);
|
||||
else CorporateSerializer.Migrate(w);
|
||||
// versione 4 (F6): magazzini della compagnia e merce propria in viaggio
|
||||
if (version >= 4) TradingSerializer.Read(w, r);
|
||||
else TradingSerializer.Migrate(w);
|
||||
}
|
||||
|
||||
private static void ReadRecipeStock(List<RecipeItemDef> items, int[] stock, SaveReader r)
|
||||
|
||||
@@ -213,6 +213,26 @@ public sealed class Station
|
||||
/// <summary>Unità in arrivo per bene (merci già in viaggio verso questa stazione).</summary>
|
||||
public int[] Incoming { get; set; } = [];
|
||||
|
||||
/// <summary>
|
||||
/// Magazzino della compagnia proprietaria (compravendita in proprio, ADR 0016): unità per bene.
|
||||
/// Vuoto (lunghezza 0) finché non serve.
|
||||
/// </summary>
|
||||
public int[] Stock { get; set; } = [];
|
||||
|
||||
/// <summary>Unità nel magazzino della compagnia, tutti i beni.</summary>
|
||||
public int StockTotal
|
||||
{
|
||||
get
|
||||
{
|
||||
int n = 0;
|
||||
foreach (int u in Stock) n += u;
|
||||
return n;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Unità del bene nel magazzino della compagnia.</summary>
|
||||
public int StockOf(int good) => good >= 0 && good < Stock.Length ? Stock[good] : 0;
|
||||
|
||||
/// <summary>Industrie, città e hub nel bacino (ricalcolati quando cambia il mondo).</summary>
|
||||
public List<IndustryId> Industries { get; } = [];
|
||||
public List<TownId> Towns { get; } = [];
|
||||
|
||||
@@ -255,4 +255,9 @@ public struct Packet
|
||||
public bool ReturnTrip;
|
||||
/// <summary>Consegnato alla stazione di destinazione ma non ancora ai consumatori del bacino.</summary>
|
||||
public bool AwaitingConsumer;
|
||||
/// <summary>
|
||||
/// Merce della compagnia (spedizione tra magazzini, ADR 0016): niente tariffa né consumatore,
|
||||
/// all'arrivo entra nel magazzino della stazione di destinazione.
|
||||
/// </summary>
|
||||
public bool Owned;
|
||||
}
|
||||
@@ -59,6 +59,9 @@ public static class CommandProcessor
|
||||
OrderPartsCommand c => MaintenanceCommandHandlers.OrderParts(w, company, c, Reply),
|
||||
AcceptAgreementCommand c => MaintenanceCommandHandlers.AcceptAgreement(w, company, c, Reply),
|
||||
RejectAgreementCommand c => MaintenanceCommandHandlers.RejectAgreement(w, company, c, Reply),
|
||||
BuyGoodsCommand c => TradingCommandHandlers.Buy(w, company, c, Reply),
|
||||
SellGoodsCommand c => TradingCommandHandlers.Sell(w, company, c, Reply),
|
||||
ShipGoodsCommand c => TradingCommandHandlers.Ship(w, company, c, ctx, Reply),
|
||||
_ => Result(CommandError.NotImplemented, $"Comando {command.Type} non ancora disponibile"),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -177,6 +177,9 @@ public static class Corporate
|
||||
}
|
||||
s.Waiting.Clear();
|
||||
Array.Clear(s.Incoming);
|
||||
// merce dei magazzini della compagnia: persa con la liquidazione (ADR 0016)
|
||||
for (int g = 0; g < s.Stock.Length; g++) w.Goods.Decayed[g] += s.Stock[g];
|
||||
Array.Clear(s.Stock);
|
||||
}
|
||||
foreach (var com in w.Commutes)
|
||||
{
|
||||
|
||||
@@ -125,6 +125,7 @@ public static class RailCommandHandlers
|
||||
BuiltDay = w.Clock.Day,
|
||||
BuildCostCents = cost.Cents,
|
||||
Incoming = new int[w.Data.GoodCount],
|
||||
Stock = new int[w.Data.GoodCount],
|
||||
};
|
||||
node.Station = station.Id;
|
||||
w.Network.Stations.Add(station);
|
||||
@@ -254,6 +255,7 @@ public static class RailCommandHandlers
|
||||
if (node.Station != st.Id) return reply(CommandError.NotFound, "Stazione già demolita");
|
||||
if (st.PlatformTrain.Any(t => t >= 0)) return reply(CommandError.Blocked, "Ci sono treni in stazione");
|
||||
if (w.Lines.Any(l => !l.Removed && l.Stops.Any(s => s.Station == st.Id))) return reply(CommandError.NotAllowed, "La stazione è fermata di una linea");
|
||||
if (st.StockTotal > 0) return reply(CommandError.NotAllowed, "Il magazzino della stazione contiene merce: vendila o spediscila prima di demolire");
|
||||
if (st.Waiting.Any(p => p.Kind == PacketKind.Freight))
|
||||
{
|
||||
foreach (var p in st.Waiting.Where(p => p.Kind == PacketKind.Freight)) w.Goods.Decayed[p.Good] += p.Units;
|
||||
|
||||
@@ -240,7 +240,7 @@ public sealed class FleetMaintenanceSystem : ISimSystem
|
||||
{
|
||||
if (p.Kind != PacketKind.Freight) continue;
|
||||
w.Goods.Decayed[p.Good] += p.Units;
|
||||
if (!p.AwaitingConsumer && p.Destination.IsValid)
|
||||
if (!p.AwaitingConsumer && !p.Owned && p.Destination.IsValid)
|
||||
{
|
||||
var dest = net.Stations[p.Destination.Value];
|
||||
dest.Incoming[p.Good] = Math.Max(0, dest.Incoming[p.Good] - p.Units);
|
||||
|
||||
@@ -28,6 +28,7 @@ public sealed class StationSystem : ISimSystem
|
||||
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;
|
||||
@@ -101,7 +102,7 @@ public sealed class StationSystem : ISimSystem
|
||||
s.Waiting.RemoveAt(i);
|
||||
if (p.Kind != PacketKind.Freight) continue;
|
||||
w.Goods.Decayed[p.Good] += p.Units;
|
||||
if (!p.AwaitingConsumer)
|
||||
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);
|
||||
|
||||
@@ -118,6 +118,12 @@ public static class StationWork
|
||||
private static void Deliver(WorldContext ctx, Train t, Station s, Packet p)
|
||||
{
|
||||
var w = ctx.World;
|
||||
// merce della compagnia: niente tariffa né consumatore, entra nel magazzino (ADR 0016)
|
||||
if (p.Owned)
|
||||
{
|
||||
TradingCommandHandlers.Store(w, s, p);
|
||||
return;
|
||||
}
|
||||
var origin = w.Network.Stations[p.Origin.Value];
|
||||
double km = Vec2.Distance(origin.Position, s.Position) / 1000;
|
||||
double days = (ctx.Tick - p.CreatedTick) / (double)w.Calendar.TicksPerDay;
|
||||
@@ -174,6 +180,12 @@ public static class StationWork
|
||||
s.Waiting.Add(p);
|
||||
return;
|
||||
}
|
||||
// merce della compagnia senza più un percorso: resta nel magazzino di questa stazione (ADR 0016)
|
||||
if (p.Owned)
|
||||
{
|
||||
TradingCommandHandlers.Store(w, s, p);
|
||||
return;
|
||||
}
|
||||
// nessun collegamento ulteriore: le merci provano a essere consegnate qui, i passeggeri rinunciano
|
||||
if (p.Kind == PacketKind.Freight)
|
||||
{
|
||||
|
||||
@@ -0,0 +1,206 @@
|
||||
using RailEnterprise.Core.Economy;
|
||||
using RailEnterprise.Core.Rail;
|
||||
|
||||
namespace RailEnterprise.Core.Simulation.Systems;
|
||||
|
||||
/// <summary>Venditore o compratore nel bacino di una stazione per la compravendita in proprio.</summary>
|
||||
public enum TradePartyKind : byte { Industry = 0, Hub = 1 }
|
||||
|
||||
/// <summary>
|
||||
/// Controparte di uno scambio: industria (con l'indice dell'output o dell'input del bene) o hub;
|
||||
/// <see cref="Limit"/> è il massimo di unità che può dare o ricevere, <see cref="Units"/> quelle
|
||||
/// già scambiate, <see cref="Cents"/> il loro valore non arrotondato.
|
||||
/// </summary>
|
||||
public sealed class TradeParty
|
||||
{
|
||||
public required TradePartyKind Kind { get; init; }
|
||||
public required int Target { get; init; }
|
||||
public required int Slot { get; init; }
|
||||
public required int Limit { get; init; }
|
||||
public int Units { get; set; }
|
||||
public double Cents { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>Quotazione di un bene in una stazione: prezzo della prossima unità e unità disponibili (−1 senza controparti).</summary>
|
||||
public readonly record struct TradeQuote(double BuyPrice, int BuyUnits, double SellPrice, int SellUnits);
|
||||
|
||||
/// <summary>
|
||||
/// Formule della compravendita in proprio (ADR 0016), senza stato: prezzi locali marginali
|
||||
/// (ADR 0004 §3) di produttori e consumatori del bacino, prezzi degli hub, spazio del magazzino.
|
||||
/// </summary>
|
||||
public static class TradingMath
|
||||
{
|
||||
/// <summary>
|
||||
/// Prezzo locale della prossima unità comprata da un produttore che ne ha <paramref name="stock"/>
|
||||
/// in magazzino: Dl = spazio libero del magazzino dell'output, Sl = giacenza. Pieno vale
|
||||
/// (1 − λ)·Pg, a metà Pg, quasi vuoto fino a (1 + λ)·Pg, entro ±maxDeviation.
|
||||
/// </summary>
|
||||
public static double ProducerPrice(World w, Industry ind, int output, int stock)
|
||||
{
|
||||
int capacity = IndustryMath.OutputCapacity(ind, output, w.Calendar.DaysPerMonth);
|
||||
int good = ind.Def.Recipe.Outputs[output].GoodIndex;
|
||||
return Market.LocalPrice(w.Market.GlobalPrice[good], Math.Max(0, capacity - stock), stock, w.Data.Balance.LocalPrice);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Prezzo locale della prossima unità venduta a un consumatore che ne ha <paramref name="stock"/>
|
||||
/// nell'input: Dl = capienza dell'input (scorta desiderata), Sl = giacenza, come «Dove conviene vendere».
|
||||
/// </summary>
|
||||
public static double ConsumerPrice(World w, Industry ind, int input, int stock)
|
||||
{
|
||||
int desired = IndustryMath.InputCapacity(ind, input, w.Calendar.DaysPerMonth);
|
||||
int good = ind.Def.Recipe.Inputs[input].GoodIndex;
|
||||
return Market.LocalPrice(w.Market.GlobalPrice[good], desired, stock, w.Data.Balance.LocalPrice);
|
||||
}
|
||||
|
||||
/// <summary>Venditori del bene nel bacino: produttori aperti con il bene in magazzino e hub con capacità.</summary>
|
||||
public static List<TradeParty> Sellers(World w, Station s, int good)
|
||||
{
|
||||
var list = new List<TradeParty>();
|
||||
foreach (var id in s.Industries)
|
||||
{
|
||||
var ind = w.Industries[id.Value];
|
||||
int o = ind.OutputIndexOf(good);
|
||||
if (ind.Closed || o < 0 || ind.OutputStock[o] <= 0) continue;
|
||||
list.Add(new TradeParty { Kind = TradePartyKind.Industry, Target = ind.Id.Value, Slot = o, Limit = ind.OutputStock[o] });
|
||||
}
|
||||
foreach (var id in s.Hubs)
|
||||
{
|
||||
var hub = w.Hubs[id.Value];
|
||||
if (hub.RemainingCapacity > 0) list.Add(new TradeParty { Kind = TradePartyKind.Hub, Target = hub.Id.Value, Slot = -1, Limit = hub.RemainingCapacity });
|
||||
}
|
||||
return list;
|
||||
}
|
||||
|
||||
/// <summary>Compratori del bene nel bacino: industrie aperte con il bene in ricetta e spazio nell'input, hub con capacità.</summary>
|
||||
public static List<TradeParty> Buyers(World w, Station s, int good)
|
||||
{
|
||||
var list = new List<TradeParty>();
|
||||
int dpm = w.Calendar.DaysPerMonth;
|
||||
foreach (var id in s.Industries)
|
||||
{
|
||||
var ind = w.Industries[id.Value];
|
||||
int i = ind.InputIndexOf(good);
|
||||
if (ind.Closed || ind.Level <= 0 || i < 0) continue;
|
||||
int free = IndustryMath.InputCapacity(ind, i, dpm) - ind.InputStock[i];
|
||||
if (free > 0) list.Add(new TradeParty { Kind = TradePartyKind.Industry, Target = ind.Id.Value, Slot = i, Limit = free });
|
||||
}
|
||||
foreach (var id in s.Hubs)
|
||||
{
|
||||
var hub = w.Hubs[id.Value];
|
||||
if (hub.RemainingCapacity > 0) list.Add(new TradeParty { Kind = TradePartyKind.Hub, Target = hub.Id.Value, Slot = -1, Limit = hub.RemainingCapacity });
|
||||
}
|
||||
return list;
|
||||
}
|
||||
|
||||
/// <summary>Prezzo della prossima unità comprata dal venditore (dopo quelle già prese).</summary>
|
||||
public static double NextBuyPrice(World w, TradeParty p, int good)
|
||||
{
|
||||
if (p.Kind == TradePartyKind.Hub) return w.Hubs[p.Target].SellPrice(w.Market.GlobalPrice[good]);
|
||||
var ind = w.Industries[p.Target];
|
||||
return ProducerPrice(w, ind, p.Slot, ind.OutputStock[p.Slot] - p.Units);
|
||||
}
|
||||
|
||||
/// <summary>Prezzo della prossima unità venduta al compratore (dopo quelle già date).</summary>
|
||||
public static double NextSellPrice(World w, TradeParty p, int good)
|
||||
{
|
||||
if (p.Kind == TradePartyKind.Hub) return w.Hubs[p.Target].BuyPrice(w.Market.GlobalPrice[good]);
|
||||
var ind = w.Industries[p.Target];
|
||||
return ConsumerPrice(w, ind, p.Slot, ind.InputStock[p.Slot] + p.Units);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Venditore con la prossima unità più conveniente (prezzo crescente, poi industrie prima degli
|
||||
/// hub, poi id), null se nessuno ha ancora unità.
|
||||
/// </summary>
|
||||
public static TradeParty? CheapestSeller(World w, List<TradeParty> sellers, int good, out double price)
|
||||
{
|
||||
TradeParty? best = null;
|
||||
price = double.PositiveInfinity;
|
||||
foreach (var p in sellers)
|
||||
{
|
||||
if (p.Units >= p.Limit) continue;
|
||||
double q = NextBuyPrice(w, p, good);
|
||||
if (best is null || q < price || (q == price && Before(p, best)))
|
||||
{
|
||||
best = p;
|
||||
price = q;
|
||||
}
|
||||
}
|
||||
return best;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Compratore che paga di più la prossima unità (prezzo decrescente, poi industrie prima degli
|
||||
/// hub, poi id), null se nessuno ha ancora spazio; le industrie senza cassa per l'unità si saltano.
|
||||
/// </summary>
|
||||
public static TradeParty? BestBuyer(World w, List<TradeParty> buyers, int good, out double price)
|
||||
{
|
||||
TradeParty? best = null;
|
||||
price = double.NegativeInfinity;
|
||||
foreach (var p in buyers)
|
||||
{
|
||||
if (p.Units >= p.Limit) continue;
|
||||
double q = NextSellPrice(w, p, good);
|
||||
if (p.Kind == TradePartyKind.Industry && !CanPay(w.Industries[p.Target], p.Cents + q)) continue;
|
||||
if (best is null || q > price || (q == price && Before(p, best)))
|
||||
{
|
||||
best = p;
|
||||
price = q;
|
||||
}
|
||||
}
|
||||
return best;
|
||||
}
|
||||
|
||||
/// <summary>L'industria ha cassa per pagare <paramref name="cents"/> (arrotondati al centesimo).</summary>
|
||||
public static bool CanPay(Industry ind, double cents) => Common.Money.FromCentsRounded(cents).Cents <= ind.Cash.Cents;
|
||||
|
||||
private static bool Before(TradeParty a, TradeParty b) => a.Kind != b.Kind ? a.Kind < b.Kind : a.Target < b.Target;
|
||||
|
||||
/// <summary>
|
||||
/// Unità di merce della compagnia in viaggio (pacchetti propri in stazione e a bordo) verso
|
||||
/// ciascuna stazione: occupano già il magazzino di destinazione.
|
||||
/// </summary>
|
||||
public static int[] ReservedByStation(World w)
|
||||
{
|
||||
var reserved = new int[w.Network.Stations.Count];
|
||||
foreach (var s in w.Network.Stations) AddReserved(s.Waiting, reserved);
|
||||
foreach (var t in w.Trains) AddReserved(t.Cargo, reserved);
|
||||
return reserved;
|
||||
}
|
||||
|
||||
private static void AddReserved(List<Packet> packets, int[] reserved)
|
||||
{
|
||||
foreach (var p in packets)
|
||||
{
|
||||
if (!p.Owned || p.Kind != PacketKind.Freight) continue;
|
||||
int d = p.Destination.Value;
|
||||
if (d >= 0 && d < reserved.Length) reserved[d] += p.Units;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Spazio libero nel magazzino di una stazione (capacità − giacenza − spedizioni in arrivo).</summary>
|
||||
public static int FreeSpace(World w, Station s, int reserved) =>
|
||||
Math.Max(0, w.Data.Balance.Trading.WarehouseCapacity - s.StockTotal - reserved);
|
||||
|
||||
/// <summary>Aggiunge unità al magazzino della compagnia nella stazione (allarga il vettore se serve).</summary>
|
||||
public static void AddToWarehouse(Station s, int good, int units, int goodCount)
|
||||
{
|
||||
if (s.Stock.Length < goodCount) s.Stock = [.. s.Stock, .. new int[goodCount - s.Stock.Length]];
|
||||
s.Stock[good] += units;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Quotazione di un bene in una stazione: prezzo della prossima unità al venditore più
|
||||
/// conveniente e al compratore migliore, con le unità disponibili (cassa delle industrie esclusa).
|
||||
/// </summary>
|
||||
public static TradeQuote Quote(World w, Station s, int good)
|
||||
{
|
||||
var sellers = Sellers(w, s, good);
|
||||
var buyers = Buyers(w, s, good);
|
||||
double buy = -1, sell = -1;
|
||||
if (CheapestSeller(w, sellers, good, out double p) is not null) buy = p;
|
||||
foreach (var b in buyers) sell = Math.Max(sell, NextSellPrice(w, b, good));
|
||||
return new TradeQuote(buy, sellers.Sum(x => x.Limit), sell, buyers.Sum(x => x.Limit));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,267 @@
|
||||
using RailEnterprise.Core.Commands;
|
||||
using RailEnterprise.Core.Common;
|
||||
using RailEnterprise.Core.Economy;
|
||||
using RailEnterprise.Core.Rail;
|
||||
using RailEnterprise.Core.Simulation.Systems;
|
||||
|
||||
namespace RailEnterprise.Core.Simulation;
|
||||
|
||||
/// <summary>
|
||||
/// Compravendita in proprio (F6, ADR 0016): comprare dai produttori e dagli hub del bacino di una
|
||||
/// stazione al prezzo locale, rivendere ai consumatori e agli hub, spedire la merce tra i magazzini
|
||||
/// della compagnia sulle sue linee. Ogni comando valida tutto prima di cambiare il mondo; il denaro
|
||||
/// passa dal registro e la merce resta sempre in un magazzino tracciato.
|
||||
/// </summary>
|
||||
public static class TradingCommandHandlers
|
||||
{
|
||||
public static CommandResult Buy(World w, Company company, BuyGoodsCommand c, RailCommandHandlers.Reply reply)
|
||||
{
|
||||
if (!Check(w, company, c.Station, c.Good, c.Units, out var s, out int good, out var error)) return reply(error.Error, error.Message);
|
||||
if (!MarketOutlook.IsAvailable(w, good))
|
||||
return reply(CommandError.EraLocked, $"{GoodName(w, good)} non è ancora disponibile (dal {w.Data.Goods[good].Era})");
|
||||
int free = TradingMath.FreeSpace(w, s, TradingMath.ReservedByStation(w)[s.Id.Value]);
|
||||
if (free <= 0)
|
||||
return reply(CommandError.Blocked, $"Magazzino di {s.Name} pieno ({w.Data.Balance.Trading.WarehouseCapacity} unità comprese le spedizioni in arrivo)");
|
||||
var sellers = TradingMath.Sellers(w, s, good);
|
||||
if (TradingMath.CheapestSeller(w, sellers, good, out double first) is null)
|
||||
return reply(CommandError.NotFound, $"Nessun produttore né hub nel bacino di {s.Name} vende {GoodName(w, good)}");
|
||||
if (first > c.MaxUnitPrice.Cents)
|
||||
return reply(CommandError.InvalidArgument, $"Il prezzo più basso è {PerUnit(w, good, first)}, oltre il tetto di {PerUnit(w, good, c.MaxUnitPrice.Cents)}");
|
||||
|
||||
int want = Math.Min(c.Units, free);
|
||||
int bought = 0;
|
||||
long committed = 0;
|
||||
bool shortOfCash = false;
|
||||
string stop = want < c.Units ? "magazzino pieno" : "";
|
||||
while (bought < want)
|
||||
{
|
||||
var best = TradingMath.CheapestSeller(w, sellers, good, out double price);
|
||||
if (best is null)
|
||||
{
|
||||
stop = "esaurita la merce in vendita nel bacino";
|
||||
break;
|
||||
}
|
||||
if (price > c.MaxUnitPrice.Cents)
|
||||
{
|
||||
stop = "nessun'altra unità sotto il tetto di prezzo";
|
||||
break;
|
||||
}
|
||||
long next = committed - Rounded(best.Cents) + Rounded(best.Cents + price);
|
||||
if (next > company.Cash.Cents)
|
||||
{
|
||||
shortOfCash = true;
|
||||
stop = "cassa esaurita";
|
||||
break;
|
||||
}
|
||||
committed = next;
|
||||
best.Units++;
|
||||
best.Cents += price;
|
||||
bought++;
|
||||
}
|
||||
if (bought == 0)
|
||||
return reply(CommandError.InsufficientFunds, shortOfCash ? $"Cassa insufficiente: un'unità costa {PerUnit(w, good, first)}" : "Nessuna unità acquistabile");
|
||||
|
||||
var from = Account.Of(company.Id);
|
||||
foreach (var p in sellers)
|
||||
{
|
||||
if (p.Units == 0) continue;
|
||||
var amount = Money.FromCentsRounded(p.Cents);
|
||||
if (p.Kind == TradePartyKind.Industry)
|
||||
{
|
||||
var ind = w.Industries[p.Target];
|
||||
ind.OutputStock[p.Slot] -= p.Units;
|
||||
w.Money.Transfer(from, Account.Of(ind.Id), amount, LedgerEntry.Trading);
|
||||
ind.SalesToday += amount.Cents;
|
||||
if (p.Slot == 0) ind.ShippedToday += p.Units;
|
||||
ind.LastServedDay = w.Clock.Day;
|
||||
}
|
||||
else
|
||||
{
|
||||
var hub = w.Hubs[p.Target];
|
||||
hub.UsedThisMonth += p.Units;
|
||||
hub.ImportedThisMonth[good] += p.Units;
|
||||
w.Goods.Imported[good] += p.Units;
|
||||
w.Money.Transfer(from, Account.External, amount, LedgerEntry.Trading);
|
||||
}
|
||||
}
|
||||
TradingMath.AddToWarehouse(s, good, bought, w.Data.GoodCount);
|
||||
var total = new Money(committed);
|
||||
string limit = bought < c.Units ? $" ({stop})" : "";
|
||||
return reply(CommandError.None,
|
||||
$"Comprate {bought} {Unit(w, good)} di {GoodName(w, good)} a {s.Name} per {total} (in media {PerUnit(w, good, (double)committed / bought)}){limit}");
|
||||
}
|
||||
|
||||
public static CommandResult Sell(World w, Company company, SellGoodsCommand c, RailCommandHandlers.Reply reply)
|
||||
{
|
||||
if (!Check(w, company, c.Station, c.Good, c.Units, out var s, out int good, out var error)) return reply(error.Error, error.Message);
|
||||
int stock = s.StockOf(good);
|
||||
if (stock <= 0) return reply(CommandError.NotFound, $"Nel magazzino di {s.Name} non c'è {GoodName(w, good)}");
|
||||
var buyers = TradingMath.Buyers(w, s, good);
|
||||
if (buyers.Count == 0)
|
||||
{
|
||||
bool consumers = s.Industries.Any(id => w.Industries[id.Value] is { Closed: false } ind && ind.Level > 0 && ind.InputIndexOf(good) >= 0);
|
||||
return reply(CommandError.NotFound, consumers
|
||||
? $"I consumatori di {GoodName(w, good)} nel bacino di {s.Name} hanno il magazzino pieno"
|
||||
: $"Nessun consumatore né hub nel bacino di {s.Name} compra {GoodName(w, good)}");
|
||||
}
|
||||
var top = TradingMath.BestBuyer(w, buyers, good, out double first);
|
||||
if (top is null) return reply(CommandError.InsufficientFunds, $"Le industrie del bacino di {s.Name} non hanno cassa per pagare {GoodName(w, good)}");
|
||||
if (first < c.MinUnitPrice.Cents)
|
||||
return reply(CommandError.InvalidArgument, $"Il prezzo più alto è {PerUnit(w, good, first)}, sotto il minimo di {PerUnit(w, good, c.MinUnitPrice.Cents)}");
|
||||
|
||||
int want = Math.Min(c.Units, stock);
|
||||
int sold = 0;
|
||||
double cents = 0;
|
||||
while (sold < want)
|
||||
{
|
||||
var best = TradingMath.BestBuyer(w, buyers, good, out double price);
|
||||
if (best is null || price < c.MinUnitPrice.Cents) break;
|
||||
best.Units++;
|
||||
best.Cents += price;
|
||||
cents += price;
|
||||
sold++;
|
||||
}
|
||||
|
||||
var to = Account.Of(company.Id);
|
||||
long received = 0;
|
||||
foreach (var p in buyers)
|
||||
{
|
||||
if (p.Units == 0) continue;
|
||||
var amount = Money.FromCentsRounded(p.Cents);
|
||||
received += amount.Cents;
|
||||
if (p.Kind == TradePartyKind.Industry)
|
||||
{
|
||||
var ind = w.Industries[p.Target];
|
||||
ind.InputStock[p.Slot] += p.Units;
|
||||
w.Money.Transfer(Account.Of(ind.Id), to, amount, LedgerEntry.Trading);
|
||||
ind.PurchasesToday += amount.Cents;
|
||||
ind.LastServedDay = w.Clock.Day;
|
||||
}
|
||||
else
|
||||
{
|
||||
var hub = w.Hubs[p.Target];
|
||||
hub.UsedThisMonth += p.Units;
|
||||
hub.ExportedThisMonth[good] += p.Units;
|
||||
w.Goods.Exported[good] += p.Units;
|
||||
w.Money.Transfer(Account.External, to, amount, LedgerEntry.Trading);
|
||||
}
|
||||
}
|
||||
s.Stock[good] -= sold;
|
||||
string rest = sold < c.Units ? $" ({(sold < stock ? "i compratori del bacino non ne prendono altre a questo prezzo" : "tutto il magazzino")})" : "";
|
||||
return reply(CommandError.None,
|
||||
$"Vendute {sold} {Unit(w, good)} di {GoodName(w, good)} a {s.Name} per {new Money(received)} (in media {PerUnit(w, good, cents / sold)}){rest}");
|
||||
}
|
||||
|
||||
public static CommandResult Ship(World w, Company company, ShipGoodsCommand c, WorldContext ctx, RailCommandHandlers.Reply reply)
|
||||
{
|
||||
if (!Check(w, company, c.From, c.Good, c.Units, out var from, out int good, out var error)) return reply(error.Error, error.Message);
|
||||
if (!TryOwnStation(w, company, c.To, out var to, out error)) return reply(error.Error, error.Message);
|
||||
if (to.Id == from.Id) return reply(CommandError.InvalidArgument, "La stazione di partenza e quella di arrivo coincidono");
|
||||
int stock = from.StockOf(good);
|
||||
if (stock <= 0) return reply(CommandError.NotFound, $"Nel magazzino di {from.Name} non c'è {GoodName(w, good)}");
|
||||
var graph = w.LineGraphs.For(w, company.Id);
|
||||
if (!graph.From(from.Id, LineGraph.GoodCargo(good)).TryGetValue(to.Id.Value, out var conn))
|
||||
return reply(CommandError.NotFound, $"Nessuna linea della compagnia porta {GoodName(w, good)} da {from.Name} a {to.Name}");
|
||||
int free = TradingMath.FreeSpace(w, to, TradingMath.ReservedByStation(w)[to.Id.Value]);
|
||||
if (free <= 0)
|
||||
return reply(CommandError.Blocked, $"Magazzino di {to.Name} pieno ({w.Data.Balance.Trading.WarehouseCapacity} unità comprese le spedizioni in arrivo)");
|
||||
|
||||
int units = Math.Min(Math.Min(c.Units, stock), free);
|
||||
var packet = new Packet
|
||||
{
|
||||
Id = w.NextIds.Packet++,
|
||||
Kind = PacketKind.Freight,
|
||||
Good = good,
|
||||
Units = units,
|
||||
Origin = from.Id,
|
||||
Destination = to.Id,
|
||||
HopLine = conn.First.Line,
|
||||
HopEnd = conn.First.To,
|
||||
CreatedTick = ctx.Tick,
|
||||
ExpiresTick = ctx.Tick + (long)w.Data.Goods[good].DecayDaysAtStation * w.Calendar.TicksPerDay,
|
||||
ExpectedDays = w.Calendar.TrainMinutesToDays(conn.Minutes),
|
||||
Contract = -1,
|
||||
Owned = true,
|
||||
};
|
||||
from.Stock[good] -= units;
|
||||
from.Waiting.Add(packet);
|
||||
string limit = units < c.Units ? $" ({(units == stock ? "tutta la giacenza" : $"limitate dallo spazio libero a {to.Name}")})" : "";
|
||||
return reply(CommandError.None,
|
||||
$"Spedite {units} {Unit(w, good)} di {GoodName(w, good)} da {from.Name} a {to.Name}, circa {packet.ExpectedDays:0.#} giorni di viaggio{limit}",
|
||||
packet.Id);
|
||||
}
|
||||
|
||||
/// <summary>Merce della compagnia arrivata a destinazione o senza più un percorso: entra nel magazzino della stazione.</summary>
|
||||
public static void Store(World w, Station s, Packet p) => TradingMath.AddToWarehouse(s, p.Good, p.Units, w.Data.GoodCount);
|
||||
|
||||
/// <summary>
|
||||
/// Costo di giacenza mensile (trading.storageCostPerUnitPerMonth) per ogni unità nei magazzini
|
||||
/// delle stazioni, addebitato alla compagnia proprietaria sulla voce «Commercio».
|
||||
/// </summary>
|
||||
public static void ChargeStorage(World w)
|
||||
{
|
||||
long perUnit = w.Data.Balance.Trading.StorageCostPerUnitPerMonth;
|
||||
if (perUnit <= 0) return;
|
||||
foreach (var s in w.Network.Stations)
|
||||
{
|
||||
int units = s.StockTotal;
|
||||
if (units <= 0 || !s.Owner.IsValid || s.Owner.Value >= w.Companies.Count) continue;
|
||||
w.Money.Transfer(Account.Of(s.Owner), Account.External, new Money(perUnit * units), LedgerEntry.Trading);
|
||||
}
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ validazione
|
||||
|
||||
private static bool Check(World w, Company company, StationId station, string goodId, int units, out Station s, out int good,
|
||||
out (CommandError Error, string Message) error)
|
||||
{
|
||||
good = -1;
|
||||
s = null!;
|
||||
if (!Tiers.Unlocks(w, company).Trading)
|
||||
{
|
||||
var tier = w.Data.Tiers.Tiers.FirstOrDefault(t => t.Unlocks.Trading);
|
||||
error = (CommandError.TierLocked, tier is null
|
||||
? "La compravendita in proprio non è disponibile"
|
||||
: $"La compravendita in proprio si sblocca al livello «{tier.NameIt}»");
|
||||
return false;
|
||||
}
|
||||
if (!TryOwnStation(w, company, station, out s, out error)) return false;
|
||||
if (!w.Data.TryGoodIndex(goodId ?? "", out good))
|
||||
{
|
||||
error = (CommandError.NotFound, $"Merce sconosciuta: {goodId}");
|
||||
return false;
|
||||
}
|
||||
if (units <= 0)
|
||||
{
|
||||
error = (CommandError.InvalidArgument, "Quantità non valida");
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
private static bool TryOwnStation(World w, Company company, StationId id, out Station s, out (CommandError Error, string Message) error)
|
||||
{
|
||||
s = null!;
|
||||
error = default;
|
||||
if (!id.IsValid || id.Value >= w.Network.Stations.Count || !w.Network.IsAlive(w.Network.Stations[id.Value]))
|
||||
{
|
||||
error = (CommandError.NotFound, "Stazione inesistente o demolita");
|
||||
return false;
|
||||
}
|
||||
s = w.Network.Stations[id.Value];
|
||||
if (s.Owner != company.Id)
|
||||
{
|
||||
error = (CommandError.NotAllowed, $"{s.Name} non è una stazione della compagnia");
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
private static long Rounded(double cents) => Money.FromCentsRounded(cents).Cents;
|
||||
|
||||
private static string GoodName(World w, int good) => w.Data.Goods[good].NameIt.ToLowerInvariant();
|
||||
|
||||
private static string Unit(World w, int good) => w.Data.Goods[good].Unit;
|
||||
|
||||
private static string PerUnit(World w, int good, double cents) => $"{Money.FromCentsRounded(cents)}/{Unit(w, good)}";
|
||||
}
|
||||
@@ -184,6 +184,7 @@ public sealed class World
|
||||
{
|
||||
if (p.Kind == PacketKind.Freight && p.Good == good) sum += p.Units;
|
||||
}
|
||||
sum += s.StockOf(good);
|
||||
}
|
||||
foreach (var tr in Trains)
|
||||
{
|
||||
|
||||
@@ -161,6 +161,12 @@ public static class CommandCodec
|
||||
w.Money(c.Budget);
|
||||
break;
|
||||
case MergeCompanyCommand c: w.I32(c.Subsidiary.Value); break;
|
||||
case ShipGoodsCommand c:
|
||||
w.I32(c.From.Value);
|
||||
w.I32(c.To.Value);
|
||||
w.String(c.Good);
|
||||
w.I32(c.Units);
|
||||
break;
|
||||
default:
|
||||
throw new ProtocolException($"comando senza codifica: {command.Type}");
|
||||
}
|
||||
@@ -225,6 +231,7 @@ public static class CommandCodec
|
||||
CommandType.FundResearch => new FundResearchCommand(r.String(), r.Money()),
|
||||
CommandType.DelegateRegion => new DelegateRegionCommand(new RegionId(r.I32()), r.String(), r.Money()),
|
||||
CommandType.MergeCompany => new MergeCompanyCommand(new CompanyId(r.I32())),
|
||||
CommandType.ShipGoods => new ShipGoodsCommand(new StationId(r.I32()), new StationId(r.I32()), r.String(), r.I32()),
|
||||
_ => throw new ProtocolException($"tipo di comando sconosciuto: {(ushort)type}"),
|
||||
};
|
||||
byte flags = r.Flags();
|
||||
|
||||
@@ -146,6 +146,60 @@ public sealed class HubMarketInfo
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Bene nel magazzino di una stazione della compagnia (compravendita in proprio, ADR 0016): unità
|
||||
/// possedute e quotazione della prossima unità al venditore più conveniente e al compratore migliore
|
||||
/// del bacino (−1 senza controparti), con le unità che offrono o accettano.
|
||||
/// </summary>
|
||||
public sealed class WarehouseGoodInfo
|
||||
{
|
||||
public int Good { get; init; }
|
||||
public int Units { get; init; }
|
||||
public double BuyPrice { get; init; } = -1;
|
||||
public int BuyUnits { get; init; }
|
||||
public double SellPrice { get; init; } = -1;
|
||||
public int SellUnits { get; init; }
|
||||
|
||||
public void Write(ref SpanWriter w)
|
||||
{
|
||||
w.I32(Good); w.I32(Units); w.F64(BuyPrice); w.I32(BuyUnits); w.F64(SellPrice); w.I32(SellUnits);
|
||||
w.Flags(0);
|
||||
}
|
||||
|
||||
public static WarehouseGoodInfo Read(ref SpanReader r)
|
||||
{
|
||||
var m = new WarehouseGoodInfo { Good = r.I32(), Units = r.I32(), BuyPrice = r.F64(), BuyUnits = r.I32(), SellPrice = r.F64(), SellUnits = r.I32() };
|
||||
r.Flags();
|
||||
return m;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Magazzino della compagnia in una sua stazione: capacità, merce in arrivo e beni.</summary>
|
||||
public sealed class WarehouseInfo
|
||||
{
|
||||
public int Station { get; init; }
|
||||
public int Capacity { get; init; }
|
||||
/// <summary>Unità di merce propria in viaggio verso la stazione (occupano già il magazzino).</summary>
|
||||
public int Incoming { get; init; }
|
||||
public List<WarehouseGoodInfo> Goods { get; init; } = [];
|
||||
|
||||
public void Write(ref SpanWriter w)
|
||||
{
|
||||
w.I32(Station); w.I32(Capacity); w.I32(Incoming);
|
||||
w.Count(Goods.Count);
|
||||
foreach (var g in Goods) g.Write(ref w);
|
||||
w.Flags(0);
|
||||
}
|
||||
|
||||
public static WarehouseInfo Read(ref SpanReader r)
|
||||
{
|
||||
var m = new WarehouseInfo { Station = r.I32(), Capacity = r.I32(), Incoming = r.I32() };
|
||||
for (int n = r.Count(), i = 0; i < n; i++) m.Goods.Add(WarehouseGoodInfo.Read(ref r));
|
||||
r.Flags();
|
||||
return m;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Quadro del mercato globale per la compagnia della sessione (F6): indice materie prime, beni con
|
||||
/// storico mensile e previsione, hub, evento in corso e avanzamento verso la compravendita in proprio.
|
||||
@@ -175,6 +229,8 @@ public sealed class MarketReport : IMessage
|
||||
public string Rating { get; init; } = "";
|
||||
public string RatingRequired { get; init; } = "";
|
||||
public bool RatingMet { get; init; }
|
||||
/// <summary>Blocco 1: magazzini della compagnia nelle sue stazioni vive (ADR 0016).</summary>
|
||||
public List<WarehouseInfo> Warehouses { get; init; } = [];
|
||||
|
||||
public void Write(ref SpanWriter w)
|
||||
{
|
||||
@@ -186,7 +242,10 @@ public sealed class MarketReport : IMessage
|
||||
w.I32(EventGood); w.F32(EventShock); w.F32(EventMonths);
|
||||
w.Bool(TradingUnlocked); w.U8(TradingTier); w.F32(TradingProgress); w.Money(NetWorth); w.Money(NetWorthRequired);
|
||||
w.I32(TownsConnected); w.I32(TownsRequired); w.I32(TownPopulation); w.String(Rating); w.String(RatingRequired); w.Bool(RatingMet);
|
||||
w.Flags(0);
|
||||
w.Flags(Warehouses.Count > 0 ? (byte)1 : (byte)0);
|
||||
if (Warehouses.Count == 0) return;
|
||||
w.Count(Warehouses.Count);
|
||||
foreach (var h in Warehouses) h.Write(ref w);
|
||||
}
|
||||
|
||||
public static MarketReport Read(ref SpanReader r)
|
||||
@@ -204,7 +263,11 @@ public sealed class MarketReport : IMessage
|
||||
TradingUnlocked = r.Bool(), TradingTier = r.U8(), TradingProgress = r.F32(), NetWorth = r.Money(), NetWorthRequired = r.Money(),
|
||||
TownsConnected = r.I32(), TownsRequired = r.I32(), TownPopulation = r.I32(), Rating = r.String(), RatingRequired = r.String(), RatingMet = r.Bool(),
|
||||
};
|
||||
r.Flags();
|
||||
byte flags = r.Flags();
|
||||
if ((flags & 1) != 0)
|
||||
{
|
||||
for (int n = r.Count(), i = 0; i < n; i++) m.Warehouses.Add(WarehouseInfo.Read(ref r));
|
||||
}
|
||||
return m;
|
||||
}
|
||||
}
|
||||
@@ -547,6 +547,34 @@ public static class Projection
|
||||
NetWorth = trading.NetWorth, NetWorthRequired = trading.NetWorthRequired, TownsConnected = trading.TownsConnected,
|
||||
TownsRequired = trading.TownsRequired, TownPopulation = trading.TownPopulation, Rating = trading.Rating.ToString(),
|
||||
RatingRequired = trading.RatingRequired.ToString(), RatingMet = trading.RatingMet,
|
||||
Warehouses = Warehouses(w, company),
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Magazzini della compagnia nelle sue stazioni vive (ADR 0016): giacenze, merce in arrivo e
|
||||
/// quotazioni locali dei beni disponibili che si possono comprare, vendere o che sono in magazzino.
|
||||
/// </summary>
|
||||
public static List<WarehouseInfo> Warehouses(World w, CompanyId company)
|
||||
{
|
||||
var list = new List<WarehouseInfo>();
|
||||
if (!company.IsValid) return list;
|
||||
int[]? reserved = null;
|
||||
foreach (var s in w.Network.Stations)
|
||||
{
|
||||
if (s.Owner != company || !w.Network.IsAlive(s)) continue;
|
||||
reserved ??= TradingMath.ReservedByStation(w);
|
||||
var goods = new List<WarehouseGoodInfo>();
|
||||
for (int g = 0; g < w.Data.GoodCount; g++)
|
||||
{
|
||||
int units = s.StockOf(g);
|
||||
if (units <= 0 && !MarketOutlook.IsAvailable(w, g)) continue;
|
||||
var q = TradingMath.Quote(w, s, g);
|
||||
if (units <= 0 && q.BuyUnits <= 0 && q.SellUnits <= 0) continue;
|
||||
goods.Add(new WarehouseGoodInfo { Good = g, Units = units, BuyPrice = q.BuyPrice, BuyUnits = q.BuyUnits, SellPrice = q.SellPrice, SellUnits = q.SellUnits });
|
||||
}
|
||||
list.Add(new WarehouseInfo { Station = s.Id.Value, Capacity = w.Data.Balance.Trading.WarehouseCapacity, Incoming = reserved[s.Id.Value], Goods = goods });
|
||||
}
|
||||
return list;
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user