|
| 1 | +using System.Globalization; |
| 2 | +using System.Text; |
| 3 | +using RustPlusBot.Features.Connections.Listening; |
| 4 | + |
| 5 | +namespace RustPlusBot.Features.Events.Formatting; |
| 6 | + |
| 7 | +/// <summary>Converts world coordinates to a Rust map grid reference (e.g. "D7"), rustplusplus-compatible.</summary> |
| 8 | +public static class GridReference |
| 9 | +{ |
| 10 | + private const float GridDiameter = 146.25f; |
| 11 | + |
| 12 | + /// <summary>Formats a grid reference, or raw rounded coordinates when <paramref name="dims"/> is null.</summary> |
| 13 | + /// <param name="x">World X coordinate.</param> |
| 14 | + /// <param name="y">World Y coordinate.</param> |
| 15 | + /// <param name="dims">Map dimensions, or null when unavailable.</param> |
| 16 | + /// <returns>A grid reference like "D7", or "(x, y)" when dimensions are unavailable.</returns> |
| 17 | + public static string From(float x, float y, MapDimensions? dims) |
| 18 | + { |
| 19 | + if (dims is null) |
| 20 | + { |
| 21 | + return string.Create( |
| 22 | + CultureInfo.InvariantCulture, |
| 23 | + $"({Math.Round(x)}, {Math.Round(y)})"); |
| 24 | + } |
| 25 | + |
| 26 | + var mapSize = dims.Width; |
| 27 | + var columns = (int)Math.Ceiling(mapSize / GridDiameter); |
| 28 | + var col = (int)Math.Floor(Math.Clamp(x, 0f, mapSize - 1) / GridDiameter); |
| 29 | + // Rows are numbered from the TOP; world Y increases upward, so invert. |
| 30 | + var rowFromBottom = (int)Math.Floor(Math.Clamp(y, 0f, mapSize - 1) / GridDiameter); |
| 31 | + var row = Math.Max(0, columns - rowFromBottom - 1); |
| 32 | + |
| 33 | + return string.Create(CultureInfo.InvariantCulture, $"{ColumnLetters(col)}{row}"); |
| 34 | + } |
| 35 | + |
| 36 | + private static string ColumnLetters(int index) |
| 37 | + { |
| 38 | + // 0->A .. 25->Z, 26->AA .. (spreadsheet-style, matching rustplusplus past Z). |
| 39 | + var sb = new StringBuilder(); |
| 40 | + var n = index; |
| 41 | + do |
| 42 | + { |
| 43 | + sb.Insert(0, (char)('A' + (n % 26))); |
| 44 | + n = (n / 26) - 1; |
| 45 | + } while (n >= 0); |
| 46 | + |
| 47 | + return sb.ToString(); |
| 48 | + } |
| 49 | +} |
0 commit comments