diff --git a/Eu07.BlackBox.Views/MapView.cs b/Eu07.BlackBox.Views/MapView.cs index d1d0f23..39f687b 100644 --- a/Eu07.BlackBox.Views/MapView.cs +++ b/Eu07.BlackBox.Views/MapView.cs @@ -25,8 +25,12 @@ public sealed class MapView : Control private Recording? _recording; private int _builtRevision = -1; private int _builtTracks = -1; - private StreamGeometry? _tracks; - private readonly List<(int Index, int Branch, StreamGeometry Way)> _switchWays = new(); + private TrackLayer? _tracks; + private readonly List<(int Index, int Branch, IReadOnlyList Points)> _switchWays = new(); + // The switches as they lay when last drawn, and their ways in two geometries: not taken, taken. + private int[] _switchStates = Array.Empty(); + private StreamGeometry? _waysOff, _waysOn; + private string? _hoverShown; private readonly StreamGeometry?[] _trail = new StreamGeometry?[5]; private Rect _world; @@ -135,33 +139,24 @@ public sealed class MapView : Control { _builtTracks = recording.Tracks.Count; _switchWays.Clear(); - var tracks = new StreamGeometry(); double left = double.MaxValue, top = double.MaxValue, right = double.MinValue, bottom = double.MinValue; - using (var g = tracks.Open()) + foreach (var track in recording.Tracks) { - foreach (var track in recording.Tracks) + if (track.Points.Count < 2) + continue; + foreach (var p in track.Points) { - if (track.Points.Count < 2) - continue; - foreach (var p in track.Points) - { - left = Math.Min(left, -p.X); - right = Math.Max(right, -p.X); - top = Math.Min(top, -p.Z); - bottom = Math.Max(bottom, -p.Z); - } - if (track.Kind == TrackKind.SwitchBranch) - { - var way = new StreamGeometry(); - using (var w = way.Open()) - Polyline(w, track.Points); - _switchWays.Add((track.Index, track.Branch, way)); - } - else - Polyline(g, track.Points); + left = Math.Min(left, -p.X); + right = Math.Max(right, -p.X); + top = Math.Min(top, -p.Z); + bottom = Math.Max(bottom, -p.Z); } + if (track.Kind == TrackKind.SwitchBranch) + _switchWays.Add((track.Index, track.Branch, track.Points)); } - _tracks = tracks; + _tracks = new TrackLayer(recording.Tracks); + _switchStates = Array.Empty(); + _waysOff = _waysOn = null; _world = left <= right ? new Rect(new Point(left, top), new Point(right, bottom)) : default; } BuildTrail(recording); @@ -247,29 +242,26 @@ public sealed class MapView : Control double pixel = 1 / _scale; using (context.PushTransform(toScreen)) { - // The tracks on a dark casing, so they stand out where they cross and run close. + // The tracks on a dark casing, so they stand out where they cross and run close. Only the + // cells in view, at the detail a pixel can show. var casing = new Pen(Palette.TrackCasing, 5 * pixel, lineCap: PenLineCap.Round); - if (_tracks is not null) - context.DrawGeometry(null, casing, _tracks); - foreach (var (_, _, way) in _switchWays) - context.DrawGeometry(null, casing, way); - if (_tracks is not null) - context.DrawGeometry(null, new Pen(Palette.Track, 1.7 * pixel, lineCap: PenLineCap.Round), _tracks); - var off = new Pen(Palette.SwitchOff, 1.7 * pixel, lineCap: PenLineCap.Round); - var on = new Pen(Palette.Track, 1.7 * pixel, lineCap: PenLineCap.Round); - // The ways not taken under those taken. - foreach (var (index, branch, way) in _switchWays) + var fill = new Pen(Palette.Track, 1.7 * pixel, lineCap: PenLineCap.Round); + if (_tracks is { } layer) { - int state = recording.SwitchAt(index, _time); - if (state >= 0 && state != branch) - context.DrawGeometry(null, off, way); - } - foreach (var (index, branch, way) in _switchWays) - { - int state = recording.SwitchAt(index, _time); - if (state < 0 || state == branch) - context.DrawGeometry(null, on, way); + var view = PlaneInView(size, 6 * pixel); + int level = TrackLayer.LevelFor(_scale); + foreach (var cell in layer.CellsIn(view, level)) + context.DrawGeometry(null, casing, cell.Casing); + foreach (var cell in layer.CellsIn(view, level)) + if (cell.Fill is { } tracks) + context.DrawGeometry(null, fill, tracks); } + // The ways not taken under those taken, each set one geometry, made again only when a switch moves. + UpdateSwitchWays(recording); + if (_waysOff is not null) + context.DrawGeometry(null, new Pen(Palette.SwitchOff, 1.7 * pixel, lineCap: PenLineCap.Round), _waysOff); + if (_waysOn is not null) + context.DrawGeometry(null, fill, _waysOn); // The way the train went, in the colour of the judgement. for (int kind = 0; kind < _trail.Length; kind++) if (_trail[kind] is { } trail) @@ -280,12 +272,67 @@ public sealed class MapView : Control DrawHornPoints(context, recording); DrawSignals(context, recording); DrawPassings(context, recording); - DrawVehicles(context, recording); + // Once a frame: the vehicles and the hover both go by them. + var vehicles = recording.VehiclesAt(_time); + DrawVehicles(context, recording, vehicles); DrawUserTrain(context, recording); DrawCamera(context, recording); DrawScale(context, size); DrawLegend(context, size); - DrawHover(context, recording); + DrawHover(context, recording, vehicles); + } + + /// The part of the map's plane on screen, with a margin in plane units. + private Rect PlaneInView(Size size, double margin) + { + double halfWidth = size.Width / 2 / _scale, halfHeight = size.Height / 2 / _scale; + return new Rect(-_centerX - halfWidth - margin, -_centerZ - halfHeight - margin, + 2 * (halfWidth + margin), 2 * (halfHeight + margin)); + } + + private void UpdateSwitchWays(Recording recording) + { + bool changed = _switchStates.Length != _switchWays.Count; + if (changed) + _switchStates = new int[_switchWays.Count]; + for (int i = 0; i < _switchWays.Count; i++) + { + int state = recording.SwitchAt(_switchWays[i].Index, _time); + if (state != _switchStates[i] || changed) + { + _switchStates[i] = state; + changed = true; + } + } + if (!changed && (_waysOff is not null || _waysOn is not null || _switchWays.Count == 0)) + return; + + var off = new StreamGeometry(); + var on = new StreamGeometry(); + bool anyOff = false, anyOn = false; + using (var gOff = off.Open()) + using (var gOn = on.Open()) + { + for (int i = 0; i < _switchWays.Count; i++) + { + var (_, branch, points) = _switchWays[i]; + if (points.Count < 2) + continue; + int state = _switchStates[i]; + if (state >= 0 && state != branch) + { + Polyline(gOff, points); + anyOff = true; + } + else + { + Polyline(gOn, points); + anyOn = true; + } + } + } + _waysOff = anyOff ? off : null; + _waysOn = anyOn ? on : null; } private bool Visible(Point p, double margin = 20) => @@ -468,10 +515,10 @@ public sealed class MapView : Control } } - private void DrawVehicles(DrawingContext context, Recording recording) + private void DrawVehicles(DrawingContext context, Recording recording, IReadOnlyList vehicles) { int user = recording.CabAt(_time) is { } sample && _time - sample.Time < 1.5 ? sample.Vehicle : 0; - foreach (var state in recording.VehiclesAt(_time)) + foreach (var state in vehicles) { var info = recording.Vehicle(state.Id); var brush = state.Id == user ? Palette.UserTrain : state.Driving == Driver.Ai ? Palette.VehicleAi : Palette.Vehicle; @@ -602,10 +649,19 @@ public sealed class MapView : Control } /// The name of the signal or the vehicle under the pointer. - private void DrawHover(DrawingContext context, Recording recording) + private void DrawHover(DrawingContext context, Recording recording, IReadOnlyList vehicles) { - if (_pointer is not { } pointer || _dragFrom is not null) + _hoverShown = _pointer is { } at && _dragFrom is null ? HoverLabel(recording, at, vehicles) : null; + if (_hoverShown is not { } label || _pointer is not { } pointer) return; + var text = Text(label, Palette.Text, 12); + var box = new Rect(pointer.X + 14, pointer.Y - 12 - text.Height, text.Width + 16, text.Height + 8); + context.DrawRectangle(Palette.Faded(Palette.Card, 0.95), new Pen(Palette.CardBorder, 1), box, 6, 6); + context.DrawText(text, new Point(box.Left + 8, box.Top + 4)); + } + + private string? HoverLabel(Recording recording, Point pointer, IReadOnlyList vehicles) + { string? label = null; double best = 10; foreach (var signal in recording.Signals) @@ -646,7 +702,7 @@ public sealed class MapView : Control label = string.Format(culture, Strings["HornHover"], point.Name, point.Duration); } } - foreach (var state in recording.VehiclesAt(_time)) + foreach (var state in vehicles) { double d = Distance(ToScreen(state.Position.X, state.Position.Z), pointer); if (d < best && recording.Vehicle(state.Id) is { } info) @@ -657,12 +713,7 @@ public sealed class MapView : Control : $"{info.Name} ({info.Train}) ยท {Math.Abs(state.SpeedKmh):0} km/h"; } } - if (label is null) - return; - var text = Text(label, Palette.Text, 12); - var box = new Rect(pointer.X + 14, pointer.Y - 12 - text.Height, text.Width + 16, text.Height + 8); - context.DrawRectangle(Palette.Faded(Palette.Card, 0.95), new Pen(Palette.CardBorder, 1), box, 6, 6); - context.DrawText(text, new Point(box.Left + 8, box.Top + 4)); + return label; } /// An aspect as the speeds it gives: stop, a speed, or go. @@ -724,8 +775,13 @@ public sealed class MapView : Control _centerX = _dragCenter.X + moved.X / _scale; _centerZ = _dragCenter.Z + moved.Y / _scale; } + InvalidateVisual(); + return; } - InvalidateVisual(); + // Not dragged, the map is the same: drawn again only for a label to show, follow the pointer or go. + if (_hoverShown is not null || + (_recording is { } recording && HoverLabel(recording, position, recording.VehiclesAt(_time)) is not null)) + InvalidateVisual(); } protected override void OnPointerReleased(PointerReleasedEventArgs e) diff --git a/Eu07.BlackBox.Views/TrackLayer.cs b/Eu07.BlackBox.Views/TrackLayer.cs new file mode 100644 index 0000000..abcfde5 --- /dev/null +++ b/Eu07.BlackBox.Views/TrackLayer.cs @@ -0,0 +1,184 @@ +using System; +using System.Collections.Generic; +using System.Numerics; +using Avalonia; +using Avalonia.Media; + +namespace Eu07.BlackBox.Views; + +/// +/// The rails of a scenery made ready to draw fast: cut into square cells so that only those in +/// view are drawn, and kept at a few levels of detail so that from afar a track is drawn with +/// fewer points than there are pixels it covers. The casing takes the switches' ways too, which +/// it is drawn under in one colour; the fill is the plain tracks alone. +/// +public sealed class TrackLayer +{ + /// The side of a cell in metres. + public const double CellSize = 500; + + /// The points of a track closer than this to the last kept are left out, by level. + public static readonly double[] Tolerances = { 0, 2, 8, 32, 128 }; + + /// A part of the map: what is drawn of it, and where it lies in the map's plane. + public sealed record Cell(Rect Bounds, StreamGeometry Casing, StreamGeometry? Fill); + + private readonly List[] _levels; + + public TrackLayer(IReadOnlyList tracks) + { + _levels = new List[Tolerances.Length]; + for (int level = 0; level < Tolerances.Length; level++) + _levels[level] = BuildLevel(tracks, Tolerances[level]); + } + + /// The level whose left-out points stay within on screen at this scale. + public static int LevelFor(double scale, double pixels = 0.75) + { + int level = 0; + for (int i = 1; i < Tolerances.Length; i++) + if (Tolerances[i] * scale <= pixels) + level = i; + return level; + } + + /// The cells of the level that reach into , a rectangle of the map's plane. + public IEnumerable CellsIn(Rect view, int level) + { + foreach (var cell in _levels[Math.Clamp(level, 0, _levels.Length - 1)]) + if (cell.Bounds.Intersects(view)) + yield return cell; + } + + public int CellCount(int level) => _levels[level].Count; + + /// The points of a track with those nearer than to the last kept left out; its ends stay. + public static List Simplified(IReadOnlyList points, double tolerance) + { + var kept = new List(points.Count); + if (points.Count == 0) + return kept; + kept.Add(points[0]); + double square = tolerance * tolerance; + for (int i = 1; i < points.Count - 1; i++) + { + var last = kept[^1]; + double dx = points[i].X - last.X, dz = points[i].Z - last.Z; + if (dx * dx + dz * dz >= square) + kept.Add(points[i]); + } + if (points.Count > 1) + kept.Add(points[^1]); + return kept; + } + + private sealed class Builder + { + public readonly List> Casing = new(); + public readonly List> Fill = new(); + public double Left = double.MaxValue, Top = double.MaxValue, Right = double.MinValue, Bottom = double.MinValue; + + public void Grow(Point p) + { + Left = Math.Min(Left, p.X); + Right = Math.Max(Right, p.X); + Top = Math.Min(Top, p.Y); + Bottom = Math.Max(Bottom, p.Y); + } + } + + private static List BuildLevel(IReadOnlyList tracks, double tolerance) + { + var cells = new Dictionary<(long, long), Builder>(); + foreach (var track in tracks) + { + if (track.Points.Count < 2) + continue; + bool fill = track.Kind != TrackKind.SwitchBranch; + var points = tolerance > 0 ? Simplified(track.Points, tolerance) : (IReadOnlyList)track.Points; + + // A run of the track's points in one cell; a segment over a border goes with the cell it ends in, + // which starts from the point before, so its bounds cover the whole segment. + List? casingRun = null, fillRun = null; + (long, long) current = default; + for (int i = 0; i < points.Count; i++) + { + var p = Plane(points[i]); + var key = ((long)Math.Floor(p.X / CellSize), (long)Math.Floor(p.Y / CellSize)); + if (casingRun is null || key != current) + { + var builder = Of(cells, key); + var start = casingRun is null ? (Point?)null : casingRun[^1]; + casingRun = new List(); + builder.Casing.Add(casingRun); + fillRun = null; + if (fill) + { + fillRun = new List(); + builder.Fill.Add(fillRun); + } + if (start is { } joined) + { + // The segment from the last cell starts there, so the line has no gap at the border. + casingRun.Add(joined); + fillRun?.Add(joined); + builder.Grow(joined); + } + current = key; + } + casingRun.Add(p); + fillRun?.Add(p); + Of(cells, key).Grow(p); + } + } + + var result = new List(cells.Count); + foreach (var builder in cells.Values) + { + var casing = Geometry(builder.Casing); + if (casing is null) + continue; + var bounds = new Rect(new Point(builder.Left, builder.Top), new Point(builder.Right, builder.Bottom)); + result.Add(new Cell(bounds, casing, Geometry(builder.Fill))); + } + return result; + } + + private static Builder Of(Dictionary<(long, long), Builder> cells, (long, long) key) + { + if (!cells.TryGetValue(key, out var builder)) + cells[key] = builder = new Builder(); + return builder; + } + + private static StreamGeometry? Geometry(List> runs) + { + StreamGeometry? geometry = null; + StreamGeometryContext? g = null; + try + { + foreach (var run in runs) + { + if (run.Count < 2) + continue; + if (geometry is null) + { + geometry = new StreamGeometry(); + g = geometry.Open(); + } + g!.BeginFigure(run[0], false); + for (int i = 1; i < run.Count; i++) + g.LineTo(run[i]); + g.EndFigure(false); + } + } + finally + { + g?.Dispose(); + } + return geometry; + } + + // As MapView draws the plane: x to the left, z up the screen. + private static Point Plane(Vector3 p) => new(-p.X, -p.Z); +} diff --git a/StarterNG.Tests/BlackBox/TrackLayerTests.cs b/StarterNG.Tests/BlackBox/TrackLayerTests.cs new file mode 100644 index 0000000..81d276a --- /dev/null +++ b/StarterNG.Tests/BlackBox/TrackLayerTests.cs @@ -0,0 +1,79 @@ +using System.Numerics; +using Avalonia; +using Eu07.BlackBox; +using Eu07.BlackBox.Views; + +namespace StarterNG.Tests.BlackBox; + +/// The rails of the black box map made ready to draw only what is in view, at the detail a pixel shows. +[Collection(AvaloniaControls.Name)] +public class TrackLayerTests +{ + public TrackLayerTests() => HeadlessDrawing.Ensure(); + + private static MapTrack Track(int index, TrackKind kind, params (float X, float Z)[] points) => + new(index, $"t{index}", kind, kind == TrackKind.SwitchBranch ? 0 : -1, 0, + points.Select(p => new Vector3(p.X, 0, p.Z)).ToList()); + + [Theory] + [InlineData(2.0, 0)] // close up: every point + [InlineData(0.3, 1)] // 2 m are 0.6 px, 8 m would be 2.4 + [InlineData(0.05, 2)] // 8 m are 0.4 px, 32 m would be 1.6 + [InlineData(0.002, 4)] // the whole of a big scenery: 128 m are 0.26 px + public void The_level_leaves_out_no_more_than_a_pixel_shows(double scale, int level) + { + Assert.Equal(level, TrackLayer.LevelFor(scale)); + } + + [Fact] + public void Only_the_cells_in_view_are_drawn() + { + var layer = new TrackLayer(new[] + { + Track(1, TrackKind.Normal, (0, 0), (100, 0)), + Track(2, TrackKind.Normal, (-5000, -5000), (-5100, -5000)) + }); + + // The plane shows x to the left: the first track lies at -100..0, the second at 5000..5100. + var near = layer.CellsIn(new Rect(-200, -50, 300, 100), 0).ToList(); + + Assert.Single(near); + Assert.Equal(2, layer.CellCount(0)); + } + + [Fact] + public void A_track_across_cells_is_drawn_without_a_gap_at_the_border() + { + var layer = new TrackLayer(new[] { Track(1, TrackKind.Normal, (-400, 0), (-600, 0), (-800, 0)) }); + + var cells = layer.CellsIn(new Rect(-10000, -10000, 20000, 20000), 0).ToList(); + + // The segment over the border goes with the cell it ends in, from the point the line left the last one: + // that cell reaches back to it, so it is drawn whenever any of the segment is in view. + var cell = Assert.Single(cells); + Assert.Equal(400, cell.Bounds.Left); + Assert.Equal(800, cell.Bounds.Right); + Assert.Single(layer.CellsIn(new Rect(450, -10, 20, 20), 0)); + } + + [Fact] + public void A_switch_way_is_in_the_casing_but_not_in_the_plain_fill() + { + var layer = new TrackLayer(new[] { Track(7, TrackKind.SwitchBranch, (0, 0), (30, 5)) }); + + var cell = Assert.Single(layer.CellsIn(new Rect(-100, -100, 200, 200), 0)); + + Assert.NotNull(cell.Casing); + Assert.Null(cell.Fill); + } + + [Fact] + public void Simplifying_keeps_the_ends_and_drops_points_closer_than_the_tolerance() + { + var points = new[] { new Vector3(0, 0, 0), new Vector3(1, 0, 0), new Vector3(2, 0, 0), new Vector3(10, 0, 0), new Vector3(11, 0, 0) }; + + var kept = TrackLayer.Simplified(points, 5); + + Assert.Equal(new[] { 0f, 10f, 11f }, kept.Select(p => p.X)); + } +}