using Godot; using RailEnterprise.Client.App; using RailEnterprise.Client.Net; using RailEnterprise.Core.Data; using RailEnterprise.Core.Rail; using RailEnterprise.Protocol.Client; using RailEnterprise.Protocol.Messages; namespace RailEnterprise.Client.Map; /// /// Treni dall'alto (immagine 03): locomotiva scura con dettagli ambra, carri e carrozze con le /// proporzioni della guida (larghezza 9, carro 16, carrozza 20, locomotiva 20–26), posizione /// interpolata avanzando la testa alla velocità ricevuta; fumo per le vaporiere; sfumatura e /// icona d'avviso sotto condizione 40. /// public partial class TrainLayer : Node2D { private GameSession? _session; private float _zoom = 1; private readonly List _smoke = []; private Dictionary _defs = []; public int SelectedTrain { get; set; } = -1; /// Mappa di calore della condizione (10.3): un alone colorato sotto ogni treno. public bool HeatMap { get; set; } /// Teste dei treni disegnate nell'ultimo fotogramma (per la selezione col mouse). public Dictionary Heads { get; } = []; public void Bind(GameSession session) { _session = session; _defs = session.World.Data.Vehicles.ToDictionary(v => v.Id); } public void SetZoom(float zoom) => _zoom = zoom; public override void _Process(double delta) => QueueRedraw(); /// Secondi di orologio dei treni trascorsi dall'arrivo del moto (fattore 60 per la velocità). private double Elapsed(int trainId, ClientWorld w) { if (_session is null || !_session.MotionReceivedMs.TryGetValue(trainId, out long at)) return 0; double realSeconds = Math.Max(0, ((long)Time.GetTicksMsec() - at) / 1000.0); double perTick = w.Calendar?.TrainSecondsPerTick ?? 3; double ticksPerSecond = 1000.0 / (w.Calendar?.TickMs ?? 50); // senza interpolare oltre mezzo secondo: il moto successivo arriva ogni 100 ms return Math.Min(realSeconds, 0.5) * ticksPerSecond * perTick * w.Speed; } public override void _Draw() { Heads.Clear(); var w = _session?.World; if (w is null) return; float s = MapScale.Symbol(_zoom); var view = VisibleWorldRect().Grow(400 * s); int smokeUsed = 0; foreach (var (id, motion) in w.Motions) { if (!w.Trains.TryGetValue(id, out var train) || train.State == (byte)TrainState.InDepot) continue; double total = ClientWorld.TotalLength(motion); double head = Math.Min(motion.HeadDistance + motion.Speed * Elapsed(id, w), total); var headPoint = w.PointAlong(motion, head); if (headPoint is null || !view.HasPoint(MapScale.V(headPoint.Value))) continue; Heads[id] = MapScale.V(headPoint.Value); double d = head; bool first = true; foreach (int vid in train.Vehicles) { if (!w.Vehicles.TryGetValue(vid, out var v) || !_defs.TryGetValue(v.Type, out var def)) continue; float length = DrawLength(def) * s; var front = w.PointAlong(motion, Math.Max(0, d)); var back = w.PointAlong(motion, Math.Max(0, d - length)); if (front is null || back is null) break; var f = MapScale.V(front.Value); var b = MapScale.V(back.Value); if (f.DistanceTo(b) < length * 0.9f) { // la coda esce dai tratti noti: si prolunga all'indietro lungo la direzione del binario var ahead = w.PointAlong(motion, Math.Min(total, Math.Max(0, d) + 5)); var dir = ahead is { } ap && MapScale.V(ap).DistanceTo(f) > 0.01f ? (MapScale.V(ap) - f).Normalized() : (f - b).LengthSquared() > 0.0001f ? (f - b).Normalized() : Vector2.Right; if (ahead is { } ap2 && MapScale.V(ap2).DistanceTo(f) <= 0.01f && (f - b).LengthSquared() > 0.0001f) dir = (f - b).Normalized(); b = f - dir * length; } DrawVehicle(def, v, f, b, s, id == SelectedTrain); if (first && def.Kind == VehicleKind.Locomotive && def.Traction == Traction.Steam && motion.Speed > 0.5f && smokeUsed < 24) PlaceSmoke(smokeUsed++, f.Lerp(b, 0.25f), s); first = false; d -= length + 1.5f * s; if (d < 0) break; } if (HeatMap) { var hp = MapScale.V(headPoint.Value); var col = Panels.MaintenancePanel.ConditionColor((int)motion.Condition); DrawCircle(hp, 14 * s, Palette.WithAlpha(col, 0.35f)); DrawArc(hp, 14 * s, 0, MathF.Tau, 32, col, 2 * s); } if (motion.Condition < 40) { // icona d'avviso: triangolo ambra sopra la testa var p = MapScale.V(headPoint.Value) + new Vector2(0, -16 * s); DrawColoredPolygon([p + new Vector2(0, -6 * s), p + new Vector2(6 * s, 5 * s), p + new Vector2(-6 * s, 5 * s)], Palette.Amber); DrawLine(p + new Vector2(0, -2.5f * s), p + new Vector2(0, 1.5f * s), Palette.AppBackground, 1.4f * s); } } for (int i = smokeUsed; i < _smoke.Count; i++) _smoke[i].Emitting = false; } private static float DrawLength(VehicleDef def) => def.Kind switch { VehicleKind.Locomotive => (float)Math.Clamp(def.LengthM * 1.25, 20, 26), VehicleKind.Coach => 20f, _ => 16f, }; private void DrawVehicle(VehicleDef def, VehicleInfo v, Vector2 front, Vector2 back, float s, bool selected) { var center = (front + back) / 2; var dir = front - back; float length = dir.Length(); DrawSetTransform(center, dir.Angle()); float width = 9f * s; var rect = new Rect2(-length / 2, -width / 2, length, width); Color body = def.Kind switch { VehicleKind.Locomotive => new Color("1d2226"), VehicleKind.Coach => def.Class == PaxClass.Staff ? Palette.Staff : Palette.Workers, _ => def.WagonType switch { WagonType.Hopper => new Color("6b4a3a"), WagonType.Flat => new Color("8a8f94"), WagonType.Tank => new Color("4b5258"), _ => new Color("8a5a44"), }, }; if (v.Condition < 40) body = body.Lerp(Palette.Danger, 0.45f); DrawRect(new Rect2(rect.Position + new Vector2(1.2f, 1.2f) * s, rect.Size), new Color(0, 0, 0, 0.25f)); DrawRect(rect, body); DrawRect(rect, selected ? Palette.Amber : body.Darkened(0.35f), false, (selected ? 1.1f : 0.6f) * s); switch (def.Kind) { case VehicleKind.Locomotive: // cabina ambra verso la coda, caldaia e fanale verso la testa DrawRect(new Rect2(-length / 2 + 1.5f * s, -width / 2 + 1.2f * s, 4.5f * s, width - 2.4f * s), Palette.Amber); DrawCircle(new Vector2(length / 2 - 3.5f * s, 0), 1.8f * s, Palette.AmberLight); DrawLine(new Vector2(-length / 2 + 7 * s, 0), new Vector2(length / 2 - 6 * s, 0), body.Lightened(0.15f), 1f * s); break; case VehicleKind.Coach: for (float x = -length / 2 + 3 * s; x < length / 2 - 2 * s; x += 3.2f * s) DrawRect(new Rect2(x, -width / 2 + 1.2f * s, 1.8f * s, 1.4f * s), Colors.White.Lerp(body, 0.4f)); break; default: if (def.WagonType == WagonType.Hopper) DrawRect(new Rect2(-length / 2 + 2 * s, -width / 2 + 1.5f * s, length - 4 * s, width - 3 * s), body.Darkened(0.3f)); else if (def.WagonType == WagonType.Tank) DrawCircle(Vector2.Zero, width * 0.35f, body.Lightened(0.15f)); break; } DrawSetTransform(Vector2.Zero, 0); } private void PlaceSmoke(int index, Vector2 at, float s) { while (_smoke.Count <= index) { var gradient = new Gradient(); gradient.SetColor(0, new Color(0.92f, 0.92f, 0.9f, 0.55f)); gradient.SetColor(1, new Color(0.92f, 0.92f, 0.9f, 0f)); var material = new ParticleProcessMaterial { Direction = new Vector3(1, -1, 0), Spread = 25, InitialVelocityMin = 6, InitialVelocityMax = 12, Gravity = new Vector3(4, -2, 0), ScaleMin = 0.8f, ScaleMax = 1.6f, ColorRamp = new GradientTexture1D { Gradient = gradient }, }; var p = new GpuParticles2D { Amount = 16, Lifetime = 1.6, ProcessMaterial = material, Texture = SmokePuff(), ZIndex = 6, LocalCoords = false }; AddChild(p); _smoke.Add(p); } var smoke = _smoke[index]; smoke.Position = at; smoke.Scale = new Vector2(s, s) * 0.25f; smoke.Emitting = true; } private static Texture2D? _puff; private static Texture2D SmokePuff() { if (_puff is not null) return _puff; const int n = 32; var img = Image.CreateEmpty(n, n, false, Image.Format.Rgba8); for (int y = 0; y < n; y++) { for (int x = 0; x < n; x++) { float dx = (x + 0.5f) / n * 2 - 1, dy = (y + 0.5f) / n * 2 - 1; float a = Math.Clamp(1 - MathF.Sqrt(dx * dx + dy * dy), 0, 1); img.SetPixel(x, y, new Color(1, 1, 1, a * a)); } } return _puff = ImageTexture.CreateFromImage(img); } private Rect2 VisibleWorldRect() { var canvas = GetCanvasTransform().AffineInverse(); var size = GetViewportRect().Size; var a = canvas * Vector2.Zero; var b = canvas * size; return new Rect2(a, b - a).Abs(); } }