F1: economia headless, dati validati, generatore di mappa e salvataggi
- Base deterministica: Money, id tipizzati, DMath, XxHash64, calendario - 12 file dati con schemi, validatore di schema interno, validazione semantica e hash dei dati; viaferrea-tools validate-data - Generatore di mappa (rilievo, mare, priority-flood, fiumi, laghi, copertura, giacimenti, città, hub, industrie) e viaferrea-tools genmap - Economia: città, industrie, hub, mercato con componente mondiale, prezzi locali, tariffe, lavoro in sede e a piedi, trasporto locale, registro a partita doppia, prestiti, rating, difficoltà - Salvataggi Brotli con rimappatura per id e hash di stato giornaliero - viaferrea-tools simulate con KPI CSV; 45 test verdi; ADR 0002-0006 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_0191R7vXgtbAvSV4V8tj8uzL
This commit is contained in:
113 files changed
+12553
-23
No files matched your search
@@ -0,0 +1,19 @@
|
||||
namespace ViaFerrea.Core.Simulation.Systems;
|
||||
|
||||
/// <summary>Primo sistema del tick: calcola una volta gli indicatori di calendario.</summary>
|
||||
public sealed class ClockSystem : ISimSystem
|
||||
{
|
||||
public string Name => "Clock";
|
||||
|
||||
public void Step(WorldContext ctx)
|
||||
{
|
||||
var clock = ctx.World.Clock;
|
||||
ctx.Tick = clock.Tick;
|
||||
ctx.Day = clock.Day;
|
||||
ctx.Year = clock.Year;
|
||||
ctx.IsNewDay = clock.IsNewDay;
|
||||
ctx.IsNewMonth = clock.IsNewMonth;
|
||||
ctx.IsNewQuarter = clock.IsNewQuarter;
|
||||
ctx.IsNewYear = clock.IsNewYear;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
using ViaFerrea.Core.Commands;
|
||||
|
||||
namespace ViaFerrea.Core.Simulation.Systems;
|
||||
|
||||
/// <summary>Drena la coda dei comandi a inizio tick e ne registra gli esiti.</summary>
|
||||
public sealed class CommandSystem : ISimSystem
|
||||
{
|
||||
public string Name => "Commands";
|
||||
|
||||
public void Step(WorldContext ctx)
|
||||
{
|
||||
var world = ctx.World;
|
||||
while (world.TryDequeueCommand(out var command))
|
||||
{
|
||||
world.CommandLog?.Add((ctx.Tick, command));
|
||||
var result = CommandProcessor.Execute(world, command, ctx);
|
||||
world.AddResult(result);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
using ViaFerrea.Core.Common;
|
||||
using ViaFerrea.Core.Economy;
|
||||
|
||||
namespace ViaFerrea.Core.Simulation.Systems;
|
||||
|
||||
/// <summary>
|
||||
/// Domanda giornaliera: consumo desiderato delle città (con elasticità al prezzo) e input
|
||||
/// richiesti dalle industrie al loro potenziale di lavoro. Alimenta D del mercato.
|
||||
/// </summary>
|
||||
public sealed class DemandSystem : ISimSystem
|
||||
{
|
||||
public string Name => "Demand";
|
||||
|
||||
public void Step(WorldContext ctx)
|
||||
{
|
||||
if (!ctx.IsNewDay) return;
|
||||
var w = ctx.World;
|
||||
var data = w.Data;
|
||||
var market = w.Market;
|
||||
int year = ctx.Year;
|
||||
|
||||
foreach (var town in w.Towns)
|
||||
{
|
||||
for (int g = 0; g < data.GoodCount; g++)
|
||||
{
|
||||
double d = TownDemand(w, town, g, year);
|
||||
town.DemandToday[g] = d;
|
||||
market.DemandToday[g] += d;
|
||||
}
|
||||
}
|
||||
|
||||
int dpm = w.Calendar.DaysPerMonth;
|
||||
foreach (var ind in w.Industries)
|
||||
{
|
||||
if (ind.Closed || ind.Level <= 0)
|
||||
{
|
||||
Array.Clear(ind.InputDemandToday);
|
||||
continue;
|
||||
}
|
||||
double eLabor = Math.Min(ind.CovWorkers, ind.CovStaff) * IndustryMath.ProfitFactor(ind, data.Balance.Industry)
|
||||
* IndustryMath.ConditionMultiplier(ind.Condition, data.Balance.IndustryMaintenance);
|
||||
double cycles = ind.CyclesPerDayAtFullCapacity(dpm) * eLabor;
|
||||
var inputs = ind.Def.Recipe.Inputs;
|
||||
for (int i = 0; i < inputs.Count; i++)
|
||||
{
|
||||
double need = cycles * inputs[i].PerCycle;
|
||||
ind.InputDemandToday[i] = need;
|
||||
market.DemandToday[inputs[i].GoodIndex] += need;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Domanda giornaliera di una città per un bene, in unità.</summary>
|
||||
public static double TownDemand(World w, Town town, int good, int year)
|
||||
{
|
||||
var def = w.Data.Goods[good];
|
||||
if (def.Town is not { } td || def.Era > year || (td.UntilYear is { } until && year >= until)) return 0;
|
||||
double ratio = w.Market.GlobalPrice[good] / def.BasePrice;
|
||||
double priceFactor = DMath.Clamp(DMath.Pow(ratio, -def.Elasticity), 0.5, 1.5);
|
||||
return town.Population / 1000.0 * td.DemandPerThousand * priceFactor;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,151 @@
|
||||
using ViaFerrea.Core.Common;
|
||||
using ViaFerrea.Core.Data;
|
||||
using ViaFerrea.Core.Economy;
|
||||
|
||||
namespace ViaFerrea.Core.Simulation.Systems;
|
||||
|
||||
/// <summary>
|
||||
/// Pendolarismo (guida, sezione 9). In F1 gestisce i servizi cittadini, i lavoratori in sede e i
|
||||
/// contratti a piedi verso posti di lavoro entro il raggio pedonale; i contratti su rotaia
|
||||
/// arrivano in F4 con il LineGraph. Ogni mese ricostruisce i contratti a piedi; ogni giorno
|
||||
/// aggiorna presenze e coperture.
|
||||
/// </summary>
|
||||
public sealed class EmploymentSystem : ISimSystem
|
||||
{
|
||||
public string Name => "Commuting";
|
||||
|
||||
public void Step(WorldContext ctx)
|
||||
{
|
||||
if (!ctx.IsNewDay) return;
|
||||
if (ctx.IsNewMonth) Rematch(ctx);
|
||||
UpdatePresence(ctx);
|
||||
}
|
||||
|
||||
/// <summary>Ricostruisce servizi cittadini e contratti a piedi.</summary>
|
||||
public static void Rematch(WorldContext ctx)
|
||||
{
|
||||
var w = ctx.World;
|
||||
var tb = w.Data.Balance.Town;
|
||||
var ib = w.Data.Balance.Industry;
|
||||
var eb = w.Data.Balance.Employment;
|
||||
|
||||
w.Commutes.RemoveAll(c => c.Walking);
|
||||
|
||||
foreach (var town in w.Towns)
|
||||
{
|
||||
int workforce = town.Workforce(tb);
|
||||
town.ServiceJobs = Math.Min(workforce, (int)(town.Population * tb.ServiceJobsShare));
|
||||
town.EmployedWorkers = town.ServiceJobs;
|
||||
town.EmployedStaff = 0;
|
||||
}
|
||||
// i contratti su rotaia (F4) restano validi e occupano forza lavoro
|
||||
foreach (var c in w.Commutes)
|
||||
{
|
||||
var town = w.Towns[c.Town.Value];
|
||||
if (c.Category == PaxClass.Staff) town.EmployedStaff += c.Headcount;
|
||||
else town.EmployedWorkers += c.Headcount;
|
||||
}
|
||||
|
||||
foreach (var ind in w.Industries)
|
||||
{
|
||||
ind.ContractedWorkers = 0;
|
||||
ind.ContractedStaff = 0;
|
||||
}
|
||||
foreach (var c in w.Commutes)
|
||||
{
|
||||
if (c.Workplace.Kind != WorkplaceKind.Industry) continue;
|
||||
var ind = w.Industries[c.Workplace.Index];
|
||||
if (c.Category == PaxClass.Staff) ind.ContractedStaff += c.Headcount;
|
||||
else ind.ContractedWorkers += c.Headcount;
|
||||
}
|
||||
|
||||
var nearby = new List<(double Km, Town Town)>();
|
||||
foreach (var ind in w.Industries)
|
||||
{
|
||||
if (ind.Closed || ind.Level <= 0) continue;
|
||||
nearby.Clear();
|
||||
foreach (var town in w.Towns)
|
||||
{
|
||||
double km = w.TownEdgeDistanceKm(town, ind.Position);
|
||||
if (km <= eb.WalkRadiusKm) nearby.Add((km, town));
|
||||
}
|
||||
if (nearby.Count == 0) continue;
|
||||
nearby.Sort((a, b) => a.Km != b.Km ? a.Km.CompareTo(b.Km) : a.Town.Id.Value.CompareTo(b.Town.Id.Value));
|
||||
|
||||
int openWorkers = ind.JobsWorkers - (int)Math.Ceiling(OnSite(ind.JobsWorkers, ib.OnSiteWorkerShare)) - ind.ContractedWorkers;
|
||||
int openStaff = ind.JobsStaff - (int)Math.Ceiling(OnSite(ind.JobsStaff, ib.OnSiteStaffShare)) - ind.ContractedStaff;
|
||||
foreach (var (km, town) in nearby)
|
||||
{
|
||||
if (openWorkers > 0)
|
||||
{
|
||||
int take = Math.Min(openWorkers, town.FreeWorkers(tb));
|
||||
if (take > 0)
|
||||
{
|
||||
AddWalking(w, town, ind, PaxClass.Worker, take, km, eb);
|
||||
town.EmployedWorkers += take;
|
||||
ind.ContractedWorkers += take;
|
||||
openWorkers -= take;
|
||||
}
|
||||
}
|
||||
if (openStaff > 0)
|
||||
{
|
||||
int take = Math.Min(openStaff, town.FreeStaff(tb));
|
||||
if (take > 0)
|
||||
{
|
||||
AddWalking(w, town, ind, PaxClass.Staff, take, km, eb);
|
||||
town.EmployedStaff += take;
|
||||
ind.ContractedStaff += take;
|
||||
openStaff -= take;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static void AddWalking(World w, Town town, Industry ind, PaxClass category, int headcount, double km, EmploymentBalance eb)
|
||||
{
|
||||
w.Commutes.Add(new CommuteContract
|
||||
{
|
||||
Id = new ContractId(w.NextIds.Contract++),
|
||||
Town = town.Id,
|
||||
Workplace = WorkplaceRef.Of(ind.Id),
|
||||
Category = category,
|
||||
Headcount = headcount,
|
||||
ExpectedMinutes = km / eb.WalkSpeedKmh * 60.0,
|
||||
});
|
||||
}
|
||||
|
||||
/// <summary>Posti coperti da chi vive in sede (quota fissa dei posti, frazionaria).</summary>
|
||||
public static double OnSite(int jobs, double share) => jobs * share;
|
||||
|
||||
private static void UpdatePresence(WorldContext ctx)
|
||||
{
|
||||
var w = ctx.World;
|
||||
var ib = w.Data.Balance.Industry;
|
||||
var eb = w.Data.Balance.Employment;
|
||||
foreach (var ind in w.Industries)
|
||||
{
|
||||
ind.WorkersPresent = OnSite(ind.JobsWorkers, ib.OnSiteWorkerShare);
|
||||
ind.StaffPresent = OnSite(ind.JobsStaff, ib.OnSiteStaffShare);
|
||||
}
|
||||
foreach (var c in w.Commutes)
|
||||
{
|
||||
// a piedi si arriva sempre; su rotaia contano i passeggeri consegnati (F4)
|
||||
if (c.Walking) c.ArrivedToday = c.Headcount;
|
||||
double ratio = c.Headcount > 0 ? Math.Min(1.0, (double)c.ArrivedToday / c.Headcount) : 0;
|
||||
c.Coverage = Ema.Step(c.Coverage, ratio, eb.CoverageEmaDays);
|
||||
if (c.Workplace.Kind == WorkplaceKind.Industry)
|
||||
{
|
||||
var ind = w.Industries[c.Workplace.Index];
|
||||
if (c.Category == PaxClass.Staff) ind.StaffPresent += c.ArrivedToday;
|
||||
else ind.WorkersPresent += c.ArrivedToday;
|
||||
}
|
||||
if (!c.Walking) c.ArrivedToday = 0;
|
||||
}
|
||||
foreach (var ind in w.Industries)
|
||||
{
|
||||
ind.WorkersPresent = Math.Min(ind.WorkersPresent, ind.JobsWorkers);
|
||||
ind.StaffPresent = Math.Min(ind.StaffPresent, ind.JobsStaff);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,113 @@
|
||||
using ViaFerrea.Core.Common;
|
||||
using ViaFerrea.Core.Data;
|
||||
using ViaFerrea.Core.Economy;
|
||||
|
||||
namespace ViaFerrea.Core.Simulation.Systems;
|
||||
|
||||
/// <summary>
|
||||
/// Finanza delle compagnie: giorni di cassa negativa e bancarotta, rate mensili dei prestiti,
|
||||
/// rating di credito, chiusura dei conti mensili e annuali (guida 6.3).
|
||||
/// </summary>
|
||||
public sealed class FinanceSystem : ISimSystem
|
||||
{
|
||||
public string Name => "Finance";
|
||||
|
||||
public void Step(WorldContext ctx)
|
||||
{
|
||||
if (!ctx.IsNewDay) return;
|
||||
var w = ctx.World;
|
||||
foreach (var c in w.Companies)
|
||||
{
|
||||
if (c.Bankrupt) continue;
|
||||
c.NegativeCashDays = c.Cash.IsNegative ? c.NegativeCashDays + 1 : 0;
|
||||
if (c.NegativeCashDays >= w.Difficulty.BankruptcyDays)
|
||||
{
|
||||
c.Bankrupt = true;
|
||||
ctx.World.Events.Add(new GameEvent(ctx.Day, EventKind.Finance, EventSeverity.Critical,
|
||||
$"{c.Name}: dichiarata la bancarotta dopo {c.NegativeCashDays} giorni di cassa negativa", EntityKind.Company, c.Id.Value, c.Id));
|
||||
}
|
||||
}
|
||||
if (ctx.IsNewMonth && ctx.Day > 0)
|
||||
{
|
||||
foreach (var c in w.Companies)
|
||||
{
|
||||
if (!c.Bankrupt) PayLoans(w, c);
|
||||
c.Rating = ComputeRating(w, c);
|
||||
Array.Clear(c.MonthEntries);
|
||||
}
|
||||
}
|
||||
if (ctx.IsNewYear && ctx.Day > 0)
|
||||
{
|
||||
foreach (var c in w.Companies)
|
||||
{
|
||||
Array.Copy(c.YearEntries, c.LastYearEntries, c.YearEntries.Length);
|
||||
Array.Clear(c.YearEntries);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Rata mensile costante (alla francese) per il residuo e i mesi restanti.</summary>
|
||||
public static Money MonthlyPayment(Money remaining, double annualRate, int monthsLeft)
|
||||
{
|
||||
if (monthsLeft <= 0) return remaining;
|
||||
double r = annualRate / 12;
|
||||
if (r <= 0) return Money.FromCentsRounded((double)remaining.Cents / monthsLeft);
|
||||
double factor = r / (1 - DMath.Pow(1 + r, -monthsLeft));
|
||||
return Money.FromCentsRounded(remaining.Cents * factor);
|
||||
}
|
||||
|
||||
private static void PayLoans(World w, Company c)
|
||||
{
|
||||
for (int i = c.Loans.Count - 1; i >= 0; i--)
|
||||
{
|
||||
var loan = c.Loans[i];
|
||||
var interest = Money.FromCentsRounded(loan.Remaining.Cents * loan.AnnualRate / 12);
|
||||
var payment = MonthlyPayment(loan.Remaining, loan.AnnualRate, loan.MonthsLeft);
|
||||
var principal = Money.Min(loan.Remaining, payment - interest);
|
||||
if (principal.IsNegative) principal = Money.Zero;
|
||||
w.Money.Transfer(Account.Of(c.Id), Account.External, interest, LedgerEntry.Interest);
|
||||
w.Money.Transfer(Account.Of(c.Id), Account.External, principal, LedgerEntry.LoanRepaid);
|
||||
loan.Remaining -= principal;
|
||||
loan.MonthsLeft--;
|
||||
if (loan.Remaining.Cents <= 0 || loan.MonthsLeft <= 0)
|
||||
{
|
||||
if (loan.Remaining.IsPositive)
|
||||
w.Money.Transfer(Account.Of(c.Id), Account.External, loan.Remaining, LedgerEntry.LoanRepaid);
|
||||
c.Loans.RemoveAt(i);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Rating da margine operativo e leva: punteggio = pesoMargine·clamp(0,5 + margine) +
|
||||
/// pesoLeva·clamp(1 − debito/attivi), confrontato con le soglie di balance.json.
|
||||
/// </summary>
|
||||
public static CreditRating ComputeRating(World w, Company c)
|
||||
{
|
||||
var fb = w.Data.Balance.Finance;
|
||||
long[] entries = w.Clock.Day % w.Calendar.DaysPerYear < 90 ? c.LastYearEntries : c.YearEntries;
|
||||
long revenue = Company.Revenue(entries);
|
||||
long profit = Company.OperatingProfit(entries);
|
||||
double margin = revenue > 0 ? (double)profit / revenue : 0;
|
||||
double assets = Math.Max(1, c.Cash.Cents + c.AssetBookValue.Cents);
|
||||
double leverage = c.Debt.Cents / assets;
|
||||
double score = fb.ProfitMarginWeight * Math.Clamp(0.5 + margin, 0, 1) + fb.LeverageWeight * Math.Clamp(1 - leverage, 0, 1);
|
||||
if (c.Bankrupt) return CreditRating.D;
|
||||
for (int i = 0; i < fb.RatingByScore.Length; i++)
|
||||
{
|
||||
if (score >= fb.RatingByScore[i]) return (CreditRating)i;
|
||||
}
|
||||
return CreditRating.D;
|
||||
}
|
||||
|
||||
/// <summary>Fido massimo della compagnia secondo il livello raggiunto.</summary>
|
||||
public static Money MaxLoan(World w, Company c)
|
||||
{
|
||||
var tier = w.Data.Tiers.Tiers[Math.Clamp(c.Tier, 1, w.Data.Tiers.Tiers.Count) - 1];
|
||||
return c.BaseCredit * tier.Unlocks.MaxLoanFactor;
|
||||
}
|
||||
|
||||
/// <summary>Tasso annuo per un nuovo prestito: base della difficoltà + spread del rating.</summary>
|
||||
public static double LoanRate(World w, Company c) =>
|
||||
w.Difficulty.BaseInterestRate + w.Data.Balance.Finance.RatingSpreads[c.Rating.ToString()];
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
using ViaFerrea.Core.Persistence;
|
||||
|
||||
namespace ViaFerrea.Core.Simulation.Systems;
|
||||
|
||||
/// <summary>Ultimo sistema: una volta al giorno calcola l'hash dello stato (resoconto giornaliero e test di determinismo).</summary>
|
||||
public sealed class HashSystem : ISimSystem
|
||||
{
|
||||
public string Name => "Hash";
|
||||
|
||||
public void Step(WorldContext ctx)
|
||||
{
|
||||
if (!ctx.IsNewDay) return;
|
||||
var w = ctx.World;
|
||||
w.LastStateHash = StateHasher.Compute(w);
|
||||
w.LastHashDay = ctx.Day;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
using ViaFerrea.Core.Data;
|
||||
using ViaFerrea.Core.Economy;
|
||||
|
||||
namespace ViaFerrea.Core.Simulation.Systems;
|
||||
|
||||
/// <summary>Formule dell'industria condivise da più sistemi (guida 6.3 e 11).</summary>
|
||||
public static class IndustryMath
|
||||
{
|
||||
/// <summary>pf = clamp(1 + 0,5·margine, 0,6, 1,2).</summary>
|
||||
public static double ProfitFactor(Industry ind, IndustryBalance b) =>
|
||||
Math.Clamp(1 + b.ProfitFactorSlope * ind.Margin, b.ProfitFactorMin, b.ProfitFactorMax);
|
||||
|
||||
/// <summary>mc: 1 sopra 70, lineare fino a 0,5 a 20, 0,3 sotto 20.</summary>
|
||||
public static double ConditionMultiplier(double condition, IndustryMaintenanceBalance m)
|
||||
{
|
||||
if (condition >= m.EfficiencyFullAbove) return 1.0;
|
||||
if (condition < 20) return m.EfficiencyBelow20;
|
||||
double t = (condition - 20) / (m.EfficiencyFullAbove - 20);
|
||||
return m.EfficiencyAt20 + (1.0 - m.EfficiencyAt20) * t;
|
||||
}
|
||||
|
||||
/// <summary>Capienza del magazzino di un output (unità) al livello corrente.</summary>
|
||||
public static int OutputCapacity(Industry ind, int outputIndex, int daysPerMonth)
|
||||
{
|
||||
if (ind.Level <= 0) return 0;
|
||||
var outputs = ind.Def.Recipe.Outputs;
|
||||
double perDay = ind.CyclesPerDayAtFullCapacity(daysPerMonth) * outputs[outputIndex].PerCycle;
|
||||
return (int)Math.Ceiling(perDay * ind.Def.StorageDays);
|
||||
}
|
||||
|
||||
/// <summary>Capienza del magazzino di un input (unità) al livello corrente.</summary>
|
||||
public static int InputCapacity(Industry ind, int inputIndex, int daysPerMonth)
|
||||
{
|
||||
if (ind.Level <= 0 || ind.Closed) return 0;
|
||||
var inputs = ind.Def.Recipe.Inputs;
|
||||
double perDay = ind.CyclesPerDayAtFullCapacity(daysPerMonth) * inputs[inputIndex].PerCycle;
|
||||
return (int)Math.Ceiling(perDay * ind.Def.StorageDays);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,225 @@
|
||||
using ViaFerrea.Core.Common;
|
||||
using ViaFerrea.Core.Data;
|
||||
using ViaFerrea.Core.Economy;
|
||||
|
||||
namespace ViaFerrea.Core.Simulation.Systems;
|
||||
|
||||
/// <summary>
|
||||
/// Produzione giornaliera delle industrie (guida 6.3), esaurimento dei giacimenti, salari,
|
||||
/// crescita trimestrale delle industrie servite, chiusure e nascita di nuove industrie.
|
||||
/// </summary>
|
||||
public sealed class IndustrySystem : ISimSystem
|
||||
{
|
||||
public string Name => "Industries";
|
||||
|
||||
public void Step(WorldContext ctx)
|
||||
{
|
||||
if (!ctx.IsNewDay) return;
|
||||
var w = ctx.World;
|
||||
foreach (var ind in w.Industries)
|
||||
{
|
||||
if (!ind.Closed) Produce(ctx, ind);
|
||||
}
|
||||
if (ctx.IsNewQuarter && ctx.Day > 0) Quarter(ctx);
|
||||
if (ctx.IsNewYear) w.SpawnedThisYear = 0;
|
||||
SpawnForUnmetDemand(ctx);
|
||||
}
|
||||
|
||||
private static void Produce(WorldContext ctx, Industry ind)
|
||||
{
|
||||
var w = ctx.World;
|
||||
var data = w.Data;
|
||||
var ib = data.Balance.Industry;
|
||||
int dpm = w.Calendar.DaysPerMonth;
|
||||
var recipe = ind.Def.Recipe;
|
||||
|
||||
// coperture di lavoratori e personale (EMA su 30 giorni)
|
||||
double covW = ind.JobsWorkers > 0 ? ind.WorkersPresent / ind.JobsWorkers : 1.0;
|
||||
double covS = ind.JobsStaff > 0 ? ind.StaffPresent / ind.JobsStaff : 1.0;
|
||||
ind.CovWorkers = Ema.Step(ind.CovWorkers, covW, ib.CoverageWindowDays);
|
||||
ind.CovStaff = Ema.Step(ind.CovStaff, covS, ib.CoverageWindowDays);
|
||||
|
||||
double pf = IndustryMath.ProfitFactor(ind, ib);
|
||||
double mc = IndustryMath.ConditionMultiplier(ind.Condition, data.Balance.IndustryMaintenance);
|
||||
double eLabor = Math.Min(ind.CovWorkers, ind.CovStaff) * pf * mc;
|
||||
|
||||
// giacimento: sotto la soglia la capacità cala linearmente, a zero l'industria chiude
|
||||
double depletion = 1.0;
|
||||
ResourceSite? site = ind.Site.IsValid ? w.Sites[ind.Site.Value] : null;
|
||||
if (ind.Def.Depletable && site is not null)
|
||||
{
|
||||
double frac = site.ReserveFraction;
|
||||
if (frac <= 0)
|
||||
{
|
||||
Close(ctx, ind, $"{ind.Name}: giacimento esaurito, l'attività chiude");
|
||||
return;
|
||||
}
|
||||
if (frac < ib.DepletionStartFraction) depletion = frac / ib.DepletionStartFraction;
|
||||
}
|
||||
|
||||
double cycles = ind.CyclesPerDayAtFullCapacity(dpm) * eLabor * depletion;
|
||||
for (int o = 0; o < recipe.Outputs.Count; o++)
|
||||
w.Market.CapacityToday[recipe.Outputs[o].GoodIndex] += ind.CyclesPerDayAtFullCapacity(dpm) * depletion * recipe.Outputs[o].PerCycle;
|
||||
|
||||
// copertura degli input di oggi: limita la produzione alle scorte disponibili
|
||||
double covInToday = 1.0;
|
||||
for (int i = 0; i < recipe.Inputs.Count; i++)
|
||||
{
|
||||
double need = cycles * recipe.Inputs[i].PerCycle;
|
||||
if (need > 0) covInToday = Math.Min(covInToday, ind.InputStock[i] / need);
|
||||
}
|
||||
covInToday = Math.Min(1.0, covInToday);
|
||||
ind.CovInput = Ema.Step(ind.CovInput, recipe.Inputs.Count == 0 ? 1.0 : covInToday, ib.CoverageWindowDays);
|
||||
|
||||
double total = cycles * covInToday + ind.CycleAccumulator;
|
||||
long whole = (long)Math.Floor(total);
|
||||
for (int i = 0; i < recipe.Inputs.Count; i++)
|
||||
whole = Math.Min(whole, ind.InputStock[i] / recipe.Inputs[i].PerCycle);
|
||||
ind.CycleAccumulator = Math.Clamp(total - whole, 0, 1);
|
||||
|
||||
for (int i = 0; i < recipe.Inputs.Count; i++)
|
||||
{
|
||||
int used = (int)(whole * recipe.Inputs[i].PerCycle);
|
||||
ind.InputStock[i] -= used;
|
||||
w.Goods.Consumed[recipe.Inputs[i].GoodIndex] += used;
|
||||
}
|
||||
for (int o = 0; o < recipe.Outputs.Count; o++)
|
||||
{
|
||||
int good = recipe.Outputs[o].GoodIndex;
|
||||
int made = (int)(whole * recipe.Outputs[o].PerCycle);
|
||||
ind.ProducedToday[o] = made;
|
||||
ind.OutputStock[o] += made;
|
||||
w.Goods.Produced[good] += made;
|
||||
w.Market.SupplyToday[good] += made;
|
||||
|
||||
// oltre la capienza del magazzino (storageDays) la merce si perde
|
||||
int cap = IndustryMath.OutputCapacity(ind, o, dpm);
|
||||
if (ind.OutputStock[o] > cap)
|
||||
{
|
||||
int lost = ind.OutputStock[o] - cap;
|
||||
ind.OutputStock[o] = cap;
|
||||
w.Goods.Decayed[good] += lost;
|
||||
}
|
||||
}
|
||||
if (site is not null && ind.Def.Depletable)
|
||||
{
|
||||
double extracted = whole * recipe.Outputs[0].PerCycle * data.Difficulty.DepletionMultipliers.For(w.Difficulty.Depletion);
|
||||
site.ReserveTonnes = Math.Max(0, site.ReserveTonnes - extracted);
|
||||
}
|
||||
ind.Efficiency = eLabor * covInToday * depletion;
|
||||
|
||||
// salari giornalieri ai presenti
|
||||
double wages = (ind.WorkersPresent * ib.WagePerWorkerPerMonth + ind.StaffPresent * ib.WagePerStaffPerMonth) / dpm;
|
||||
var wageMoney = Money.FromCentsRounded(wages);
|
||||
w.Money.Transfer(Account.Of(ind.Id), Account.External, wageMoney, LedgerEntry.Wages);
|
||||
|
||||
ind.RevenueEma = Ema.Step(ind.RevenueEma, ind.SalesToday, ib.MarginWindowDays);
|
||||
ind.CostEma = Ema.Step(ind.CostEma, wageMoney.Cents + ind.PurchasesToday, ib.MarginWindowDays);
|
||||
ind.SalesToday = 0;
|
||||
ind.PurchasesToday = 0;
|
||||
|
||||
// statistiche del trimestre
|
||||
ind.QuarterProduced += whole * recipe.Outputs[0].PerCycle;
|
||||
ind.QuarterShipped += ind.ShippedToday;
|
||||
ind.ShippedToday = 0;
|
||||
ind.QuarterCoverageSum += Math.Min(ind.CovInput, Math.Min(ind.CovWorkers, ind.CovStaff));
|
||||
ind.QuarterDays++;
|
||||
}
|
||||
|
||||
private static void Quarter(WorldContext ctx)
|
||||
{
|
||||
var w = ctx.World;
|
||||
var g = w.Data.Balance.Growth;
|
||||
foreach (var ind in w.Industries)
|
||||
{
|
||||
if (ind.Closed) continue;
|
||||
double shipped = ind.QuarterProduced > 0 ? Math.Min(1.0, (double)ind.QuarterShipped / ind.QuarterProduced) : 0;
|
||||
double coverage = ind.QuarterDays > 0 ? ind.QuarterCoverageSum / ind.QuarterDays : 0;
|
||||
double profit = Math.Clamp((ind.Margin + 1) / 2, 0, 1);
|
||||
double score = g.WeightShipped * shipped + g.WeightCoverage * coverage + g.WeightProfit * profit;
|
||||
ind.LastScore = score;
|
||||
ind.QuarterProduced = 0;
|
||||
ind.QuarterShipped = 0;
|
||||
ind.QuarterCoverageSum = 0;
|
||||
ind.QuarterDays = 0;
|
||||
|
||||
// solo le industrie servite da un vettore crescono o regrediscono (ADR 0004)
|
||||
if (!ind.Served) continue;
|
||||
|
||||
if (ind.Level == 0)
|
||||
{
|
||||
ind.QuartersAtZero++;
|
||||
if (ind.QuartersAtZero >= g.CloseQuartersAtZero)
|
||||
{
|
||||
Close(ctx, ind, $"{ind.Name} chiude dopo un anno di inattività");
|
||||
continue;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
ind.QuartersAtZero = 0;
|
||||
}
|
||||
|
||||
if (score > g.UpgradeThreshold)
|
||||
{
|
||||
ind.QuartersAboveUpgrade++;
|
||||
if (ind.QuartersAboveUpgrade >= g.UpgradeQuarters && ind.Level < g.MaxLevel)
|
||||
{
|
||||
ind.Level++;
|
||||
ind.QuartersAboveUpgrade = 0;
|
||||
ctx.Emit(EventKind.Industry, EventSeverity.Opportunity, $"{ind.Name} si espande al livello {ind.Level}", EntityKind.Industry, ind.Id.Value);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
ind.QuartersAboveUpgrade = 0;
|
||||
if (score < g.DowngradeThreshold && ind.Level > 0)
|
||||
{
|
||||
ind.Level--;
|
||||
ctx.Emit(EventKind.Industry, EventSeverity.Warning, $"{ind.Name} riduce l'attività (livello {ind.Level})", EntityKind.Industry, ind.Id.Value);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Chiude un'industria: le scorte si perdono, l'impronta torna libera.</summary>
|
||||
public static void Close(WorldContext ctx, Industry ind, string reason)
|
||||
{
|
||||
var w = ctx.World;
|
||||
ind.Closed = true;
|
||||
ind.Level = 0;
|
||||
var recipe = ind.Def.Recipe;
|
||||
for (int i = 0; i < recipe.Inputs.Count; i++)
|
||||
{
|
||||
w.Goods.Decayed[recipe.Inputs[i].GoodIndex] += ind.InputStock[i];
|
||||
ind.InputStock[i] = 0;
|
||||
}
|
||||
for (int o = 0; o < recipe.Outputs.Count; o++)
|
||||
{
|
||||
w.Goods.Decayed[recipe.Outputs[o].GoodIndex] += ind.OutputStock[o];
|
||||
ind.OutputStock[o] = 0;
|
||||
}
|
||||
IndustryPlacer.ClearFootprint(w, ind);
|
||||
w.Commutes.RemoveAll(c => c.Workplace.Kind == WorkplaceKind.Industry && c.Workplace.Index == ind.Id.Value);
|
||||
ctx.Emit(EventKind.Industry, EventSeverity.Warning, reason, EntityKind.Industry, ind.Id.Value);
|
||||
}
|
||||
|
||||
private static void SpawnForUnmetDemand(WorldContext ctx)
|
||||
{
|
||||
var w = ctx.World;
|
||||
var g = w.Data.Balance.Growth;
|
||||
if (w.SpawnedThisYear >= g.SpawnMaxPerYear) return;
|
||||
for (int good = 0; good < w.Data.GoodCount; good++)
|
||||
{
|
||||
if (w.Market.UnmetDays[good] < g.SpawnUnmetDays) continue;
|
||||
w.Market.UnmetDays[good] = 0;
|
||||
var ind = IndustryPlacer.TrySpawnProducer(w, good, ctx.Year);
|
||||
if (ind is null) continue;
|
||||
w.SpawnedThisYear++;
|
||||
ctx.Emit(EventKind.Industry, EventSeverity.Opportunity,
|
||||
$"Apre {ind.Name}: la domanda di {w.Data.Goods[good].NameIt.ToLowerInvariant()} è rimasta insoddisfatta per un anno",
|
||||
EntityKind.Industry, ind.Id.Value);
|
||||
if (w.SpawnedThisYear >= g.SpawnMaxPerYear) return;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,180 @@
|
||||
using ViaFerrea.Core.Common;
|
||||
using ViaFerrea.Core.Data;
|
||||
using ViaFerrea.Core.Economy;
|
||||
|
||||
namespace ViaFerrea.Core.Simulation.Systems;
|
||||
|
||||
/// <summary>
|
||||
/// Trasporto locale su strada (carrettieri, ADR 0004): piccole quantità tra produttori, consumatori
|
||||
/// e hub vicinissimi, senza vettore. Tiene vivo il territorio senza rendere superflua la ferrovia.
|
||||
/// Vendite e acquisti avvengono ai prezzi locali; le merci passano solo da un magazzino all'altro.
|
||||
/// </summary>
|
||||
public sealed class LocalTransportSystem : ISimSystem
|
||||
{
|
||||
public string Name => "LocalTransport";
|
||||
|
||||
private int _cacheIndustries = -1;
|
||||
private int _cacheTowns = -1;
|
||||
private List<(int Industry, double Km)>[] _nearIndustries = [];
|
||||
private List<(int Town, double Km)>[] _nearTowns = [];
|
||||
private List<(int Hub, double Km)>[] _nearHubs = [];
|
||||
|
||||
public void Step(WorldContext ctx)
|
||||
{
|
||||
if (!ctx.IsNewDay) return;
|
||||
var w = ctx.World;
|
||||
var lt = w.Data.Balance.LocalTransport;
|
||||
if (!lt.Enabled) return;
|
||||
RebuildCache(w, lt);
|
||||
if (ctx.IsNewMonth)
|
||||
{
|
||||
foreach (var hub in w.Hubs)
|
||||
{
|
||||
hub.UsedThisMonth = 0;
|
||||
Array.Clear(hub.ImportedThisMonth);
|
||||
Array.Clear(hub.ExportedThisMonth);
|
||||
}
|
||||
}
|
||||
|
||||
var lp = w.Data.Balance.LocalPrice;
|
||||
int dpm = w.Calendar.DaysPerMonth;
|
||||
foreach (var producer in w.Industries)
|
||||
{
|
||||
if (producer.Closed) continue;
|
||||
var outputs = producer.Def.Recipe.Outputs;
|
||||
for (int o = 0; o < outputs.Count; o++)
|
||||
{
|
||||
int good = outputs[o].GoodIndex;
|
||||
int available = Math.Min(lt.MaxUnitsPerDay, (int)Math.Ceiling(producer.OutputStock[o] * lt.DailyShare));
|
||||
if (available <= 0) continue;
|
||||
double sellPrice = Market.LocalPrice(w.Market.GlobalPrice[good], 0, producer.OutputStock[o], lp);
|
||||
|
||||
foreach (var (ci, _) in _nearIndustries[producer.Id.Value])
|
||||
{
|
||||
if (available <= 0) break;
|
||||
var consumer = w.Industries[ci];
|
||||
int i = consumer.InputIndexOf(good);
|
||||
if (i < 0 || consumer.Closed) continue;
|
||||
int free = IndustryMath.InputCapacity(consumer, i, dpm) - consumer.InputStock[i];
|
||||
int units = Math.Min(available, free);
|
||||
if (units <= 0) continue;
|
||||
double buyPrice = Market.LocalPrice(w.Market.GlobalPrice[good], consumer.InputDemandToday[i] * consumer.Def.StorageDays, consumer.InputStock[i], lp);
|
||||
producer.OutputStock[o] -= units;
|
||||
consumer.InputStock[i] += units;
|
||||
available -= units;
|
||||
Sell(w, producer, o, units, sellPrice);
|
||||
Buy(w, consumer, units, buyPrice);
|
||||
}
|
||||
foreach (var (ti, _) in _nearTowns[producer.Id.Value])
|
||||
{
|
||||
if (available <= 0) break;
|
||||
var town = w.Towns[ti];
|
||||
double demand = town.DemandToday[good];
|
||||
if (demand <= 0) continue;
|
||||
int free = (int)Math.Ceiling(demand * w.Data.Balance.Town.StockDays) - town.Stock[good];
|
||||
int units = Math.Min(available, free);
|
||||
if (units <= 0) continue;
|
||||
producer.OutputStock[o] -= units;
|
||||
town.Stock[good] += units;
|
||||
available -= units;
|
||||
Sell(w, producer, o, units, sellPrice);
|
||||
}
|
||||
foreach (var (hi, _) in _nearHubs[producer.Id.Value])
|
||||
{
|
||||
if (available <= 0) break;
|
||||
var hub = w.Hubs[hi];
|
||||
int units = Math.Min(available, hub.RemainingCapacity);
|
||||
if (units <= 0) continue;
|
||||
producer.OutputStock[o] -= units;
|
||||
hub.UsedThisMonth += units;
|
||||
hub.ExportedThisMonth[good] += units;
|
||||
w.Goods.Exported[good] += units;
|
||||
available -= units;
|
||||
Sell(w, producer, o, units, hub.BuyPrice(w.Market.GlobalPrice[good]));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// importazioni dagli hub verso i consumatori vicini
|
||||
foreach (var hub in w.Hubs)
|
||||
{
|
||||
foreach (var consumer in w.Industries)
|
||||
{
|
||||
if (consumer.Closed || hub.RemainingCapacity <= 0) continue;
|
||||
if (Vec2.Distance(hub.Position, consumer.Position) > lt.RadiusKm * 1000) continue;
|
||||
var inputs = consumer.Def.Recipe.Inputs;
|
||||
for (int i = 0; i < inputs.Count; i++)
|
||||
{
|
||||
int good = inputs[i].GoodIndex;
|
||||
int free = IndustryMath.InputCapacity(consumer, i, dpm) - consumer.InputStock[i];
|
||||
int units = Math.Min(Math.Min(lt.MaxUnitsPerDay, free), hub.RemainingCapacity);
|
||||
if (units <= 0) continue;
|
||||
consumer.InputStock[i] += units;
|
||||
hub.UsedThisMonth += units;
|
||||
hub.ImportedThisMonth[good] += units;
|
||||
w.Goods.Imported[good] += units;
|
||||
Buy(w, consumer, units, hub.SellPrice(w.Market.GlobalPrice[good]));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static void Sell(World w, Industry producer, int outputIndex, int units, double unitPrice)
|
||||
{
|
||||
var amount = Money.FromCentsRounded(units * unitPrice);
|
||||
w.Money.Transfer(Account.External, Account.Of(producer.Id), amount, LedgerEntry.Other);
|
||||
producer.SalesToday += amount.Cents;
|
||||
if (outputIndex == 0) producer.ShippedToday += units;
|
||||
}
|
||||
|
||||
private static void Buy(World w, Industry consumer, int units, double unitPrice)
|
||||
{
|
||||
var amount = Money.FromCentsRounded(units * unitPrice);
|
||||
w.Money.Transfer(Account.Of(consumer.Id), Account.External, amount, LedgerEntry.Other);
|
||||
consumer.PurchasesToday += amount.Cents;
|
||||
}
|
||||
|
||||
// vicini entro il raggio, ordinati per distanza e id; ricalcolati quando cambiano le entità
|
||||
private void RebuildCache(World w, LocalTransportBalance lt)
|
||||
{
|
||||
if (_cacheIndustries == w.Industries.Count && _cacheTowns == w.Towns.Count) return;
|
||||
_cacheIndustries = w.Industries.Count;
|
||||
_cacheTowns = w.Towns.Count;
|
||||
int n = w.Industries.Count;
|
||||
_nearIndustries = new List<(int, double)>[n];
|
||||
_nearTowns = new List<(int, double)>[n];
|
||||
_nearHubs = new List<(int, double)>[n];
|
||||
double radiusM = lt.RadiusKm * 1000;
|
||||
for (int p = 0; p < n; p++)
|
||||
{
|
||||
var producer = w.Industries[p];
|
||||
var li = new List<(int, double)>();
|
||||
for (int c = 0; c < n; c++)
|
||||
{
|
||||
if (c == p) continue;
|
||||
double d = Vec2.Distance(producer.Position, w.Industries[c].Position);
|
||||
if (d <= radiusM) li.Add((c, d / 1000));
|
||||
}
|
||||
li.Sort((a, b) => a.Item2 != b.Item2 ? a.Item2.CompareTo(b.Item2) : a.Item1.CompareTo(b.Item1));
|
||||
_nearIndustries[p] = li;
|
||||
|
||||
var lt2 = new List<(int, double)>();
|
||||
foreach (var town in w.Towns)
|
||||
{
|
||||
double km = w.TownEdgeDistanceKm(town, producer.Position);
|
||||
if (km <= lt.RadiusKm) lt2.Add((town.Id.Value, km));
|
||||
}
|
||||
lt2.Sort((a, b) => a.Item2 != b.Item2 ? a.Item2.CompareTo(b.Item2) : a.Item1.CompareTo(b.Item1));
|
||||
_nearTowns[p] = lt2;
|
||||
|
||||
var lh = new List<(int, double)>();
|
||||
foreach (var hub in w.Hubs)
|
||||
{
|
||||
double d = Vec2.Distance(producer.Position, hub.Position);
|
||||
if (d <= radiusM) lh.Add((hub.Id.Value, d / 1000));
|
||||
}
|
||||
lh.Sort((a, b) => a.Item2 != b.Item2 ? a.Item2.CompareTo(b.Item2) : a.Item1.CompareTo(b.Item1));
|
||||
_nearHubs[p] = lh;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
using ViaFerrea.Core.Common;
|
||||
using ViaFerrea.Core.Economy;
|
||||
|
||||
namespace ViaFerrea.Core.Simulation.Systems;
|
||||
|
||||
/// <summary>
|
||||
/// Prezzi globali giornalieri (guida 6.3, ADR 0004):
|
||||
/// Pg' = clamp(Pg·(1 + k·(D/S − 1)), 0,3·Pb, 3·Pb), Pg ← α·Pg' + (1 − α)·Pg,
|
||||
/// dove D e S sono domanda e offerta degli ultimi 30 giorni più la componente mondiale:
|
||||
/// un volume V scambiato con il resto del mondo al prezzo mondiale Pw = Pb·(1 + W(t)).
|
||||
/// </summary>
|
||||
public sealed class MarketSystem : ISimSystem
|
||||
{
|
||||
public string Name => "Market";
|
||||
|
||||
public void Step(WorldContext ctx)
|
||||
{
|
||||
if (!ctx.IsNewDay) return;
|
||||
var w = ctx.World;
|
||||
var data = w.Data;
|
||||
var m = data.Balance.Market;
|
||||
var market = w.Market;
|
||||
var rng = w.Stream("market");
|
||||
double volatility = w.Difficulty.MarketVolatilityMultiplier;
|
||||
double years = w.Clock.YearsElapsed;
|
||||
double decay = DMath.Exp(-1.0 / m.World.ShockDecayDays);
|
||||
double shockChance = m.World.ShockChancePerYear / w.Calendar.DaysPerYear;
|
||||
var growth = data.Balance.Growth;
|
||||
|
||||
for (int g = 0; g < data.GoodCount; g++)
|
||||
{
|
||||
var def = data.Goods[g];
|
||||
market.Demand[g].Add(market.DemandToday[g]);
|
||||
market.Supply[g].Add(market.SupplyToday[g]);
|
||||
market.DemandToday[g] = 0;
|
||||
market.SupplyToday[g] = 0;
|
||||
|
||||
// shock mondiali per bene
|
||||
market.Shock[g] *= decay;
|
||||
if (rng.Chance(shockChance))
|
||||
{
|
||||
double magnitude = rng.NextDouble(m.World.ShockMin, m.World.ShockMax) * volatility;
|
||||
double sign = rng.Chance(0.5) ? 1 : -1;
|
||||
market.Shock[g] += sign * magnitude;
|
||||
int pct = (int)Math.Round(magnitude * 100);
|
||||
ctx.Emit(EventKind.Market, sign > 0 ? EventSeverity.Opportunity : EventSeverity.Warning,
|
||||
$"{def.NameIt}: prezzo mondiale {(sign > 0 ? "in rialzo" : "in calo")} del {pct}%");
|
||||
}
|
||||
|
||||
double pb = def.BasePrice;
|
||||
double pg = market.GlobalPrice[g];
|
||||
if (def.Era > ctx.Year)
|
||||
{
|
||||
market.PriceHistory[g].Add(pg);
|
||||
market.CapacityToday[g] = 0;
|
||||
continue;
|
||||
}
|
||||
double pw = pb * Math.Max(0.05, 1 + Market.WorldFactor(m, volatility, years, market.Shock[g]));
|
||||
double d = market.Demand[g].Sum;
|
||||
double s = market.Supply[g].Sum;
|
||||
double v = Math.Max(m.World.BaselinePerDay * market.Demand[g].Count, m.World.VolumeShare * (d + s) / 2);
|
||||
double dTot = d + v * DMath.Pow(pw / pg, m.World.Elasticity);
|
||||
double sTot = s + v * DMath.Pow(pg / pw, m.World.Elasticity);
|
||||
double ratio = DMath.Clamp(dTot / Math.Max(1e-9, sTot), m.RatioMin, m.RatioMax);
|
||||
double target = DMath.Clamp(pg * (1 + m.K * (ratio - 1)), m.MinPriceFactor * pb, m.MaxPriceFactor * pb);
|
||||
pg = m.Alpha * target + (1 - m.Alpha) * pg;
|
||||
market.GlobalPrice[g] = pg;
|
||||
market.PriceHistory[g].Add(pg);
|
||||
|
||||
// domanda insoddisfatta per mancanza di capacità installata (non di trasporto):
|
||||
// è il segnale per la nascita di nuove industrie
|
||||
double avgDemand = market.Demand[g].Average;
|
||||
if (avgDemand > growth.SpawnUnmetRatio * market.CapacityToday[g] + m.World.BaselinePerDay) market.UnmetDays[g]++;
|
||||
else market.UnmetDays[g] = 0;
|
||||
market.CapacityToday[g] = 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,157 @@
|
||||
using ViaFerrea.Core.Common;
|
||||
using ViaFerrea.Core.Data;
|
||||
using ViaFerrea.Core.Economy;
|
||||
using ViaFerrea.Core.Map;
|
||||
|
||||
namespace ViaFerrea.Core.Simulation.Systems;
|
||||
|
||||
/// <summary>
|
||||
/// Città: consumo giornaliero e soddisfazione per categoria, crescita mensile, espansione
|
||||
/// dell'abitato e migrazione annuale verso le città meglio servite (guida 6.3).
|
||||
/// </summary>
|
||||
public sealed class TownSystem : ISimSystem
|
||||
{
|
||||
public string Name => "Towns";
|
||||
|
||||
private readonly double[] _catDemand = new double[Town.CategoryCount];
|
||||
private readonly double[] _catConsumed = new double[Town.CategoryCount];
|
||||
|
||||
public void Step(WorldContext ctx)
|
||||
{
|
||||
if (!ctx.IsNewDay) return;
|
||||
var w = ctx.World;
|
||||
foreach (var town in w.Towns) Consume(w, town);
|
||||
if (ctx.IsNewMonth && ctx.Day > 0)
|
||||
{
|
||||
foreach (var town in w.Towns) Grow(ctx, town);
|
||||
}
|
||||
if (ctx.IsNewYear && ctx.Day > 0)
|
||||
{
|
||||
Migrate(ctx);
|
||||
foreach (var town in w.Towns) ExpandFootprint(w, town);
|
||||
}
|
||||
}
|
||||
|
||||
private void Consume(World w, Town town)
|
||||
{
|
||||
var data = w.Data;
|
||||
var tb = data.Balance.Town;
|
||||
Array.Clear(_catDemand);
|
||||
Array.Clear(_catConsumed);
|
||||
for (int g = 0; g < data.GoodCount; g++)
|
||||
{
|
||||
double demand = town.DemandToday[g];
|
||||
if (demand <= 0)
|
||||
{
|
||||
town.DemandAccumulator[g] = 0;
|
||||
continue;
|
||||
}
|
||||
int cat = (int)data.Goods[g].Town!.Category;
|
||||
town.DemandAccumulator[g] += demand;
|
||||
int want = (int)Math.Floor(town.DemandAccumulator[g]);
|
||||
int used = Math.Min(want, town.Stock[g]);
|
||||
town.Stock[g] -= used;
|
||||
w.Goods.Consumed[g] += used;
|
||||
town.DemandAccumulator[g] -= want; // la domanda non servita non si accumula
|
||||
_catDemand[cat] += demand;
|
||||
_catConsumed[cat] += used;
|
||||
}
|
||||
for (int c = 0; c < Town.CategoryCount; c++)
|
||||
{
|
||||
town.CategoryActive[c] = _catDemand[c] > 0;
|
||||
if (_catDemand[c] <= 0) continue;
|
||||
double ratio = Math.Min(1.0, _catConsumed[c] / _catDemand[c]);
|
||||
town.Satisfaction[c] = Ema.Step(town.Satisfaction[c], ratio, tb.SatisfactionEmaDays);
|
||||
}
|
||||
town.WorkDissatisfaction *= 1.0 - 1.0 / 90.0;
|
||||
}
|
||||
|
||||
private static void Grow(WorldContext ctx, Town town)
|
||||
{
|
||||
var tb = ctx.Data.Balance.Town;
|
||||
int services = 0;
|
||||
for (int c = 0; c < Town.CategoryCount; c++)
|
||||
{
|
||||
if (town.CategoryActive[c] && town.Satisfaction[c] >= tb.ServicesSatisfactionThreshold) services++;
|
||||
}
|
||||
town.Services = services;
|
||||
double sat = town.OverallSatisfaction;
|
||||
double employment = town.Population > 0 ? (double)(town.EmployedWorkers + town.EmployedStaff) / town.Population : 0;
|
||||
double g = tb.BaseGrowth + tb.SatisfactionWeight * (sat - tb.SatisfactionPivot) + tb.EmploymentWeight * (employment - tb.EmploymentPivot);
|
||||
g = Math.Clamp(g, -tb.MaxMonthlyGrowth, tb.MaxMonthlyGrowth);
|
||||
town.LastGrowth = g;
|
||||
int before = town.Population;
|
||||
town.Population = Math.Clamp((int)Math.Round(town.Population * (1 + g)), 0, tb.MaxPopulation);
|
||||
if (before < 10_000 && town.Population >= 10_000)
|
||||
ctx.Emit(EventKind.Town, EventSeverity.Info, $"{town.Name} supera i 10.000 abitanti", EntityKind.Town, town.Id.Value);
|
||||
}
|
||||
|
||||
private static void Migrate(WorldContext ctx)
|
||||
{
|
||||
var w = ctx.World;
|
||||
var mb = w.Data.Balance.Migration;
|
||||
var leaving = new List<(Town Town, int People)>();
|
||||
foreach (var town in w.Towns)
|
||||
{
|
||||
if (town.OverallSatisfaction >= mb.SatisfactionThreshold) continue;
|
||||
int people = (int)(town.Population * mb.Share);
|
||||
if (people > 0) leaving.Add((town, people));
|
||||
}
|
||||
foreach (var (from, people) in leaving)
|
||||
{
|
||||
var targets = w.Towns
|
||||
.Where(t => t != from && t.OverallSatisfaction > from.OverallSatisfaction
|
||||
&& Vec2.Distance(t.Position, from.Position) <= mb.MaxDistanceKm * 1000)
|
||||
.ToList();
|
||||
from.Population -= people;
|
||||
if (targets.Count == 0)
|
||||
{
|
||||
// nessuna destinazione migliore: una parte emigra fuori regione, il resto resta
|
||||
int emigrants = (int)(people * mb.EmigrationShareWhenNoTarget);
|
||||
from.Population += people - emigrants;
|
||||
if (emigrants >= 100)
|
||||
ctx.Emit(EventKind.Town, EventSeverity.Warning, $"{emigrants} abitanti di {from.Name} emigrano fuori regione", EntityKind.Town, from.Id.Value);
|
||||
continue;
|
||||
}
|
||||
double totalWeight = targets.Sum(t => t.OverallSatisfaction * t.Population);
|
||||
int moved = 0;
|
||||
for (int i = 0; i < targets.Count; i++)
|
||||
{
|
||||
int share = i == targets.Count - 1
|
||||
? people - moved
|
||||
: (int)Math.Floor(people * targets[i].OverallSatisfaction * targets[i].Population / Math.Max(1e-9, totalWeight));
|
||||
targets[i].Population += share;
|
||||
moved += share;
|
||||
}
|
||||
if (people >= 100)
|
||||
ctx.Emit(EventKind.Town, EventSeverity.Warning, $"{people} abitanti lasciano {from.Name} per città meglio servite", EntityKind.Town, from.Id.Value);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>L'abitato si allarga con la popolazione sulle celle libere vicine.</summary>
|
||||
private static void ExpandFootprint(World w, Town town)
|
||||
{
|
||||
var tp = w.Data.Balance.Map.Towns;
|
||||
double radius = tp.RadiusBaseCells + tp.RadiusPerSqrtPop * Math.Sqrt(town.Population);
|
||||
if (radius <= town.RadiusCells + 0.25) return;
|
||||
town.RadiusCells = radius;
|
||||
int r = (int)Math.Ceiling(radius);
|
||||
bool changed = false;
|
||||
for (int y = town.CellY - r; y <= town.CellY + r; y++)
|
||||
{
|
||||
for (int x = town.CellX - r; x <= town.CellX + r; x++)
|
||||
{
|
||||
if (!w.Terrain.InBounds(x, y)) continue;
|
||||
double dx = x - town.CellX, dy = y - town.CellY;
|
||||
if (dx * dx + dy * dy > radius * radius) continue;
|
||||
var type = w.Terrain.TypeAt(x, y);
|
||||
if (type is CellType.Plain or CellType.Field or CellType.Forest or CellType.Hill)
|
||||
{
|
||||
w.Terrain.SetType(x, y, CellType.Town);
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (changed) w.TerrainHash = 0;
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user