using System; using System.Collections.Generic; using UnityEngine; using UnityEngine.UIElements; namespace GrassCutter { /// /// M: the map of Herbaria-7. It opens close in on you, a few hundred metres across, where every sector is its own /// hexagon; the wheel zooms out to the whole ball and back, dragging turns it, SPACE (or ME) brings you back to the /// middle. Untouched sectors are the meadow, begun ones gold, finished ones the pale straw of mown ground. /// /// The sectors go to the screen as one plain triangle mesh, not as painted paths: a few thousand hexagons cost next to /// nothing that way, where tessellating them as shapes every repaint made the old globe stutter once much was mown. /// public class MapScreen { /// Closest in: the view this many metres across. const float NearestMetres = 90f; /// Where it opens: this many metres across. const float OpenMetres = 650f; /// Hexagons from this many pixels across; smaller and each worked sector is a speck. const float HexPixels = 7f; const int MaxHexes = 9000; public VisualElement Card { get; } readonly VisualElement _chart, _ball, _ground, _marks, _scaleBar; readonly Label _stats, _scaleText; Quaternion _view; float _zoom = -1f; bool _dragging, _follow = true; Vector2 _last; static readonly Color Meadow = new Color(0.27f, 0.47f, 0.17f); static readonly Color Grid = new Color(0.19f, 0.34f, 0.12f); static readonly Color Space = new Color(0.09f, 0.11f, 0.13f); static readonly Color Lines = new Color(1f, 1f, 1f, 0.1f); static readonly Color Rim = new Color(0.72f, 0.86f, 0.5f, 0.8f); static readonly Color Begun = new Color(0.93f, 0.71f, 0.22f); static readonly Color Done = new Color(0.9f, 0.84f, 0.56f); static readonly Color Base = new Color(0.78f, 0.28f, 0.18f); static readonly Color Stake = new Color(1f, 0.45f, 0.35f); static readonly Color Robot = new Color(0.55f, 0.8f, 1f); static readonly Color Station = new Color(1f, 0.85f, 0.3f); static readonly Color Unload = new Color(0.98f, 0.55f, 0.2f); static readonly Dictionary s_corners = new Dictionary(); readonly HashSet _seen = new HashSet(); readonly Queue _queue = new Queue(); readonly Dictionary _masks = new Dictionary(); readonly List _verts = new List(); readonly List _tris = new List(); public MapScreen(VisualElement layer, Action close, float zoom = 1f) { Card = UIK.El("card rig-map", layer); var header = UIK.El("card-header", Card); UIK.Text("HERBARIA-7", "t-h1 t-dark", header); _stats = UIK.Text("", "t-body t-dark", header, false); var tools = UIK.El("map-tools", header); UIK.Btn(Loc.T("ME"), () => { _follow = true; Centre(); }, "btn btn-small", tools); UIK.Btn("+", () => ZoomBy(1.6f), "btn btn-small", tools); UIK.Btn("−", () => ZoomBy(1f / 1.6f), "btn btn-small", tools); UIK.Btn(Loc.T("GLOBE"), () => { _zoom = 1f; Repaint(); }, "btn btn-small", tools); UIK.Btn("X", close, "btn btn-red btn-small", header); _chart = UIK.El("map-chart", Card); _chart.pickingMode = PickingMode.Position; _chart.style.overflow = Overflow.Hidden; _chart.focusable = true; // space is the chart's own colour; over it three layers, each its own element so the order is plain: the // ball, the sectors on it, the marks. _chart.style.backgroundColor = Space; _ball = Layer(DrawBall); _ground = Layer(DrawGround); _marks = Layer(DrawMarks); _chart.RegisterCallback(e => ZoomBy(e.delta.y > 0 ? 0.8f : 1.25f)); _chart.RegisterCallback(e => { _dragging = true; _follow = false; _last = e.position; _chart.CapturePointer(e.pointerId); }); _chart.RegisterCallback(e => { _dragging = false; _chart.ReleasePointer(e.pointerId); }); _chart.RegisterCallback(e => { if (!_dragging) return; var d = (Vector2)e.position - _last; _last = e.position; float k = 57.3f / (Radius * Zoom); _view = Quaternion.Euler(d.y * k, d.x * k, 0f) * _view; Repaint(); }); _chart.schedule.Execute(() => { var kb = UnityEngine.InputSystem.Keyboard.current; if (kb != null && kb.spaceKey.wasPressedThisFrame) { _follow = true; Centre(); } }).Every(0); // the scale: a bar and what it measures, bottom left over the chart var scale = UIK.El("map-scale", _chart); _scaleBar = UIK.El("map-scale-bar", scale); _scaleText = UIK.Text("", "t-small map-scale-text", scale, false); var legend = UIK.El("map-legend", Card); Key(legend, Meadow, Loc.T("Untouched")); Key(legend, Begun, Loc.T("Started")); Key(legend, Done, Loc.T("Mown")); Key(legend, Base, Loc.T("Base")); Key(legend, Unload, Loc.T("Unload")); Key(legend, Stake, Loc.T("Stake or point done")); Key(legend, Robot, Loc.T("Robot")); Key(legend, Station, Loc.T("Station")); UIK.Text(Loc.T("DRAG move · WHEEL zoom · SPACE back to you · M close"), "t-small t-muted", legend, false); // asked to open at a zoom of its own (1 is "close in on you", the usual) if (zoom != 1f) _zoom = Mathf.Max(1f, zoom); Centre(); Refresh(); _chart.schedule.Execute(Refresh).Every(500); } /// The planet's radius on screen, against the chart's size, at this zoom. float Zoom { get { // the first time it knows its size: open a few hundred metres across if (_zoom < 0f && Area.width > 4f) _zoom = Mathf.Clamp(PxPerMetre(OpenMetres) * Planet.Radius / Radius, 1f, MaxZoom); return _zoom < 0f ? 1f : _zoom; } } float MaxZoom => Mathf.Max(1f, PxPerMetre(NearestMetres) * Planet.Radius / Radius); float PxPerMetre(float across) => Mathf.Max(100f, Area.width) / across; void ZoomBy(float k) { _zoom = Mathf.Clamp(Zoom * k, 1f, MaxZoom); Repaint(); } /// You in the middle, north up. void Centre() { var me = PlayerAgent.Local; var up = me ? Planet.Up(me.transform.position) : Vector3.up; var north = Vector3.ProjectOnPlane(Vector3.up, up); if (north.sqrMagnitude < 1e-4f) north = Vector3.forward; _view = Quaternion.Inverse(Quaternion.LookRotation(up, north)); Repaint(); } void Refresh() { var ts = TeamState.Instance; MowMap.Count(); if (ts) _stats.text = Loc.F("{0:N0} started · {1:N0} mown · {2:0.0000}% of the planet", MowMap.Started, ts.Closed.Value, ts.Mown01 * 100.0); // keeps up with you as you go, until you drag it somewhere else if (_follow) Centre(); Repaint(); } static void Key(VisualElement parent, Color c, string label) { var row = UIK.El("map-key", parent); UIK.El("swatch", row).style.backgroundColor = c; UIK.Text(label, "t-small t-dark", row, false); } float Radius { get { var r = Area; return Mathf.Max(40f, Mathf.Min(r.width, r.height) * 0.47f); } } Vector2 Screen(Vector3 d, out bool front) { var v = _view * d; front = v.z > 0f; return Area.center + new Vector2(v.x, -v.y) * Radius * Zoom; } /// A sector's corners, in order round its middle. static Vector3[] Corners(HexGrid.Sector s) { if (s_corners.TryGetValue(s.id, out var c)) return c; var near = new List(); foreach (int n in s.neighbours) near.Add(HexGrid.Get(n).c); near.Sort((a, b) => Angle(s, a).CompareTo(Angle(s, b))); c = new Vector3[near.Count]; for (int i = 0; i < c.Length; i++) c[i] = (s.c + near[i] + near[(i + 1) % c.Length]).normalized; s_corners[s.id] = c; return c; } static float Angle(HexGrid.Sector s, Vector3 n) => Mathf.Atan2(Vector3.Dot(n - s.c, s.e2), Vector3.Dot(n - s.c, s.e1)); static Color Shade(MowMap.Mask m) => m == null || !m.keep ? Meadow : m.done ? Done : Begun; VisualElement Layer(Action draw) { var e = new VisualElement { pickingMode = PickingMode.Ignore }; e.style.position = Position.Absolute; e.style.left = 0f; e.style.top = 0f; e.style.right = 0f; e.style.bottom = 0f; e.generateVisualContent += draw; _chart.Add(e); return e; } void Repaint() { _ball?.MarkDirtyRepaint(); _ground?.MarkDirtyRepaint(); _marks?.MarkDirtyRepaint(); // the scale bar is an element: sized here, never while drawing if (_scaleBar != null && Area.width > 4f) Scale(Radius * Zoom); } /// The chart's drawing area, in the layers' own space. Rect Area => _ground != null ? _ground.contentRect : _chart.contentRect; float HexPx(float size) => Mathf.Sqrt(GameDefs.SectorArea) / Planet.Radius * size; void DrawBall(MeshGenerationContext ctx) { var r = Area; if (r.width < 4f) return; _clip = r; float size = Radius * Zoom; Disc(r, size, HexPx(size) >= HexPixels ? Grid : Meadow); Flush(ctx); } /// The sectors on the ball, one mesh, kept inside the chart. void DrawGround(MeshGenerationContext ctx) { var r = Area; if (r.width < 4f) return; _clip = r; float size = Radius * Zoom; float hexPx = HexPx(size); _masks.Clear(); foreach (var m in MowMap.All) _masks[m.s.id] = m; if (hexPx >= HexPixels) Hexes(ctx, r); else Dots(ctx, r, Mathf.Max(1.5f, hexPx * 0.5f)); Flush(ctx); } /// The ball as a fan, cut to the part of it that shows (close in it is far bigger than the chart). void Disc(Rect r, float size, Color32 col) { var c = r.center; float reach = new Vector2(r.width, r.height).magnitude * 0.5f; if (size > reach * 1.5f) { // the chart sits wholly inside the ball: a plain quad int q = _verts.Count; Vert(new Vector2(r.xMin, r.yMin), col); Vert(new Vector2(r.xMax, r.yMin), col); Vert(new Vector2(r.xMax, r.yMax), col); Vert(new Vector2(r.xMin, r.yMax), col); _tris.Add((ushort)q); _tris.Add((ushort)(q + 1)); _tris.Add((ushort)(q + 2)); _tris.Add((ushort)q); _tris.Add((ushort)(q + 2)); _tris.Add((ushort)(q + 3)); return; } const int Steps = 96; int k = _verts.Count; Vert(c, col); for (int i = 0; i < Steps; i++) { float a = i * Mathf.PI * 2f / Steps; Vert(c + new Vector2(Mathf.Cos(a), Mathf.Sin(a)) * size, col); } for (int i = 0; i < Steps; i++) { _tris.Add((ushort)k); _tris.Add((ushort)(k + 1 + i)); _tris.Add((ushort)(k + 1 + (i + 1) % Steps)); } } /// Over the ground: the lattice, the rim, and everything that stands on the ball. void DrawMarks(MeshGenerationContext ctx) { var r = Area; if (r.width < 4f) return; var ts = TeamState.Instance; float size = Radius * Zoom; var p = ctx.painter2D; if (Zoom < 6f) Lattice(p); p.strokeColor = Rim; p.lineWidth = 3f; p.BeginPath(); p.Arc(r.center, size, 0f, 360f); p.Stroke(); // what stands on the ball Dot(p, Vector3.up, 7f, Base); foreach (var b in BuildPiece.All) if (b && (b.piece == PieceId.UnloadBay || b.piece == PieceId.Intake)) Dot(p, Planet.Up(b.transform.position), 5f, Unload); if (ts) { foreach (int id in ts.Found) Dot(p, Planet.Up(Landmarks.Spot(id)), 4f, Stake); for (int i = 1; i < Stations.Count; i++) if (ts.StationOpen(i)) Dot(p, Stations.Dir(i), 6f, Station); } foreach (var m in Mowbot.All) if (m) Dot(p, Planet.Up(m.At.Value), 4f, Robot); foreach (var v in Vehicle.All) if (v) Arrow(p, v.transform, 7f, new Color(0.96f, 0.9f, 0.72f)); foreach (var pl in PlayerAgent.All) if (pl) Arrow(p, pl.transform, pl.IsOwner ? 11f : 8f, pl.Tint); } /// A round number of metres about a fifth of the chart wide. void Scale(float size) { float pxPerM = size / Planet.Radius; float want = Area.width * 0.18f / pxPerM; float step = Mathf.Pow(10f, Mathf.Floor(Mathf.Log10(Mathf.Max(1f, want)))); float metres = want >= step * 5f ? step * 5f : want >= step * 2f ? step * 2f : step; _scaleBar.style.width = metres * pxPerM; _scaleText.text = metres >= 1000f ? Loc.F("{0:0.0} km", metres / 1000f) : Loc.F("{0:0} m", metres); } void Dot(Painter2D p, Vector3 dir, float size, Color col) { var at = Screen(dir, out bool front); if (!front) return; p.fillColor = col; p.strokeColor = Color.white; p.lineWidth = 2f; p.BeginPath(); p.Arc(at, size, 0f, 360f); p.Fill(); p.Stroke(); } // ───────────────────────── the sectors, as a mesh ───────────────────────── /// The sectors go out in pieces of this size at most, well inside what one mesh may hold. const int ChunkVerts = 6000, ChunkIndices = 18000; void Room(MeshGenerationContext ctx, int verts, int indices) { if (_verts.Count + verts > ChunkVerts || _tris.Count + indices > ChunkIndices) Flush(ctx); } void Flush(MeshGenerationContext ctx) { if (_verts.Count == 0) return; var mesh = ctx.Allocate(_verts.Count, _tris.Count); mesh.SetAllVertices(_verts.ToArray()); mesh.SetAllIndices(_tris.ToArray()); _verts.Clear(); _tris.Clear(); } /// Every corner is held inside the chart, so a sector across its edge is cut off there instead of spilling /// past it onto the card (the chart's rounded edge doesn't clip a hand-made mesh). Rect _clip = new Rect(-1e6f, -1e6f, 2e6f, 2e6f); void Vert(Vector2 at, Color32 c) { at = new Vector2(Mathf.Clamp(at.x, _clip.xMin, _clip.xMax), Mathf.Clamp(at.y, _clip.yMin, _clip.yMax)); _verts.Add(new Vertex { position = new Vector3(at.x, at.y, Vertex.nearZ), tint = c }); } /// Far out each worked sector is a speck. void Dots(MeshGenerationContext ctx, Rect r, float half) { var view = new Rect(r.x - half, r.y - half, r.width + half * 2f, r.height + half * 2f); foreach (var m in _masks.Values) { if (!m.keep) continue; var at = Screen(m.s.c, out bool front); if (!front || !view.Contains(at)) continue; Room(ctx, 4, 6); Color32 c = m.done ? Done : Begun; int k = _verts.Count; Vert(at + new Vector2(-half, -half), c); Vert(at + new Vector2(half, -half), c); Vert(at + new Vector2(half, half), c); Vert(at + new Vector2(-half, half), c); _tris.Add((ushort)k); _tris.Add((ushort)(k + 1)); _tris.Add((ushort)(k + 2)); _tris.Add((ushort)k); _tris.Add((ushort)(k + 2)); _tris.Add((ushort)(k + 3)); } Flush(ctx); } /// Close up, every sector in view, walking out from the one in the middle; each a little smaller than it is, so the grid shows between. void Hexes(MeshGenerationContext ctx, Rect r) { _seen.Clear(); _queue.Clear(); int first = HexGrid.SectorAt(Quaternion.Inverse(_view) * Vector3.forward); _queue.Enqueue(first); _seen.Add(first); var view = new Rect(r.x - 60f, r.y - 60f, r.width + 120f, r.height + 120f); int drawn = 0; Flipped = 0; while (_queue.Count > 0 && drawn < MaxHexes) { var s = HexGrid.Get(_queue.Dequeue()); var at = Screen(s.c, out bool front); if (!front || !view.Contains(at)) continue; drawn++; _masks.TryGetValue(s.id, out var m); Color32 col = Shade(m); var c = Corners(s); Room(ctx, c.Length + 1, c.Length * 3); int k = _verts.Count; Vert(at, col); for (int i = 0; i < c.Length; i++) Vert(Vector2.LerpUnclamped(at, Screen(c[i], out _), 0.92f), col); // the screen drops faces wound the wrong way round, and the corners go round whichever way the // sector's own frame does: turned the screen's way here, or half the map never shows var e0 = (Vector2)_verts[k + 1].position - at; var e1 = (Vector2)_verts[k + 2].position - at; bool flip = e0.x * e1.y - e0.y * e1.x < 0f; if (flip) Flipped++; for (int i = 0; i < c.Length; i++) { int i0 = k + 1 + i, i1 = k + 1 + (i + 1) % c.Length; _tris.Add((ushort)k); _tris.Add((ushort)(flip ? i1 : i0)); _tris.Add((ushort)(flip ? i0 : i1)); } foreach (int n in s.neighbours) if (_seen.Add(n)) _queue.Enqueue(n); } Flush(ctx); Drawn = drawn; } /// Tests: sectors in the last close-in drawing, and how many of them had to be turned round. public static int Drawn, Flipped; /// Latitude and longitude every 30°. void Lattice(Painter2D p) { p.strokeColor = Lines; p.lineWidth = 1.5f; for (int lat = -60; lat <= 60; lat += 30) Trace(p, t => Planet.FromLatLon(lat, t * 360f)); for (int lon = 0; lon < 360; lon += 30) Trace(p, t => Planet.FromLatLon(-90f + t * 180f, lon)); } void Trace(Painter2D p, Func along) { bool open = false; p.BeginPath(); for (int i = 0; i <= 60; i++) { var at = Screen(along(i / 60f), out bool front); if (!front) { open = false; continue; } if (open) p.LineTo(at); else p.MoveTo(at); open = true; } p.Stroke(); } void Arrow(Painter2D p, Transform t, float size, Color col) { var d = Planet.Up(t.position); var at = Screen(d, out bool front); if (!front) return; var ahead = Screen((d + t.forward * 0.02f).normalized, out _); var f = (ahead - at).normalized; if (f.sqrMagnitude < 0.01f) f = Vector2.up; var side = new Vector2(-f.y, f.x); p.fillColor = col; p.strokeColor = Color.white; p.lineWidth = 2f; p.BeginPath(); p.MoveTo(at + f * size); p.LineTo(at - f * size * 0.7f + side * size * 0.7f); p.LineTo(at - f * size * 0.35f); p.LineTo(at - f * size * 0.7f - side * size * 0.7f); p.ClosePath(); p.Fill(); p.Stroke(); } } }