Files
grass-cutters/Assets/Scripts/UI/EndingEarth.cs
Bonchellon 3ee5956694 Ending: the Director's call, flyovers into orbit, Earth turning green, credits
When the planet is mown the ending plays by itself: G.R.A.S.S.A. calls, the
camera skims the stubble into the base, circles it and rises without a cut
into orbit over the bald planet (title, the crew's results). Then a jump
across space to a scorched, dried-out Earth: a rocket from Herbaria-7 passes
the lens and lands in Africa, and the green spreads from there over the whole
globe (seed pods, a glowing front, clouds and blue air coming back). The
credits roll over the green Earth (PlayWay credited as publisher), then THE
END and a card to keep mowing, leave a review or go to the menu. Space, Enter
or Esc skips to the green Earth and the card.

- EndingCinematic, EndingEarth (globe, air shell, rocket, seeds), SpaceSky
  (split out of the intro), EarthGlobe/EarthAir shaders and Earth maps in
  Resources/Ending
- the far meadow shows as stubble once the planet is mown
- "all of it" mown now means no sector with grass left (MowMap.Left); mown
  area summed in double
- the crew's total pay and play time are counted and saved for the results
- the "ending" cheat; -ending previews it in a test world; the -ending bot
  shoots every stage
- loc for the new lines in all 11 languages

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-28 01:52:24 +03:00

420 lines
21 KiB
C#

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace GrassCutter
{
/// <summary>
/// The ending's last stop: Earth, out in a patch of space of its own, scorched and dried out. A rocket from Herbaria-7
/// comes past the lens and down onto it, and from where it lands the green spreads over the whole ball, seed pods thrown
/// off it starting patches of their own, the air going from dust to blue and the clouds coming back.
/// </summary>
public sealed class EndingEarth
{
public const float R = 2000f;
// a seed spread this far (radians, before the shader's wobble) has covered the ball
const float Full = 4.8f;
const int MaxSeeds = 12;
const float Spin = 1.1f;
public readonly Vector3 Center;
/// <summary>Towards the sun; the frame the camera keeps to: Side across the sun, Up square to both.</summary>
public readonly Vector3 Sun, Side, Up;
/// <summary>The main patch has covered the ball.</summary>
public bool Healed => _seeds.Count > 0 && _seeds[0].age >= _seeds[0].grow;
public bool Landed => _seeds.Count > 0;
/// <summary>0 dead … 1 green all over: the air, the clouds.</summary>
public float Life { get; private set; }
readonly GameObject _root;
readonly Transform _ball;
readonly Material _mat, _airMat;
readonly ParticleSystem _glow, _rings, _sparks;
readonly Quaternion _tilt;
float _spin;
class Seed { public Vector3 dir; public float age, grow, full; }
class Pod { public Vector3 from, to; public float t, time; }
readonly List<Seed> _seeds = new List<Seed>();
readonly List<Pod> _pods = new List<Pod>();
readonly Vector4[] _seedVec = new Vector4[MaxSeeds], _seedFx = new Vector4[MaxSeeds];
static readonly int SeedsId = Shader.PropertyToID("_Seeds"), SeedFxId = Shader.PropertyToID("_SeedFx"), SeedCountId = Shader.PropertyToID("_SeedCount"),
LifeId = Shader.PropertyToID("_Life"), AirId = Shader.PropertyToID("_AirColor"), SunId = Shader.PropertyToID("_SunDir"),
PowerId = Shader.PropertyToID("_Power"), EdgeId = Shader.PropertyToID("_Edge");
static readonly Color DeadAir = new Color(0.85f, 0.52f, 0.28f), LiveAir = new Color(0.3f, 0.58f, 1f);
static Mesh s_sphere;
/// <summary>Earth far out from Herbaria-7 (its centre given), on the side of it that the lens keeps behind itself.</summary>
public EndingEarth(Vector3 herbaria, Vector3 sun)
{
Sun = sun.normalized;
Up = Vector3.ProjectOnPlane(Mathf.Abs(Sun.y) < 0.9f ? Vector3.up : Vector3.right, Sun).normalized;
Side = Vector3.Cross(Up, Sun).normalized;
// the lens sits between the sun and Side from the ball: Herbaria-7 out along sun + Side is behind it
Center = herbaria - (Sun * 0.5f + Side).normalized * 150000f;
var center = Center;
_root = new GameObject("EndingEarth");
var ball = new GameObject("Ball", typeof(MeshFilter), typeof(MeshRenderer));
_ball = ball.transform;
_ball.SetParent(_root.transform, false);
_ball.position = center;
_ball.localScale = Vector3.one * R;
// the poles a little towards the lens, the way a globe stands
_tilt = Quaternion.LookRotation(Side, Up) * Quaternion.Euler(16f, 0f, 0f);
_ball.rotation = _tilt;
ball.GetComponent<MeshFilter>().sharedMesh = Sphere();
_mat = new Material(Resources.Load<Shader>("Ending/EarthGlobe"));
_mat.SetTexture("_DryTex", Resources.Load<Texture2D>("Ending/earth_dry"));
_mat.SetTexture("_GreenTex", Resources.Load<Texture2D>("Ending/earth_green"));
var mr = ball.GetComponent<MeshRenderer>();
mr.sharedMaterial = _mat;
mr.shadowCastingMode = UnityEngine.Rendering.ShadowCastingMode.Off;
mr.receiveShadows = false;
var air = new GameObject("Air", typeof(MeshFilter), typeof(MeshRenderer));
air.transform.SetParent(_root.transform, false);
air.transform.position = center;
air.transform.localScale = Vector3.one * R * 1.07f;
air.GetComponent<MeshFilter>().sharedMesh = Sphere();
_airMat = new Material(Resources.Load<Shader>("Ending/EarthAir"));
_airMat.SetFloat(EdgeId, Mathf.Sqrt(1f - 1f / (1.07f * 1.07f)));
var amr = air.GetComponent<MeshRenderer>();
amr.sharedMaterial = _airMat;
amr.shadowCastingMode = UnityEngine.Rendering.ShadowCastingMode.Off;
amr.receiveShadows = false;
var bank = AssetBank.I;
_glow = Particles("Glow", bank.Mat("FX_Soft"), AnimationCurve.EaseInOut(0f, 1f, 1f, 0.6f));
_rings = Particles("Rings", bank.Mat("FX_Ring") ?? bank.Mat("FX_Soft"), AnimationCurve.EaseInOut(0f, 0.08f, 1f, 1f));
_sparks = Particles("Sparks", bank.Mat("FX_Sparkle") ?? bank.Mat("FX_Soft"), AnimationCurve.EaseInOut(0f, 1f, 1f, 0.2f));
Apply();
}
ParticleSystem Particles(string name, Material mat, AnimationCurve size)
{
var go = new GameObject(name);
go.transform.SetParent(_root.transform, false);
var ps = go.AddComponent<ParticleSystem>();
ps.Stop(true, ParticleSystemStopBehavior.StopEmittingAndClear);
var main = ps.main;
main.playOnAwake = false; main.loop = false;
main.simulationSpace = ParticleSystemSimulationSpace.World;
main.maxParticles = 6000;
main.startSpeed = 0f;
var em = ps.emission; em.enabled = false;
var sh = ps.shape; sh.enabled = false;
var sol = ps.sizeOverLifetime; sol.enabled = true; sol.size = new ParticleSystem.MinMaxCurve(1f, size);
var col = ps.colorOverLifetime; col.enabled = true;
var g = new Gradient();
g.SetKeys(new[] { new GradientColorKey(Color.white, 0f), new GradientColorKey(Color.white, 1f) },
new[] { new GradientAlphaKey(1f, 0f), new GradientAlphaKey(0.8f, 0.4f), new GradientAlphaKey(0f, 1f) });
col.color = g;
var r = go.GetComponent<ParticleSystemRenderer>();
r.sharedMaterial = mat;
r.maxParticleSize = 4f;
r.shadowCastingMode = UnityEngine.Rendering.ShadowCastingMode.Off;
ps.Play();
return ps;
}
static void Emit(ParticleSystem ps, Vector3 pos, Vector3 vel, float size, Color c, float life)
{
var ep = new ParticleSystem.EmitParams { position = pos, velocity = vel, startSize = size, startColor = c, startLifetime = life, applyShapeToPosition = false };
ps.Emit(ep, 1);
}
/// <summary>The ball's own direction to a place on the map (latitude, longitude in degrees, as the map is laid out).</summary>
public static Vector3 Geo(float lat, float lon)
{
float a = lat * Mathf.Deg2Rad, o = lon * Mathf.Deg2Rad;
return new Vector3(Mathf.Cos(a) * Mathf.Cos(o), Mathf.Sin(a), Mathf.Cos(a) * Mathf.Sin(o));
}
/// <summary>Spin the ball so the place given (its own direction) faces the world direction given, this many seconds from now.</summary>
public void Face(Vector3 dirOS, Vector3 worldDir, float inSeconds)
{
var w = Quaternion.Inverse(_tilt) * worldDir.normalized;
float aw = Mathf.Atan2(w.x, w.z) * Mathf.Rad2Deg, ad = Mathf.Atan2(dirOS.x, dirOS.z) * Mathf.Rad2Deg;
_spin = aw - ad - Spin * inSeconds;
_ball.rotation = _tilt * Quaternion.AngleAxis(_spin, Vector3.up);
}
/// <summary>A world point on the ball (a little over it) for a direction in the ball's own space.</summary>
public Vector3 Surface(Vector3 dirOS, float over = 0f) => Center + _ball.rotation * dirOS.normalized * (R + over);
public Vector3 ToBall(Vector3 worldDir) => Quaternion.Inverse(_ball.rotation) * worldDir.normalized;
public void Tick(float dt)
{
_spin += dt * Spin;
_ball.rotation = _tilt * Quaternion.AngleAxis(_spin, Vector3.up);
foreach (var s in _seeds) s.age += dt;
for (int i = _pods.Count - 1; i >= 0; i--)
{
var p = _pods[i];
p.t += dt;
if (p.t < 0f) continue;
float k = Mathf.Clamp01(p.t / p.time);
var dir = Vector3.Slerp(p.from, p.to, k);
var pos = Surface(dir, R * 0.24f * Mathf.Sin(k * Mathf.PI));
Emit(_glow, pos, Vector3.zero, 46f, new Color(0.75f, 1f, 0.45f, 0.95f), 0.9f);
Emit(_sparks, pos, Random.onUnitSphere * 12f, Random.Range(10f, 18f), new Color(1f, 0.95f, 0.6f), 0.7f);
if (k >= 1f)
{
_pods.RemoveAt(i);
Plant(p.to, Random.Range(0.8f, 1.35f), Random.Range(6f, 9f));
var at = Surface(p.to, 4f);
Emit(_glow, at, Vector3.zero, 320f, new Color(0.8f, 1f, 0.55f, 0.9f), 1f);
Emit(_rings, at, Vector3.zero, 900f, new Color(0.7f, 1f, 0.5f, 0.9f), 1.6f);
Sfx.Play("plater_shimmer", 0.25f, Random.Range(1.1f, 1.4f), 0f);
}
}
// sparkles along every front still moving
for (int i = 0; i < _seeds.Count; i++)
{
var s = _seeds[i];
float w = Spread(s);
if (w >= s.full * 0.98f || w <= 0f) continue;
int n = Mathf.Min(14, Mathf.CeilToInt((i == 0 ? 120f : 30f) * dt * Mathf.Clamp(w, 0.3f, 2f)));
var ortho = Vector3.Cross(s.dir, Mathf.Abs(s.dir.y) < 0.9f ? Vector3.up : Vector3.right).normalized;
for (int k = 0; k < n; k++)
{
float a = Mathf.Min(Mathf.PI * 0.999f, w * Random.Range(0.72f, 1.05f));
var axis = Quaternion.AngleAxis(Random.Range(0f, 360f), s.dir) * ortho;
var d = Quaternion.AngleAxis(a * Mathf.Rad2Deg, axis) * s.dir;
var pos = Surface(d, 6f);
var nrm = (pos - Center).normalized;
Emit(_sparks, pos, nrm * Random.Range(25f, 70f), Random.Range(9f, 22f),
Color.Lerp(new Color(0.6f, 1f, 0.35f), new Color(1f, 0.92f, 0.5f), Random.value), Random.Range(0.6f, 1.3f));
}
}
Apply();
}
static float Spread(Seed s)
{
float k = Mathf.Clamp01(s.age / s.grow);
// under way at once, quickest half way, easing into its last stretch
return s.full * Mathf.Max(0.5f - 0.5f * Mathf.Cos(Mathf.PI * k), Mathf.Min(k * 0.6f, 0.05f));
}
void Apply()
{
int n = Mathf.Min(MaxSeeds, _seeds.Count);
for (int i = 0; i < MaxSeeds; i++)
_seedVec[i] = i < n ? new Vector4(_seeds[i].dir.x, _seeds[i].dir.y, _seeds[i].dir.z, Spread(_seeds[i])) : Vector4.zero;
for (int i = 0; i < MaxSeeds; i++)
_seedFx[i] = i < n ? new Vector4(1f - Mathf.SmoothStep(0f, 1f, Mathf.InverseLerp(0.7f, 1f, _seeds[i].age / _seeds[i].grow)), 0f, 0f, 0f) : Vector4.zero;
_mat.SetVectorArray(SeedsId, _seedVec);
_mat.SetVectorArray(SeedFxId, _seedFx);
_mat.SetFloat(SeedCountId, n);
float main = n > 0 ? Spread(_seeds[0]) / Full : 0f;
Life = Mathf.SmoothStep(0f, 1f, Mathf.InverseLerp(0.08f, 0.85f, main));
var air = Color.Lerp(DeadAir, LiveAir, Life);
_mat.SetFloat(LifeId, Life);
_mat.SetColor(AirId, air);
_mat.SetVector(SunId, Sun);
_airMat.SetColor(AirId, air);
_airMat.SetVector(SunId, Sun);
_airMat.SetFloat(PowerId, Mathf.Lerp(0.55f, 1.25f, Life));
}
void Plant(Vector3 dirOS, float full, float grow)
{
if (_seeds.Count >= MaxSeeds) return;
_seeds.Add(new Seed { dir = dirOS.normalized, full = full, grow = grow });
}
/// <summary>The rocket comes down here (a direction in the ball's own space): the flash, and the green under way.</summary>
public void Land(Vector3 dirOS, Vector3 viewDirWorld)
{
Plant(dirOS, Full, 17f);
var at = Surface(dirOS, 6f);
var nrm = (at - Center).normalized;
Emit(_glow, at, Vector3.zero, 1100f, new Color(1f, 1f, 0.85f, 1f), 1.3f);
Emit(_glow, at, Vector3.zero, 520f, new Color(0.7f, 1f, 0.45f, 1f), 2.2f);
Emit(_rings, at, Vector3.zero, 2600f, new Color(0.75f, 1f, 0.55f, 1f), 2.4f);
Emit(_rings, at, Vector3.zero, 1500f, new Color(1f, 0.95f, 0.7f, 0.9f), 1.6f);
for (int k = 0; k < 90; k++)
Emit(_sparks, at, (nrm * 0.8f + Random.insideUnitSphere).normalized * Random.Range(60f, 260f), Random.Range(12f, 30f),
Color.Lerp(new Color(0.6f, 1f, 0.35f), new Color(1f, 0.9f, 0.5f), Random.value), Random.Range(1f, 2.2f));
// seed pods thrown out all round: half to the side we see, half anywhere
var view = ToBall(viewDirWorld);
for (int i = 0; i < 9; i++)
{
Vector3 to;
int tries = 0;
do
{
to = Random.onUnitSphere;
if (i % 2 == 0 && Vector3.Dot(to, view) < 0.25f) to = Vector3.Slerp(to, view, 0.6f).normalized;
} while (Vector3.Angle(to, dirOS) < 35f && ++tries < 20);
_pods.Add(new Pod { from = dirOS.normalized, to = to, t = -(0.7f + i * 0.32f), time = Random.Range(1.5f, 2.4f) });
}
}
/// <summary>Green all over at once (the skip).</summary>
public void HealNow()
{
_pods.Clear();
if (_seeds.Count == 0) Plant(Vector3.up, Full, 17f);
_seeds[0].full = Full;
_seeds[0].age = _seeds[0].grow;
_rocketDone = true;
if (_rocket) _rocket.gameObject.SetActive(false);
Apply();
}
// ───────── the rocket ─────────
Transform _rocket;
bool _rocketDone;
/// <summary>
/// From behind the lens, past it close on the right, then away and down onto the ball where it lands (a direction in the
/// ball's own space). It never gets smaller than a speck with a trail; then it lands.
/// </summary>
/// The lens is asked for each frame (the film's own pose of it: the camera's transform is the player's until late in the frame).
public IEnumerator Rocket(System.Func<Pose> lens, Vector3 landOS, float seconds)
{
var prefab = AssetBank.I.Model("SM_Rocket");
if (prefab)
{
var go = Object.Instantiate(prefab, _root.transform);
foreach (var r in go.GetComponentsInChildren<Renderer>()) { r.shadowCastingMode = UnityEngine.Rendering.ShadowCastingMode.Off; r.receiveShadows = false; }
foreach (var c in go.GetComponentsInChildren<Collider>()) Object.Destroy(c);
_rocket = go.transform;
}
float tall = 1f;
if (_rocket)
{
var b = new Bounds(_rocket.position, Vector3.zero);
bool any = false;
foreach (var r in _rocket.GetComponentsInChildren<Renderer>()) { if (!any) { b = r.bounds; any = true; } else b.Encapsulate(r.bounds); }
tall = Mathf.Max(0.1f, b.size.y);
}
const float Height = 9f;
float baseScale = Height / tall;
// the pass: straight by the lens on the right, measured from the lens as it moves (it is still drifting in on the
// ball, about as fast as the rocket goes by); then a boost away along a smooth curve down onto the ball
var a0 = new Vector3(6f, -2.2f, -25f);
var a1 = new Vector3(9f, -0.6f, 110f);
var l0 = lens();
var p1 = l0.position + l0.rotation * a0;
var passDir = l0.rotation * (a1 - a0).normalized;
var up = l0.up;
Sfx.Play("rocket_launch", 0.5f, 1.2f, 0f);
bool whoosh = false;
var prev = p1;
float t = 0f;
while (t < seconds && !_rocketDone)
{
t += Time.deltaTime;
float k = Mathf.Clamp01(t / seconds);
var land = Surface(landOS, 0f);
var nrm = (land - Center).normalized;
var ln = lens();
Vector3 pos;
if (k < 0.3f)
{
pos = ln.position + ln.rotation * Vector3.Lerp(a0, a1, k / 0.3f);
// where the pass ends and which way it was going: the curve down starts from there
p1 = pos;
passDir = ln.rotation * (a1 - a0).normalized;
up = ln.up;
}
else
{
// off quick, easing in to land
float v = (k - 0.3f) / 0.7f;
float w = Mathf.Lerp(v, v * v * (3f - 2f * v), 0.85f);
var b1 = p1 + passDir * R * 0.9f + up * R * 0.1f;
var b2 = land + nrm * R * 0.9f;
pos = Bezier(p1, b1, b2, land + nrm * 3f, w);
}
var dir = pos - prev;
if (dir.sqrMagnitude < 1e-6f) dir = passDir;
dir.Normalize();
float far = Vector3.Distance(ln.position, pos);
float s = Mathf.Max(1f, far / 320f);
if (_rocket)
{
_rocket.position = pos;
_rocket.rotation = Quaternion.FromToRotation(Vector3.up, dir) * Quaternion.AngleAxis(t * 90f, Vector3.up);
_rocket.localScale = Vector3.one * baseScale * s;
}
// the flame and the trail, filled in between frames so it never breaks into dots
float step = Mathf.Max(0.6f, s * 2.2f);
int n = Mathf.Clamp(Mathf.CeilToInt(Vector3.Distance(prev, pos) / step), 1, 40);
for (int i = 0; i < n; i++)
{
var at = Vector3.Lerp(prev, pos, (i + 1f) / n);
// close by the lens a small flame and no smoke: left in the air there, it would fill the frame
float flame = Mathf.Min(s * Random.Range(2.2f, 3.2f), 0.4f + far * 0.035f);
Emit(_glow, at - dir * s * 0.4f, -dir * s * 6f, flame, new Color(1f, 0.62f, 0.25f, 0.95f), 0.22f);
if (i % 2 == 0 && far > 45f)
Emit(_glow, at - dir * s * 1.2f, Random.insideUnitSphere * s * 0.6f, s * Random.Range(2.6f, 3.8f), new Color(0.92f, 0.9f, 0.86f, 0.55f), 2.4f);
}
if (!whoosh && Vector3.Dot(pos - ln.position, ln.forward) > 0f) { whoosh = true; Sfx.Play("meteor_whoosh", 0.6f, 0.95f, 0f); }
prev = pos;
yield return null;
}
if (_rocket) _rocket.gameObject.SetActive(false);
if (!_rocketDone)
{
_rocketDone = true;
Sfx.Play("rocket_land", 0.7f, 0.8f, 0f);
Sfx.Play("buff_shimmer", 0.5f, 0.9f, 0f);
Land(landOS, lens().position - Center);
}
}
static Vector3 Bezier(Vector3 a, Vector3 b, Vector3 c, Vector3 d, float t)
{
float u = 1f - t;
return u * u * u * a + 3f * u * u * t * b + 3f * u * t * t * c + t * t * t * d;
}
public void Destroy()
{
if (_root) Object.Destroy(_root);
if (_mat) Object.Destroy(_mat);
if (_airMat) Object.Destroy(_airMat);
}
/// <summary>A unit sphere fine enough that its edge stays round across the screen.</summary>
static Mesh Sphere()
{
if (s_sphere) return s_sphere;
const int lon = 160, lat = 80;
var v = new Vector3[(lon + 1) * (lat + 1)];
var idx = new int[lon * lat * 6];
int vi = 0;
for (int y = 0; y <= lat; y++)
{
float th = Mathf.PI * y / lat;
for (int x = 0; x <= lon; x++)
{
float ph = 2f * Mathf.PI * x / lon;
v[vi++] = new Vector3(Mathf.Sin(th) * Mathf.Cos(ph), Mathf.Cos(th), Mathf.Sin(th) * Mathf.Sin(ph));
}
}
int ii = 0;
for (int y = 0; y < lat; y++)
for (int x = 0; x < lon; x++)
{
int a = y * (lon + 1) + x, b = a + lon + 1;
idx[ii++] = a; idx[ii++] = a + 1; idx[ii++] = b;
idx[ii++] = a + 1; idx[ii++] = b + 1; idx[ii++] = b;
}
s_sphere = new Mesh { name = "EndingSphere", indexFormat = UnityEngine.Rendering.IndexFormat.UInt32, vertices = v, normals = v, triangles = idx };
s_sphere.RecalculateBounds();
return s_sphere;
}
}
}