F2: pianificatore dei binari, profilo altimetrico e scenario Valdoria

- TrackGeometry: polilinea raccordata con il raggio della classe
- TrackPlanner: campioni ogni 25 m, due passate di pendenza, smussatura,
  franchi sui fiumi, classificazione delle opere, costi, giorni, vincoli
  per era (campate per classe di fiume, lunghezza delle gallerie)
- Scenari a mano (ScenarioLoader) e tests/scenarios/valdoria.json
- viaferrea-tools profile; industrie al prezzo globale; servizi di base

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:54:57 +00:00
1 parent 7cb98fa206
commit 259e6ab65f
21 files changed
+1558 -16

No files matched your search

+2
View File
@@ -240,6 +240,8 @@ public sealed class TownBalance
public required int StaffMinPopulation { get; init; }
public required int StaffMinServices { get; init; }
public required double ServicesSatisfactionThreshold { get; init; }
/// <summary>Servizi di base (scuole, ospedali…) ogni tanti abitanti, oltre alle categorie soddisfatte.</summary>
public required int BaseServicesPerPopulation { get; init; }
public required double ServiceJobsShare { get; init; }
public required int SatisfactionEmaDays { get; init; }
public required double InitialSatisfaction { get; init; }
@@ -31,6 +31,8 @@ public sealed class ProfileParams
public required double RiverClearanceM { get; init; }
public required double NavigableClearanceM { get; init; }
public required int NavigableMinWidthCells { get; init; }
/// <summary>Larghezza reale dell'alveo per classe di fiume 1–4 (la cella da 100 m contiene anche le sponde).</summary>
public required double[] RiverWidthMByClass { get; init; }
public required double SnapAngleDeg { get; init; }
}
+1
View File
@@ -194,6 +194,7 @@ public static class DataValidator
}
RequireKeys("construction.json", "physics.cxByKind", c.Physics.CxByKind.Keys, ["locomotive", "wagon", "coach"], errors);
if (c.Profile.SmoothingWindow % 2 == 0) Err("construction.json", "profile.smoothingWindow deve essere dispari");
if (c.Profile.RiverWidthMByClass.Length != 4) Err("construction.json", "profile.riverWidthMByClass deve avere 4 valori (classi 1–4)");
// --- manutenzione
var m = d.Maintenance;
+175
View File
@@ -0,0 +1,175 @@
using ViaFerrea.Core.Common;
namespace ViaFerrea.Core.Rail;
/// <summary>Tratto elementare della linea d'asse: rettilineo o arco di cerchio.</summary>
public readonly record struct TrackPiece(Vec2 Start, Vec2 End, double Length, bool IsArc, Vec2 Center, double Radius, double StartAngle, double Sweep)
{
/// <summary>Punto e direzione a distanza s dall'inizio del tratto.</summary>
public (Vec2 Point, Vec2 Direction) At(double s)
{
if (!IsArc)
{
var dir = Length > 0 ? (End - Start) / Length : new Vec2(1, 0);
return (Start + dir * s, dir);
}
double a = StartAngle + Sweep * (s / Length);
var p = Center + new Vec2(DMath.Cos(a), DMath.Sin(a)) * Radius;
// tangente: derivata rispetto all'angolo, orientata nel verso di percorrenza
var t = new Vec2(-DMath.Sin(a), DMath.Cos(a)) * Math.Sign(Sweep);
return (p, t);
}
}
/// <summary>Campione della linea d'asse ogni Δ metri.</summary>
public readonly record struct GeometrySample(double S, Vec2 Point, Vec2 Direction, double RadiusM);
/// <summary>
/// Linea d'asse di un binario: la polilinea dell'utente con un raccordo circolare a ogni
/// vertice (raggio della classe di velocità). Se un raccordo non entra tra due vertici il
/// raggio effettivo si riduce e il pianificatore lo segnala.
/// </summary>
public sealed class TrackGeometry
{
public IReadOnlyList<TrackPiece> Pieces { get; }
public double Length { get; }
/// <summary>Raggio minimo effettivamente ottenuto (∞ per un rettilineo).</summary>
public double MinRadius { get; }
private TrackGeometry(List<TrackPiece> pieces, double minRadius)
{
Pieces = pieces;
Length = pieces.Sum(p => p.Length);
MinRadius = minRadius;
}
/// <summary>Costruisce la geometria raccordando i vertici con il raggio richiesto.</summary>
public static TrackGeometry FromPolyline(IReadOnlyList<Vec2> points, double radius)
{
var pts = new List<Vec2>();
foreach (var p in points)
{
if (pts.Count == 0 || Vec2.Distance(pts[^1], p) > 1e-6) pts.Add(p);
}
var pieces = new List<TrackPiece>();
if (pts.Count < 2) return new TrackGeometry(pieces, double.PositiveInfinity);
int n = pts.Count;
var segLen = new double[n - 1];
for (int i = 0; i < n - 1; i++) segLen[i] = Vec2.Distance(pts[i], pts[i + 1]);
// tangenti di ogni vertice interno con il raggio richiesto, poi riduzione se non entrano
var theta = new double[n];
var tangent = new double[n];
var radii = new double[n];
for (int i = 1; i < n - 1; i++)
{
var d1 = (pts[i] - pts[i - 1]).Normalized();
var d2 = (pts[i + 1] - pts[i]).Normalized();
double cos = Math.Clamp(Vec2.Dot(d1, d2), -1, 1);
double sin = Vec2.Cross(d1, d2);
theta[i] = Math.Abs(DMath.Atan2(sin, cos));
radii[i] = radius;
tangent[i] = theta[i] < 1e-9 ? 0 : radius * DMath.Tan(theta[i] / 2);
}
for (int i = 1; i < n - 1; i++)
{
if (tangent[i] <= 0) continue;
// ogni segmento è condiviso tra i raccordi ai suoi due estremi
double availPrev = i - 1 == 0 ? segLen[i - 1] : segLen[i - 1] * Share(tangent[i], tangent[i - 1]);
double availNext = i + 1 == n - 1 ? segLen[i] : segLen[i] * Share(tangent[i], tangent[i + 1]);
double maxT = Math.Min(availPrev, availNext);
if (tangent[i] > maxT)
{
tangent[i] = maxT;
radii[i] = theta[i] >= DMath.Pi - 1e-9 ? 0 : maxT / DMath.Tan(theta[i] / 2);
}
}
double minRadius = double.PositiveInfinity;
var cursor = pts[0];
for (int i = 1; i < n; i++)
{
var dirIn = (pts[i] - pts[i - 1]).Normalized();
double t = i < n - 1 ? tangent[i] : 0;
var lineEnd = pts[i] - dirIn * t;
double lineLen = Vec2.Distance(cursor, lineEnd);
if (lineLen > 1e-9) pieces.Add(new TrackPiece(cursor, lineEnd, lineLen, false, default, 0, 0, 0));
cursor = lineEnd;
if (i < n - 1 && t > 0 && radii[i] > 0)
{
var dirOut = (pts[i + 1] - pts[i]).Normalized();
double turn = Math.Sign(Vec2.Cross(dirIn, dirOut));
// centro a sinistra o a destra della direzione d'ingresso
var normal = new Vec2(-dirIn.Y, dirIn.X) * turn;
var center = lineEnd + normal * radii[i];
double startAngle = DMath.Atan2(lineEnd.Y - center.Y, lineEnd.X - center.X);
double sweep = theta[i] * turn;
var arcEnd = pts[i] + dirOut * t;
double arcLen = radii[i] * theta[i];
pieces.Add(new TrackPiece(lineEnd, arcEnd, arcLen, true, center, radii[i], startAngle, sweep));
minRadius = Math.Min(minRadius, radii[i]);
cursor = arcEnd;
}
}
return new TrackGeometry(pieces, minRadius);
}
// quota di un segmento spettante al raccordo «mine» quando l'altro estremo ne chiede «other»
private static double Share(double mine, double other) => other <= 0 ? 1.0 : mine / (mine + other);
/// <summary>Campioni ogni «spacing» metri, più l'estremo finale.</summary>
public List<GeometrySample> Sample(double spacing)
{
var samples = new List<GeometrySample>();
if (Pieces.Count == 0) return samples;
double s = 0;
int piece = 0;
double pieceStart = 0;
while (true)
{
while (piece < Pieces.Count - 1 && s > pieceStart + Pieces[piece].Length + 1e-9)
{
pieceStart += Pieces[piece].Length;
piece++;
}
var p = Pieces[piece];
var (point, dir) = p.At(Math.Clamp(s - pieceStart, 0, p.Length));
samples.Add(new GeometrySample(s, point, dir, p.IsArc ? p.Radius : double.PositiveInfinity));
if (s >= Length - 1e-9) break;
s = Math.Min(Length, s + spacing);
if (Length - s < 1e-6) s = Length;
}
return samples;
}
/// <summary>Punto alla distanza s lungo la linea d'asse.</summary>
public (Vec2 Point, Vec2 Direction) At(double s)
{
double start = 0;
for (int i = 0; i < Pieces.Count; i++)
{
var p = Pieces[i];
if (s <= start + p.Length || i == Pieces.Count - 1)
return p.At(Math.Clamp(s - start, 0, p.Length));
start += p.Length;
}
return (Vec2.Zero, new Vec2(1, 0));
}
/// <summary>Velocità massima in curva: vMax = 3,6·√(fattore·R) km/h.</summary>
public static double CurveSpeedKmh(double radius, double factor) =>
double.IsPositiveInfinity(radius) ? double.PositiveInfinity : 3.6 * Math.Sqrt(factor * radius);
/// <summary>Aggancia la direzione dell'ultimo segmento a multipli di 45° (strumento binari del client).</summary>
public static Vec2 SnapDirection(Vec2 from, Vec2 to, double snapDeg = 45)
{
var d = to - from;
double len = d.Length;
if (len < 1e-9) return to;
double step = snapDeg * DMath.Pi / 180;
double a = Math.Round(DMath.Atan2(d.Y, d.X) / step) * step;
return from + new Vec2(DMath.Cos(a), DMath.Sin(a)) * len;
}
}
+81
View File
@@ -0,0 +1,81 @@
using ViaFerrea.Core.Common;
using ViaFerrea.Core.Map;
namespace ViaFerrea.Core.Rail;
/// <summary>Tipo di opera lungo il tracciato (guida 8.1).</summary>
public enum WorkKind : byte { Natural = 0, Embankment = 1, Cutting = 2, Bridge = 3, Tunnel = 4 }
/// <summary>Opera: tratto contiguo dello stesso tipo, con costo e giorni di cantiere.</summary>
public sealed record Work(WorkKind Kind, double StartM, double EndM, double MaxHeightM, long CostCents, int Days, string? BridgeType)
{
public double LengthM => EndM - StartM;
}
/// <summary>Motivo di rifiuto o avviso del pianificatore.</summary>
public enum PlanIssueCode : byte
{
TooShort = 0,
OutOfMap = 1,
GradientExceeded = 2,
RadiusTooSmall = 3,
BridgeNeeded = 4,
BridgeTooLong = 5,
TunnelNotAllowed = 6,
TunnelTooLong = 7,
ForbiddenArea = 8,
CrossesOwnTrack = 9,
UnknownTrackClass = 10,
ClassNotAvailable = 11,
ElectrificationNotAvailable = 12,
EndpointHeight = 13,
SteepForTraction = 14,
}
/// <summary>Problema localizzato lungo il tracciato (AtM in metri dall'inizio).</summary>
public readonly record struct PlanIssue(PlanIssueCode Code, string Message, double AtM);
/// <summary>Campione del profilo: terreno, binario, opera, velocità ammessa.</summary>
public readonly record struct ProfileSample(double S, Vec2 Point, double TerrainM, double TrackM, WorkKind Kind, CellType Cell, double SpeedLimitKmh);
/// <summary>Richiesta di pianificazione (comando BuildTrack e anteprima del client).</summary>
public sealed record TrackPlanRequest
{
public required IReadOnlyList<Vec2> Polyline { get; init; }
public double HeightOffsetM { get; init; }
public bool AllowBridges { get; init; } = true;
public bool AllowTunnels { get; init; } = true;
public string TrackClass { get; init; } = "c60";
public bool DoubleTrack { get; init; }
public bool Electrified { get; init; }
public CompanyId Company { get; init; }
/// <summary>Quota imposta all'inizio (aggancio a un nodo esistente); null = quota del terreno.</summary>
public double? StartHeightM { get; init; }
public double? EndHeightM { get; init; }
}
/// <summary>Risultato della pianificazione: profilo, opere, costi, tempi, errori e avvisi.</summary>
public sealed class TrackPlan
{
public required TrackPlanRequest Request { get; init; }
public required TrackGeometry Geometry { get; init; }
public List<PlanIssue> Errors { get; } = [];
public List<PlanIssue> Warnings { get; } = [];
public List<ProfileSample> Samples { get; } = [];
public List<Work> Works { get; } = [];
public bool Valid => Errors.Count == 0;
public double LengthM => Geometry.Length;
public Money WorksCost { get; set; }
public Money LandCost { get; set; }
public Money TotalCost => WorksCost + LandCost;
public int Days { get; set; }
public double MaxGradient { get; set; }
public double GradientLimit { get; set; }
public double MinRadiusM => Geometry.MinRadius;
public double ClassSpeedKmh { get; set; }
public string? BridgeType { get; set; }
/// <summary>Lunghezza totale per tipo di opera.</summary>
public double LengthOf(WorkKind kind) => Works.Where(w => w.Kind == kind).Sum(w => w.LengthM);
}
+482
View File
@@ -0,0 +1,482 @@
using ViaFerrea.Core.Common;
using ViaFerrea.Core.Data;
using ViaFerrea.Core.Map;
namespace ViaFerrea.Core.Rail;
/// <summary>Attraversamento di un binario esistente lungo un segmento (T = frazione 0–1).</summary>
public readonly record struct TrackCrossing(double T, double OtherHeightM, bool Foreign);
/// <summary>Interrogazioni sulla rete esistente necessarie al pianificatore.</summary>
public interface ITrackObstacles
{
/// <summary>Aggiunge a results gli attraversamenti di binari esistenti tra a e b.</summary>
void FindCrossings(Vec2 a, Vec2 b, CompanyId company, List<TrackCrossing> results);
/// <summary>Vero se il punto cade nell'area di una stazione o di un deposito (foreign = di un'altra compagnia).</summary>
bool IsStationArea(Vec2 p, CompanyId company, out bool foreign);
}
/// <summary>Contesto del pianificatore: terreno, anno, moltiplicatori, rete e città.</summary>
public sealed class TrackPlanContext
{
public required GameData Data { get; init; }
public required TerrainSampler Sampler { get; init; }
public required int Year { get; init; }
/// <summary>Moltiplicatore dei costi (difficoltà, eventuale sconto IA).</summary>
public double CostMultiplier { get; init; } = 1.0;
public ITrackObstacles? Obstacles { get; init; }
/// <summary>Distanza in km dal bordo della città più vicina (per il costo dei terreni); null = nessuna città.</summary>
public Func<Vec2, double>? NearestTownEdgeKm { get; init; }
}
/// <summary>
/// Pianificatore dei binari (guida 8.1–8.2): campiona il terreno ogni 25 m lungo la linea
/// d'asse raccordata, calcola il profilo con le due passate di limitazione della pendenza e la
/// smussatura, rispetta franchi sui fiumi e divieti, classifica le opere, ne stima costi e
/// giorni di cantiere. Usato identico dal server e dall'anteprima del client.
/// </summary>
public static class TrackPlanner
{
public static TrackPlan Plan(TrackPlanContext ctx, TrackPlanRequest req)
{
var c = ctx.Data.Construction;
var eras = ctx.Data.Eras;
var terrain = ctx.Sampler.Terrain;
var trackClass = eras.TrackClasses.FirstOrDefault(t => t.Id == req.TrackClass);
var speedClass = c.SpeedClasses.FirstOrDefault(s => s.TrackClass == req.TrackClass);
double minRadius = speedClass?.MinRadiusM ?? 200;
var geometry = TrackGeometry.FromPolyline(req.Polyline, minRadius);
var plan = new TrackPlan { Request = req, Geometry = geometry };
if (trackClass is null || speedClass is null)
{
plan.Errors.Add(new PlanIssue(PlanIssueCode.UnknownTrackClass, $"Classe di binario sconosciuta: {req.TrackClass}", 0));
return plan;
}
plan.ClassSpeedKmh = trackClass.SpeedKmh;
if (trackClass.From > ctx.Year)
plan.Errors.Add(new PlanIssue(PlanIssueCode.ClassNotAvailable, $"{trackClass.NameIt} disponibile dal {trackClass.From}", 0));
if (req.Electrified && eras.ElectrificationFrom > ctx.Year)
plan.Errors.Add(new PlanIssue(PlanIssueCode.ElectrificationNotAvailable, $"Elettrificazione disponibile dal {eras.ElectrificationFrom}", 0));
double spacing = c.Profile.SampleSpacingM;
if (geometry.Length < spacing * 2)
{
plan.Errors.Add(new PlanIssue(PlanIssueCode.TooShort, $"Binario troppo corto (minimo {spacing * 2:F0} m)", 0));
return plan;
}
foreach (var pt in req.Polyline)
{
if (pt.X < 0 || pt.Y < 0 || pt.X > terrain.WidthM || pt.Y > terrain.HeightM)
{
plan.Errors.Add(new PlanIssue(PlanIssueCode.OutOfMap, "Il tracciato esce dalla mappa", 0));
return plan;
}
}
if (geometry.MinRadius < minRadius - 1e-6)
{
double at = AtOfMinRadius(geometry);
plan.Errors.Add(new PlanIssue(PlanIssueCode.RadiusTooSmall,
$"Curva di raggio {geometry.MinRadius:F0} m: la classe {trackClass.SpeedKmh:F0} km/h richiede almeno {minRadius:F0} m", at));
}
// pendenza massima: la trazione più permissiva disponibile quest'anno su questo binario
double gMax = 0;
foreach (var t in eras.Tractions)
{
if (t.From <= ctx.Year && (!t.NeedsElectrification || req.Electrified))
gMax = Math.Max(gMax, c.MaxGradientByTraction.For(t.Id));
}
plan.GradientLimit = gMax;
var geo = geometry.Sample(spacing);
int n = geo.Count;
var terrainH = new double[n];
var cells = new CellType[n];
var water = new bool[n];
var navigable = new bool[n];
var riverClass = new int[n];
var forcedBridge = new bool[n];
var crossingClearance = new double[n];
Array.Fill(crossingClearance, double.NegativeInfinity);
for (int i = 0; i < n; i++)
{
var pt = geo[i].Point;
terrainH[i] = ctx.Sampler.HeightAt(pt);
var (cx, cy) = terrain.CellAt(pt);
cells[i] = terrain.TypeAt(cx, cy);
water[i] = cells[i] is CellType.Water or CellType.Sea;
if (water[i])
{
int width = terrain.RiverWidth[terrain.Index(cx, cy)];
riverClass[i] = cells[i] == CellType.Sea ? 0 : width;
navigable[i] = cells[i] == CellType.Sea || width == 0 || width >= c.Profile.NavigableMinWidthCells;
// la superficie dell'acqua è la quota della cella, non l'interpolazione con le sponde
terrainH[i] = Math.Min(terrainH[i], terrain.CellHeightM(cx, cy));
}
forcedBridge[i] = water[i] || cells[i] == CellType.Marsh;
bool forbidden = (cells[i] == CellType.Town && c.Rules.ForbidTownFootprint)
|| (cells[i] == CellType.Industry && c.Rules.ForbidIndustryFootprint);
if (forbidden)
{
plan.Errors.Add(new PlanIssue(PlanIssueCode.ForbiddenArea,
cells[i] == CellType.Town ? "Il tracciato attraversa l'abitato di una città" : "Il tracciato attraversa un'industria", geo[i].S));
return Finish(plan, ctx, geo, terrainH, terrainH, cells);
}
if (ctx.Obstacles is { } obs && i > 0 && i < n - 1 && obs.IsStationArea(pt, req.Company, out bool foreign))
{
plan.Errors.Add(new PlanIssue(PlanIssueCode.ForbiddenArea,
foreign ? "Il tracciato attraversa una stazione di un'altra compagnia" : "Il tracciato attraversa una stazione: collegalo all'estremità", geo[i].S));
return Finish(plan, ctx, geo, terrainH, terrainH, cells);
}
}
// attraversamenti di binari esistenti: altrui → cavalcavia automatico, propri → vietati
if (ctx.Obstacles is { } obstacles)
{
var found = new List<TrackCrossing>();
for (int i = 0; i < n - 1; i++)
{
found.Clear();
obstacles.FindCrossings(geo[i].Point, geo[i + 1].Point, req.Company, found);
foreach (var x in found)
{
int k = x.T < 0.5 ? i : i + 1;
if (!x.Foreign)
{
if (k > 0 && k < n - 1)
plan.Errors.Add(new PlanIssue(PlanIssueCode.CrossesOwnTrack,
"Incrocio a raso con un proprio binario: termina il tracciato sul binario esistente", geo[k].S));
continue;
}
forcedBridge[k] = true;
crossingClearance[k] = Math.Max(crossingClearance[k], x.OtherHeightM + c.Rules.OverpassClearanceM);
}
}
}
if (!req.AllowBridges)
{
for (int i = 0; i < n; i++)
{
if (forcedBridge[i])
{
plan.Errors.Add(new PlanIssue(PlanIssueCode.BridgeNeeded,
water[i] ? "Serve un ponte per attraversare l'acqua" : cells[i] == CellType.Marsh ? "Serve un viadotto sulla palude" : "Serve un cavalcavia", geo[i].S));
return Finish(plan, ctx, geo, terrainH, terrainH, cells);
}
}
}
// ---- profilo
var delta = new double[n - 1];
for (int i = 0; i < n - 1; i++) delta[i] = geo[i + 1].S - geo[i].S;
double offset = Math.Clamp(req.HeightOffsetM, -c.Profile.HeightOffsetRangeM, c.Profile.HeightOffsetRangeM);
double startPin = req.StartHeightM ?? terrainH[0];
double endPin = req.EndHeightM ?? terrainH[n - 1];
var target = new double[n];
var lower = new double[n];
var upper = new double[n];
for (int i = 0; i < n; i++)
{
target[i] = terrainH[i] + offset;
lower[i] = double.NegativeInfinity;
upper[i] = double.PositiveInfinity;
if (water[i])
lower[i] = terrainH[i] + (navigable[i] ? c.Profile.NavigableClearanceM : c.Profile.RiverClearanceM);
lower[i] = Math.Max(lower[i], crossingClearance[i]);
if (!req.AllowTunnels && !water[i]) lower[i] = Math.Max(lower[i], terrainH[i] - c.Profile.CuttingMaxM);
if (!req.AllowBridges && !water[i]) upper[i] = Math.Min(upper[i], terrainH[i] + c.Profile.EmbankmentMaxM);
}
target[0] = lower[0] = upper[0] = startPin;
target[n - 1] = lower[n - 1] = upper[n - 1] = endPin;
var l = MaxEnvelope(lower, delta, gMax);
var u = MinEnvelope(upper, delta, gMax);
for (int i = 0; i < n; i++)
{
if (l[i] > u[i] + 1e-6)
{
double needed = RequiredGradient(lower, upper, delta, i);
string reason = !req.AllowTunnels
? "servirebbe una galleria o un altro tracciato"
: "abbassa o alza il tracciato o cambia percorso";
plan.Errors.Add(new PlanIssue(PlanIssueCode.GradientExceeded,
$"Pendenza necessaria {needed * 100:F1}% oltre il massimo {gMax * 100:F1}%: {reason}", geo[i].S));
return Finish(plan, ctx, geo, terrainH, terrainH, cells);
}
}
// due passate di limitazione della pendenza (guida 8.1), poi i vincoli inferiori
var h = new double[n];
for (int i = 0; i < n; i++) h[i] = Math.Clamp(target[i], l[i], u[i]);
h = MinEnvelope(h, delta, gMax);
for (int i = 0; i < n; i++) h[i] = Math.Max(h[i], l[i]);
// smussatura a finestra mobile, estremi fissi, poi ripristino rigoroso dei vincoli
int half = c.Profile.SmoothingWindow / 2;
var smooth = new double[n];
smooth[0] = h[0];
smooth[n - 1] = h[n - 1];
for (int i = 1; i < n - 1; i++)
{
int k = Math.Min(half, Math.Min(i, n - 1 - i));
double sum = 0;
for (int j = i - k; j <= i + k; j++) sum += h[j];
smooth[i] = sum / (2 * k + 1);
}
for (int i = 0; i < n; i++) smooth[i] = Math.Clamp(smooth[i], l[i], u[i]);
h = MinEnvelope(smooth, delta, gMax);
for (int i = 0; i < n; i++) h[i] = Math.Max(h[i], l[i]);
if (Math.Abs(h[0] - startPin) > 0.05 || Math.Abs(h[n - 1] - endPin) > 0.05)
plan.Errors.Add(new PlanIssue(PlanIssueCode.EndpointHeight, "Dislivello eccessivo alle estremità del tracciato", 0));
double maxGrade = 0;
for (int i = 0; i < n - 1; i++) maxGrade = Math.Max(maxGrade, Math.Abs(h[i + 1] - h[i]) / delta[i]);
plan.MaxGradient = maxGrade;
if (maxGrade > gMax + 1e-9)
plan.Errors.Add(new PlanIssue(PlanIssueCode.GradientExceeded, $"Pendenza {maxGrade * 100:F2}% oltre il massimo {gMax * 100:F1}%", 0));
// ---- classificazione per campione
var kinds = new WorkKind[n];
var p = c.Profile;
for (int i = 0; i < n; i++)
{
double d = h[i] - terrainH[i];
if (forcedBridge[i]) kinds[i] = WorkKind.Bridge;
else if (Math.Abs(d) <= p.NaturalToleranceM) kinds[i] = WorkKind.Natural;
else if (d > 0 && d <= p.EmbankmentMaxM) kinds[i] = WorkKind.Embankment;
else if (d < 0 && d >= -p.CuttingMaxM) kinds[i] = WorkKind.Cutting;
else if (d > p.EmbankmentMaxM) kinds[i] = WorkKind.Bridge;
else kinds[i] = WorkKind.Tunnel;
}
if (!req.AllowTunnels && kinds.Contains(WorkKind.Tunnel))
{
int at = Array.IndexOf(kinds, WorkKind.Tunnel);
plan.Errors.Add(new PlanIssue(PlanIssueCode.TunnelNotAllowed, "Il profilo richiede una galleria ma le gallerie sono disattivate", geo[at].S));
}
if (!req.AllowBridges && kinds.Contains(WorkKind.Bridge))
{
int at = Array.IndexOf(kinds, WorkKind.Bridge);
plan.Errors.Add(new PlanIssue(PlanIssueCode.BridgeNeeded, "Il profilo richiede un viadotto ma i ponti sono disattivati", geo[at].S));
}
BuildWorks(plan, ctx, geo, terrainH, h, kinds, cells, water, riverClass);
return Finish(plan, ctx, geo, terrainH, h, cells, kinds);
}
private static void BuildWorks(TrackPlan plan, TrackPlanContext ctx, List<GeometrySample> geo, double[] terrainH, double[] h,
WorkKind[] kinds, CellType[] cells, bool[] water, int[] riverClass)
{
var c = ctx.Data.Construction;
var eras = ctx.Data.Eras;
int n = geo.Count;
double classMult = c.SpeedClasses.First(s => s.TrackClass == plan.Request.TrackClass).CostMultiplier;
double extra = (plan.Request.DoubleTrack ? c.Costs.DoubleTrackMultiplier : 1.0) * (plan.Request.Electrified ? 1.0 + c.Costs.ElectrificationExtra : 1.0);
double tunnelLimit = eras.TunnelLimits.Where(t => t.From <= ctx.Year).Select(t => t.MaxLengthM).DefaultIfEmpty(0).Max();
var bridgeTypes = eras.BridgeTypes.Where(b => b.From <= ctx.Year).ToList();
int start = 0;
double totalDays = 0;
while (start < n)
{
int end = start;
while (end + 1 < n && kinds[end + 1] == kinds[start]) end++;
var kind = kinds[start];
double from = start == 0 ? 0 : (geo[start - 1].S + geo[start].S) / 2;
double to = end == n - 1 ? geo[n - 1].S : (geo[end].S + geo[end + 1].S) / 2;
// campata d'acqua più lunga del tratto (per il tipo di ponte): per i fiumi conta la
// larghezza dell'alveo della loro classe, per laghi e mare l'estensione attraversata
double waterSpan = 0, run = 0;
for (int i = start; i <= end; i++)
{
if (!water[i])
{
run = 0;
continue;
}
if (riverClass[i] > 0)
{
waterSpan = Math.Max(waterSpan, c.Profile.RiverWidthMByClass[Math.Min(riverClass[i], 4) - 1]);
run = 0;
}
else
{
run += SampleLength(geo, i);
waterSpan = Math.Max(waterSpan, run);
}
}
BridgeTypeDef? bridge = null;
if (kind == WorkKind.Bridge)
{
bridge = bridgeTypes.Where(b => b.MaxSpanM >= waterSpan).OrderBy(b => b.CostMultiplier).ThenBy(b => b.From).FirstOrDefault();
if (bridge is null)
{
double best = bridgeTypes.Count == 0 ? 0 : bridgeTypes.Max(b => b.MaxSpanM);
plan.Errors.Add(new PlanIssue(PlanIssueCode.BridgeTooLong,
$"Corso d'acqua di {waterSpan:F0} m oltre la campata massima ({best:F0} m) dell'epoca: attraversalo dove è più stretto", from));
}
else
{
plan.BridgeType = bridge.Id;
}
}
if (kind == WorkKind.Tunnel && to - from > tunnelLimit)
plan.Errors.Add(new PlanIssue(PlanIssueCode.TunnelTooLong,
$"Galleria di {to - from:F0} m oltre il limite dell'epoca ({tunnelLimit:F0} m)", from));
double cost = 0, maxHeight = 0;
for (int i = start; i <= end; i++)
{
double d = h[i] - terrainH[i];
maxHeight = Math.Max(maxHeight, Math.Abs(d));
double perMeter = c.Costs.BasePerMeter * classMult * TerrainModifier(c, cells[i]) * KindFactor(c, kind, d)
* (kind == WorkKind.Bridge ? bridge?.CostMultiplier ?? 1.0 : 1.0);
cost += perMeter * SampleLength(geo, i);
}
cost *= extra * ctx.CostMultiplier;
double rate = c.Crews.MetersPerDay[KindKey(kind)];
int days = (int)Math.Ceiling((to - from) / rate);
totalDays += days;
plan.Works.Add(new Work(kind, from, to, maxHeight, (long)Math.Round(cost), days, kind == WorkKind.Bridge ? bridge?.Id : null));
start = end + 1;
}
plan.WorksCost = new Money(plan.Works.Sum(w => w.CostCents));
plan.Days = (int)totalDays;
// terreni: celle sotto il binario (le gallerie non ne occupano)
var land = c.Costs.Land;
var counted = new HashSet<int>();
double landCents = 0;
var terrain = ctx.Sampler.Terrain;
for (int i = 0; i < n; i++)
{
if (kinds[i] == WorkKind.Tunnel) continue;
var (cx, cy) = terrain.CellAt(geo[i].Point);
if (!counted.Add(terrain.Index(cx, cy))) continue;
double m = 1.0;
if (ctx.NearestTownEdgeKm is { } nearest && nearest(geo[i].Point) <= land.NearTownKm) m *= land.NearTownMultiplier;
if (cells[i] == CellType.Field) m *= land.FieldMultiplier;
landCents += land.BasePerCell * m;
}
plan.LandCost = Money.FromCentsRounded(landCents * ctx.CostMultiplier);
}
private static TrackPlan Finish(TrackPlan plan, TrackPlanContext ctx, List<GeometrySample> geo, double[] terrainH, double[] h,
CellType[] cells, WorkKind[]? kinds = null)
{
var c = ctx.Data.Construction;
double classSpeed = plan.ClassSpeedKmh > 0 ? plan.ClassSpeedKmh : 60;
for (int i = 0; i < geo.Count; i++)
{
double speed = Math.Min(classSpeed, TrackGeometry.CurveSpeedKmh(geo[i].RadiusM, c.CurveSpeedFactor));
plan.Samples.Add(new ProfileSample(geo[i].S, geo[i].Point, terrainH[i], h[i], kinds?[i] ?? WorkKind.Natural, cells[i], speed));
}
if (plan.Valid)
{
foreach (var t in ctx.Data.Eras.Tractions)
{
if (t.From > ctx.Year) continue;
double g = c.MaxGradientByTraction.For(t.Id);
if (plan.MaxGradient > g + 1e-9)
plan.Warnings.Add(new PlanIssue(PlanIssueCode.SteepForTraction,
$"Pendenza {plan.MaxGradient * 100:F1}% oltre il limite della trazione {t.NameIt.ToLowerInvariant()} ({g * 100:F1}%): servirà la doppia trazione", 0));
}
}
return plan;
}
private static double SampleLength(List<GeometrySample> geo, int i)
{
double left = i == 0 ? 0 : (geo[i].S - geo[i - 1].S) / 2;
double right = i == geo.Count - 1 ? 0 : (geo[i + 1].S - geo[i].S) / 2;
return left + right;
}
private static double KindFactor(ConstructionFile c, WorkKind kind, double d) => kind switch
{
WorkKind.Natural => c.Costs.Natural,
WorkKind.Embankment => 1 + c.Costs.EmbankmentPerM * Math.Max(0, d),
WorkKind.Cutting => 1 + c.Costs.CuttingPerM * Math.Max(0, -d),
WorkKind.Bridge => c.Costs.BridgeBase + c.Costs.BridgePerM * Math.Max(0, d),
_ => c.Costs.Tunnel,
};
private static double TerrainModifier(ConstructionFile c, CellType cell) =>
c.Costs.TerrainModifiers.TryGetValue(cell.ToString().ToLowerInvariant(), out double m) ? m : 1.0;
public static string KindKey(WorkKind kind) => kind switch
{
WorkKind.Natural => "natural",
WorkKind.Embankment => "embankment",
WorkKind.Cutting => "cutting",
WorkKind.Bridge => "bridge",
_ => "tunnel",
};
/// <summary>Funzione g-lipschitziana più alta che non supera i limiti (passate avanti e indietro).</summary>
public static double[] MinEnvelope(double[] values, double[] delta, double g)
{
int n = values.Length;
var r = (double[])values.Clone();
for (int i = 1; i < n; i++) r[i] = Math.Min(r[i], r[i - 1] + g * delta[i - 1]);
for (int i = n - 2; i >= 0; i--) r[i] = Math.Min(r[i], r[i + 1] + g * delta[i]);
return r;
}
/// <summary>Funzione g-lipschitziana più bassa che non scende sotto i limiti.</summary>
public static double[] MaxEnvelope(double[] values, double[] delta, double g)
{
int n = values.Length;
var r = (double[])values.Clone();
for (int i = 1; i < n; i++) r[i] = Math.Max(r[i], r[i - 1] - g * delta[i - 1]);
for (int i = n - 2; i >= 0; i--) r[i] = Math.Max(r[i], r[i + 1] - g * delta[i]);
return r;
}
// pendenza minima che renderebbe compatibili i vincoli attorno al punto di conflitto
private static double RequiredGradient(double[] lower, double[] upper, double[] delta, int at)
{
double worst = 0;
int n = lower.Length;
for (int i = 0; i < n; i++)
{
if (double.IsNegativeInfinity(lower[i])) continue;
double dist = 0;
for (int j = i; j < n - 1 && dist < 5000; j++)
{
dist += delta[j];
if (!double.IsPositiveInfinity(upper[j + 1]))
worst = Math.Max(worst, (lower[i] - upper[j + 1]) / dist);
}
dist = 0;
for (int j = i; j > 0 && dist < 5000; j--)
{
dist += delta[j - 1];
if (!double.IsPositiveInfinity(upper[j - 1]))
worst = Math.Max(worst, (lower[i] - upper[j - 1]) / dist);
}
}
_ = at;
return worst;
}
private static double AtOfMinRadius(TrackGeometry g)
{
double s = 0;
foreach (var p in g.Pieces)
{
if (p.IsArc && Math.Abs(p.Radius - g.MinRadius) < 1e-9) return s;
s += p.Length;
}
return 0;
}
}
@@ -0,0 +1,103 @@
using System.Text.Json.Serialization;
namespace ViaFerrea.Core.Simulation.Scenarios;
/// <summary>
/// Scenario costruito a mano (tests/scenarios/*.json): terreno da elementi geometrici, città,
/// industrie e hub in posizioni precise. Coordinate in km dall'angolo nord-ovest.
/// </summary>
public sealed class ScenarioFile
{
[JsonPropertyName("$schema")] public string? Schema { get; init; }
public required string Name { get; init; }
[JsonPropertyName("description_it")] public string? DescriptionIt { get; init; }
public required ulong Seed { get; init; }
public int StartYear { get; set; } = 1850;
public string Difficulty { get; set; } = "imprenditore";
public required ScenarioTerrain Terrain { get; init; }
public List<ScenarioTown> Towns { get; set; } = [];
public List<ScenarioIndustry> Industries { get; set; } = [];
public List<ScenarioHub> Hubs { get; set; } = [];
public ScenarioPlayer? Player { get; init; }
/// <summary>Tracciati nominati, usati dai test e dallo strumento profile.</summary>
public Dictionary<string, ScenarioRoute> Routes { get; set; } = [];
}
public sealed class ScenarioTerrain
{
public required int WidthCells { get; init; }
public required int HeightCells { get; init; }
public double BaseHeightM { get; set; } = 100;
/// <summary>Inclinazione generale in metri per km verso est e verso sud.</summary>
public double TiltEastMPerKm { get; init; }
public double TiltSouthMPerKm { get; init; }
/// <summary>Ampiezza del microrilievo (rumore) in metri.</summary>
public double NoiseM { get; init; }
public List<ScenarioFeature> Features { get; set; } = [];
}
/// <summary>Elemento del terreno: hill, river, marsh, forest, lake, sea, field.</summary>
public sealed class ScenarioFeature
{
public required string Kind { get; init; }
public double X { get; init; }
public double Y { get; init; }
public double RadiusKm { get; init; }
/// <summary>Semiassi dell'ellisse (palude, bosco, lago); se assenti vale RadiusKm.</summary>
public double? RadiusXKm { get; init; }
public double? RadiusYKm { get; init; }
public double HeightM { get; init; }
public List<double[]>? Points { get; init; }
public int WidthClass { get; set; } = 1;
public double DepthM { get; set; } = 4;
/// <summary>Lato per il mare: north, east, south, west.</summary>
public string? Side { get; init; }
public double WidthKm { get; init; }
}
public sealed class ScenarioTown
{
public required string Name { get; init; }
public required double X { get; init; }
public required double Y { get; init; }
public required int Population { get; init; }
}
public sealed class ScenarioIndustry
{
public required string Type { get; init; }
public required string Name { get; init; }
public required double X { get; init; }
public required double Y { get; init; }
public int Level { get; set; } = 1;
public long? ReserveTonnes { get; init; }
}
public sealed class ScenarioHub
{
public required string Kind { get; init; }
public required string Name { get; init; }
public required double X { get; init; }
public required double Y { get; init; }
}
public sealed class ScenarioPlayer
{
public string? Name { get; init; }
public long? Cash { get; init; }
}
public sealed class ScenarioRoute
{
public required List<double[]> Points { get; init; }
public double HeightOffsetM { get; init; }
public bool AllowBridges { get; set; } = true;
public bool AllowTunnels { get; set; } = true;
public string TrackClass { get; set; } = "c60";
}
[JsonSourceGenerationOptions(PropertyNamingPolicy = JsonKnownNamingPolicy.CamelCase, PropertyNameCaseInsensitive = true,
UnmappedMemberHandling = JsonUnmappedMemberHandling.Disallow, ReadCommentHandling = System.Text.Json.JsonCommentHandling.Skip,
AllowTrailingCommas = true)]
[JsonSerializable(typeof(ScenarioFile))]
public sealed partial class ScenarioJsonContext : JsonSerializerContext;
@@ -0,0 +1,244 @@
using System.Text.Json;
using ViaFerrea.Core.Common;
using ViaFerrea.Core.Data;
using ViaFerrea.Core.Economy;
using ViaFerrea.Core.Map;
using ViaFerrea.Core.Rail;
namespace ViaFerrea.Core.Simulation.Scenarios;
/// <summary>Scenario caricato: mondo pronto e definizioni originali (per i tracciati nominati).</summary>
public sealed record LoadedScenario(World World, ScenarioFile File)
{
/// <summary>Richiesta di pianificazione per un tracciato nominato dello scenario.</summary>
public TrackPlanRequest Route(string name, CompanyId company)
{
var r = File.Routes[name];
return new TrackPlanRequest
{
Polyline = r.Points.Select(p => new Vec2(p[0] * 1000, p[1] * 1000)).ToList(),
HeightOffsetM = r.HeightOffsetM,
AllowBridges = r.AllowBridges,
AllowTunnels = r.AllowTunnels,
TrackClass = r.TrackClass,
Company = company,
};
}
}
/// <summary>Costruisce un mondo da uno scenario JSON (terreno a mano + entità in posizioni date).</summary>
public static class ScenarioLoader
{
public static LoadedScenario LoadFile(GameData data, string path) => Load(data, File.ReadAllText(path));
public static LoadedScenario Load(GameData data, string json)
{
var file = JsonSerializer.Deserialize(json, ScenarioJsonContext.Default.ScenarioFile)
?? throw new InvalidDataException("Scenario vuoto");
var terrain = BuildTerrain(file.Terrain, new Rng(file.Seed));
double cs = terrain.CellSizeM;
(int, int) Cell(double xKm, double yKm) =>
(Math.Clamp((int)(xKm * 1000 / cs), 0, terrain.Width - 1), Math.Clamp((int)(yKm * 1000 / cs), 0, terrain.Height - 1));
var tp = data.Balance.Map.Towns;
var towns = new List<TownSeed>();
foreach (var t in file.Towns)
{
var (x, y) = Cell(t.X, t.Y);
double radius = tp.RadiusBaseCells + tp.RadiusPerSqrtPop * Math.Sqrt(t.Population);
towns.Add(new TownSeed(t.Name, x, y, t.Population, radius));
MarkDisc(terrain, x, y, radius, CellType.Town);
}
var sites = new List<ResourceSiteSeed>();
var industries = new List<IndustrySeed>();
foreach (var ind in file.Industries)
{
var def = data.Industry(ind.Type);
var (x, y) = Cell(ind.X, ind.Y);
int footprint = data.Balance.Industry.FootprintCells[def.Footprint.ToString().ToLowerInvariant()];
int site = -1;
if (def.Placement.Needs == PlacementNeed.Deposit && def.Placement.Resource is { } kind)
{
site = sites.Count;
var range = data.Balance.Map.Deposits.ReserveTonnes[kind.ToString().ToLowerInvariant()];
sites.Add(new ResourceSiteSeed(kind, x, y, 4, ind.ReserveTonnes ?? range[1]));
}
industries.Add(new IndustrySeed(def.Index, ind.Name, x, y, ind.Level, site, footprint));
}
var hubs = new List<HubSeed>();
foreach (var h in file.Hubs)
{
var kind = Enum.Parse<HubKind>(h.Kind, ignoreCase: true);
var (x, y) = Cell(h.X, h.Y);
int footprint = data.Balance.Industry.FootprintCells[data.Balance.Hubs.For(kind).Footprint.ToString().ToLowerInvariant()];
hubs.Add(new HubSeed(kind, h.Name, x, y, footprint));
var (x0, y0) = GeneratedMap.FootprintOrigin(x, y, footprint);
for (int yy = y0; yy < y0 + footprint; yy++)
for (int xx = x0; xx < x0 + footprint; xx++)
if (terrain.InBounds(xx, yy)) terrain.SetType(xx, yy, CellType.Industry);
}
var seaSide = file.Terrain.Features.FirstOrDefault(f => f.Kind == "sea")?.Side?.ToLowerInvariant() switch
{
"north" => MapSide.North,
"south" => MapSide.South,
"west" => MapSide.West,
_ => MapSide.East,
};
var map = new GeneratedMap
{
Spec = new MapSpec(file.Seed, (int)Math.Round(terrain.WidthM / 1000), file.StartYear),
Terrain = terrain,
SeaSide = seaSide,
Sites = sites,
Towns = towns,
Industries = industries,
Hubs = hubs,
};
var settings = new NewGameSettings
{
Seed = file.Seed,
SizeKm = map.Spec.SizeKm,
StartYear = file.StartYear,
DifficultyId = file.Difficulty,
PlayerCompanyName = file.Player?.Name ?? "Società Ferroviaria Valdoria",
};
var world = WorldFactory.FromMap(data, map, settings);
if (file.Player?.Cash is { } cash)
{
var player = world.Player;
world.Money.Transfer(Account.Of(player.Id), Account.External, player.Cash, LedgerEntry.Other);
world.Money.Transfer(Account.External, Account.Of(player.Id), new Money(cash), LedgerEntry.Other);
}
return new LoadedScenario(world, file);
}
private static Terrain BuildTerrain(ScenarioTerrain spec, Rng rng)
{
var t = new Terrain(spec.WidthCells, spec.HeightCells, 100, 64);
double cs = t.CellSizeM;
var noise = new ValueNoise(rng.NextU64());
var heights = new double[t.Width * t.Height];
for (int y = 0; y < t.Height; y++)
{
for (int x = 0; x < t.Width; x++)
{
double xKm = (x + 0.5) * cs / 1000, yKm = (y + 0.5) * cs / 1000;
double h = spec.BaseHeightM + spec.TiltEastMPerKm * xKm + spec.TiltSouthMPerKm * yKm
+ (noise.Fbm(x, y, 2, 12, 0.5, 2) - 0.5) * 2 * spec.NoiseM;
foreach (var f in spec.Features)
{
if (f.Kind != "hill") continue;
double r = Math.Sqrt((xKm - f.X) * (xKm - f.X) + (yKm - f.Y) * (yKm - f.Y)) / f.RadiusKm;
if (r < 1) h += f.HeightM * (1 - r * r) * (1 - r * r);
}
heights[t.Index(x, y)] = h;
}
}
foreach (var f in spec.Features)
{
switch (f.Kind)
{
case "marsh":
case "forest":
case "field":
case "lake":
{
var type = f.Kind switch { "marsh" => CellType.Marsh, "forest" => CellType.Forest, "field" => CellType.Field, _ => CellType.Water };
double rx = f.RadiusXKm ?? f.RadiusKm, ry = f.RadiusYKm ?? f.RadiusKm;
for (int y = 0; y < t.Height; y++)
{
for (int x = 0; x < t.Width; x++)
{
double xKm = (x + 0.5) * cs / 1000, yKm = (y + 0.5) * cs / 1000;
double e = Sq((xKm - f.X) / rx) + Sq((yKm - f.Y) / ry);
if (e > 1) continue;
if (t.Types[t.Index(x, y)] is (byte)CellType.Water or (byte)CellType.Sea) continue;
t.Types[t.Index(x, y)] = (byte)type;
if (type == CellType.Marsh) heights[t.Index(x, y)] -= 1;
if (type == CellType.Water) heights[t.Index(x, y)] -= f.DepthM;
}
}
break;
}
case "sea":
{
int band = (int)Math.Round(f.WidthKm * 1000 / cs);
for (int y = 0; y < t.Height; y++)
{
for (int x = 0; x < t.Width; x++)
{
bool sea = (f.Side ?? "east") switch
{
"north" => y < band,
"south" => y >= t.Height - band,
"west" => x < band,
_ => x >= t.Width - band,
};
if (!sea) continue;
t.Types[t.Index(x, y)] = (byte)CellType.Sea;
heights[t.Index(x, y)] = 0;
}
}
break;
}
}
}
// fiumi: superficie che scende verso valle lungo la polilinea, alveo largo «widthClass» celle;
// la superficie si calcola sul terreno originale, non su quello già scavato
var original = (double[])heights.Clone();
foreach (var f in spec.Features.Where(f => f.Kind == "river" && f.Points is { Count: >= 2 }))
{
var pts = f.Points!.Select(p => new Vec2(p[0] * 1000, p[1] * 1000)).ToList();
double surface = double.PositiveInfinity;
double step = cs / 4;
for (int k = 0; k < pts.Count - 1; k++)
{
double len = Vec2.Distance(pts[k], pts[k + 1]);
for (double s = 0; s <= len; s += step)
{
var p = Vec2.Lerp(pts[k], pts[k + 1], s / len);
var (cx, cy) = t.CellAt(p);
surface = Math.Min(surface, original[t.Index(cx, cy)] - f.DepthM);
int w = Math.Clamp(f.WidthClass, 1, 4);
int off = (w - 1) / 2;
for (int dy = 0; dy < w; dy++)
{
for (int dx = 0; dx < w; dx++)
{
int x = cx + dx - off, y = cy + dy - off;
if (!t.InBounds(x, y)) continue;
int i = t.Index(x, y);
if (t.Types[i] == (byte)CellType.Sea) continue;
t.Types[i] = (byte)CellType.Water;
t.RiverWidth[i] = (byte)w;
heights[i] = Math.Min(heights[i], Math.Max(0.5, surface));
}
}
}
}
}
for (int i = 0; i < heights.Length; i++) t.Heights[i] = Terrain.ToDecimeters(Math.Max(0, heights[i]));
return t;
}
private static void MarkDisc(Terrain t, int cx, int cy, double radius, CellType type)
{
int r = (int)Math.Ceiling(radius);
for (int y = cy - r; y <= cy + r; y++)
{
for (int x = cx - r; x <= cx + r; x++)
{
if (!t.InBounds(x, y) || Sq(x - cx) + Sq(y - cy) > radius * radius || t.IsWater(x, y)) continue;
t.SetType(x, y, type);
}
}
}
private static double Sq(double v) => v * v;
}
@@ -7,7 +7,7 @@ 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.
/// Vendite e acquisti avvengono al prezzo globale; le merci passano solo da un magazzino all'altro.
/// </summary>
public sealed class LocalTransportSystem : ISimSystem
{
@@ -36,7 +36,6 @@ public sealed class LocalTransportSystem : ISimSystem
}
}
var lp = w.Data.Balance.LocalPrice;
int dpm = w.Calendar.DaysPerMonth;
foreach (var producer in w.Industries)
{
@@ -47,7 +46,8 @@ public sealed class LocalTransportSystem : ISimSystem
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);
// le industrie comprano e vendono al prezzo globale (ADR 0004)
double sellPrice = w.Market.GlobalPrice[good];
foreach (var (ci, _) in _nearIndustries[producer.Id.Value])
{
@@ -58,7 +58,7 @@ public sealed class LocalTransportSystem : ISimSystem
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);
double buyPrice = w.Market.GlobalPrice[good];
producer.OutputStock[o] -= units;
consumer.InputStock[i] += units;
available -= units;
@@ -69,7 +69,7 @@ public sealed class TownSystem : ISimSystem
private static void Grow(WorldContext ctx, Town town)
{
var tb = ctx.Data.Balance.Town;
int services = 0;
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++;