Files
grass-cutters/Assets/Scripts/World/Ground.cs
NiemandKG d1c3761e58 Grass Cutters Together: the project as of moon-sweepers f3666f0
A clean start for the shared repository: the Unity project (Assets, Packages, ProjectSettings), ArtSource, Docs and
Tools as they stood at f3666f0 in the old local repository, with its generated prefabs and scene brought up to date.
Images, audio, models and binaries go through Git LFS (.gitattributes).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-06 18:44:40 +06:00

347 lines
16 KiB
C#

using System.Collections.Generic;
using UnityEngine;
namespace GrassCutter
{
/// <summary>
/// The soil of Herbaria-7, seen. One polar mesh wraps the whole ball, its fine middle always under the camera; the
/// shader lifts every vertex to the soil from the heights <see cref="Planet.Bake"/> published. Nobody has lived here: rock
/// mesas, trees and bushes are all that stands on it. Everything is deterministic, so every peer sees the same world.
/// Also carries the sky along with the camera.
/// </summary>
[DefaultExecutionOrder(-70)]
public class Ground : MonoBehaviour
{
public static Ground Instance { get; private set; }
public Material soil;
public GameObject[] spires = new GameObject[3];
public GameObject[] trees = new GameObject[3];
public GameObject bush;
const int Rings = 112, Spokes = 192, WildRocks = 800, Groves = 110;
const float FirstRing = 1f, RingGrowth = 1.06f, RockDraw = 1800f;
struct Rock { public GameObject go; public Vector3 pos; public float radius; public bool gone; public Vector3 size; public Quaternion turn; }
readonly List<Rock> _rocks = new List<Rock>();
/// <summary>The trees and bushes standing in each sector, by index into the rocks: they go when it's mown clean.</summary>
readonly Dictionary<int, List<int>> _plants = new Dictionary<int, List<int>>();
/// <summary>A plant this close to the camera falls over when its sector is finished; further off it just isn't there any more.</summary>
const float FellSeen = 260f;
Transform _root, _skin;
int _rockAt;
static readonly int SkyRotId = Shader.PropertyToID("_GcSkyRot"), SkyOnId = Shader.PropertyToID("_GcSkyOn");
void Awake()
{
Instance = this;
_root = new GameObject("GroundRoot").transform;
_root.SetParent(transform, false);
Planet.Bake();
HexGrid.Publish();
MowMap.ResetBlocks();
BuildSkin();
Populate();
MowMap.Bared += Clear;
MowMap.Restarted += Regrow;
Planet.Rescaled += Rebuild;
foreach (var m in MowMap.All) if (m.done) Clear(m.s.id);
gameObject.AddComponent<Landmarks>();
gameObject.AddComponent<DayNight>();
}
void OnDestroy()
{
MowMap.Bared -= Clear;
MowMap.Restarted -= Regrow;
Planet.Rescaled -= Rebuild;
}
/// <summary>The ball has changed size: the soil, the rocks and the trees go down again on the new one, and so do the
/// stakes, the far stations and whatever keeps the grass off its spot.</summary>
void Rebuild()
{
if (_root) Destroy(_root.gameObject);
_rocks.Clear();
_plants.Clear();
_rockAt = 0;
_root = new GameObject("GroundRoot").transform;
_root.SetParent(transform, false);
HexGrid.Publish();
MowMap.ResetBlocks();
BuildSkin();
Populate();
var marks = GetComponent<Landmarks>();
if (marks) marks.Replace();
if (Stations.Instance) Stations.Instance.Replace();
if (GrassField.Instance) GrassField.Instance.Redeck();
foreach (var p in BuildPiece.All) if (p) p.Reblock();
GrassBlocker.ReblockAll();
BuildPiece.Moved();
}
/// <summary>A sector has been mown clean: the trees and bushes on it come down.</summary>
void Clear(int sector)
{
if (!_plants.TryGetValue(sector, out var list)) return;
var cam = CameraFx.Cam ? CameraFx.Cam : Camera.main;
foreach (int i in list)
{
var r = _rocks[i];
if (r.gone) continue;
r.gone = true;
_rocks[i] = r;
bool seen = cam && Time.timeSinceLevelLoad > 3f && (r.pos - cam.transform.position).sqrMagnitude < FellSeen * FellSeen;
if (seen) StartCoroutine(Fell(r.go, r.pos, r.radius));
else r.go.SetActive(false);
}
}
/// <summary>The tree or bush still standing nearest a point, and the sector it's in (for the test bot). Zero if none.</summary>
public Vector3 NearestPlant(Vector3 from, out int sector)
{
sector = -1;
var best = Vector3.zero;
float d = float.MaxValue;
foreach (var kv in _plants)
foreach (int i in kv.Value)
{
var r = _rocks[i];
float m = (r.pos - from).sqrMagnitude;
if (r.gone || m > d) continue;
d = m; best = r.pos; sector = kv.Key;
}
return best;
}
/// <summary>A new game on a new planet: everything stands again.</summary>
void Regrow()
{
StopAllCoroutines();
for (int i = 0; i < _rocks.Count; i++)
{
var r = _rocks[i];
if (!r.gone) continue;
r.gone = false;
_rocks[i] = r;
r.go.transform.SetPositionAndRotation(r.pos, r.turn);
r.go.transform.localScale = r.size;
foreach (var c in r.go.GetComponentsInChildren<Collider>(true)) c.enabled = true;
r.go.SetActive(false);
}
}
/// <summary>It leans, goes over faster and faster, and is gone in a puff of dust where it lands.</summary>
System.Collections.IEnumerator Fell(GameObject go, Vector3 foot, float radius)
{
go.SetActive(true);
foreach (var c in go.GetComponentsInChildren<Collider>()) c.enabled = false;
var up = Planet.Up(foot);
var side = Vector3.Cross(up, Random.onUnitSphere).normalized;
var start = go.transform.rotation;
var size = go.transform.localScale;
yield return new WaitForSeconds(Random.Range(0f, 0.5f));
Sfx.PlayAt("giant_roll_creak", foot, 0.7f, 1.3f);
for (float t = 0f; t < 1f; t += Time.deltaTime / 1.1f)
{
go.transform.rotation = Quaternion.AngleAxis(88f * t * t, side) * start;
yield return null;
}
var down = foot + Vector3.Cross(side, up) * radius * 2.2f;
Sfx.PlayAt("cardboard_thud_" + Random.Range(1, 4), foot, 0.9f, 0.7f);
for (int k = 0; k < 5; k++) Fx.Dust(Vector3.Lerp(foot, down, k / 4f), 0.6f + radius * 0.15f, 4);
for (float t = 0f; t < 1f; t += Time.deltaTime / 0.35f)
{
go.transform.localScale = size * (1f - t * t);
yield return null;
}
Fx.Smoke(down, 1.2f + radius * 0.3f);
go.SetActive(false);
}
void OnEnable()
{
Planet.Bake();
HexGrid.Publish();
}
void LateUpdate()
{
var cam = CameraFx.Cam ? CameraFx.Cam : Camera.main;
if (!cam) return;
var p = cam.transform.position;
Planet.SetFrame(p);
_skin.rotation = Quaternion.FromToRotation(Vector3.up, Planet.LocalUp);
Shader.SetGlobalMatrix(SkyRotId, Matrix4x4.Rotate(Quaternion.Inverse(Planet.Frame)));
Shader.SetGlobalFloat(SkyOnId, 1f);
// climb and the haze lets go of the planet
float alt = Mathf.Max(0f, Planet.Altitude(p));
RenderSettings.fogStartDistance = (180f + alt * 2f) * WeatherFx.FogMul;
RenderSettings.fogEndDistance = (1900f + alt * 3.2f) * WeatherFx.FogMul;
WakeRocks(p);
ContactShade.Publish(p);
}
/// <summary>A slice of the rocks each frame: only the ones nearby are drawn at all.</summary>
void WakeRocks(Vector3 p)
{
for (int i = 0; i < 40 && _rocks.Count > 0; i++)
{
_rockAt = (_rockAt + 1) % _rocks.Count;
var r = _rocks[_rockAt];
if (r.gone) continue;
bool on = (r.pos - p).sqrMagnitude < RockDraw * RockDraw;
if (r.go.activeSelf != on) r.go.SetActive(on);
}
}
// ───────────────────────── terrain ─────────────────────────
void BuildSkin()
{
// rings of unit directions around +Y, each a little wider apart than the last, right round to -Y
var angle = new List<float> { 0f };
float step = FirstRing, s = 0f;
for (int i = 0; i < Rings && s < Mathf.PI * Planet.Radius; i++)
{
s += step;
step *= RingGrowth;
angle.Add(Mathf.Min(s / Planet.Radius, Mathf.PI));
}
int rings = angle.Count;
var verts = new Vector3[1 + (rings - 1) * Spokes];
verts[0] = Vector3.up;
for (int r = 1; r < rings; r++)
for (int j = 0; j < Spokes; j++)
{
float a = j * Mathf.PI * 2f / Spokes;
verts[1 + (r - 1) * Spokes + j] = new Vector3(Mathf.Sin(angle[r]) * Mathf.Sin(a), Mathf.Cos(angle[r]), Mathf.Sin(angle[r]) * Mathf.Cos(a));
}
var tris = new List<int>(verts.Length * 6);
for (int j = 0; j < Spokes; j++) { tris.Add(0); tris.Add(1 + j); tris.Add(1 + (j + 1) % Spokes); }
for (int r = 1; r < rings - 1; r++)
for (int j = 0; j < Spokes; j++)
{
int a = 1 + (r - 1) * Spokes + j, b = 1 + (r - 1) * Spokes + (j + 1) % Spokes;
int c = a + Spokes, d = b + Spokes;
tris.Add(a); tris.Add(c); tris.Add(b);
tris.Add(b); tris.Add(c); tris.Add(d);
}
var m = new Mesh { name = "PlanetSkin", indexFormat = UnityEngine.Rendering.IndexFormat.UInt32 };
m.vertices = verts;
m.SetTriangles(tris, 0);
m.bounds = new Bounds(Vector3.zero, Vector3.one * Planet.Radius * 3f);
var go = new GameObject("Terrain");
go.transform.SetParent(_root, false);
go.transform.position = Planet.Center;
go.AddComponent<MeshFilter>().sharedMesh = m;
var mr = go.AddComponent<MeshRenderer>();
mr.sharedMaterial = soil;
mr.shadowCastingMode = UnityEngine.Rendering.ShadowCastingMode.Off;
_skin = go.transform;
}
void Populate()
{
var rng = new System.Random(7177);
float R(float a, float b) => a + (float)rng.NextDouble() * (b - a);
// giant far mesas on the hills
for (int i = 0; i < 9; i++)
{
float a = i / 9f * Mathf.PI * 2f + R(-0.2f, 0.2f);
float d = R(320f, 620f);
Place(spires[i % 3], Planet.FromBase(Mathf.Cos(a) * d, Mathf.Sin(a) * d), R(0f, 360f), R(1.8f, 2.8f), true);
}
// closer boulders poking out of the grass
for (int i = 0; i < 22; i++)
{
float a = R(0f, Mathf.PI * 2f);
float d = R(95f, 300f);
Place(spires[rng.Next(3)], Planet.FromBase(Mathf.Cos(a) * d, Mathf.Sin(a) * d), R(0f, 360f), R(0.35f, 0.8f), true);
}
// the rest of the planet
// fewer on a smaller ball, so the land isn't crowded
int wild = Mathf.Max(60, Mathf.RoundToInt(WildRocks * Planet.Scale * Planet.Scale));
for (int i = 0; i < wild; i++)
{
var dir = new Vector3(R(-1f, 1f), R(-1f, 1f), R(-1f, 1f)).normalized;
if (dir.y > 0.94f) continue;
bool giant = rng.NextDouble() < 0.2;
Place(spires[rng.Next(3)], dir, R(0f, 360f), giant ? R(1.6f, 2.8f) : R(0.35f, 0.9f), true);
}
// a loose ring of trees and bushes around the clearing, and groves all over the ball
if (trees == null || !trees[0]) return;
for (int i = 0; i < 34; i++)
{
float a = i / 34f * Mathf.PI * 2f + R(-0.05f, 0.05f);
float d = R(84f, 112f);
var dir = Planet.FromBase(Mathf.Cos(a) * d, Mathf.Sin(a) * d);
if (i % 3 == 2) Place(bush, dir, R(0f, 360f), R(1f, 1.5f), false, true);
else Place(trees[rng.Next(3)], dir, R(0f, 360f), R(1.3f, 2.1f), true, true);
}
int groves = Mathf.Max(14, Mathf.RoundToInt(Groves * Planet.Scale * Planet.Scale));
for (int i = 0; i < groves; i++)
{
var dir = new Vector3(R(-1f, 1f), R(-1f, 1f), R(-1f, 1f)).normalized;
if (dir.y > 0.94f) continue;
var e1 = Vector3.Cross(dir, Vector3.right).normalized;
var e2 = Vector3.Cross(dir, e1);
int count = rng.Next(4, 9);
for (int k = 0; k < count; k++)
{
var at = (dir + (e1 * R(-18f, 18f) + e2 * R(-18f, 18f)) / Planet.Radius).normalized;
Place(trees[rng.Next(3)], at, R(0f, 360f), R(1.2f, 2.2f), true, true);
}
}
}
/// <summary>70 m round each far station, on any ball.</summary>
static float StationClear => Mathf.Cos(70f / Planet.Radius);
GameObject Place(GameObject prefab, Vector3 dir, float yaw, float scale, bool collide, bool plant = false)
{
if (!prefab) return null;
// nothing stands on a station's clearing
float clear = StationClear;
for (int i = 1; i < Stations.Count; i++) if (Vector3.Dot(dir, Stations.Dir(i)) > clear) return null;
var pos = Planet.OnSurface(dir) - dir * 0.4f * scale;
var go = Instantiate(prefab, _root);
go.transform.localScale = prefab.transform.localScale * scale;
go.transform.SetPositionAndRotation(pos, Quaternion.Euler(0f, yaw, 0f) * prefab.transform.localRotation);
float radius = 4f;
var rs = go.GetComponentsInChildren<Renderer>();
if (rs.Length > 0)
{
var b = rs[0].bounds;
foreach (var r in rs) b.Encapsulate(r.bounds);
radius = Mathf.Max(b.extents.x, b.extents.z);
}
// measured standing up, then stood on its spot of the ball
go.transform.rotation = Quaternion.FromToRotation(Vector3.up, dir) * go.transform.rotation;
if (collide)
foreach (var mf in go.GetComponentsInChildren<MeshFilter>())
mf.gameObject.AddComponent<MeshCollider>().sharedMesh = mf.sharedMesh;
if (plant)
{
int sector = HexGrid.SectorAt(dir);
if (!_plants.TryGetValue(sector, out var list)) _plants[sector] = list = new List<int>();
list.Add(_rocks.Count);
}
_rocks.Add(new Rock { go = go, pos = pos, radius = radius * 0.8f, size = go.transform.localScale, turn = go.transform.rotation });
MowMap.BlockRound(pos, radius * 0.7f);
go.SetActive(false);
return go;
}
/// <summary>Is a rock standing on this spot?</summary>
public bool RockAt(Vector3 p)
{
foreach (var r in _rocks)
if (!r.gone && (r.pos - p).sqrMagnitude < r.radius * r.radius) return true;
return false;
}
}
}