using ViaFerrea.Core.Common; using ViaFerrea.Core.Data; using ViaFerrea.Core.Economy; using ViaFerrea.Core.Map; namespace ViaFerrea.Core.Simulation.Systems; /// /// Città: consumo giornaliero e soddisfazione per categoria, crescita mensile, espansione /// dell'abitato e migrazione annuale verso le città meglio servite (guida 6.3). /// 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 = town.Population / Math.Max(1, tb.BaseServicesPerPopulation); 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); } } /// L'abitato si allarga con la popolazione sulle celle libere vicine. 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; } }