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:
Claude committed 2026-10-01 22:38:17 +00:00
1 parent 290a1d886c
commit 7cb98fa206
113 files changed
+12553 -23

No files matched your search

+98
View File
@@ -0,0 +1,98 @@
using ViaFerrea.Core.Common;
using ViaFerrea.Tests.Harness;
namespace ViaFerrea.Tests.Basics;
public static class CommonTests
{
[Test]
public static void MoneyFormatsItalian()
{
Assert.Equal("₤ 1.284.500", Money.FromLire(1_284_500).ToString());
Assert.Equal("₤ 1.284.500,25", Money.FromLire(1_284_500.25m).ToString("it2"));
Assert.Equal("₤ 3,91 mln", Money.FromLire(3_910_000).ToString("short"));
Assert.Equal("₤ 48.200", Money.FromLire(48_200).ToString("short"));
Assert.Equal("−₤ 19.700", Money.FromLire(-19_700).ToString());
Assert.Equal("₤ 0", Money.Zero.ToString());
Assert.Equal("₤ 999", Money.FromLire(999).ToString());
}
[Test]
public static void MoneyArithmeticIsExact()
{
var a = Money.FromLire(10.10m);
var b = Money.FromLire(0.20m);
Assert.Equal(1030L, (a + b).Cents);
Assert.Equal(990L, (a - b).Cents);
Assert.Equal(3030L, (a * 3).Cents);
Assert.Equal(1515L, (a * 1.5).Cents);
Assert.True(a > b);
Assert.Throws<OverflowException>(() => _ = new Money(long.MaxValue) + new Money(1));
}
[Test]
public static void XxHash64MatchesReferenceVectors()
{
Assert.Equal(0xef46db3751d8e999UL, XxHash64.Hash([]));
Assert.Equal(0xd24ec4f1a98c6e5bUL, XxHash64.Hash("a"u8));
Assert.Equal(0x44bc2cf5ad770999UL, XxHash64.Hash("abc"u8));
Assert.Equal(0x7e13e2793f7d6198UL, XxHash64.Hash("Via Ferrea"u8));
Assert.Equal(0x95584af7701f808dUL, XxHash64.Hash([], 12345));
var hundred = new byte[100];
for (int i = 0; i < hundred.Length; i++) hundred[i] = (byte)i;
Assert.Equal(0x6ac1e58032166597UL, XxHash64.Hash(hundred));
Assert.Equal(0x28ba1ae2de4de27UL, XxHash64.Hash(hundred, 12345));
}
[Test(Description = "DMath coincide con Math entro 1e-14 relativi su argomenti casuali")]
public static void DMathMatchesMathClosely()
{
var rng = new Rng(2024);
for (int i = 0; i < 20_000; i++)
{
double x = rng.NextDouble(-50, 50);
Check(Math.Exp(x), DMath.Exp(x), "exp", x);
double p = rng.NextDouble(1e-6, 1e6);
Check(Math.Log(p), DMath.Log(p), "log", p);
double a = rng.NextDouble(-1000, 1000);
CheckAbs(Math.Sin(a), DMath.Sin(a), "sin", a);
CheckAbs(Math.Cos(a), DMath.Cos(a), "cos", a);
double t = rng.NextDouble(-100, 100);
Check(Math.Atan(t), DMath.Atan(t), "atan", t);
double y = rng.NextDouble(-5, 5), xx = rng.NextDouble(-5, 5);
CheckAbs(Math.Atan2(y, xx), DMath.Atan2(y, xx), "atan2", y);
double b = rng.NextDouble(0.01, 300), e = rng.NextDouble(-3, 3);
Check(Math.Pow(b, e), DMath.Pow(b, e), "pow", b);
}
Assert.Equal(1.0, DMath.Exp(0));
Assert.Equal(0.0, DMath.Log(1));
Assert.Equal(8.0, DMath.Pow(2, 3));
Assert.Equal(0.125, DMath.Pow(2, -3));
Assert.True(double.IsNaN(DMath.Log(-1)));
Assert.Equal(double.PositiveInfinity, DMath.Exp(1000));
Assert.Equal(0.0, DMath.Exp(-1000));
Assert.Approx(Math.Exp(-740), DMath.Exp(-740), 1e-320);
Assert.Approx(Math.Log(5e-310), DMath.Log(5e-310), 1e-12);
}
private static void Check(double expected, double actual, string fn, double arg)
{
double tol = Math.Max(1e-300, Math.Abs(expected) * 2e-14);
Assert.Approx(expected, actual, tol, $"{fn}({arg:R})");
}
private static void CheckAbs(double expected, double actual, string fn, double arg)
{
Assert.Approx(expected, actual, 1e-13, $"{fn}({arg:R})");
}
[Test]
public static void TypedIdsAreDistinctAndOrdered()
{
var a = new StationId(3);
var b = new StationId(5);
Assert.True(a.CompareTo(b) < 0);
Assert.False(StationId.None.IsValid);
Assert.Equal("Station#3", a.ToString());
}
}
+1 -1
View File
@@ -1,7 +1,7 @@
using ViaFerrea.Core.Common;
using ViaFerrea.Tests.Harness;
namespace ViaFerrea.Tests.Core;
namespace ViaFerrea.Tests.Basics;
public static class RngTests
{
+46
View File
@@ -0,0 +1,46 @@
using ViaFerrea.Core.Time;
using ViaFerrea.Tests.Harness;
namespace ViaFerrea.Tests.Basics;
public static class TimeTests
{
private static Calendar Cal() => new(TestData.Data.Balance.Time, 1850);
[Test]
public static void CalendarConstantsMatchGuide()
{
var c = Cal();
Assert.Equal(240, c.TicksPerDay);
Assert.Equal(360, c.DaysPerYear);
Assert.Approx(3.0, c.TrainSecondsPerTick, 1e-12, "un tick = 3 s di orologio dei treni");
Assert.Approx(2.5, c.TrainMinutesToDays(30), 1e-12, "30 minuti di orologio = 2,5 giorni");
}
[Test]
public static void DatesRoundTripAndFormatInItalian()
{
var c = Cal();
var d = c.DateOfDay(22 * 360 + 2 * 30 + 13);
Assert.Equal(new GameDate(1872, 3, 14), d);
Assert.Equal("14 marzo 1872", d.ToString());
Assert.Equal(22L * 360 + 2 * 30 + 13, c.DayOf(d));
}
[Test]
public static void ClockFlagsFireAtBoundaries()
{
var clock = new GameClock(Cal());
Assert.True(clock.IsNewDay && clock.IsNewMonth && clock.IsNewYear);
clock.Advance();
Assert.False(clock.IsNewDay);
clock.Restore(240L * 30);
Assert.True(clock.IsNewMonth);
Assert.False(clock.IsNewQuarter);
clock.Restore(240L * 90);
Assert.True(clock.IsNewQuarter);
clock.Restore(240L * 360);
Assert.True(clock.IsNewYear);
Assert.Equal(1851, clock.Year);
}
}
+148
View File
@@ -0,0 +1,148 @@
using System.Text.Json.Nodes;
using ViaFerrea.Core.Data;
using ViaFerrea.Tests.Harness;
namespace ViaFerrea.Tests.Data;
public static class DataTests
{
[Test(Description = "I file dati reali superano schema e validazione semantica, con le quantità minime richieste")]
public static void RealDataLoadsWithMinimumCounts()
{
var d = TestData.Data;
Assert.True(d.Goods.Count >= 12, "almeno 12 beni");
Assert.True(d.Industries.Count >= 14, "almeno 14 industrie");
Assert.True(d.Vehicles.Count >= 8, "almeno 8 veicoli");
Assert.True(d.Eras.Eras.Count >= 4, "almeno 4 ere");
Assert.Equal(5, d.Tiers.Tiers.Count);
Assert.True(d.Difficulty.Presets.Count >= 4, "almeno 4 difficoltà");
Assert.Equal("spare_parts", d.Goods[d.SparePartsGood].Id);
Assert.Equal("machinery", d.Goods[d.MachineryGood].Id);
Assert.NotEqual(0UL, d.Hash);
}
[Test]
public static void ReferencesAreResolvedToIndices()
{
var d = TestData.Data;
var steel = d.Industry("steel_mill");
Assert.Equal(d.GoodIndex("iron_ore"), steel.Recipe.Inputs[0].GoodIndex);
Assert.Equal(d.GoodIndex("steel"), steel.Recipe.Outputs[0].GoodIndex);
Assert.Equal(Traction.Steam, d.Vehicle("loco_steam_1850").Traction);
Assert.True(d.Vehicle("wagon_hopper").GoodIndices.Contains(d.GoodIndex("coal")));
Assert.Equal(120, steel.Capacity(1));
Assert.Equal(900, steel.Capacity(5));
}
[Test]
public static void DifficultyPresetsMatchGuideTable()
{
var d = TestData.Data;
var a = d.DifficultyPreset("apprendista");
var f = d.DifficultyPreset("ferro_e_sangue");
Assert.Equal(50_000_000L, a.InitialCapital);
Assert.Equal(180, a.BankruptcyDays);
Assert.Equal(TakeoverRule.Disabled, a.PlayerTakeover);
Assert.Equal(5, f.AiCompetitors);
Assert.True(f.PublicFromStart);
Assert.Approx(0.6, f.PlayerShareAtStart, 1e-12);
Assert.Equal(IronmanRule.Yes, f.Ironman);
}
[Test]
public static void HashIgnoresFormatting()
{
var files = MemoryDataSource.Snapshot(TestData.Source);
var node = JsonNode.Parse(files["goods.json"])!;
files["goods.json"] = node.ToJsonString(new System.Text.Json.JsonSerializerOptions { WriteIndented = false });
var reformatted = GameData.Load(new MemoryDataSource(files));
Assert.Equal(TestData.Data.Hash, reformatted.Hash);
}
[Test]
public static void HashChangesWithContent()
{
var files = MemoryDataSource.Snapshot(TestData.Source);
files["goods.json"] = files["goods.json"].Replace("\"basePrice\": 3800", "\"basePrice\": 3900", StringComparison.Ordinal);
Assert.NotEqual(TestData.Data.Hash, GameData.Load(new MemoryDataSource(files)).Hash);
}
[Test]
public static void SchemaRejectsUnknownAndMissingProperties()
{
var errors = LoadErrors(files =>
{
var root = JsonNode.Parse(files["goods.json"])!;
root["goods"]![0]!["colour"] = "black";
root["goods"]![1]!.AsObject().Remove("basePrice");
files["goods.json"] = root.ToJsonString();
});
Assert.True(errors.Any(e => e.Contains("colour", StringComparison.Ordinal)), "proprietà sconosciuta segnalata");
Assert.True(errors.Any(e => e.Contains("basePrice", StringComparison.Ordinal)), "proprietà mancante segnalata");
}
[Test]
public static void SchemaRejectsOutOfRangeAndBadEnum()
{
var errors = LoadErrors(files =>
{
var root = JsonNode.Parse(files["industries.json"])!;
root["industries"]![0]!["kind"] = "magical";
root["industries"]![0]!["capacityPerLevel"] = new JsonArray(1, 2, 3);
files["industries.json"] = root.ToJsonString();
});
Assert.True(errors.Any(e => e.Contains("non tra quelli ammessi", StringComparison.Ordinal)));
Assert.True(errors.Any(e => e.Contains("almeno 5 elementi", StringComparison.Ordinal)));
}
[Test]
public static void SemanticRejectsUnknownReferenceAndDuplicates()
{
var errors = LoadErrors(files =>
{
var root = JsonNode.Parse(files["industries.json"])!;
root["industries"]![7]!["recipe"]!["inputs"]![0]!["good"] = "unobtanium";
root["industries"]![1]!["id"] = "coal_mine";
files["industries.json"] = root.ToJsonString();
});
Assert.True(errors.Any(e => e.Contains("unobtanium", StringComparison.Ordinal)));
Assert.True(errors.Any(e => e.Contains("duplicato «coal_mine»", StringComparison.Ordinal)));
}
[Test(Description = "Un refuso in balance.json (sezione con schema aperto) è comunque bloccato dal deserializzatore")]
public static void TypoInBalanceIsRejected()
{
var errors = LoadErrors(files =>
{
files["balance.json"] = files["balance.json"].Replace("\"wagePerWorkerPerMonth\"", "\"wagePerWorkerPerMoth\"", StringComparison.Ordinal);
});
Assert.True(errors.Count > 0);
Assert.True(errors.Any(e => e.Contains("balance.json", StringComparison.Ordinal)));
}
[Test]
public static void SemanticRejectsBrokenFailureShares()
{
var errors = LoadErrors(files =>
{
files["maintenance.json"] = files["maintenance.json"].Replace("\"minorShare\": 0.70", "\"minorShare\": 0.60", StringComparison.Ordinal);
});
Assert.True(errors.Any(e => e.Contains("failure.*Share", StringComparison.Ordinal)));
}
private static IReadOnlyList<string> LoadErrors(Action<Dictionary<string, string>> mutate)
{
var files = MemoryDataSource.Snapshot(TestData.Source);
mutate(files);
try
{
GameData.Load(new MemoryDataSource(files));
}
catch (DataValidationException ex)
{
return ex.Errors;
}
Assert.Fail("i dati alterati dovevano essere rifiutati");
return [];
}
}
@@ -0,0 +1,215 @@
using ViaFerrea.Core.Commands;
using ViaFerrea.Core.Common;
using ViaFerrea.Core.Data;
using ViaFerrea.Core.Economy;
using ViaFerrea.Core.Simulation;
using ViaFerrea.Core.Simulation.Systems;
using ViaFerrea.Tests.Harness;
namespace ViaFerrea.Tests.Economy;
public static class EconomyTests
{
[Test(Description = "Invarianti: la somma di tutti i saldi resta zero, nessun bene nasce dal nulla")]
public static void MoneyAndGoodsInvariantsHold()
{
var w = TestWorlds.Small(101);
for (int month = 0; month < 18; month++)
{
w.RunDays(30);
Assert.Equal(0L, w.MoneyBalanceSum(), $"denaro al mese {month}");
for (int g = 0; g < w.Data.GoodCount; g++)
Assert.Equal(w.Goods.ExpectedStock(g), w.TotalStock(g), $"merce {w.Data.Goods[g].Id} al mese {month}");
}
Assert.True(w.Goods.Produced.Sum() > 0, "qualcosa è stato prodotto");
}
[Test(Description = "I prezzi globali restano sempre entro 0,3·Pb e 3·Pb")]
public static void PricesStayWithinLimits()
{
var w = TestWorlds.Small(102, "ferro_e_sangue");
var m = w.Data.Balance.Market;
for (int day = 0; day < 3 * 360; day++)
{
w.RunDays(1);
for (int g = 0; g < w.Data.GoodCount; g++)
{
double pb = w.Data.Goods[g].BasePrice;
Assert.InRange(w.Market.GlobalPrice[g], m.MinPriceFactor * pb - 1e-6, m.MaxPriceFactor * pb + 1e-6);
}
}
}
[Test]
public static void PriceRisesWhenDemandExceedsSupply()
{
var w = TestWorlds.Small(103);
int food = w.Data.GoodIndex("food");
double before = w.Market.GlobalPrice[food];
// nessuna produzione di alimentari raggiunge il mercato: la domanda cittadina spinge il prezzo
w.RunDays(120);
Assert.True(w.Market.GlobalPrice[food] > before * 1.5, $"prezzo alimentari {before} → {w.Market.GlobalPrice[food]}");
}
[Test]
public static void LocalPriceFollowsImbalanceWithinBounds()
{
var lp = TestData.Data.Balance.LocalPrice;
Assert.Approx(100.0, Market.LocalPrice(100, 10, 10, lp), 1e-9);
Assert.True(Market.LocalPrice(100, 50, 0, lp) > 130);
Assert.True(Market.LocalPrice(100, 0, 50, lp) < 70);
Assert.InRange(Market.LocalPrice(100, 1e9, 0, lp), 60, 140);
Assert.InRange(Market.LocalPrice(100, 0, 1e9, lp), 60, 140);
}
[Test]
public static void FreightAndPassengerTariffsFollowFormulas()
{
var t = TestData.Data.Balance.Tariffs;
// a prezzo base: 40 t × 150 × 1 × 20^0,9 centesimi
var freight = Tariffs.Freight(40, 20, 3800, 3800, 1, 1, t, 1.0);
Assert.Equal(Money.FromCentsRounded(40 * 150 * DMath.Pow(20, 0.9)), freight);
// consegna con il doppio del tempo atteso: oltre la soglia del 50 % la tariffa cala
var late = Tariffs.Freight(40, 20, 3800, 3800, 2, 1, t, 1.0);
Assert.True(late < freight && late.Cents >= freight.Cents / 2);
var staff = Tariffs.Passenger(10, 15, PaxClass.Staff, 1, 1, t, 1.0);
var worker = Tariffs.Passenger(10, 15, PaxClass.Worker, 1, 1, t, 1.0);
Assert.Approx(3.0, (double)staff.Cents / worker.Cents, 0.01, "classe personale ×3");
}
[Test(Description = "Solo le industrie servite crescono; con punteggio alto salgono di livello dopo due trimestri")]
public static void ServedIndustryWithGoodScoreUpgrades()
{
var w = TestWorlds.Small(104);
var mine = w.Industries.First(i => i.Def.Kind == IndustryKind.Primary && i.Level == 1 && !i.Closed);
var other = w.Industries.First(i => i != mine && i.Def.Kind == IndustryKind.Primary && !i.Closed);
int otherLevel = other.Level;
mine.Served = true;
for (int q = 0; q < 2; q++)
{
for (int d = 0; d < 90; d++)
{
// tutta la produzione viene spedita e i posti sono coperti
mine.WorkersPresent = mine.JobsWorkers;
mine.StaffPresent = mine.JobsStaff;
mine.CovWorkers = 1;
mine.CovStaff = 1;
mine.RevenueEma = 1_000_000;
mine.CostEma = 100_000;
mine.QuarterShipped = mine.QuarterProduced;
w.RunDays(1);
}
}
w.RunDays(1); // il secondo trimestre si chiude nel primo tick del giorno 180
Assert.Equal(2, mine.Level, "livello dopo due trimestri ottimi");
Assert.Equal(otherLevel, other.Level, "un'industria non servita non cambia livello");
}
[Test(Description = "Un'industria servita ma abbandonata scende fino a 0 e chiude dopo quattro trimestri a zero")]
public static void NeglectedServedIndustryDeclinesAndCloses()
{
var w = TestWorlds.Small(105);
var ind = w.Industries.First(i => i.Def.Kind == IndustryKind.Processing && !i.Closed);
ind.Served = true;
int startLevel = ind.Level;
w.RunDays(90 * (startLevel + 5) + 1);
Assert.True(ind.Closed, $"chiusa (livello iniziale {startLevel}, ultimo punteggio {ind.LastScore:F2})");
Assert.True(w.Events.Recent.Any(e => e.Text.Contains(ind.Name, StringComparison.Ordinal) && e.Text.Contains("chiude", StringComparison.Ordinal)));
}
[Test]
public static void TownsGrowWithSatisfactionAndShrinkWithout()
{
var w = TestWorlds.Small(106);
var served = w.Towns[0];
var neglected = w.Towns[1];
int s0 = served.Population, n0 = neglected.Population;
for (int d = 0; d < 360; d++)
{
for (int g = 0; g < w.Data.GoodCount; g++)
{
int need = (int)Math.Ceiling(served.DemandToday[g]) + 1;
if (served.DemandToday[g] > 0 && served.Stock[g] < need)
{
int add = need - served.Stock[g];
served.Stock[g] += add;
w.Goods.Produced[g] += add; // consegna simulata, contabilizzata
}
}
w.RunDays(1);
}
Assert.True(served.OverallSatisfaction > 0.9, $"soddisfazione {served.OverallSatisfaction:F2}");
Assert.True(served.Population > s0, $"la città servita cresce: {s0} → {served.Population}");
Assert.True(neglected.Population < n0, $"la città trascurata cala: {n0} → {neglected.Population}");
Assert.True(served.Services >= 2);
}
[Test]
public static void LoansRespectCreditAndAccrueInterest()
{
var w = TestWorlds.Small(107);
var player = w.Player;
var credit = FinanceSystem.MaxLoan(w, player);
Assert.Equal(new Money(w.Difficulty.InitialCredit), credit);
var cash0 = player.Cash;
w.Enqueue(new TakeLoanCommand(credit + Money.FromLire(1)) { Issuer = player.Id, Seq = 1 });
w.Enqueue(new TakeLoanCommand(Money.FromLire(100_000)) { Issuer = player.Id, Seq = 2 });
w.RunTicks(1);
var results = w.DrainResults();
Assert.Equal(CommandError.CreditLimit, results[0].Error);
Assert.True(results[1].Ok, results[1].Message);
Assert.Equal(cash0 + Money.FromLire(100_000), player.Cash);
Assert.Equal(Money.FromLire(100_000), player.Debt);
w.RunDays(31);
Assert.True(player.Debt < Money.FromLire(100_000), "la rata riduce il debito");
Assert.True(player.YearEntries[(int)LedgerEntry.Interest] < 0, "interessi pagati");
Assert.Equal(0L, w.MoneyBalanceSum());
var loanId = player.Loans[0].Id;
w.Enqueue(new RepayLoanCommand(loanId, player.Debt) { Issuer = player.Id, Seq = 3 });
w.RunTicks(1);
Assert.True(w.DrainResults()[0].Ok);
Assert.Equal(Money.Zero, player.Debt);
}
[Test]
public static void UnimplementedCommandsAreRejectedWithoutSideEffects()
{
var w = TestWorlds.Small(108);
ulong before = ViaFerrea.Core.Persistence.StateHasher.Compute(w);
w.Enqueue(new PendingCommand(CommandType.BuildTrack, []) { Issuer = w.Player.Id, Seq = 9 });
w.Enqueue(new TakeLoanCommand(Money.FromLire(1)) { Issuer = new CompanyId(99), Seq = 10 });
w.Pipeline.Get<CommandSystem>().Step(w.Context);
var results = w.DrainResults();
Assert.Equal(CommandError.NotImplemented, results[0].Error);
Assert.Equal(CommandError.UnknownCompany, results[1].Error);
Assert.Equal(before, ViaFerrea.Core.Persistence.StateHasher.Compute(w));
}
[Test]
public static void WalkingWorkersStaffIndustriesNextToTowns()
{
var w = TestWorlds.Small(109);
w.RunDays(40);
var manufacturing = w.Industries.Where(i => i.Def.Kind == IndustryKind.Manufacturing && !i.Closed).ToList();
Assert.True(manufacturing.Count > 0);
Assert.True(manufacturing.Any(i => i.CovWorkers > 0.9), "almeno una manifattura con lavoratori a piedi dalla città vicina");
Assert.True(w.Commutes.All(c => c.Walking));
foreach (var town in w.Towns)
Assert.True(town.EmployedWorkers <= town.Workforce(w.Data.Balance.Town), $"{town.Name}: occupati oltre la forza lavoro");
}
[Test]
public static void DifficultyChangesStartingConditions()
{
var easy = TestWorlds.Small(110, "apprendista");
var hard = TestWorlds.Small(110, "ferro_e_sangue");
Assert.Equal(Money.FromLire(500_000), easy.Player.Cash);
Assert.Equal(Money.FromLire(100_000), hard.Player.Cash);
Assert.Equal(1 + 1, easy.Companies.Count);
Assert.Equal(1 + 5, hard.Companies.Count);
Assert.Equal(easy.Terrain.ComputeHash(), hard.Terrain.ComputeHash(), "la difficoltà non cambia la mappa");
}
}
+126
View File
@@ -0,0 +1,126 @@
using System.Diagnostics;
using ViaFerrea.Core.Common;
using ViaFerrea.Core.Data;
using ViaFerrea.Core.Map;
using ViaFerrea.Tests.Harness;
namespace ViaFerrea.Tests.Map;
public static class MapTests
{
[Test(Description = "Accettazione F1: mappa da 128 km generata in meno di 3 s", Slow = true, Isolated = true)]
public static void Map128GeneratesUnderThreeSeconds()
{
TestWorlds.Map(1, 64); // riscaldamento JIT
var sw = Stopwatch.StartNew();
var map = TestWorlds.Map(3, 128);
sw.Stop();
Assert.Equal(1280, map.Terrain.Width);
Assert.True(sw.ElapsedMilliseconds < 3000, $"generazione in {sw.ElapsedMilliseconds} ms");
}
[Test]
public static void SameSeedSameMapDifferentSeedDifferentMap()
{
var a = TestWorlds.Map(5, 64);
var b = TestWorlds.Map(5, 64);
var c = TestWorlds.Map(6, 64);
Assert.Equal(a.Terrain.ComputeHash(), b.Terrain.ComputeHash());
Assert.SequenceEqual(a.Towns.Select(t => t.Name), b.Towns.Select(t => t.Name));
Assert.NotEqual(a.Terrain.ComputeHash(), c.Terrain.ComputeHash());
}
[Test(Description = "Distanze della guida: città ≥ 6 km, industrie entro i vincoli di collocazione")]
public static void PlacementDistancesAreRespected()
{
var data = TestData.Data;
foreach (ulong seed in new ulong[] { 11, 12 })
{
var map = TestWorlds.Map(seed, 128);
double cs = map.Terrain.CellSizeM;
int expectedTowns = data.Balance.Map.Towns.CountBySize["128"];
Assert.True(map.Towns.Count >= expectedTowns * 0.8, $"città {map.Towns.Count} su {expectedTowns}");
for (int i = 0; i < map.Towns.Count; i++)
{
for (int j = i + 1; j < map.Towns.Count; j++)
{
var a = map.Towns[i];
var b = map.Towns[j];
double km = Math.Sqrt(Sq(a.CellX - b.CellX) + Sq(a.CellY - b.CellY)) * cs / 1000;
Assert.True(km >= data.Balance.Map.Towns.MinDistanceKm - 1e-9, $"{a.Name}–{b.Name}: {km:F2} km");
}
}
foreach (var ind in map.Industries)
{
var def = data.Industries[ind.TypeIndex];
var p = map.Terrain.CellCenter(ind.CellX, ind.CellY);
double nearest = map.Towns.Min(t => MapGenerator.TownEdgeDistanceKm(t, p, cs));
if (def.Placement.MinTownDistanceKm is { } mn) Assert.True(nearest >= mn, $"{ind.Name}: {nearest:F2} km < {mn}");
if (def.Placement.MaxTownDistanceKm is { } mx) Assert.True(nearest <= mx, $"{ind.Name}: {nearest:F2} km > {mx}");
if (def.Placement.MaxInputDistanceKm is { } maxIn)
{
foreach (var input in def.Recipe.Inputs)
{
bool near = map.Industries.Any(o => data.Industries[o.TypeIndex].Recipe.Outputs.Any(x => x.Good == input.Good)
&& Math.Sqrt(Sq(o.CellX - ind.CellX) + Sq(o.CellY - ind.CellY)) * cs / 1000 <= maxIn + 1e-9);
Assert.True(near, $"{ind.Name}: nessun produttore di {input.Good} entro {maxIn} km");
}
}
if (def.Placement.Needs == PlacementNeed.Deposit)
{
Assert.True(ind.SiteIndex >= 0, $"{ind.Name} senza giacimento");
Assert.Equal(def.Placement.Resource, map.Sites[ind.SiteIndex].Kind);
}
var (x0, y0) = GeneratedMap.FootprintOrigin(ind.CellX, ind.CellY, ind.FootprintCells);
for (int y = y0; y < y0 + ind.FootprintCells; y++)
for (int x = x0; x < x0 + ind.FootprintCells; x++)
Assert.Equal(CellType.Industry, map.Terrain.TypeAt(x, y));
}
Assert.True(map.Hubs.Any(h => h.Kind == HubKind.Port), "almeno un porto");
Assert.True(map.Hubs.Any(h => h.Kind == HubKind.Border), "almeno un valico");
}
}
private static double Sq(double v) => v * v;
[Test]
public static void TerrainHasSeaRiversAndCover()
{
var map = TestWorlds.Map(21, 64);
var t = map.Terrain;
var counts = new int[11];
foreach (byte b in t.Types) counts[b]++;
Assert.True(counts[(int)CellType.Sea] > 0, "mare presente");
Assert.True(counts[(int)CellType.Water] > 0, "fiumi o laghi presenti");
Assert.True(counts[(int)CellType.Forest] > 0, "boschi presenti");
Assert.True(counts[(int)CellType.Plain] > t.Types.Length / 10, "pianure abbondanti");
// il mare tocca il lato scelto ed è a quota zero
bool seaOnEdge = false;
for (int i = 0; i < t.Width; i++)
{
seaOnEdge |= t.TypeAt(i, 0) == CellType.Sea || t.TypeAt(i, t.Height - 1) == CellType.Sea
|| t.TypeAt(0, i) == CellType.Sea || t.TypeAt(t.Width - 1, i) == CellType.Sea;
}
Assert.True(seaOnEdge);
for (int i = 0; i < t.Types.Length; i++)
{
if (t.Types[i] == (byte)CellType.Sea) Assert.Equal((ushort)0, t.Heights[i]);
}
Assert.True(t.RiverWidth.Any(w => w >= 2), "almeno un fiume largo più di una cella");
}
[Test]
public static void SamplerInterpolatesBetweenCellCenters()
{
var t = new Terrain(4, 4, 100, 64);
for (int y = 0; y < 4; y++)
for (int x = 0; x < 4; x++)
t.Heights[t.Index(x, y)] = Terrain.ToDecimeters(x * 10); // pendenza costante del 10 %
var s = new TerrainSampler(t);
Assert.Approx(0.0, s.HeightAt(50, 150), 1e-9);
Assert.Approx(5.0, s.HeightAt(100, 150), 1e-9);
Assert.Approx(15.0, s.HeightAt(200, 250), 1e-9);
Assert.Approx(0.1, s.Slope(150, 150), 1e-9);
Assert.Approx(DMath.Pi, Math.Abs(s.Aspect(150, 150)), 1e-9, "discesa verso ovest");
}
}
@@ -0,0 +1,104 @@
using ViaFerrea.Core.Commands;
using ViaFerrea.Core.Common;
using ViaFerrea.Core.Persistence;
using ViaFerrea.Core.Simulation;
using ViaFerrea.Tests.Harness;
namespace ViaFerrea.Tests.Persistence;
public static class PersistenceTests
{
[Test(Description = "Determinismo: stesso seme e stessi comandi agli stessi tick → stesso hash")]
public static void SameSeedAndCommandsGiveSameHash()
{
ulong Run()
{
var w = TestWorlds.Small(200);
w.RunDays(45);
w.Enqueue(new TakeLoanCommand(Money.FromLire(50_000)) { Issuer = w.Player.Id, Seq = 1 });
w.RunDays(400);
return w.LastStateHash;
}
ulong a = Run();
ulong b = Run();
Assert.Equal(a, b);
var other = TestWorlds.Small(201);
other.RunDays(445);
Assert.NotEqual(a, other.LastStateHash);
}
[Test(Description = "Salvataggio e caricamento: stesso hash subito e dopo altri 200 giorni")]
public static void SaveLoadRoundTripPreservesFuture()
{
var a = TestWorlds.Small(202);
a.Enqueue(new TakeLoanCommand(Money.FromLire(80_000)) { Issuer = a.Player.Id });
a.RunDays(100);
byte[] file = SaveFile.Save(a, "test");
var b = SaveFile.Load(TestData.Data, file);
Assert.Equal(StateHasher.Compute(a), StateHasher.Compute(b));
Assert.Equal(a.LastStateHash, b.LastStateHash);
Assert.Equal(a.Clock.Tick, b.Clock.Tick);
Assert.Equal(a.Events.Total, b.Events.Total);
a.RunDays(200);
b.RunDays(200);
Assert.Equal(a.LastStateHash, b.LastStateHash);
Assert.Equal(0L, b.MoneyBalanceSum());
// un secondo giro di salvataggio produce un file identico
Assert.SequenceEqual(SaveFile.Save(a, "test"), SaveFile.Save(b, "test"));
}
[Test]
public static void SaveHeaderIsReadableWithoutDecompressing()
{
var w = TestWorlds.Small(203);
w.RunDays(10);
var info = SaveFile.ReadInfo(SaveFile.Save(w, "0.1.0"));
Assert.Equal("0.1.0", info.GameVersion);
Assert.Equal(w.Clock.Tick, info.Tick);
Assert.Equal(w.Settings.Seed, info.Seed);
Assert.Equal(w.Player.Name, info.CompanyName);
Assert.Equal(w.Data.Hash, info.DataHash);
}
[Test]
public static void CorruptSavesAreRejected()
{
var w = TestWorlds.Small(204);
byte[] file = SaveFile.Save(w, "test");
Assert.Throws<InvalidDataException>(() => SaveFile.Load(TestData.Data, "XXXX"u8.ToArray()));
var truncated = file.AsSpan(0, file.Length / 2).ToArray();
Assert.Throws<Exception>(() => SaveFile.Load(TestData.Data, truncated));
}
[Test]
public static void SaveWriterReaderRoundTripPrimitives()
{
var wtr = new SaveWriter(4);
wtr.Write((byte)7);
wtr.Write(true);
wtr.Write(-12345);
wtr.Write(long.MinValue);
wtr.Write(ulong.MaxValue);
wtr.Write(Math.PI);
wtr.Write("Città d'acqua €");
wtr.Write((string?)null);
wtr.Write(new[] { 1, 2, 3 }.AsSpan());
wtr.Write(new ushort[] { 0, 65535 }.AsSpan());
var r = new SaveReader(wtr.ToArray());
Assert.Equal((byte)7, r.ReadByte());
Assert.True(r.ReadBool());
Assert.Equal(-12345, r.ReadInt32());
Assert.Equal(long.MinValue, r.ReadInt64());
Assert.Equal(ulong.MaxValue, r.ReadUInt64());
Assert.Equal(Math.PI, r.ReadDouble());
Assert.Equal("Città d'acqua €", r.ReadString());
Assert.Equal(null, r.ReadString());
Assert.SequenceEqual(new[] { 1, 2, 3 }, r.ReadInt32Array());
Assert.SequenceEqual(new ushort[] { 0, 65535 }, r.ReadUInt16Array());
Assert.True(r.AtEnd);
Assert.Throws<InvalidDataException>(() => r.ReadInt32());
}
}
+13
View File
@@ -0,0 +1,13 @@
using ViaFerrea.Core.Data;
namespace ViaFerrea.Tests;
/// <summary>Dati di gioco caricati una volta sola e condivisi dai test (sono immutabili).</summary>
public static class TestData
{
private static readonly Lazy<GameData> Shared = new(() => GameData.Load(Source), LazyThreadSafetyMode.ExecutionAndPublication);
public static DirectoryDataSource Source => DirectoryDataSource.FindDefault();
public static GameData Data => Shared.Value;
}
+14
View File
@@ -0,0 +1,14 @@
using ViaFerrea.Core.Map;
using ViaFerrea.Core.Simulation;
namespace ViaFerrea.Tests;
/// <summary>Mondi di prova generati dal seme (64 km: veloci da creare).</summary>
public static class TestWorlds
{
public static World Small(ulong seed = 42, string difficulty = "imprenditore") =>
WorldFactory.Create(TestData.Data, new NewGameSettings { Seed = seed, SizeKm = 64, DifficultyId = difficulty });
public static GeneratedMap Map(ulong seed, int sizeKm) =>
MapGenerator.Generate(TestData.Data, new MapSpec(seed, sizeKm, TestData.Data.Balance.Time.DefaultStartYear));
}