using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using UnityEngine;
using UnityEngine.UIElements;
using Random = UnityEngine.Random;
namespace GrassCutter
{
///
/// The Director of G.R.A.S.S.A. (Earth's grass agency, which runs the mission) rings the phone: rarely, at milestones of
/// the planet and when something big is unlocked. The phone comes out, he shouts from mission control on Earth with his
/// head flapping like a cut-out puppet, the words run along the bottom of the view, and the phone goes back where it was.
/// V hangs up early.
///
public class DirectorCall : MonoBehaviour
{
public static DirectorCall I { get; private set; }
/// A call is ringing or on.
public static bool Busy => I && I._on;
// the words as recorded (the tags steer the voice); the captions are the same with the tags taken out
static readonly Dictionary Lines = new Dictionary
{
["dir_intro"] = "[angry] Listen up, you incompetent idiots! [shouting] EARTH IS OUT OF GRASS! NO GRASS! NOT A SINGLE DAMN BLADE! [frustrated] And you morons are standing around doing NOTHING?! [stern] That planet is covered in grass. And Earth needs EVERY. SINGLE. BLADE. [shouting] I want it CUT! I want it PACKED! And I want it SHIPPED BACK TO EARTH! [furious] I don't care if you have to use nail scissors! [shouting] NOW GET OUT THERE AND MOW THAT GODDAMN PLANET!",
["dir_intro_tag"] = "[deadpan] This is G.R.A.S.S.A. We take grass very seriously.",
["dir_m0001"] = "[suspicious] Wait. Is that... progress? [sniffs] Zero point zero zero one percent. [grudging] Earth thanks you. Barely. [shouting] NOW DO THE OTHER NINETY-NINE POINT NINE NINE NINE!",
["dir_m1"] = "[excited] ONE PERCENT! [clears throat] [stern] I mean... one percent. Acceptable. My grandmother mowed faster, and she used her teeth. [shouting] KEEP CUTTING!",
["dir_m50"] = "[emotional] Fifty percent. Half a planet. [sniffles] Somewhere on Earth, a cow just smiled for the first time in ten years. [shouting] DON'T YOU DARE STOP NOW!",
["dir_m100"] = "[voice breaking] One hundred percent. [pause] You did it. You magnificent idiots actually did it. [sobbing] Earth has grass again! [pause] [stern] Now. About the second planet. [pause] [deadpan] I'm kidding. [pause] Unless?",
["dir_machine"] = "[impressed] A machine! Finally, somebody down there with a brain! [shouting] Now put it to work before I bill you for the fuel!",
["dir_combine"] = "[shouting] A COMBINE HARVESTER?! [laughs maniacally] NOW we're talking! Earth's lawns will be green by Christmas!",
["dir_drones"] = "[suspicious] Drones? You bought DRONES? [pause] [grudging] Fine. But if they start a robot uprising, it's coming out of YOUR pay.",
["dir_belts"] = "[delighted] Conveyor belts! Grass that moves BY ITSELF! [whispers] This is what peak civilization looks like.",
["dir_ufo"] = "[panicked] Was that a UFO?! [whispers] Listen to me. Do NOT let them take the grass. [shouting] THAT GRASS BELONGS TO EARTH!",
};
// the planet's milestones, as fractions
static readonly (double at, string line)[] Milestones = { (0.00001d, "dir_m0001"), (0.01d, "dir_m1"), (0.5d, "dir_m50"), (0.99999d, "dir_m100") };
readonly Queue _queue = new Queue();
AudioSource _voice;
PhoneCall _view;
Label _caption, _ring;
bool _on;
float _open, _openVel;
// what the watcher saw last: a call goes when one of these rises past a line while you're playing
bool _seeded;
float _seedAt = -1f;
double _mown;
bool _machine, _combine, _drones, _belts, _ufo;
void Awake()
{
I = this;
_voice = gameObject.AddComponent();
_voice.playOnAwake = false;
_voice.spatialBlend = 0f;
_voice.priority = 0;
}
/// Rings with this line. Calls wait their turn.
/// The trailer: no calls but the ones it asks for.
public static bool Quiet;
public static void Call(string line)
{
if (!I || !Lines.ContainsKey(line) || Quiet) return;
if (I._queue.Contains(line)) return;
I._queue.Enqueue(line);
}
/// The opening film plays the call itself: no ring, the phone already up.
public static IEnumerator Speak(string line, bool hangUp)
{
if (!I) yield break;
yield return I.Talk(line, false, hangUp);
}
/// Cuts a call off where it is (the opening film was skipped).
public static void Abort()
{
if (!I) return;
I.StopAllCoroutines();
I._voice.Stop();
I.Caption("");
if (I._ring != null) I._ring.style.display = DisplayStyle.None;
I._view?.Show(false);
I._on = false;
Sfx.Duck(1f);
}
void Update()
{
Watch();
if (!_on && _queue.Count > 0 && Ready()) StartCoroutine(Ring(_queue.Dequeue()));
Mouth();
}
/// Not over a menu, not inside the opening film, in a game with a body to hold the phone.
static bool Ready()
{
var me = PlayerAgent.Local;
return me && me.IsSpawned && Phone.I && !Ctl.Cinematic && !Ctl.UIOpen;
}
IEnumerator Ring(string line)
{
_on = true;
Caption("");
var ring = Ensure(ref _ring, "director-ring t-outline");
ring.text = Loc.T("G.R.A.S.S.A. IS CALLING");
ring.style.display = DisplayStyle.Flex;
UIK.PopIn(ring, 0f, 0.3f);
for (int i = 0; i < 2; i++)
{
Sfx.Play("phone_ring", 0.5f, 1f, 0f);
UIK.Punch(ring, 0.12f);
yield return new WaitForSeconds(1.5f);
}
ring.style.display = DisplayStyle.None;
yield return Talk(line, true, true);
}
IEnumerator Talk(string line, bool takeOut, bool hangUp)
{
_on = true;
var phone = Phone.I;
var was = phone ? phone.Mode : PhoneMode.Away;
if (phone && takeOut && was == PhoneMode.Away) phone.Show(PhoneMode.Side);
yield return null;
if (phone && phone.Screen != null && phone.Mode != PhoneMode.Away)
{
if (phone.Screen.Wide) phone.Screen.Turn();
_view ??= new PhoneCall(phone.Screen.Root);
_view.Show(true);
}
Sfx.Play("call_connect", 0.6f, 1f, 0f);
yield return new WaitForSeconds(0.45f);
var clip = AssetBank.I.Clip(line);
var words = Captions(Lines[line]);
var moods = Moods(Lines[line]);
if (clip)
{
_voice.clip = clip;
_voice.volume = VoiceGain(Envelope(clip));
_voice.Play();
Sfx.Heard?.Invoke(clip.name, 1f, 1f, null);
}
float length = clip ? clip.length : 4f, t = 0f;
bool hungUp = false;
_env = clip ? Envelope(clip) : null;
while (t < length)
{
// V puts the phone away, and that ends the call
if (takeOut && phone && phone.Mode == PhoneMode.Away) { hungUp = true; break; }
Sfx.Duck(0.35f);
_voice.volume = VoiceGain(_env);
_talkT = t;
Caption(CaptionAt(words, Spoken(t)));
_view?.Tick(_open, t, MoodAt(moods, Spoken(t)));
t += Time.deltaTime;
yield return null;
}
_env = null;
_voice.Stop();
Caption("");
Sfx.Duck(1f);
if (hangUp)
{
Sfx.Play("call_hangup", 0.3f, 1f, 0f);
if (!hungUp) yield return new WaitForSeconds(0.35f);
if (phone && takeOut && was == PhoneMode.Away && phone.Mode != PhoneMode.Away) phone.Show(PhoneMode.Away);
}
_view?.Show(false);
_on = false;
}
/// The jaw follows how loud he is, quick to open and a little slower to shut.
void Mouth()
{
float target = 0f;
if (_env != null)
{
int i = Mathf.Clamp((int)(_talkT * EnvRate), 0, _env.level.Length - 1);
target = _env.level[i];
}
_open = Mathf.SmoothDamp(_open, target, ref _openVel, target > _open ? 0.035f : 0.07f);
}
// how loud he is through the clip, read from the clip itself (so it works with the sound off, too), and how much
// of the talking is done by each moment, which is what the captions follow
internal const int EnvRate = 60;
internal class Env { public float[] level, said; }
/// The volume a line plays at now: the Voices slider. The lines themselves are levelled to one loudness by
/// Tools/director/finish_audio.py.
internal static float VoiceGain(Env e) => Sfx.VoiceVolume;
Env _env;
float _talkT;
static readonly Dictionary s_envs = new Dictionary();
internal static Env Envelope(AudioClip clip)
{
if (s_envs.TryGetValue(clip, out var e)) return e;
int frames = Mathf.Max(1, Mathf.CeilToInt(clip.length * EnvRate));
e = new Env { level = new float[frames], said = new float[frames] };
var data = new float[clip.samples * clip.channels];
if (clip.loadState == AudioDataLoadState.Loaded && clip.GetData(data, 0))
{
int per = Mathf.Max(1, data.Length / frames);
var rms = new float[frames];
for (int f = 0; f < frames; f++)
{
double sum = 0;
int a = f * per, b = Mathf.Min(data.Length, a + per);
for (int k = a; k < b; k++) sum += data[k] * data[k];
rms[f] = Mathf.Sqrt((float)(sum / Mathf.Max(1, b - a)));
}
var sorted = (float[])rms.Clone();
System.Array.Sort(sorted);
float loud = Mathf.Max(0.02f, sorted[(int)(sorted.Length * 0.92f)]);
float run = 0f;
for (int f = 0; f < frames; f++)
{
e.level[f] = Mathf.Clamp01((rms[f] / loud - 0.12f) * 1.25f);
if (rms[f] > loud * 0.12f) run += 1f;
e.said[f] = run;
}
for (int f = 0; f < frames; f++) e.said[f] /= Mathf.Max(1f, run);
}
else
{
// nothing to read: a steady natter, and captions by the clock
for (int f = 0; f < frames; f++) { e.level[f] = 0.35f + 0.35f * Mathf.Sin(f * 0.9f) * Mathf.Sin(f * 0.23f); e.said[f] = f / (float)frames; }
}
s_envs[clip] = e;
return e;
}
/// How much of the line has been said by this time, 0..1.
float Spoken(float t)
{
if (_env == null || _env.said.Length == 0) return 0f;
return _env.said[Mathf.Clamp((int)(t * EnvRate), 0, _env.said.Length - 1)];
}
// ───────── captions ─────────
static readonly Regex Tag = new Regex(@"\[[^\]]*\]\s*");
/// The line split at its sentences, each with where it starts in the clip (by its share of the letters).
internal static List<(float at, string text)> Captions(string line)
{
var plain = Tag.Replace(line, "").Trim();
var parts = Regex.Split(plain, @"(?<=[\.\!\?])\s+").Where(p => p.Length > 0).ToList();
// short bursts ride together so the captions don't flicker
var merged = new List();
foreach (var p in parts)
{
if (merged.Count > 0 && (merged[merged.Count - 1].Length < 22 || p.Length < 10) && merged[merged.Count - 1].Length + p.Length < 70) merged[merged.Count - 1] += " " + p;
else merged.Add(p);
}
float total = merged.Sum(p => p.Length + 6f), run = 0f;
var outp = new List<(float, string)>();
foreach (var p in merged) { outp.Add((run / total, p)); run += p.Length + 6f; }
return outp;
}
/// Each tag in the line, as a mood and where in the spoken text it starts (0..1).
internal static List<(float at, Mood mood)> Moods(string line)
{
var outp = new List<(float, Mood)>();
var plainLen = Tag.Replace(line, "").Trim().Length;
int said = 0, i = 0;
foreach (Match m in Regex.Matches(line, @"\[([^\]]*)\]"))
{
said += Tag.Replace(line.Substring(i, m.Index - i), "").Length;
i = m.Index + m.Length;
outp.Add((said / (float)Mathf.Max(1, plainLen), MoodOf(m.Groups[1].Value)));
}
return outp;
}
static Mood MoodOf(string tag)
{
switch (tag.Trim().ToLowerInvariant())
{
case "angry": case "furious": case "frustrated": case "shouting": return Mood.Angry;
case "stern": case "deadpan": case "suspicious": case "grudging": case "clears throat": return Mood.Stern;
case "excited": case "delighted": case "impressed": case "laughs maniacally": return Mood.Happy;
case "emotional": case "sniffles": case "sobbing": case "voice breaking": return Mood.Sad;
case "panicked": case "alarmed": case "nervous": return Mood.Scared;
case "concerned": return Mood.Sad;
case "sighs": return Mood.Stern;
case "whispers": case "softly": return Mood.Whisper;
default: return Mood.Calm;
}
}
internal static Mood MoodAt(List<(float at, Mood mood)> moods, float k)
{
var m = Mood.Calm;
// a pause or a sniff keeps the mood that came before it
foreach (var x in moods) if (x.at <= k + 0.005f && x.mood != Mood.Calm) m = x.mood;
return m;
}
internal static string CaptionAt(List<(float at, string text)> words, float k)
{
string s = "";
foreach (var w in words) if (w.at <= k + 0.01f) s = w.text;
// timed on the English voice, shown in the interface language (Tools/loc/extract.py lists these pieces)
return Loc.T(s);
}
void Caption(string text)
{
var c = Ensure(ref _caption, "director-caption t-outline");
c.text = text;
c.style.display = string.IsNullOrEmpty(text) ? DisplayStyle.None : DisplayStyle.Flex;
}
static Label Ensure(ref Label l, string cls)
{
if (l != null && l.panel != null) return l;
var root = UIRoot.I ? UIRoot.I.Cinema : null;
l = UIK.Text("", cls, root, false);
l.pickingMode = PickingMode.Ignore;
l.style.display = DisplayStyle.None;
return l;
}
// ───────── what makes him call ─────────
void Watch()
{
var ts = TeamState.Instance;
var me = PlayerAgent.Local;
if (!ts || !ts.IsSpawned || !me || !me.IsSpawned) { _seeded = false; _seedAt = -1f; return; }
// the world comes back from the save first, then whatever is already there doesn't count
if (_seedAt < 0f) _seedAt = Time.time + 6f;
bool machine = Vehicle.All.Any(v => v && v.Crew.Value.ToString() == me.SaveId);
bool combine = Vehicle.All.Any(v => v && v.kind == VehicleKind.Combine);
bool drones = BuildPiece.All.Any(p => p && p.piece == PieceId.DronePad);
bool belts = BuildPiece.All.Any(p => p && p is BeltRun);
bool ufo = ts.UfoOn;
double mown = ts.Mown01;
if (!_seeded)
{
if (Time.time < _seedAt) return;
_seeded = true;
(_mown, _machine, _combine, _drones, _belts, _ufo) = (mown, machine, combine, drones, belts, ufo);
return;
}
foreach (var (at, line) in Milestones)
if (_mown < at && mown >= at) Call(line);
if (machine && !_machine) Call("dir_machine");
if (combine && !_combine) Call("dir_combine");
if (drones && !_drones) Call("dir_drones");
if (belts && !_belts) Call("dir_belts");
// the saucer only the first time it is ever seen
if (ufo && !_ufo && PlayerPrefs.GetInt("dir_ufo", 0) == 0) { PlayerPrefs.SetInt("dir_ufo", 1); Call("dir_ufo"); }
(_mown, _machine, _combine, _drones, _belts, _ufo) = (mown, machine, combine, drones, belts, ufo);
}
}
/// What the Director is feeling, read off the tags in his lines.
public enum Mood { Calm, Angry, Stern, Happy, Sad, Scared, Whisper }
///
/// The call on the phone's display: the Director in 3D at mission control on Earth (filmed in his booth in the Studio),
/// talking like a South Park cut-out, the top of his head tipping up off one side and then the other over a dark mouth.
/// How he feels shows on him and round him: red in the face with steam out of his ears and a throbbing vein when he
/// shouts, arms up and sparkles when he's pleased, tears when he's moved, sweat when he panics, leaning in to whisper.
///
public class PhoneCall
{
const float W = PhoneScreen.W, H = PhoneScreen.H;
const int RtW = 540, RtH = 1184; // the screen's shape, at three quarters
static readonly Vector2[] SparkRing =
{
new Vector2(-1f, -0.55f), new Vector2(1f, -0.4f), new Vector2(-1.1f, 0.35f), new Vector2(1.1f, 0.3f), new Vector2(0f, -1.05f),
};
readonly VisualElement _root, _picture, _fx, _vein;
readonly VisualElement[] _sparks;
readonly Label _timer;
readonly Booth _booth;
// the user's filmed loops of him, one per mood: they carry his face, so the drawn-on vein, steam and tears stay off
readonly TalkVideo _talk;
float _lastT, _puffDue, _tearDue, _sweatDue;
// where his picture stands on the screen: under the agency's bar, over the red button
const float PicTop = 200f, PicBottom = 170f;
// how much of each mood is showing, eased in and out
readonly float[] _mood = new float[7];
class Bit { public VisualElement e; public Vector2 at, vel; public float age, life, size; public bool live; public int kind; }
readonly List _bits = new List();
public PhoneCall(VisualElement screen)
{
_root = Box(screen, 0f, 0f, W, H);
_root.style.backgroundColor = new Color(0.02f, 0.04f, 0.09f);
// his office on Earth behind him, him in front from the hips up, like a video call: the whole screen is one
// picture, which comes in and goes out as a hologram (TalkVideo)
var fig = new Rect(0f, PicBottom / H, 1f, (H - PicTop - PicBottom) / H);
_talk = new TalkVideo("boss", new[] { "calm", "stern", "angry" }, 640, 650, RtW, RtH, fig, "T_Talk_BossBg");
_picture = Box(_root, 0f, 0f, W, H);
_picture.style.unityBackgroundScaleMode = ScaleMode.StretchToFill;
_picture.style.backgroundImage = new StyleBackground(Background.FromRenderTexture(_talk.Rt));
_talk.Gone = () => _root.style.display = DisplayStyle.None;
_fx = Box(_root, 0f, 0f, W, H);
// the anger vein on his forehead
_vein = Box(_fx, 0f, 0f, 76f, 76f);
_vein.generateVisualContent += DrawVein;
_vein.style.opacity = 0f;
// sparkles round him
_sparks = new VisualElement[SparkRing.Length];
for (int i = 0; i < SparkRing.Length; i++)
{
_sparks[i] = Box(_fx, 0f, 0f, 64f, 64f);
_sparks[i].generateVisualContent += DrawSpark;
_sparks[i].style.opacity = 0f;
}
// the agency's bar
var bar = Box(_root, 0f, 0f, W, 230f);
bar.style.backgroundColor = new Color(0.02f, 0.05f, 0.12f, 0.72f);
bar.style.alignItems = Align.Center;
bar.style.paddingTop = 46;
var name = UIK.Text("G.R.A.S.S.A.", "", bar, true);
name.style.fontSize = 64; name.style.color = new Color(1f, 0.86f, 0.4f);
var row = new VisualElement { pickingMode = PickingMode.Ignore };
row.style.flexDirection = FlexDirection.Row;
row.style.alignItems = Align.Center;
bar.Add(row);
var dot = new VisualElement { pickingMode = PickingMode.Ignore };
dot.style.width = 20; dot.style.height = 20; dot.style.marginRight = 12;
dot.style.backgroundColor = new Color(1f, 0.25f, 0.2f);
Radius(dot, 10f);
row.Add(dot);
var who = UIK.Text(Loc.T("THE DIRECTOR · LIVE FROM EARTH"), "", row, false);
who.style.fontSize = 28; who.style.color = new Color(0.86f, 0.92f, 1f);
_timer = UIK.Text("00:00", "", bar, false);
_timer.style.fontSize = 26; _timer.style.color = new Color(0.7f, 0.8f, 0.9f, 0.8f);
_timer.style.marginTop = 6;
// the bar is a fixed height: nothing in it may be squeezed (the row under the name was, to nothing, and the
// timer sat on top of it)
name.style.flexShrink = 0; row.style.flexShrink = 0; _timer.style.flexShrink = 0;
// the red button at the foot
var hang = Box(_root, (W - 110f) * 0.5f, H - 160f, 110f, 110f);
hang.style.backgroundColor = new Color(0.92f, 0.2f, 0.18f);
Radius(hang, 55f);
var key = UIK.Text("V", "", hang, true);
key.style.fontSize = 48; key.style.color = Color.white;
key.style.unityTextAlign = TextAnchor.MiddleCenter;
key.style.flexGrow = 1;
// the agency's bar and the button light up ahead of the picture, and go out after it
_talk.Drawn = a => { float o = Mathf.Clamp01(a * 3f); bar.style.opacity = o; hang.style.opacity = o; };
_root.style.display = DisplayStyle.None;
}
static VisualElement Box(VisualElement parent, float x, float y, float w, float h)
{
var e = new VisualElement { pickingMode = PickingMode.Ignore };
e.style.position = Position.Absolute;
e.style.left = x; e.style.top = y; e.style.width = w; e.style.height = h;
parent.Add(e);
return e;
}
static void Radius(VisualElement e, float r)
{
e.style.borderTopLeftRadius = e.style.borderTopRightRadius = e.style.borderBottomLeftRadius = e.style.borderBottomRightRadius = r;
}
public void Show(bool on)
{
_booth?.Show(on);
// off: the hologram fades out, then TalkVideo.Gone hides the screen
_talk?.Show(on);
if (!on)
{
if (_talk == null) _root.style.display = DisplayStyle.None;
return;
}
_root.style.display = DisplayStyle.Flex;
_root.BringToFront();
_lastT = 0f;
for (int i = 0; i < _mood.Length; i++) _mood[i] = 0f;
foreach (var b in _bits) { b.live = false; b.e.style.display = DisplayStyle.None; }
Tick(0f, 0f, Mood.Calm);
}
// with the filmed loops there are no bones to follow: round about where his head is in them
Vector2 At(string anchor) => _booth != null && _booth.Puppet != null ? _booth.OnPicture(_booth.Puppet.Anchor(anchor), W, H) : new Vector2(W * 0.5f, PicTop + 330f);
/// open 0..1: how far the top of his head is up; t: seconds into the call; mood: what the line says now.
public void Tick(float open, float t, Mood mood)
{
float dt = Mathf.Clamp(t - _lastT, 0f, 0.1f);
_lastT = t;
for (int i = 0; i < _mood.Length; i++) _mood[i] = Mathf.MoveTowards(_mood[i], i == (int)mood ? 1f : 0f, dt * 3f);
float angry = _mood[(int)Mood.Angry], happy = _mood[(int)Mood.Happy];
float sad = _mood[(int)Mood.Sad], scared = _mood[(int)Mood.Scared];
_booth?.Puppet?.Tick(t, open, _mood);
_booth?.Flush(angry * (0.18f + open * 0.14f));
_talk?.Play(TalkVideo.BossMood(TalkVideo.Strongest(_mood)));
if (_talk != null) angry = sad = scared = 0f;
// the vein throbs on his forehead while he's angry
var brow = At("Forehead");
float throb = 1f + Mathf.Max(0f, Mathf.Sin(t * 9f)) * 0.25f * angry;
_vein.style.left = brow.x + 22f - 38f;
_vein.style.top = brow.y - 30f - 38f;
_vein.style.opacity = angry;
_vein.style.scale = new Scale(new Vector3(throb, throb, 1f));
// sparkles pop in turn round his head while he's pleased
var head = At("Forehead");
for (int i = 0; i < _sparks.Length; i++)
{
float ph = Mathf.Repeat(t * 1.3f + i * 0.37f, 1f);
float k = Mathf.Sin(ph * Mathf.PI) * happy;
var p = head + SparkRing[i] * 230f;
_sparks[i].style.left = p.x - 32f;
_sparks[i].style.top = p.y - 32f;
_sparks[i].style.opacity = k;
_sparks[i].style.scale = new Scale(new Vector3(0.4f + k * 0.8f, 0.4f + k * 0.8f, 1f));
_sparks[i].style.rotate = new Rotate(t * 90f + i * 40f);
}
// steam out of his ears, tears down his cheeks, sweat on his temple
_puffDue += dt * angry * (5f + open * 8f);
for (; _puffDue >= 1f; _puffDue -= 1f)
{
int side = Random.value < 0.5f ? 0 : 1;
var ear = At(side == 0 ? "Ear_L" : "Ear_R");
float out_ = Mathf.Sign(ear.x - head.x);
Spawn(0, ear, new Vector2(out_ * Random.Range(40f, 90f), Random.Range(-170f, -120f)), Random.Range(30f, 46f), 0.9f);
}
_tearDue += dt * sad * 2.4f;
for (; _tearDue >= 1f; _tearDue -= 1f)
{
var eye = At(Random.value < 0.5f ? "Eye_L" : "Eye_R");
Spawn(1, eye + new Vector2(0f, 26f), new Vector2(0f, 70f), Random.Range(16f, 22f), 1.6f);
}
_sweatDue += dt * scared * 1.6f;
for (; _sweatDue >= 1f; _sweatDue -= 1f)
Spawn(2, At("Temple") + new Vector2(Random.Range(-12f, 12f), 0f), new Vector2(0f, 50f), Random.Range(16f, 22f), 1.4f);
Bits(dt);
_timer.text = $"{(int)(t / 60f):00}:{(int)t % 60:00}";
}
void Spawn(int kind, Vector2 at, Vector2 vel, float size, float life)
{
Bit b = null;
foreach (var x in _bits) if (!x.live && x.kind == kind) { b = x; break; }
if (b == null)
{
if (_bits.Count > 60) return;
var e = Box(_fx, 0f, 0f, 1f, 1f);
if (kind == 0) e.style.backgroundColor = new Color(1f, 1f, 1f, 0.85f);
else e.style.backgroundColor = kind == 1 ? new Color(0.55f, 0.8f, 1f, 0.95f) : new Color(0.7f, 0.9f, 1f, 0.9f);
b = new Bit { e = e, kind = kind };
_bits.Add(b);
}
b.live = true; b.at = at; b.vel = vel; b.age = 0f; b.life = life; b.size = size;
b.e.style.display = DisplayStyle.Flex;
b.e.BringToFront();
}
void Bits(float dt)
{
foreach (var b in _bits)
{
if (!b.live) continue;
b.age += dt;
if (b.age >= b.life) { b.live = false; b.e.style.display = DisplayStyle.None; continue; }
float k = b.age / b.life;
b.at += b.vel * dt;
float w, h;
if (b.kind == 0)
{
// a puff swells and thins as it rises
b.vel *= 1f - dt * 0.8f;
w = h = b.size * (0.6f + k * 1.6f);
b.e.style.opacity = (1f - k) * 0.9f;
Radius(b.e, w * 0.5f);
}
else
{
// a drop runs down, picking up speed
b.vel.y += 90f * dt;
w = b.size * 0.7f; h = b.size;
b.e.style.opacity = Mathf.Clamp01((1f - k) * 3f);
b.e.style.borderTopLeftRadius = b.e.style.borderTopRightRadius = w * 0.5f;
b.e.style.borderBottomLeftRadius = b.e.style.borderBottomRightRadius = w * 0.5f;
}
b.e.style.left = b.at.x - w * 0.5f;
b.e.style.top = b.at.y - h * 0.5f;
b.e.style.width = w;
b.e.style.height = h;
}
}
static void DrawVein(MeshGenerationContext ctx)
{
// the cartoon cross-popping vein: four little arcs bowing in
var p = ctx.painter2D;
float s = ctx.visualElement.contentRect.width;
var c = new Vector2(s * 0.5f, s * 0.5f);
p.strokeColor = new Color(0.86f, 0.12f, 0.12f);
p.lineWidth = s * 0.11f;
p.lineCap = LineCap.Round;
for (int i = 0; i < 4; i++)
{
float a = i * 90f + 45f;
var dir = new Vector2(Mathf.Cos(a * Mathf.Deg2Rad), Mathf.Sin(a * Mathf.Deg2Rad));
var mid = c + dir * s * 0.3f;
p.BeginPath();
p.Arc(mid + dir * s * 0.12f, s * 0.2f, a + 180f - 50f, a + 180f + 50f);
p.Stroke();
}
}
static void DrawSpark(MeshGenerationContext ctx)
{
// a four-pointed star
var p = ctx.painter2D;
float s = ctx.visualElement.contentRect.width;
var c = new Vector2(s * 0.5f, s * 0.5f);
p.fillColor = new Color(1f, 0.9f, 0.35f);
p.BeginPath();
for (int i = 0; i < 8; i++)
{
float a = i * 45f * Mathf.Deg2Rad;
float r = i % 2 == 0 ? s * 0.5f : s * 0.13f;
var v = c + new Vector2(Mathf.Sin(a), -Mathf.Cos(a)) * r;
if (i == 0) p.MoveTo(v); else p.LineTo(v);
}
p.ClosePath();
p.Fill();
}
}
}