using System.Collections.Generic;
using UnityEngine;
namespace GrassCutter
{
///
/// The sectors of Herbaria-7: an icosahedron with every face cut into a 128-to-a-side triangular lattice and blown out
/// onto the ball. Each lattice point owns the cell around it: 163 830 hexagons and 12 pentagons at the corners, the
/// first of them right under the base. Ids are worked out on the fly, so nothing here costs memory until a sector
/// comes near the camera ().
///
public static class HexGrid
{
public const int N = 128;
public const int Cells = 10 * N * N + 2;
const int EdgePoints = N - 1, Inner = (N - 1) * (N - 2) / 2;
/// One sector: its centre, a flat frame through it, and its neighbours as planes that fence it in.
public class Sector
{
public int id;
public Vector3 c, e1, e2;
/// Metres-per-unit-direction normal of the border toward each neighbour (a pentagon repeats its last).
public readonly Vector4[] borders = new Vector4[6];
public readonly List neighbours = new List(6);
/// Half size of the sector in its own frame, and the corner farthest from the centre.
public float halfU, halfV, radius;
/// The square its mow map covers: half a side, in metres.
public float half;
public Vector4 salt;
public Bounds bounds;
/// What grows here, worked out the first time it's asked: see .
public sbyte crop = -1;
}
static readonly Vector3[] Corner = new Vector3[12];
static readonly int[,] Face = new int[20, 3];
static readonly int[,] EdgeOf = new int[12, 12];
static readonly Vector4[] Normal = new Vector4[20], Row0 = new Vector4[20], Row1 = new Vector4[20], Row2 = new Vector4[20];
static readonly Dictionary s_cache = new Dictionary();
static HexGrid()
{
float lat = Mathf.Atan(0.5f);
Corner[0] = Vector3.up;
Corner[11] = Vector3.down;
for (int i = 0; i < 5; i++)
{
float a = i * 72f * Mathf.Deg2Rad, b = (i + 0.5f) * 72f * Mathf.Deg2Rad;
Corner[1 + i] = new Vector3(Mathf.Cos(lat) * Mathf.Sin(a), Mathf.Sin(lat), Mathf.Cos(lat) * Mathf.Cos(a));
Corner[6 + i] = new Vector3(Mathf.Cos(lat) * Mathf.Sin(b), -Mathf.Sin(lat), Mathf.Cos(lat) * Mathf.Cos(b));
}
for (int i = 0; i < 5; i++)
{
int u0 = 1 + i, u1 = 1 + (i + 1) % 5, d0 = 6 + i, d1 = 6 + (i + 1) % 5;
SetFace(i * 4, 0, u0, u1);
SetFace(i * 4 + 1, u0, d0, u1);
SetFace(i * 4 + 2, u1, d0, d1);
SetFace(i * 4 + 3, 11, d1, d0);
}
int edges = 0;
for (int a = 0; a < 12; a++) for (int b = 0; b < 12; b++) EdgeOf[a, b] = -1;
for (int f = 0; f < 20; f++)
for (int k = 0; k < 3; k++)
{
int a = Face[f, k], b = Face[f, (k + 1) % 3];
if (a > b) (a, b) = (b, a);
if (EdgeOf[a, b] < 0) EdgeOf[a, b] = edges++;
}
for (int f = 0; f < 20; f++)
{
Vector3 a = Corner[Face[f, 0]], b = Corner[Face[f, 1]], c = Corner[Face[f, 2]];
Normal[f] = (a + b + c).normalized;
float det = Vector3.Dot(a, Vector3.Cross(b, c));
Row0[f] = Vector3.Cross(b, c) / det;
Row1[f] = Vector3.Cross(c, a) / det;
Row2[f] = Vector3.Cross(a, b) / det;
}
}
static void SetFace(int f, int a, int b, int c) { Face[f, 0] = a; Face[f, 1] = b; Face[f, 2] = c; }
/// The Ground shader draws the same lattice.
/// The ball changed size: every sector is cut again when it's next asked for.
public static void Forget() => s_cache.Clear();
public static void Publish()
{
Shader.SetGlobalVectorArray("_GcIcoN", Normal);
Shader.SetGlobalVectorArray("_GcIcoR0", Row0);
Shader.SetGlobalVectorArray("_GcIcoR1", Row1);
Shader.SetGlobalVectorArray("_GcIcoR2", Row2);
}
// ───────────────────────── ids ─────────────────────────
/// Which sector a direction falls in.
public static int SectorAt(Vector3 d)
{
int f = 0;
float best = -2f;
for (int i = 0; i < 20; i++)
{
float dot = Normal[i].x * d.x + Normal[i].y * d.y + Normal[i].z * d.z;
if (dot > best) { best = dot; f = i; }
}
float w0 = Dot(Row0[f], d), w1 = Dot(Row1[f], d), w2 = Dot(Row2[f], d);
float sum = N / (w0 + w1 + w2);
float x = w0 * sum, y = w1 * sum, z = w2 * sum;
int rx = Mathf.RoundToInt(x), ry = Mathf.RoundToInt(y), rz = Mathf.RoundToInt(z);
float ex = Mathf.Abs(rx - x), ey = Mathf.Abs(ry - y), ez = Mathf.Abs(rz - z);
if (ex > ey && ex > ez) rx = N - ry - rz;
else if (ey > ez) ry = N - rx - rz;
else rz = N - rx - ry;
return Id(f, Mathf.Clamp(ry, 0, N), Mathf.Clamp(rz, 0, N));
}
static float Dot(Vector4 a, Vector3 b) => a.x * b.x + a.y * b.y + a.z * b.z;
/// Lattice point (i toward corner 1, j toward corner 2) of a face to its one id across the shared edges.
static int Id(int f, int i, int j)
{
int k = N - i - j;
if (k < 0) { j += k; k = 0; }
int a = Face[f, 0], b = Face[f, 1], c = Face[f, 2];
if (k == N) return a;
if (i == N) return b;
if (j == N) return c;
if (j == 0) return OnEdge(a, b, i);
if (i == 0) return OnEdge(a, c, j);
if (k == 0) return OnEdge(b, c, j);
return 12 + 30 * EdgePoints + f * Inner + (i - 1) * (2 * N - 2 - i) / 2 + j - 1;
}
static int OnEdge(int a, int b, int t)
{
if (a > b) { (a, b) = (b, a); t = N - t; }
return 12 + EdgeOf[a, b] * EdgePoints + t - 1;
}
/// Unit direction of a sector's centre.
public static Vector3 Centre(int id)
{
if (id < 12) return Corner[id];
int e = id - 12;
if (e < 30 * EdgePoints)
{
int edge = e / EdgePoints, t = e % EdgePoints + 1;
for (int a = 0; a < 12; a++)
for (int b = a + 1; b < 12; b++)
if (EdgeOf[a, b] == edge) return (Corner[a] * (N - t) + Corner[b] * t).normalized;
}
e -= 30 * EdgePoints;
int f = e / Inner, tri = e % Inner, row = 1;
while (tri >= N - 1 - row) { tri -= N - 1 - row; row++; }
int j = tri + 1, k = N - row - j;
return (Corner[Face[f, 0]] * k + Corner[Face[f, 1]] * row + Corner[Face[f, 2]] * j).normalized;
}
// ───────────────────────── sectors ─────────────────────────
public static Sector Get(int id)
{
if (s_cache.TryGetValue(id, out var s)) return s;
s = Build(id);
s_cache[id] = s;
return s;
}
static Sector Build(int id)
{
var c = Centre(id);
var s = new Sector { id = id, c = c };
var side = Vector3.Cross(c, Mathf.Abs(c.y) < 0.9f ? Vector3.up : Vector3.right).normalized;
var fwd = Vector3.Cross(c, side);
FindNeighbours(id, c, side, fwd, s.neighbours);
s.neighbours.Sort((p, q) => Bearing(c, side, fwd, p).CompareTo(Bearing(c, side, fwd, q)));
for (int k = 0; k < 6; k++)
{
var d = Centre(s.neighbours[Mathf.Min(k, s.neighbours.Count - 1)]) - c;
s.borders[k] = d.normalized * Planet.Radius;
}
s.e1 = Vector3.ProjectOnPlane(Centre(s.neighbours[0]) - c, c).normalized;
s.e2 = Vector3.Cross(c, s.e1);
// the cell's corners: where three neighbours meet
float u = 0f, v = 0f, far = 0f;
int count = s.neighbours.Count;
for (int k = 0; k < count; k++)
{
var a = Centre(s.neighbours[k]);
var b = Centre(s.neighbours[(k + 1) % count]);
// the true Voronoi vertex, projected onto the sector's plane: around the
// pentagons it sits well past the centroid, and the grass square left holes
var vx = Vector3.Cross(a - c, b - c).normalized;
if (Vector3.Dot(vx, c) < 0f) vx = -vx;
for (int pass = 0; pass < 2; pass++)
{
var corner = (pass == 0 ? vx / Vector3.Dot(vx, c) - c : (c + a + b) / 3f - c) * Planet.Radius;
u = Mathf.Max(u, Mathf.Abs(Vector3.Dot(corner, s.e1)));
v = Mathf.Max(v, Mathf.Abs(Vector3.Dot(corner, s.e2)));
far = Mathf.Max(far, corner.magnitude);
}
}
s.halfU = u * 1.04f; s.halfV = v * 1.04f; s.radius = far * 1.04f;
s.half = Mathf.Max(s.halfU, s.halfV);
s.salt = new Vector4(id % 991 * 17.3f, id % 613 * 29.1f, 0.5f / s.half, 0f);
float size = s.radius * 2.2f;
s.bounds = new Bounds(Planet.OnSurface(c), new Vector3(size, size, size));
return s;
}
///
/// Twelve looks around the centre, reaching further until all of them have left the cell. Lattice steps differ by
/// half across a face, so no fixed reach works; just past the cell's corners each neighbour owns a 60 degree slice.
///
static void FindNeighbours(int id, Vector3 c, Vector3 side, Vector3 fwd, List into)
{
for (float reach = 12f / GameDefs.PlanetRadius; ; reach *= 1.1f) // an angle: the lattice is the same on any ball
{
into.Clear();
bool left = true;
for (int k = 0; k < 12 && left; k++)
{
float a = k * 30f * Mathf.Deg2Rad;
int n = SectorAt((c + (side * Mathf.Cos(a) + fwd * Mathf.Sin(a)) * reach).normalized);
if (n == id) left = false;
else if (!into.Contains(n)) into.Add(n);
}
if (left) return;
}
}
static float Bearing(Vector3 c, Vector3 side, Vector3 fwd, int n)
{
var d = Centre(n) - c;
return Mathf.Atan2(Vector3.Dot(d, fwd), Vector3.Dot(d, side));
}
/// Walk every id both ways and count the shapes: what the demo reports.
public static string SelfTest()
{
int bad = 0, hex = 0, pent = 0, odd = 0;
float min = float.MaxValue, max = 0f;
var seen = new List(6);
for (int id = 0; id < Cells; id++)
{
var c = Centre(id);
if (SectorAt(c) != id) bad++;
var side = Vector3.Cross(c, Mathf.Abs(c.y) < 0.9f ? Vector3.up : Vector3.right).normalized;
FindNeighbours(id, c, side, Vector3.Cross(c, side), seen);
if (seen.Count == 6) hex++;
else if (seen.Count == 5) pent++;
else odd++;
foreach (int n in seen)
{
float d = (Centre(n) - c).magnitude * Planet.Radius;
min = Mathf.Min(min, d);
max = Mathf.Max(max, d);
}
}
float area = 4f * Mathf.PI * Planet.Radius * Planet.Radius / Cells;
return $"hex grid: {Cells} cells, {hex} hexagons, {pent} pentagons, odd {odd}, ids that fail the round trip {bad}, mean area {area:0} m², across {min:0.0}-{max:0.0} m";
}
}
}